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

#609 Ci fix

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:bugfix/infra-000_ci
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
  1. import math
  2. import time
  3. from functools import lru_cache
  4. from pathlib import Path
  5. from typing import Mapping, Optional, Tuple, Union, List, Dict, Any
  6. from zipfile import ZipFile
  7. import os
  8. from jsonschema import validate
  9. import tarfile
  10. from PIL import Image, ExifTags
  11. import re
  12. import torch
  13. import torch.nn as nn
  14. # These functions changed from torch 1.2 to torch 1.3
  15. import random
  16. import numpy as np
  17. from importlib import import_module
  18. from super_gradients.common.abstractions.abstract_logger import get_logger
  19. logger = get_logger(__name__)
  20. def empty_list():
  21. """Instantiate an empty list. This is a workaround to generate a list with a function call in hydra, instead of the "[]"."""
  22. return list()
  23. def convert_to_tensor(array):
  24. """Converts numpy arrays and lists to Torch tensors before calculation losses
  25. :param array: torch.tensor / Numpy array / List
  26. """
  27. return torch.FloatTensor(array) if type(array) != torch.Tensor else array
  28. class HpmStruct:
  29. def __init__(self, **entries):
  30. self.__dict__.update(entries)
  31. self.schema = None
  32. def set_schema(self, schema: dict):
  33. self.schema = schema
  34. def override(self, **entries):
  35. recursive_override(self.__dict__, entries)
  36. def to_dict(self, include_schema=True) -> dict:
  37. """Convert this HpmStruct instance into a dict.
  38. :param include_schema: If True, also return the field "schema"
  39. :return: Dict representation of this HpmStruct instance.
  40. """
  41. out_dict = self.__dict__.copy()
  42. if not include_schema:
  43. out_dict.pop("schema")
  44. return out_dict
  45. def validate(self):
  46. """
  47. Validate the current dict values according to the provided schema
  48. :raises
  49. `AttributeError` if schema was not set
  50. `jsonschema.exceptions.ValidationError` if the instance is invalid
  51. `jsonschema.exceptions.SchemaError` if the schema itselfis invalid
  52. """
  53. if self.schema is None:
  54. raise AttributeError("schema was not set")
  55. else:
  56. validate(self.__dict__, self.schema)
  57. class WrappedModel(nn.Module):
  58. def __init__(self, module):
  59. super(WrappedModel, self).__init__()
  60. self.module = module # that I actually define.
  61. def forward(self, x):
  62. return self.module(x)
  63. class Timer:
  64. """A class to measure time handling both GPU & CPU processes
  65. Returns time in milliseconds"""
  66. def __init__(self, device: str):
  67. """
  68. :param device: str
  69. 'cpu'\'cuda'
  70. """
  71. self.on_gpu = device == "cuda"
  72. # On GPU time is measured using cuda.events
  73. if self.on_gpu:
  74. self.starter = torch.cuda.Event(enable_timing=True)
  75. self.ender = torch.cuda.Event(enable_timing=True)
  76. # On CPU time is measured using time
  77. else:
  78. self.starter, self.ender = 0, 0
  79. def start(self):
  80. if self.on_gpu:
  81. self.starter.record()
  82. else:
  83. self.starter = time.time()
  84. def stop(self):
  85. if self.on_gpu:
  86. self.ender.record()
  87. torch.cuda.synchronize()
  88. timer = self.starter.elapsed_time(self.ender)
  89. else:
  90. # Time measures in seconds -> convert to milliseconds
  91. timer = (time.time() - self.starter) * 1000
  92. # Return time in milliseconds
  93. return timer
  94. class AverageMeter:
  95. """A class to calculate the average of a metric, for each batch
  96. during training/testing"""
  97. def __init__(self):
  98. self._sum = None
  99. self._count = 0
  100. def update(self, value: Union[float, tuple, list, torch.Tensor], batch_size: int):
  101. if not isinstance(value, torch.Tensor):
  102. value = torch.tensor(value)
  103. if self._sum is None:
  104. self._sum = value * batch_size
  105. else:
  106. self._sum += value * batch_size
  107. self._count += batch_size
  108. @property
  109. def average(self):
  110. if self._sum is None:
  111. return 0
  112. return ((self._sum / self._count).__float__()) if self._sum.dim() < 1 else tuple((self._sum / self._count).cpu().numpy())
  113. # return (self._sum / self._count).__float__() if self._sum.dim() < 1 or len(self._sum) == 1 \
  114. # else tuple((self._sum / self._count).cpu().numpy())
  115. def tensor_container_to_device(obj: Union[torch.Tensor, tuple, list, dict], device: str, non_blocking=True):
  116. """
  117. recursively send compounded objects to device (sending all tensors to device and maintaining structure)
  118. :param obj the object to send to device (list / tuple / tensor / dict)
  119. :param device: device to send the tensors to
  120. :param non_blocking: used for DistributedDataParallel
  121. :returns an object with the same structure (tensors, lists, tuples) with the device pointers (like
  122. the return value of Tensor.to(device)
  123. """
  124. if isinstance(obj, torch.Tensor):
  125. return obj.to(device, non_blocking=non_blocking)
  126. elif isinstance(obj, tuple):
  127. return tuple(tensor_container_to_device(x, device, non_blocking=non_blocking) for x in obj)
  128. elif isinstance(obj, list):
  129. return [tensor_container_to_device(x, device, non_blocking=non_blocking) for x in obj]
  130. elif isinstance(obj, dict):
  131. return {k: tensor_container_to_device(v, device, non_blocking=non_blocking) for k, v in obj.items()}
  132. else:
  133. return obj
  134. def fuzzy_keys(params: Mapping) -> List[str]:
  135. """
  136. Returns params.key() removing leading and trailing white space, lower-casing and dropping symbols.
  137. :param params: Mapping, the mapping containing the keys to be returned.
  138. :return: List[str], list of keys as discussed above.
  139. """
  140. return [fuzzy_str(s) for s in params.keys()]
  141. def fuzzy_str(s: str):
  142. """
  143. Returns s removing leading and trailing white space, lower-casing and drops
  144. :param s: str, string to apply the manipulation discussed above.
  145. :return: str, s after the manipulation discussed above.
  146. """
  147. return re.sub(r"[^\w]", "", s).replace("_", "").lower()
  148. def _get_fuzzy_attr_map(params):
  149. return {fuzzy_str(a): a for a in params.__dir__()}
  150. def _has_fuzzy_attr(params, name):
  151. return fuzzy_str(name) in _get_fuzzy_attr_map(params)
  152. def get_fuzzy_mapping_param(name: str, params: Mapping):
  153. """
  154. Returns parameter value, with key=name with no sensitivity to lowercase, uppercase and symbols.
  155. :param name: str, the key in params which is fuzzy-matched and retruned.
  156. :param params: Mapping, the mapping containing param.
  157. :return:
  158. """
  159. fuzzy_params = {fuzzy_str(key): params[key] for key in params.keys()}
  160. return fuzzy_params[fuzzy_str(name)]
  161. def get_fuzzy_attr(params: Any, name: str):
  162. """
  163. Returns attribute (same functionality as getattr), but non sensitive to symbols, uppercase and lowercase.
  164. :param params: Any, any object which wed looking for the attribute name in.
  165. :param name: str, the attribute of param to be returned.
  166. :return: Any, the attribute value or None when not fuzzy matching of the attribute is found
  167. """
  168. return getattr(params, _get_fuzzy_attr_map(params)[fuzzy_str(name)])
  169. def fuzzy_idx_in_list(name: str, lst: List[str]) -> int:
  170. """
  171. Returns the index of name in lst, with non sensitivity to symbols, uppercase and lowercase.
  172. :param name: str, the name to be searched in lst.
  173. :param lst: List[str], the list as described above.
  174. :return: int, index of name in lst in the matter discussed above.
  175. """
  176. return [fuzzy_str(x) for x in lst].index(fuzzy_str(name))
  177. def get_param(params, name, default_val=None):
  178. """
  179. Retrieves a param from a parameter object/dict . If the parameter does not exist, will return default_val.
  180. In case the default_val is of type dictionary, and a value is found in the params - the function
  181. will return the default value dictionary with internal values overridden by the found value
  182. IMPORTANT: Not sensitive to lowercase, uppercase and symbols.
  183. i.e.
  184. default_opt_params = {'lr':0.1, 'momentum':0.99, 'alpha':0.001}
  185. training_params = {'optimizer_params': {'lr':0.0001}, 'batch': 32 .... }
  186. get_param(training_params, name='OptimizerParams', default_val=default_opt_params)
  187. will return {'lr':0.0001, 'momentum':0.99, 'alpha':0.001}
  188. :param params: an object (typically HpmStruct) or a dict holding the params
  189. :param name: name of the searched parameter
  190. :param default_val: assumed to be the same type as the value searched in the params
  191. :return: the found value, or default if not found
  192. """
  193. if isinstance(params, Mapping):
  194. if name in params:
  195. param_val = params[name]
  196. elif fuzzy_str(name) in fuzzy_keys(params):
  197. param_val = get_fuzzy_mapping_param(name, params)
  198. else:
  199. param_val = default_val
  200. elif hasattr(params, name):
  201. param_val = getattr(params, name)
  202. elif _has_fuzzy_attr(params, name):
  203. param_val = get_fuzzy_attr(params, name)
  204. else:
  205. param_val = default_val
  206. if isinstance(default_val, Mapping):
  207. return {**default_val, **param_val}
  208. else:
  209. return param_val
  210. def static_vars(**kwargs):
  211. def decorate(func):
  212. for k in kwargs:
  213. setattr(func, k, kwargs[k])
  214. return func
  215. return decorate
  216. @static_vars(printed=set())
  217. def print_once(s: str):
  218. if s not in print_once.printed:
  219. print_once.printed.add(s)
  220. print(s)
  221. def move_state_dict_to_device(model_sd, device):
  222. """
  223. Moving model state dict tensors to target device (cuda or cpu)
  224. :param model_sd: model state dict
  225. :param device: either cuda or cpu
  226. """
  227. for k, v in model_sd.items():
  228. model_sd[k] = v.to(device)
  229. return model_sd
  230. def random_seed(is_ddp, device, seed):
  231. """
  232. Sets random seed of numpy, torch and random.
  233. When using ddp a seed will be set for each process according to its local rank derived from the device number.
  234. :param is_ddp: bool, will set different random seed for each process when using ddp.
  235. :param device: 'cuda','cpu', 'cuda:<device_number>'
  236. :param seed: int, random seed to be set
  237. """
  238. rank = 0 if not is_ddp else int(device.split(":")[1])
  239. torch.manual_seed(seed + rank)
  240. np.random.seed(seed + rank)
  241. random.seed(seed + rank)
  242. def load_func(dotpath: str):
  243. """
  244. load function in module. function is right-most segment.
  245. Used for passing functions (without calling them) in yaml files.
  246. @param dotpath: path to module.
  247. @return: a python function
  248. """
  249. module_, func = dotpath.rsplit(".", maxsplit=1)
  250. m = import_module(module_)
  251. return getattr(m, func)
  252. def get_filename_suffix_by_framework(framework: str):
  253. """
  254. Return the file extension of framework.
  255. @param framework: (str)
  256. @return: (str) the suffix for the specific framework
  257. """
  258. frameworks_dict = {
  259. "TENSORFLOW1": ".pb",
  260. "TENSORFLOW2": ".zip",
  261. "PYTORCH": ".pth",
  262. "ONNX": ".onnx",
  263. "TENSORRT": ".pkl",
  264. "OPENVINO": ".pkl",
  265. "TORCHSCRIPT": ".pth",
  266. "TVM": "",
  267. "KERAS": ".h5",
  268. "TFLITE": ".tflite",
  269. }
  270. if framework.upper() not in frameworks_dict.keys():
  271. raise ValueError(f"Unsupported framework: {framework}")
  272. return frameworks_dict[framework.upper()]
  273. def check_models_have_same_weights(model_1: torch.nn.Module, model_2: torch.nn.Module):
  274. """
  275. Checks whether two networks have the same weights
  276. @param model_1: Net to be checked
  277. @param model_2: Net to be checked
  278. @return: True iff the two networks have the same weights
  279. """
  280. model_1, model_2 = model_1.to("cpu"), model_2.to("cpu")
  281. models_differ = 0
  282. for key_item_1, key_item_2 in zip(model_1.state_dict().items(), model_2.state_dict().items()):
  283. if torch.equal(key_item_1[1], key_item_2[1]):
  284. pass
  285. else:
  286. models_differ += 1
  287. if key_item_1[0] == key_item_2[0]:
  288. print(f"Layer names match but layers have different weights for layers: {key_item_1[0]}")
  289. if models_differ == 0:
  290. return True
  291. else:
  292. return False
  293. def recursive_override(base: dict, extension: dict):
  294. for k, v in extension.items():
  295. if k in base:
  296. if isinstance(v, Mapping):
  297. recursive_override(base[k], extension[k])
  298. else:
  299. base[k] = extension[k]
  300. else:
  301. base[k] = extension[k]
  302. def download_and_unzip_from_url(url, dir=".", unzip=True, delete=True):
  303. """
  304. Downloads a zip file from url to dir, and unzips it.
  305. :param url: Url to download the file from.
  306. :param dir: Destination directory.
  307. :param unzip: Whether to unzip the downloaded file.
  308. :param delete: Whether to delete the zip file.
  309. used to downlaod VOC.
  310. Source:
  311. https://github.com/ultralytics/yolov5/blob/master/data/VOC.yaml
  312. """
  313. def download_one(url, dir):
  314. # Download 1 file
  315. f = dir / Path(url).name # filename
  316. if Path(url).is_file(): # exists in current path
  317. Path(url).rename(f) # move to dir
  318. elif not f.exists():
  319. print(f"Downloading {url} to {f}...")
  320. torch.hub.download_url_to_file(url, f, progress=True) # torch download
  321. if unzip and f.suffix in (".zip", ".gz"):
  322. print(f"Unzipping {f}...")
  323. if f.suffix == ".zip":
  324. ZipFile(f).extractall(path=dir) # unzip
  325. elif f.suffix == ".gz":
  326. os.system(f"tar xfz {f} --directory {f.parent}") # unzip
  327. if delete:
  328. f.unlink() # remove zip
  329. dir = Path(dir)
  330. dir.mkdir(parents=True, exist_ok=True) # make directory
  331. for u in [url] if isinstance(url, (str, Path)) else url:
  332. download_one(u, dir)
  333. def download_and_untar_from_url(urls: List[str], dir: Union[str, Path] = "."):
  334. """
  335. Download a file from url and untar.
  336. :param urls: Url to download the file from.
  337. :param dir: Destination directory.
  338. """
  339. dir = Path(dir)
  340. dir.mkdir(parents=True, exist_ok=True)
  341. for url in urls:
  342. url_path = Path(url)
  343. filepath = dir / url_path.name
  344. if url_path.is_file():
  345. url_path.rename(filepath)
  346. elif not filepath.exists():
  347. logger.info(f"Downloading {url} to {filepath}...")
  348. torch.hub.download_url_to_file(url, str(filepath), progress=True)
  349. modes = {".tar.gz": "r:gz", ".tar": "r:"}
  350. assert filepath.suffix in modes.keys(), f"{filepath} has {filepath.suffix} suffix which is not supported"
  351. logger.info(f"Extracting to {dir}...")
  352. with tarfile.open(filepath, mode=modes[filepath.suffix]) as f:
  353. f.extractall(dir)
  354. filepath.unlink()
  355. def make_divisible(x: int, divisor: int, ceil: bool = True) -> int:
  356. """
  357. Returns x evenly divisible by divisor.
  358. If ceil=True it will return the closest larger number to the original x, and ceil=False the closest smaller number.
  359. """
  360. if ceil:
  361. return math.ceil(x / divisor) * divisor
  362. else:
  363. return math.floor(x / divisor) * divisor
  364. def check_img_size_divisibility(img_size: int, stride: int = 32) -> Tuple[bool, Optional[Tuple[int, int]]]:
  365. """
  366. :param img_size: Int, the size of the image (H or W).
  367. :param stride: Int, the number to check if img_size is divisible by.
  368. :return: (True, None) if img_size is divisble by stride, (False, Suggestions) if it's not.
  369. Note: Suggestions are the two closest numbers to img_size that *are* divisible by stride.
  370. For example if img_size=321, stride=32, it will return (False,(352, 320)).
  371. """
  372. new_size = make_divisible(img_size, int(stride))
  373. if new_size != img_size:
  374. return False, (new_size, make_divisible(img_size, int(stride), ceil=False))
  375. else:
  376. return True, None
  377. @lru_cache(None)
  378. def get_orientation_key() -> int:
  379. """Get the orientation key according to PIL, which is useful to get the image size for instance
  380. :return: Orientation key according to PIL"""
  381. for key, value in ExifTags.TAGS.items():
  382. if value == "Orientation":
  383. return key
  384. def exif_size(image: Image) -> Tuple[int, int]:
  385. """Get the size of image.
  386. :param image: The image to get size from
  387. :return: (height, width)
  388. """
  389. orientation_key = get_orientation_key()
  390. image_size = image.size
  391. try:
  392. exif_data = image._getexif()
  393. if exif_data is not None:
  394. rotation = dict(exif_data.items())[orientation_key]
  395. # ROTATION 270
  396. if rotation == 6:
  397. image_size = (image_size[1], image_size[0])
  398. # ROTATION 90
  399. elif rotation == 8:
  400. image_size = (image_size[1], image_size[0])
  401. except Exception as ex:
  402. print("Caught Exception trying to rotate: " + str(image) + str(ex))
  403. width, height = image_size
  404. return height, width
  405. def get_image_size_from_path(img_path: str) -> Tuple[int, int]:
  406. """Get the image size of an image at a specific path"""
  407. with open(img_path, "rb") as f:
  408. return exif_size(Image.open(f))
  409. def override_default_params_without_nones(params: Dict, default_params: Dict) -> Dict:
  410. """
  411. Helper method for overriding default dictionary's entries excluding entries with None values.
  412. :param params: dict, output dictionary which will take the defaults.
  413. :param default_params: dict, dictionary for the defaults.
  414. :return: dict, params after manipulation,
  415. """
  416. for key, val in default_params.items():
  417. if key not in params.keys() or params[key] is None:
  418. params[key] = val
  419. return params
Discard
Tip!

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