Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

utils.py 9.2 KB

You have to be logged in to leave a comment. Sign In
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
  1. """Some helper functions for PyTorch, including:
  2. - get_mean_and_std: calculate the mean and std value of dataset.
  3. - msr_init: net parameter initialization.
  4. - progress_bar: progress bar mimic xlua.progress.
  5. """
  6. import time
  7. from typing import Union
  8. from jsonschema import validate
  9. import torch
  10. import torch.nn as nn
  11. # These functions changed from torch 1.2 to torch 1.3
  12. import random
  13. import numpy as np
  14. from importlib import import_module
  15. def convert_to_tensor(array):
  16. """Converts numpy arrays and lists to Torch tensors before calculation losses
  17. :param array: torch.tensor / Numpy array / List
  18. """
  19. return torch.FloatTensor(array) if type(array) != torch.Tensor else array
  20. class HpmStruct:
  21. def __init__(self, **entries):
  22. self.__dict__.update(entries)
  23. self.schema = None
  24. def set_schema(self, schema: dict):
  25. self.schema = schema
  26. def override(self, **entries):
  27. self.__dict__.update(entries)
  28. def to_dict(self):
  29. return self.__dict__
  30. def validate(self):
  31. """
  32. Validate the current dict values according to the provided schema
  33. :raises
  34. `AttributeError` if schema was not set
  35. `jsonschema.exceptions.ValidationError` if the instance is invalid
  36. `jsonschema.exceptions.SchemaError` if the schema itselfis invalid
  37. """
  38. if self.schema is None:
  39. raise AttributeError('schema was not set')
  40. else:
  41. validate(self.__dict__, self.schema)
  42. class WrappedModel(nn.Module):
  43. def __init__(self, module):
  44. super(WrappedModel, self).__init__()
  45. self.module = module # that I actually define.
  46. def forward(self, x):
  47. return self.module(x)
  48. class Timer:
  49. """A class to measure time handling both GPU & CPU processes
  50. Returns time in milliseconds"""
  51. def __init__(self, device: str):
  52. """
  53. :param device: str
  54. 'cpu'\'cuda'
  55. """
  56. self.on_gpu = (device == 'cuda')
  57. # On GPU time is measured using cuda.events
  58. if self.on_gpu:
  59. self.starter = torch.cuda.Event(enable_timing=True)
  60. self.ender = torch.cuda.Event(enable_timing=True)
  61. # On CPU time is measured using time
  62. else:
  63. self.starter, self.ender = 0, 0
  64. def start(self):
  65. if self.on_gpu:
  66. self.starter.record()
  67. else:
  68. self.starter = time.time()
  69. def stop(self):
  70. if self.on_gpu:
  71. self.ender.record()
  72. torch.cuda.synchronize()
  73. timer = self.starter.elapsed_time(self.ender)
  74. else:
  75. # Time measures in seconds -> convert to milliseconds
  76. timer = (time.time() - self.starter) * 1000
  77. # Return time in milliseconds
  78. return timer
  79. class AverageMeter:
  80. """A class to calculate the average of a metric, for each batch
  81. during training/testing"""
  82. def __init__(self):
  83. self._sum = None
  84. self._count = 0
  85. def update(self, value: Union[float, tuple, list, torch.Tensor], batch_size: int):
  86. if not isinstance(value, torch.Tensor):
  87. value = torch.tensor(value)
  88. if self._sum is None:
  89. self._sum = value * batch_size
  90. else:
  91. self._sum += value * batch_size
  92. self._count += batch_size
  93. @property
  94. def average(self):
  95. if self._sum is None:
  96. return 0
  97. return ((self._sum / self._count).__float__()) if self._sum.dim() < 1 else tuple(
  98. (self._sum / self._count).cpu().numpy())
  99. # return (self._sum / self._count).__float__() if self._sum.dim() < 1 or len(self._sum) == 1 \
  100. # else tuple((self._sum / self._count).cpu().numpy())
  101. def tensor_container_to_device(obj: Union[torch.Tensor, tuple, list, dict], device: str, non_blocking=True):
  102. """
  103. recursively send compounded objects to device (sending all tensors to device and maintaining structure)
  104. :param obj the object to send to device (list / tuple / tensor / dict)
  105. :param device: device to send the tensors to
  106. :param non_blocking: used for DistributedDataParallel
  107. :returns an object with the same structure (tensors, lists, tuples) with the device pointers (like
  108. the return value of Tensor.to(device)
  109. """
  110. if isinstance(obj, torch.Tensor):
  111. return obj.to(device, non_blocking=non_blocking)
  112. elif isinstance(obj, tuple):
  113. return tuple(tensor_container_to_device(x, device, non_blocking=non_blocking) for x in obj)
  114. elif isinstance(obj, list):
  115. return [tensor_container_to_device(x, device, non_blocking=non_blocking) for x in obj]
  116. elif isinstance(obj, dict):
  117. return {k: tensor_container_to_device(v, device, non_blocking=non_blocking) for k, v in obj.items()}
  118. else:
  119. return obj
  120. def get_param(params, name, default_val=None):
  121. """
  122. Retrieves a param from a parameter object/dict. If the parameter does not exist, will return default_val.
  123. In case the default_val is of type dictionary, and a value is found in the params - the function
  124. will return the default value dictionary with internal values overridden by the found value
  125. i.e.
  126. default_opt_params = {'lr':0.1, 'momentum':0.99, 'alpha':0.001}
  127. training_params = {'optimizer_params': {'lr':0.0001}, 'batch': 32 .... }
  128. get_param(training_params, name='optimizer_params', default_val=default_opt_params)
  129. will return {'lr':0.0001, 'momentum':0.99, 'alpha':0.001}
  130. :param params: an object (typically HpmStruct) or a dict holding the params
  131. :param name: name of the searched parameter
  132. :param default_val: assumed to be the same type as the value searched in the params
  133. :return: the found value, or default if not found
  134. """
  135. if isinstance(params, dict):
  136. if name in params:
  137. if isinstance(default_val, dict):
  138. return {**default_val, **params[name]}
  139. else:
  140. return params[name]
  141. else:
  142. return default_val
  143. elif hasattr(params, name):
  144. if isinstance(default_val, dict):
  145. return {**default_val, **getattr(params, name)}
  146. else:
  147. return getattr(params, name)
  148. else:
  149. return default_val
  150. def static_vars(**kwargs):
  151. def decorate(func):
  152. for k in kwargs:
  153. setattr(func, k, kwargs[k])
  154. return func
  155. return decorate
  156. @static_vars(printed=set())
  157. def print_once(s: str):
  158. if s not in print_once.printed:
  159. print_once.printed.add(s)
  160. print(s)
  161. def move_state_dict_to_device(model_sd, device):
  162. """
  163. Moving model state dict tensors to target device (cuda or cpu)
  164. :param model_sd: model state dict
  165. :param device: either cuda or cpu
  166. """
  167. for k, v in model_sd.items():
  168. model_sd[k] = v.to(device)
  169. return model_sd
  170. def random_seed(is_ddp, device, seed):
  171. """
  172. Sets random seed of numpy, torch and random.
  173. When using ddp a seed will be set for each process according to its local rank derived from the device number.
  174. :param is_ddp: bool, will set different random seed for each process when using ddp.
  175. :param device: 'cuda','cpu', 'cuda:<device_number>'
  176. :param seed: int, random seed to be set
  177. """
  178. rank = 0 if not is_ddp else int(device.split(':')[1])
  179. torch.manual_seed(seed + rank)
  180. np.random.seed(seed + rank)
  181. random.seed(seed + rank)
  182. def load_func(dotpath: str):
  183. """
  184. load function in module. function is right-most segment.
  185. Used for passing functions (without calling them) in yaml files.
  186. @param dotpath: path to module.
  187. @return: a python function
  188. """
  189. module_, func = dotpath.rsplit(".", maxsplit=1)
  190. m = import_module(module_)
  191. return getattr(m, func)
  192. def get_filename_suffix_by_framework(framework: str):
  193. """
  194. Return the file extension of framework.
  195. @param framework: (str)
  196. @return: (str) the suffix for the specific framework
  197. """
  198. frameworks_dict = \
  199. {
  200. 'TENSORFLOW1': '.pb',
  201. 'TENSORFLOW2': '.zip',
  202. 'PYTORCH': '.pth',
  203. 'ONNX': '.onnx',
  204. 'TENSORRT': '.pkl',
  205. 'OPENVINO': '.pkl',
  206. 'TORCHSCRIPT': '.pth',
  207. 'TVM': '',
  208. 'KERAS': '.h5',
  209. 'TFLITE': '.tflite'
  210. }
  211. if framework.upper() not in frameworks_dict.keys():
  212. raise ValueError(f'Unsupported framework: {framework}')
  213. return frameworks_dict[framework.upper()]
  214. def check_models_have_same_weights(model_1: torch.nn.Module, model_2: torch.nn.Module):
  215. """
  216. Checks whether two networks have the same weights
  217. @param model_1: Net to be checked
  218. @param model_2: Net to be checked
  219. @return: True iff the two networks have the same weights
  220. """
  221. model_1, model_2 = model_1.to('cpu'), model_2.to('cpu')
  222. models_differ = 0
  223. for key_item_1, key_item_2 in zip(model_1.state_dict().items(), model_2.state_dict().items()):
  224. if torch.equal(key_item_1[1], key_item_2[1]):
  225. pass
  226. else:
  227. models_differ += 1
  228. if (key_item_1[0] == key_item_2[0]):
  229. print(f'Layer names match but layers have different weights for layers: {key_item_1[0]}')
  230. if models_differ == 0:
  231. return True
  232. else:
  233. return False
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...