forked from FederatedAI/FATE
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponent_base.py
More file actions
209 lines (156 loc) · 6.77 KB
/
Copy pathcomponent_base.py
File metadata and controls
209 lines (156 loc) · 6.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import copy
from pipeline.utils.logger import LOGGER
class Component(object):
__instance = {}
def __init__(self, *args, **kwargs):
LOGGER.debug(f"kwargs: {kwargs}")
if "name" in kwargs:
self._component_name = kwargs["name"]
self.__party_instance = {}
self._component_parameter_keywords = set(kwargs.keys())
self._role_parameter_keywords = set()
self._module_name = None
self._component_param = {}
self._provider = None
def __new__(cls, *args, **kwargs):
if cls.__name__.lower() not in cls.__instance:
cls.__instance[cls.__name__.lower()] = 0
new_cls = object.__new__(cls)
new_cls.set_name(cls.__instance[cls.__name__.lower()])
cls.__instance[cls.__name__.lower()] += 1
return new_cls
def set_name(self, idx):
self._component_name = self.__class__.__name__.lower() + "_" + str(idx)
LOGGER.debug(f"enter set name func {self._component_name}")
def reset_name(self, name):
self._component_name = name
@property
def provider(self):
return self._provider
@provider.setter
def provider(self, provider):
self._provider = provider
def get_party_instance(self, role="guest", party_id=None) -> 'Component':
if role not in ["guest", "host", "arbiter"]:
raise ValueError("Role should be one of guest/host/arbiter")
if party_id is not None:
if isinstance(party_id, list):
for _id in party_id:
if not isinstance(_id, int) or _id <= 0:
raise ValueError("party id should be positive integer")
elif not isinstance(party_id, int) or party_id <= 0:
raise ValueError("party id should be positive integer")
if role not in self.__party_instance:
self.__party_instance[role] = {}
self.__party_instance[role]["party"] = {}
party_key = party_id
if isinstance(party_id, list):
party_key = "|".join(map(str, party_id))
if party_key not in self.__party_instance[role]["party"]:
self.__party_instance[role]["party"][party_key] = None
if not self.__party_instance[role]["party"][party_key]:
party_instance = copy.deepcopy(self)
self._decrease_instance_count()
self.__party_instance[role]["party"][party_key] = party_instance
LOGGER.debug(f"enter init")
return self.__party_instance[role]["party"][party_key]
@classmethod
def _decrease_instance_count(cls):
cls.__instance[cls.__name__.lower()] -= 1
LOGGER.debug(f"decrease instance count")
@property
def name(self):
return self._component_name
@property
def module(self):
return self._module_name
def component_param(self, **kwargs):
new_kwargs = copy.deepcopy(kwargs)
for attr in self.__dict__:
if attr in new_kwargs:
setattr(self, attr, new_kwargs[attr])
self._component_param[attr] = new_kwargs[attr]
del new_kwargs[attr]
for attr in new_kwargs:
LOGGER.warning(f"key {attr}, value {new_kwargs[attr]} not use")
self._role_parameter_keywords |= set(kwargs.keys())
def get_component_param(self):
return self._component_param
def get_common_param_conf(self):
"""
exclude_attr = ["_component_name", "__party_instance",
"_component_parameter_keywords", "_role_parameter_keywords"]
"""
common_param_conf = {}
for attr in self.__dict__:
if attr.startswith("_"):
continue
if attr in self._role_parameter_keywords:
continue
if attr not in self._component_parameter_keywords:
continue
common_param_conf[attr] = getattr(self, attr)
return common_param_conf
def get_role_param_conf(self, roles=None):
role_param_conf = {}
if not self.__party_instance:
return role_param_conf
for role in self.__party_instance:
role_param_conf[role] = {}
if None in self.__party_instance[role]["party"]:
role_all_party_conf = self.__party_instance[role]["party"][None].get_component_param()
if "all" not in role_param_conf:
role_param_conf[role]["all"] = {}
role_param_conf[role]["all"][self._component_name] = role_all_party_conf
valid_partyids = roles.get(role)
for party_id in self.__party_instance[role]["party"]:
if not party_id:
continue
if isinstance(party_id, int):
party_key = str(valid_partyids.index(party_id))
else:
party_list = list(map(int, party_id.split("|", -1)))
party_key = "|".join(map(str, [valid_partyids.index(party) for party in party_list]))
party_inst = self.__party_instance[role]["party"][party_id]
if party_key not in role_param_conf:
role_param_conf[role][party_key] = {}
role_param_conf[role][party_key][self._component_name] = party_inst.get_component_param()
# print ("role_param_conf {}".format(role_param_conf))
LOGGER.debug(f"role_param_conf {role_param_conf}")
return role_param_conf
@classmethod
def erase_component_base_param(cls, **kwargs):
new_kwargs = copy.deepcopy(kwargs)
if "name" in new_kwargs:
del new_kwargs["name"]
return new_kwargs
def get_config(self, *args, **kwargs):
"""need to implement"""
roles = kwargs["roles"]
common_param_conf = self.get_common_param_conf()
role_param_conf = self.get_role_param_conf(roles)
conf = {}
if common_param_conf:
conf['common'] = {self._component_name: common_param_conf}
if role_param_conf:
conf["role"] = role_param_conf
return conf
def _get_all_party_instance(self):
return self.__party_instance
class PlaceHolder(object):
pass