forked from alibaba/TinyNeuralNetwork
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
271 lines (195 loc) · 7.47 KB
/
util.py
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import importlib.util
import logging
import os
import types
import typing
from functools import wraps
loggers = []
class LazyExpression(object):
""" An expression object that can be lazily evaluated """
expr: typing.Callable[[], typing.Any]
def __init__(self, expr: typing.Callable[[], typing.Any]):
""" Constructs a new LazyExpression object
Args:
expr (typing.Callable[[], typing.Any]): the expression
"""
self.expr = expr
def eval(self) -> typing.Any:
""" Evaluates the lazy expression
Returns:
typing.Any: the value of the expression
"""
return self.expr()
class LazyObject(object):
""" An object that can be construct lazily using lazy expressions """
cls: type
pos_options: list
kw_options: typing.Dict[str, typing.Any]
current_obj: typing.Any
def __init__(self, cls: type, pos_options: typing.Optional[list] = None,
kw_options: typing.Optional[typing.Dict[str, typing.Any]] = None):
""" Constructs a new lazy object
Args:
cls (type): The type of the class to be construct lazily
pos_options (typing.Optional[list], optional): The positional options. Defaults to None.
kw_options (typing.Optional[typing.Dict[str, typing.Any]], optional): The keyword options. Defaults to None.
"""
self.cls = cls
if pos_options is None:
self.pos_options = []
else:
self.pos_options = pos_options
if kw_options is None:
self.kw_options = {}
else:
self.kw_options = kw_options
# Try construct object once
self.get_next()
def __str__(self) -> str:
""" Proxy __str__ to the underlying the object
Returns:
str: String representation of the underlying object
"""
return str(self.current_obj)
def __repr__(self) -> str:
""" Proxy __repr__ to the underlying the object
Returns:
str: String representation of the underlying object
"""
return self.current_obj.__repr__()
def get_current(self) -> typing.Any:
""" Gets the current copy of the lazily-constructed object
Returns:
typing.Any: The current copy of the lazily-constructed object
"""
return self.current_obj
def get_next(self):
""" Create a new object with the class and the arguments """
pos_options = []
kw_options = {}
for opt in self.pos_options:
if isinstance(opt, LazyObject):
pos_options.append(opt.get_current())
elif isinstance(opt, LazyExpression):
pos_options.append(opt.eval())
else:
pos_options.append(opt)
for opt_k, opt_v in self.kw_options.items():
if isinstance(opt_v, LazyObject):
kw_options[opt_k] = opt.get_current()
elif isinstance(opt_v, LazyExpression):
kw_options[opt_k] = opt_v.eval()
else:
kw_options[opt_k] = opt_v
self.current_obj = self.cls(*pos_options, **kw_options)
return self.current_obj
def get_actual_type(param_type: type) -> typing.List[type]:
""" Gets the candidate actual types of a given type
Args:
param_type (type): The type to extract actual type from
Returns:
typing.List[type]: The candidate types
"""
param_types = []
if hasattr(param_type, '__origin__'):
if param_type.__origin__ is typing.Union:
for arg in param_type.__args__:
param_types.extend(get_actual_type(arg))
else:
param_types.append(param_type.__origin__)
else:
param_types.append(param_type)
return param_types
def conditional(cond: typing.Callable[[], bool]) -> typing.Callable:
""" A function wrapper that only runs the code of the function under given condition
Args:
cond (typing.Callable[[], bool]): The predicate given
Returns:
typing.Callable: A new function that only runs under given condition
"""
def conditional_decorator(f):
@wraps(f)
def wrapper(*args, **kwds):
if cond():
f(*args, **kwds)
return wrapper
return conditional_decorator
def class_conditional(cond: typing.Callable[[typing.Any], bool]) -> typing.Callable:
""" A class function wrapper that only runs the code of the function under given condition
Args:
cond (typing.Callable[[], bool]): The predicate given
Returns:
typing.Callable: A new function that only runs under given condition
"""
def conditional_decorator(f):
@wraps(f)
def wrapper(*args, **kwds):
if cond(args[0]):
f(*args, **kwds)
return wrapper
return conditional_decorator
def tensors2ndarray(tensors) -> list:
""" Convert tensors in arbitrary format into list of ndarray
Args:
output: tensors in arbitrary format
Returns:
typing.List[numpy.ndarray]: list of ndarray
"""
new_tensors = []
if isinstance(tensors, (list, tuple)):
for i in tensors:
new_tensors.extend(tensors2ndarray(i))
elif isinstance(tensors, dict):
for k, v in tensors.items():
new_tensors.extend(tensors2ndarray(v))
elif hasattr(tensors, 'detach') and hasattr(tensors, 'numpy'):
new_tensors.append(tensors.detach().numpy())
elif not isinstance(tensors, (bool, str, int, float, types.FunctionType)):
for k in tensors.__dir__():
if not k.startswith('__'):
v = getattr(tensors, v)
new_tensors.extend(tensors2ndarray(v))
return new_tensors
def import_from(module: str, name: str):
""" Import a module with the given name (Equivalent of `from module import name`)
Args:
module (str): The namespace of the module
name (str): The name to be imported
Returns:
The imported class, function, and etc
"""
module = __import__(module, fromlist=[name])
return getattr(module, name)
def import_from_path(module: str, path: str, name: str):
""" Import a module with the given name and path (Equivalent of `from module import name`)
Args:
module (str): The namespace of the module
path (str): The path of the file
name (str): The name to be imported
Returns:
The imported class, function, and etc
"""
spec = importlib.util.spec_from_file_location(module, path)
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
return getattr(foo, name)
def get_logger(name: str, level: typing.Optional[str] = None) -> logging.Logger:
""" Acquires the logger for a module with the given name
Args:
name (str): The name of the module
level (typing.Optional[str]): The level of the logger. Defaults to None ('INFO').
Returns:
logging.Logger: The logger of the module
"""
if level is None:
level = 'INFO'
level = os.environ.get('LOGLEVEL', level)
logger = logging.getLogger(name)
logger.setLevel(level)
# Initialze the log level of the logger. Other possible values are `INFO`, `DEBUG` and `ERROR`
logging.basicConfig(format='%(levelname)s (%(name)s) %(message)s')
loggers.append(logger)
return logger
def set_global_log_level(level: str = "INFO"):
for logger in loggers:
logger.setLevel(level)