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

#364 build_model refs replaced

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:hotfix/SG-000_remove_build_model
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
  1. import copy
  2. import os
  3. from abc import ABC, abstractmethod
  4. from multiprocessing import Value, Lock
  5. import random
  6. from typing import List
  7. import numpy as np
  8. import torch.nn.functional as F
  9. import torchvision
  10. from PIL import Image
  11. import torch
  12. import torch.distributed as dist
  13. from super_gradients.common.sg_loggers.abstract_sg_logger import AbstractSGLogger
  14. from super_gradients.common.abstractions.abstract_logger import get_logger
  15. from deprecate import deprecated
  16. from matplotlib.patches import Rectangle
  17. from torchvision.datasets import ImageFolder
  18. from super_gradients.training.datasets.auto_augment import rand_augment_transform
  19. from torchvision.transforms import transforms, InterpolationMode, RandomResizedCrop
  20. from tqdm import tqdm
  21. from super_gradients.training.utils.utils import AverageMeter
  22. from super_gradients.training.utils.detection_utils import DetectionVisualization, Anchors
  23. import uuid
  24. from super_gradients.training.utils.distributed_training_utils import get_local_rank, get_world_size
  25. import matplotlib.pyplot as plt
  26. def get_mean_and_std_torch(data_dir=None, dataloader=None, num_workers=4, RandomResizeSize=224):
  27. """
  28. A function for getting the mean and std of large datasets using pytorch dataloader and gpu functionality.
  29. :param data_dir: String, path to none-library dataset folder. For example "/data/Imagenette" or "/data/TinyImagenet"
  30. :param dataloader: a torch DataLoader, as it would feed the data into the trainer (including transforms etc).
  31. :param RandomResizeSize: Int, the size of the RandomResizeCrop as it appears in the DataInterface (for example, for Imagenet,
  32. this value should be 224).
  33. :return: 2 lists,mean and std, each one of len 3 (1 for each channel)
  34. """
  35. assert data_dir is None or dataloader is None, 'Please provide either path to data folder or DataLoader, not both.'
  36. if dataloader is None:
  37. traindir = os.path.join(os.path.abspath(data_dir), 'train')
  38. trainset = ImageFolder(traindir, transforms.Compose([transforms.RandomResizedCrop(RandomResizeSize),
  39. transforms.RandomHorizontalFlip(),
  40. transforms.ToTensor()]))
  41. dataloader = torch.utils.data.DataLoader(trainset, batch_size=1, num_workers=num_workers)
  42. print(f'Calculating on {len(dataloader.dataset.targets)} Training Samples')
  43. device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
  44. h, w = 0, 0
  45. for batch_idx, (inputs, targets) in enumerate(dataloader):
  46. inputs = inputs.to(device)
  47. if batch_idx == 0:
  48. h, w = inputs.size(2), inputs.size(3)
  49. print(f'Min: {inputs.min()}, Max: {inputs.max()}')
  50. chsum = inputs.sum(dim=(0, 2, 3), keepdim=True)
  51. else:
  52. chsum += inputs.sum(dim=(0, 2, 3), keepdim=True)
  53. mean = chsum / len(trainset) / h / w
  54. print(f'mean: {mean.view(-1)}')
  55. chsum = None
  56. for batch_idx, (inputs, targets) in enumerate(dataloader):
  57. inputs = inputs.to(device)
  58. if batch_idx == 0:
  59. chsum = (inputs - mean).pow(2).sum(dim=(0, 2, 3), keepdim=True)
  60. else:
  61. chsum += (inputs - mean).pow(2).sum(dim=(0, 2, 3), keepdim=True)
  62. std = torch.sqrt(chsum / (len(trainset) * h * w - 1))
  63. print(f'std: {std.view(-1)}')
  64. return mean.view(-1).cpu().numpy().tolist(), std.view(-1).cpu().numpy().tolist()
  65. @deprecated(target=get_mean_and_std_torch, deprecated_in="2.1.0", remove_in="3.0.0")
  66. def get_mean_and_std(dataset):
  67. '''Compute the mean and std value of dataset.'''
  68. dataloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True, num_workers=1)
  69. mean = torch.zeros(3)
  70. std = torch.zeros(3)
  71. print('==> Computing mean and std..')
  72. j = 0
  73. for inputs, targets in dataloader:
  74. if j % 10 == 0:
  75. print(j)
  76. j += 1
  77. for i in range(3):
  78. mean[i] += inputs[:, i, :, :].mean()
  79. std[i] += inputs[:, i, :, :].std()
  80. mean.div_(len(dataset))
  81. std.div_(len(dataset))
  82. return mean, std
  83. class AbstractCollateFunction(ABC):
  84. """
  85. A collate function (for torch DataLoader)
  86. """
  87. @abstractmethod
  88. def __call__(self, batch):
  89. pass
  90. class ComposedCollateFunction(AbstractCollateFunction):
  91. """
  92. A function (for torch DataLoader) which executes a sequence of sub collate functions
  93. """
  94. def __init__(self, functions: list):
  95. self.functions = functions
  96. def __call__(self, batch):
  97. for f in self.functions:
  98. batch = f(batch)
  99. return batch
  100. class AtomicInteger:
  101. def __init__(self, value: int = 0):
  102. self._value = Value('i', value)
  103. def __set__(self, instance, value):
  104. self._value.value = value
  105. def __get__(self, instance, owner):
  106. return self._value.value
  107. class MultiScaleCollateFunction(AbstractCollateFunction):
  108. """
  109. a collate function to implement multi-scale data augmentation
  110. according to https://arxiv.org/pdf/1612.08242.pdf
  111. """
  112. _counter = AtomicInteger(0)
  113. _current_size = AtomicInteger(0)
  114. _lock = Lock()
  115. def __init__(self, target_size: int = None, min_image_size: int = None, max_image_size: int = None,
  116. image_size_steps: int = 32,
  117. change_frequency: int = 10):
  118. """
  119. set parameters for the multi-scale collate function
  120. the possible image sizes are in range [min_image_size, max_image_size] in steps of image_size_steps
  121. a new size will be randomly selected every change_frequency calls to the collate_fn()
  122. :param target_size: scales will be [0.66 * target_size, 1.5 * target_size]
  123. :param min_image_size: the minimum size to scale down to (in pixels)
  124. :param max_image_size: the maximum size to scale up to (in pixels)
  125. :param image_size_steps: typically, the stride of the net, which defines the possible image
  126. size multiplications
  127. :param change_frequency:
  128. """
  129. assert target_size is not None or (max_image_size is not None and min_image_size is not None), \
  130. 'either target_size or min_image_size and max_image_size has to be set'
  131. assert target_size is None or max_image_size is None, 'target_size and max_image_size cannot be both defined'
  132. if target_size is not None:
  133. min_image_size = int(0.66 * target_size - ((0.66 * target_size) % image_size_steps) + image_size_steps)
  134. max_image_size = int(1.5 * target_size - ((1.5 * target_size) % image_size_steps))
  135. print('Using multi-scale %g - %g' % (min_image_size, max_image_size))
  136. self.sizes = np.arange(min_image_size, max_image_size + image_size_steps, image_size_steps)
  137. self.image_size_steps = image_size_steps
  138. self.frequency = change_frequency
  139. self._current_size = random.choice(self.sizes)
  140. def __call__(self, batch):
  141. with self._lock:
  142. # Important: this implementation was tailored for a specific input. it assumes the batch is a tuple where
  143. # the images are the first item
  144. assert isinstance(batch, tuple), 'this collate function expects the input to be a tuple (images, labels)'
  145. images = batch[0]
  146. if self._counter % self.frequency == 0:
  147. self._current_size = random.choice(self.sizes)
  148. self._counter += 1
  149. assert images.shape[2] % self.image_size_steps == 0 and images.shape[3] % self.image_size_steps == 0, \
  150. 'images sized not divisible by %d. (resize images before calling multi_scale)' % self.image_size_steps
  151. if self._current_size != max(images.shape[2:]):
  152. ratio = float(self._current_size) / max(images.shape[2:])
  153. new_size = (int(round(images.shape[2] * ratio)), int(round(images.shape[3] * ratio)))
  154. images = F.interpolate(images, size=new_size, mode='bilinear', align_corners=False)
  155. return images, batch[1]
  156. class AbstractPrePredictionCallback(ABC):
  157. """
  158. Abstract class for forward pass preprocessing function, to be used by passing its inheritors through training_params
  159. pre_prediction_callback keyword arg.
  160. Should implement __call__ and return images, targets after applying the desired preprocessing.
  161. """
  162. @abstractmethod
  163. def __call__(self, inputs, targets, batch_idx):
  164. pass
  165. class MultiscalePrePredictionCallback(AbstractPrePredictionCallback):
  166. """
  167. Mutiscale pre-prediction callback pass function.
  168. When passed through train_params images, targets will be applied by the below transform to support multi scaling
  169. on the fly.
  170. After each self.frequency forward passes, change size randomly from
  171. (input_size-self.multiscale_range*self.image_size_steps, input_size-(self.multiscale_range-1)*self.image_size_steps,
  172. ...input_size+self.multiscale_range*self.image_size_steps)
  173. Attributes:
  174. multiscale_range: (int) Range of values for resize sizes as discussed above (default=5)
  175. image_size_steps: (int) Image step sizes as discussed abov (default=32)
  176. change_frequency: (int) The frequency to apply change in input size.
  177. """
  178. def __init__(self, multiscale_range: int = 5,
  179. image_size_steps: int = 32,
  180. change_frequency: int = 10):
  181. self.multiscale_range = multiscale_range
  182. self.image_size_steps = image_size_steps
  183. self.frequency = change_frequency
  184. self.rank = None
  185. self.is_distributed = None
  186. self.sampled_imres_once = False
  187. self.new_input_size = None
  188. def __call__(self, inputs, targets, batch_idx):
  189. if self.rank is None:
  190. self.rank = get_local_rank()
  191. if self.is_distributed is None:
  192. self.is_distributed = get_world_size() > 1
  193. # GENERATE A NEW SIZE AND BROADCAST IT TO THE THE OTHER RANKS SO THEY HAVE THE SAME SCALE
  194. input_size = inputs.shape[2:]
  195. if batch_idx % self.frequency == 0:
  196. tensor = torch.LongTensor(2).to(inputs.device)
  197. if self.rank == 0:
  198. size_factor = input_size[1] * 1.0 / input_size[0]
  199. min_size = int(input_size[0] / self.image_size_steps) - self.multiscale_range
  200. max_size = int(input_size[0] / self.image_size_steps) + self.multiscale_range
  201. random_size = (min_size, max_size)
  202. if self.sampled_imres_once:
  203. size = random.randint(*random_size)
  204. else:
  205. # sample the biggest resolution first to make sure the run fits into the GPU memory
  206. size = max_size
  207. self.sampled_imres_once = True
  208. size = (int(self.image_size_steps * size), self.image_size_steps * int(size * size_factor))
  209. tensor[0] = size[0]
  210. tensor[1] = size[1]
  211. if self.is_distributed:
  212. dist.barrier()
  213. dist.broadcast(tensor, 0)
  214. self.new_input_size = (tensor[0].item(), tensor[1].item())
  215. scale_y = self.new_input_size[0] / input_size[0]
  216. scale_x = self.new_input_size[1] / input_size[1]
  217. if scale_x != 1 or scale_y != 1:
  218. inputs = torch.nn.functional.interpolate(inputs, size=self.new_input_size, mode="bilinear", align_corners=False)
  219. return inputs, targets
  220. class DetectionMultiscalePrePredictionCallback(MultiscalePrePredictionCallback):
  221. """
  222. Mutiscalepre-prediction callback for object detection.
  223. When passed through train_params images, targets will be applied by the below transform to support multi scaling
  224. on the fly.
  225. After each self.frequency forward passes, change size randomly from
  226. (input_size-self.multiscale_range*self.image_size_steps, input_size-(self.multiscale_range-1)*self.image_size_steps,
  227. ...input_size+self.multiscale_range*self.image_size_steps) and apply the same rescaling to the box coordinates.
  228. Attributes:
  229. multiscale_range: (int) Range of values for resize sizes as discussed above (default=5)
  230. image_size_steps: (int) Image step sizes as discussed abov (default=32)
  231. change_frequency: (int) The frequency to apply change in input size.
  232. """
  233. def __call__(self, inputs, targets, batch_idx):
  234. # RESCALE THE IMAGE FIRST WITH SUPER(), AND IF RESCALING HAS ACTUALLY BEEN DONE APPLY TO BOXES AS WELL
  235. input_size = inputs.shape[2:]
  236. inputs, targets = super(DetectionMultiscalePrePredictionCallback, self).__call__(inputs, targets, batch_idx)
  237. new_input_size = inputs.shape[2:]
  238. scale_y = new_input_size[0] / input_size[0]
  239. scale_x = new_input_size[1] / input_size[1]
  240. if scale_x != 1 or scale_y != 1:
  241. targets[..., 2::2] = targets[..., 2::2] * scale_x
  242. targets[..., 3::2] = targets[..., 3::2] * scale_y
  243. return inputs, targets
  244. _pil_interpolation_to_str = {
  245. Image.NEAREST: 'PIL.Image.NEAREST',
  246. Image.BILINEAR: 'PIL.Image.BILINEAR',
  247. Image.BICUBIC: 'PIL.Image.BICUBIC',
  248. Image.LANCZOS: 'PIL.Image.LANCZOS',
  249. Image.HAMMING: 'PIL.Image.HAMMING',
  250. Image.BOX: 'PIL.Image.BOX',
  251. }
  252. def _pil_interp(method):
  253. if method == 'bicubic':
  254. return InterpolationMode.BICUBIC
  255. elif method == 'lanczos':
  256. return InterpolationMode.LANCZOS
  257. elif method == 'hamming':
  258. return InterpolationMode.HAMMING
  259. elif method == 'nearest':
  260. return InterpolationMode.NEAREST
  261. elif method == 'bilinear':
  262. return InterpolationMode.BILINEAR
  263. elif method == 'box':
  264. return InterpolationMode.BOX
  265. else:
  266. raise ValueError("interpolation type must be one of ['bilinear', 'bicubic', 'lanczos', 'hamming', "
  267. "'nearest', 'box'] for explicit interpolation type, or 'random' for random")
  268. _RANDOM_INTERPOLATION = (InterpolationMode.BILINEAR, InterpolationMode.BICUBIC)
  269. class RandomResizedCropAndInterpolation(RandomResizedCrop):
  270. """
  271. Crop the given PIL Image to random size and aspect ratio with explicitly chosen or random interpolation.
  272. A crop of random size (default: of 0.08 to 1.0) of the original size and a random
  273. aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop
  274. is finally resized to given size.
  275. This is popularly used to train the Inception networks.
  276. Args:
  277. size: expected output size of each edge
  278. scale: range of size of the origin size cropped
  279. ratio: range of aspect ratio of the origin aspect ratio cropped
  280. interpolation: Default: PIL.Image.BILINEAR
  281. """
  282. def __init__(self, size, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.),
  283. interpolation='default'):
  284. super(RandomResizedCropAndInterpolation, self).__init__(size=size, scale=scale, ratio=ratio, interpolation=interpolation)
  285. if interpolation == 'random':
  286. self.interpolation = _RANDOM_INTERPOLATION
  287. elif interpolation == 'default':
  288. self.interpolation = InterpolationMode.BILINEAR
  289. else:
  290. self.interpolation = _pil_interp(interpolation)
  291. def forward(self, img):
  292. """
  293. Args:
  294. img (PIL Image): Image to be cropped and resized.
  295. Returns:
  296. PIL Image: Randomly cropped and resized image.
  297. """
  298. i, j, h, w = self.get_params(img, self.scale, self.ratio)
  299. if isinstance(self.interpolation, (tuple, list)):
  300. interpolation = random.choice(self.interpolation)
  301. else:
  302. interpolation = self.interpolation
  303. return torchvision.transforms.functional.resized_crop(img, i, j, h, w, self.size, interpolation)
  304. def __repr__(self):
  305. if isinstance(self.interpolation, (tuple, list)):
  306. interpolate_str = ' '.join([_pil_interpolation_to_str[x] for x in self.interpolation])
  307. else:
  308. interpolate_str = _pil_interpolation_to_str[self.interpolation]
  309. format_string = self.__class__.__name__ + '(size={0}'.format(self.size)
  310. format_string += ', scale={0}'.format(tuple(round(s, 4) for s in self.scale))
  311. format_string += ', ratio={0}'.format(tuple(round(r, 4) for r in self.ratio))
  312. format_string += ', interpolation={0})'.format(interpolate_str)
  313. return format_string
  314. STAT_LOGGER_FONT_SIZE = 15
  315. class DatasetStatisticsTensorboardLogger:
  316. logger = get_logger(__name__)
  317. DEFAULT_SUMMARY_PARAMS = {
  318. 'sample_images': 32, # by default, 32 images will be sampled from each dataset
  319. 'plot_class_distribution': True,
  320. 'plot_box_size_distribution': True,
  321. 'plot_anchors_coverage': True,
  322. 'max_batches': 30
  323. }
  324. def __init__(self, sg_logger: AbstractSGLogger, summary_params: dict = DEFAULT_SUMMARY_PARAMS):
  325. self.sg_logger = sg_logger
  326. self.summary_params = {**DatasetStatisticsTensorboardLogger.DEFAULT_SUMMARY_PARAMS, **summary_params}
  327. def analyze(self, data_loader: torch.utils.data.DataLoader, title: str,
  328. all_classes: List[str], anchors: list = None):
  329. """
  330. :param data_loader: the dataset data loader
  331. :param dataset_params: the dataset parameters
  332. :param title: the title for this dataset (i.e. Coco 2017 test set)
  333. :param anchors: the list of anchors used by the model. applicable only for detection datasets
  334. :param all_classes: the list of all classes names
  335. """
  336. # FIXME: UNCOMMENT AND APPLY TO NEW DetectionDataSet ONCE ITS MERGED
  337. # if isinstance(data_loader.dataset, DetectionDataSet):
  338. # self._analyze_detection(data_loader=data_loader, title=title,
  339. # all_classes=all_classes, anchors=anchors)
  340. # else:
  341. # DatasetStatisticsTensorboardLogger.logger.warning('only DetectionDataSet are currently supported')
  342. DatasetStatisticsTensorboardLogger.logger.warning('only DetectionDataSet are currently supported')
  343. def _analyze_detection(self, data_loader, title, all_classes, anchors=None):
  344. """
  345. Analyze a detection dataset
  346. :param data_loader: the dataset data loader
  347. :param dataset_params: the dataset parameters
  348. :param all_classes: the list of all classes names
  349. :param title: the title for this dataset (i.e. Coco 2017 test set)
  350. :param anchors: the list of anchors used by the model. if not provided, anchors coverage will not be analyzed
  351. """
  352. try:
  353. color_mean = AverageMeter()
  354. color_std = AverageMeter()
  355. all_labels = []
  356. image_size = 0
  357. for i, (images, labels) in enumerate(tqdm(data_loader)):
  358. if i >= self.summary_params['max_batches'] > 0:
  359. break
  360. if i == 0:
  361. image_size = max(images[0].shape[1], images[0].shape[2])
  362. if images.shape[0] > self.summary_params['sample_images']:
  363. samples = images[:self.summary_params['sample_images']]
  364. else:
  365. samples = images
  366. pred = [torch.zeros(size=(0, 6)) for _ in range(len(samples))]
  367. try:
  368. result_images = DetectionVisualization.visualize_batch(image_tensor=samples, pred_boxes=pred,
  369. target_boxes=copy.deepcopy(labels),
  370. batch_name=title,
  371. class_names=all_classes,
  372. box_thickness=1,
  373. gt_alpha=1.0)
  374. self.sg_logger.add_images(tag=f'{title} sample images', images=np.stack(result_images)
  375. .transpose([0, 3, 1, 2])[:, ::-1, :, :])
  376. except Exception as e:
  377. DatasetStatisticsTensorboardLogger.logger.error(
  378. f'Dataset Statistics failed at adding an example batch:\n{e}')
  379. return
  380. all_labels.append(labels)
  381. color_mean.update(torch.mean(images, dim=[0, 2, 3]), 1)
  382. color_std.update(torch.std(images, dim=[0, 2, 3]), 1)
  383. all_labels = torch.cat(all_labels, dim=0)[1:].numpy()
  384. try:
  385. if self.summary_params['plot_class_distribution']:
  386. self._analyze_class_distribution(labels=all_labels, num_classes=len(all_classes), title=title)
  387. except Exception as e:
  388. DatasetStatisticsTensorboardLogger.logger.error(f'Dataset Statistics failed at analyzing class distributions.\n{e}')
  389. return
  390. try:
  391. if self.summary_params['plot_box_size_distribution']:
  392. self._analyze_object_size_distribution(labels=all_labels, title=title)
  393. except Exception as e:
  394. DatasetStatisticsTensorboardLogger.logger.error(f'Dataset Statistics failed at analyzing object size '
  395. f'distributions.\n{e}')
  396. return
  397. summary = ''
  398. summary += f'dataset size: {len(data_loader)} \n'
  399. summary += f'color mean: {color_mean.average} \n'
  400. summary += f'color std: {color_std.average} \n'
  401. try:
  402. if anchors is not None and image_size > 0:
  403. coverage = self._analyze_anchors_coverage(anchors=anchors, image_size=image_size,
  404. title=title, labels=all_labels)
  405. summary += f'anchors: {anchors} \n'
  406. summary += f'anchors coverage: {coverage} \n'
  407. except Exception as e:
  408. DatasetStatisticsTensorboardLogger.logger.error(f'Dataset Statistics failed at analyzing anchors '
  409. f'coverage.\n{e}')
  410. return
  411. self.sg_logger.add_text(tag=f'{title} Statistics', text_string=summary)
  412. self.sg_logger.flush()
  413. except Exception as e:
  414. DatasetStatisticsTensorboardLogger.logger.error(f'dataset analysis failed!\n{e}')
  415. def _analyze_class_distribution(self, labels: list, num_classes: int, title: str):
  416. hist, edges = np.histogram(labels[:, 0], num_classes)
  417. f = plt.figure(figsize=[10, 8])
  418. plt.bar(range(num_classes), hist, width=0.5, color='#0504aa', alpha=0.7)
  419. plt.xlim(-1, num_classes)
  420. plt.grid(axis='y', alpha=0.75)
  421. plt.xlabel('Value', fontsize=STAT_LOGGER_FONT_SIZE)
  422. plt.ylabel('Frequency', fontsize=STAT_LOGGER_FONT_SIZE)
  423. plt.xticks(fontsize=STAT_LOGGER_FONT_SIZE)
  424. plt.yticks(fontsize=STAT_LOGGER_FONT_SIZE)
  425. plt.title(f'{title} class distribution', fontsize=STAT_LOGGER_FONT_SIZE)
  426. self.sg_logger.add_figure(f"{title} class distribution", figure=f)
  427. text_dist = ''
  428. for i, val in enumerate(hist):
  429. text_dist += f'[{i}]: {val}, '
  430. self.sg_logger.add_text(tag=f"{title} class distribution", text_string=text_dist)
  431. def _analyze_object_size_distribution(self, labels: list, title: str):
  432. """
  433. This function will add two plots to the tensorboard.
  434. one is a 2D histogram and the other is a scatter plot. in both cases the X axis is the object width and Y axis
  435. is the object width (both normalized by image size)
  436. :param labels: all the labels of the dataset of the shape [class_label, x_center, y_center, w, h]
  437. :param title: the dataset title
  438. """
  439. # histogram plot
  440. hist, xedges, yedges = np.histogram2d(labels[:, 4], labels[:, 3], 50) # x and y are deliberately switched
  441. fig = plt.figure(figsize=(10, 6))
  442. fig.suptitle(f'{title} boxes w/h distribution')
  443. ax = fig.add_subplot(121)
  444. ax.set_xlabel('W', fontsize=STAT_LOGGER_FONT_SIZE)
  445. ax.set_ylabel('H', fontsize=STAT_LOGGER_FONT_SIZE)
  446. plt.imshow(np.log(hist + 1), interpolation='nearest', origin='lower',
  447. extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
  448. # scatter plot
  449. if len(labels) > 10000:
  450. # we randomly sample just 10000 objects so that the scatter plot will not get too dense
  451. labels = labels[np.random.randint(0, len(labels) - 1, 10000)]
  452. ax = fig.add_subplot(122)
  453. ax.set_xlabel('W', fontsize=STAT_LOGGER_FONT_SIZE)
  454. ax.set_ylabel('H', fontsize=STAT_LOGGER_FONT_SIZE)
  455. plt.scatter(labels[:, 3], labels[:, 4], marker='.')
  456. self.sg_logger.add_figure(tag=f'{title} boxes w/h distribution', figure=fig)
  457. @staticmethod
  458. def _get_rect(w, h):
  459. min_w = w / 4.0
  460. min_h = h / 4.0
  461. return Rectangle((min_w, min_h), w * 4 - min_w, h * 4 - min_h, linewidth=1, edgecolor='b', facecolor='none')
  462. @staticmethod
  463. def _get_score(anchors: np.ndarray, points: np.ndarray, image_size: int):
  464. """
  465. Calculate the ratio (and 1/ratio) between each anchor width and height and each point (representing a possible
  466. object width and height).
  467. i.e. for an anchor with w=10,h=20 the point w=11,h=25 will have the ratios 11/10=1.1 and 25/20=1.25
  468. or 10/11=0.91 and 20/25=0.8 respectively
  469. :param anchors: array of anchors of the shape [2,N]
  470. :param points: array of points of the shape [2,M]
  471. :param image_size the size of the input image
  472. :returns: an array of size [image_size - 1, image_size - 1] where each cell i,j represent the minimum ratio
  473. for that cell (point) from all anchors
  474. """
  475. ratio = anchors[:, :, None] / points[:, ]
  476. inv_ratio = 1 / ratio
  477. min_ratio = 1 - np.minimum(ratio, inv_ratio)
  478. min_ratio = np.max(min_ratio, axis=1)
  479. to_closest_anchor = np.min(min_ratio, axis=0)
  480. to_closest_anchor[to_closest_anchor > 0.75] = 2
  481. return to_closest_anchor.reshape(image_size - 1, -1)
  482. def _analyze_anchors_coverage(self, anchors: Anchors, image_size: int, labels: list, title: str):
  483. """
  484. This function will add anchors coverage plots to the tensorboard.
  485. :param anchors: a list of anchors
  486. :param image_size: the input image size for this training
  487. :param labels: all the labels of the dataset of the shape [class_label, x_center, y_center, w, h]
  488. :param title: the dataset title
  489. """
  490. fig = plt.figure(figsize=(12, 5))
  491. fig.suptitle(f'{title} anchors coverage')
  492. # box style plot
  493. ax = fig.add_subplot(121)
  494. ax.set_xlabel('W', fontsize=STAT_LOGGER_FONT_SIZE)
  495. ax.set_ylabel('H', fontsize=STAT_LOGGER_FONT_SIZE)
  496. ax.set_xlim([0, image_size])
  497. ax.set_ylim([0, image_size])
  498. anchors_boxes = anchors.anchors.cpu().numpy()
  499. anchors_len = anchors.num_anchors
  500. anchors_boxes = anchors_boxes.reshape(-1, 2)
  501. for i in range(anchors_len):
  502. rect = self._get_rect(anchors_boxes[i][0], anchors_boxes[i][1])
  503. rect.set_alpha(0.3)
  504. rect.set_facecolor([random.random(), random.random(), random.random(), 0.3])
  505. ax.add_patch(rect)
  506. # distance from anchor plot
  507. ax = fig.add_subplot(122)
  508. ax.set_xlabel('W', fontsize=STAT_LOGGER_FONT_SIZE)
  509. ax.set_ylabel('H', fontsize=STAT_LOGGER_FONT_SIZE)
  510. x = np.arange(1, image_size, 1)
  511. y = np.arange(1, image_size, 1)
  512. xx, yy = np.meshgrid(x, y, sparse=False)
  513. points = np.concatenate([xx.reshape(1, -1), yy.reshape(1, -1)])
  514. color = self._get_score(anchors_boxes, points, image_size)
  515. ax.set_xlabel('W', fontsize=STAT_LOGGER_FONT_SIZE)
  516. ax.set_ylabel('H', fontsize=STAT_LOGGER_FONT_SIZE)
  517. plt.imshow(color, interpolation='nearest', origin='lower',
  518. extent=[0, image_size, 0, image_size])
  519. # calculate the coverage for the dataset labels
  520. cover_masks = []
  521. for i in range(anchors_len):
  522. w_max = (anchors_boxes[i][0] / image_size) * 4
  523. w_min = (anchors_boxes[i][0] / image_size) * 0.25
  524. h_max = (anchors_boxes[i][1] / image_size) * 4
  525. h_min = (anchors_boxes[i][1] / image_size) * 0.25
  526. cover_masks.append(np.logical_and(
  527. np.logical_and(np.logical_and(labels[:, 3] < w_max, labels[:, 3] > w_min), labels[:, 4] < h_max),
  528. labels[:, 4] > h_min))
  529. cover_masks = np.stack(cover_masks)
  530. coverage = np.count_nonzero(np.any(cover_masks, axis=0)) / len(labels)
  531. self.sg_logger.add_figure(tag=f'{title} anchors coverage', figure=fig)
  532. return coverage
  533. def get_color_augmentation(rand_augment_config_string: str, color_jitter: tuple, crop_size=224, img_mean=[0.485, 0.456, 0.406]):
  534. """
  535. Returns color augmentation class. As these augmentation cannot work on top one another, only one is returned
  536. according to rand_augment_config_string
  537. :param rand_augment_config_string: string which defines the auto augment configurations.
  538. If none, color jitter will be returned. For possibile values see auto_augment.py
  539. :param color_jitter: tuple for color jitter value.
  540. :param crop_size: relevant only for auto augment
  541. :param img_mean: relevant only for auto augment
  542. :return: RandAugment transform or ColorJitter
  543. """
  544. if rand_augment_config_string:
  545. color_augmentation = rand_augment_transform(rand_augment_config_string, crop_size, img_mean)
  546. else: # RandAugment includes colorjitter like augmentations, both cannot be applied together.
  547. color_augmentation = transforms.ColorJitter(*color_jitter)
  548. return color_augmentation
  549. def worker_init_reset_seed(worker_id):
  550. """
  551. Make sure each process has different random seed, especially for 'fork' method.
  552. Check https://github.com/pytorch/pytorch/issues/63311 for more details.
  553. :param worker_id: placeholder (needs to be passed to DataLoader init).
  554. """
  555. seed = uuid.uuid4().int % 2 ** 32
  556. random.seed(seed)
  557. torch.set_rng_state(torch.manual_seed(seed).get_state())
  558. np.random.seed(seed)
Discard
Tip!

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