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

#578 Feature/sg 516 support head replacement for local pretrained weights unknown dataset

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:feature/SG-516_support_head_replacement_for_local_pretrained_weights_unknown_dataset
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. import random
  4. import uuid
  5. from abc import ABC, abstractmethod
  6. from multiprocessing import Value, Lock
  7. from typing import List
  8. import matplotlib.pyplot as plt
  9. import numpy as np
  10. import torch
  11. import torch.distributed as dist
  12. import torch.nn.functional as F
  13. import torchvision
  14. from PIL import Image
  15. from deprecate import deprecated
  16. from matplotlib.patches import Rectangle
  17. from torchvision.datasets import ImageFolder
  18. from torchvision.transforms import transforms, InterpolationMode, RandomResizedCrop
  19. from tqdm import tqdm
  20. from super_gradients.common.abstractions.abstract_logger import get_logger
  21. from super_gradients.common.sg_loggers.abstract_sg_logger import AbstractSGLogger
  22. from super_gradients.training.datasets.auto_augment import rand_augment_transform
  23. from super_gradients.training.utils.detection_utils import DetectionVisualization, Anchors
  24. from super_gradients.training.utils.distributed_training_utils import get_local_rank, get_world_size
  25. from super_gradients.training.utils.utils import AverageMeter
  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(
  39. traindir, transforms.Compose([transforms.RandomResizedCrop(RandomResizeSize), transforms.RandomHorizontalFlip(), transforms.ToTensor()])
  40. )
  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, image_size_steps: int = 32, change_frequency: int = 10):
  116. """
  117. set parameters for the multi-scale collate function
  118. the possible image sizes are in range [min_image_size, max_image_size] in steps of image_size_steps
  119. a new size will be randomly selected every change_frequency calls to the collate_fn()
  120. :param target_size: scales will be [0.66 * target_size, 1.5 * target_size]
  121. :param min_image_size: the minimum size to scale down to (in pixels)
  122. :param max_image_size: the maximum size to scale up to (in pixels)
  123. :param image_size_steps: typically, the stride of the net, which defines the possible image
  124. size multiplications
  125. :param change_frequency:
  126. """
  127. assert target_size is not None or (
  128. max_image_size is not None and min_image_size is not None
  129. ), "either target_size or min_image_size and max_image_size has to be set"
  130. assert target_size is None or max_image_size is None, "target_size and max_image_size cannot be both defined"
  131. if target_size is not None:
  132. min_image_size = int(0.66 * target_size - ((0.66 * target_size) % image_size_steps) + image_size_steps)
  133. max_image_size = int(1.5 * target_size - ((1.5 * target_size) % image_size_steps))
  134. print("Using multi-scale %g - %g" % (min_image_size, max_image_size))
  135. self.sizes = np.arange(min_image_size, max_image_size + image_size_steps, image_size_steps)
  136. self.image_size_steps = image_size_steps
  137. self.frequency = change_frequency
  138. self._current_size = random.choice(self.sizes)
  139. def __call__(self, batch):
  140. with self._lock:
  141. # Important: this implementation was tailored for a specific input. it assumes the batch is a tuple where
  142. # the images are the first item
  143. assert isinstance(batch, tuple), "this collate function expects the input to be a tuple (images, labels)"
  144. images = batch[0]
  145. if self._counter % self.frequency == 0:
  146. self._current_size = random.choice(self.sizes)
  147. self._counter += 1
  148. assert images.shape[2] % self.image_size_steps == 0 and images.shape[3] % self.image_size_steps == 0, (
  149. "images sized not divisible by %d. (resize images before calling multi_scale)" % self.image_size_steps
  150. )
  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, image_size_steps: int = 32, change_frequency: int = 10):
  179. self.multiscale_range = multiscale_range
  180. self.image_size_steps = image_size_steps
  181. self.frequency = change_frequency
  182. self.rank = None
  183. self.is_distributed = None
  184. self.sampled_imres_once = False
  185. self.new_input_size = None
  186. def __call__(self, inputs, targets, batch_idx):
  187. if self.rank is None:
  188. self.rank = get_local_rank()
  189. if self.is_distributed is None:
  190. self.is_distributed = get_world_size() > 1
  191. # GENERATE A NEW SIZE AND BROADCAST IT TO THE THE OTHER RANKS SO THEY HAVE THE SAME SCALE
  192. input_size = inputs.shape[2:]
  193. if batch_idx % self.frequency == 0:
  194. tensor = torch.LongTensor(2).to(inputs.device)
  195. if self.rank == 0:
  196. size_factor = input_size[1] * 1.0 / input_size[0]
  197. min_size = int(input_size[0] / self.image_size_steps) - self.multiscale_range
  198. max_size = int(input_size[0] / self.image_size_steps) + self.multiscale_range
  199. random_size = (min_size, max_size)
  200. if self.sampled_imres_once:
  201. size = random.randint(*random_size)
  202. else:
  203. # sample the biggest resolution first to make sure the run fits into the GPU memory
  204. size = max_size
  205. self.sampled_imres_once = True
  206. size = (int(self.image_size_steps * size), self.image_size_steps * int(size * size_factor))
  207. tensor[0] = size[0]
  208. tensor[1] = size[1]
  209. if self.is_distributed:
  210. dist.barrier()
  211. dist.broadcast(tensor, 0)
  212. self.new_input_size = (tensor[0].item(), tensor[1].item())
  213. scale_y = self.new_input_size[0] / input_size[0]
  214. scale_x = self.new_input_size[1] / input_size[1]
  215. if scale_x != 1 or scale_y != 1:
  216. inputs = torch.nn.functional.interpolate(inputs, size=self.new_input_size, mode="bilinear", align_corners=False)
  217. return inputs, targets
  218. class DetectionMultiscalePrePredictionCallback(MultiscalePrePredictionCallback):
  219. """
  220. Mutiscalepre-prediction callback for object detection.
  221. When passed through train_params images, targets will be applied by the below transform to support multi scaling
  222. on the fly.
  223. After each self.frequency forward passes, change size randomly from
  224. (input_size-self.multiscale_range*self.image_size_steps, input_size-(self.multiscale_range-1)*self.image_size_steps,
  225. ...input_size+self.multiscale_range*self.image_size_steps) and apply the same rescaling to the box coordinates.
  226. Attributes:
  227. multiscale_range: (int) Range of values for resize sizes as discussed above (default=5)
  228. image_size_steps: (int) Image step sizes as discussed abov (default=32)
  229. change_frequency: (int) The frequency to apply change in input size.
  230. """
  231. def __call__(self, inputs, targets, batch_idx):
  232. # RESCALE THE IMAGE FIRST WITH SUPER(), AND IF RESCALING HAS ACTUALLY BEEN DONE APPLY TO BOXES AS WELL
  233. input_size = inputs.shape[2:]
  234. inputs, targets = super(DetectionMultiscalePrePredictionCallback, self).__call__(inputs, targets, batch_idx)
  235. new_input_size = inputs.shape[2:]
  236. scale_y = new_input_size[0] / input_size[0]
  237. scale_x = new_input_size[1] / input_size[1]
  238. if scale_x != 1 or scale_y != 1:
  239. targets[..., 2::2] = targets[..., 2::2] * scale_x
  240. targets[..., 3::2] = targets[..., 3::2] * scale_y
  241. return inputs, targets
  242. _pil_interpolation_to_str = {
  243. Image.NEAREST: "PIL.Image.NEAREST",
  244. Image.BILINEAR: "PIL.Image.BILINEAR",
  245. Image.BICUBIC: "PIL.Image.BICUBIC",
  246. Image.LANCZOS: "PIL.Image.LANCZOS",
  247. Image.HAMMING: "PIL.Image.HAMMING",
  248. Image.BOX: "PIL.Image.BOX",
  249. }
  250. def _pil_interp(method):
  251. if method == "bicubic":
  252. return InterpolationMode.BICUBIC
  253. elif method == "lanczos":
  254. return InterpolationMode.LANCZOS
  255. elif method == "hamming":
  256. return InterpolationMode.HAMMING
  257. elif method == "nearest":
  258. return InterpolationMode.NEAREST
  259. elif method == "bilinear":
  260. return InterpolationMode.BILINEAR
  261. elif method == "box":
  262. return InterpolationMode.BOX
  263. else:
  264. raise ValueError(
  265. "interpolation type must be one of ['bilinear', 'bicubic', 'lanczos', 'hamming', "
  266. "'nearest', 'box'] for explicit interpolation type, or 'random' for random"
  267. )
  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.0 / 4.0, 4.0 / 3.0), interpolation="default"):
  283. super(RandomResizedCropAndInterpolation, self).__init__(size=size, scale=scale, ratio=ratio, interpolation=interpolation)
  284. if interpolation == "random":
  285. self.interpolation = _RANDOM_INTERPOLATION
  286. elif interpolation == "default":
  287. self.interpolation = InterpolationMode.BILINEAR
  288. else:
  289. self.interpolation = _pil_interp(interpolation)
  290. def forward(self, img):
  291. """
  292. Args:
  293. img (PIL Image): Image to be cropped and resized.
  294. Returns:
  295. PIL Image: Randomly cropped and resized image.
  296. """
  297. i, j, h, w = self.get_params(img, self.scale, self.ratio)
  298. if isinstance(self.interpolation, (tuple, list)):
  299. interpolation = random.choice(self.interpolation)
  300. else:
  301. interpolation = self.interpolation
  302. return torchvision.transforms.functional.resized_crop(img, i, j, h, w, self.size, interpolation)
  303. def __repr__(self):
  304. if isinstance(self.interpolation, (tuple, list)):
  305. interpolate_str = " ".join([_pil_interpolation_to_str[x] for x in self.interpolation])
  306. else:
  307. interpolate_str = _pil_interpolation_to_str[self.interpolation]
  308. format_string = self.__class__.__name__ + "(size={0}".format(self.size)
  309. format_string += ", scale={0}".format(tuple(round(s, 4) for s in self.scale))
  310. format_string += ", ratio={0}".format(tuple(round(r, 4) for r in self.ratio))
  311. format_string += ", interpolation={0})".format(interpolate_str)
  312. return format_string
  313. STAT_LOGGER_FONT_SIZE = 15
  314. class DatasetStatisticsTensorboardLogger:
  315. logger = get_logger(__name__)
  316. DEFAULT_SUMMARY_PARAMS = {
  317. "sample_images": 32, # by default, 32 images will be sampled from each dataset
  318. "plot_class_distribution": True,
  319. "plot_box_size_distribution": True,
  320. "plot_anchors_coverage": True,
  321. "max_batches": 30,
  322. }
  323. def __init__(self, sg_logger: AbstractSGLogger, summary_params: dict = DEFAULT_SUMMARY_PARAMS):
  324. self.sg_logger = sg_logger
  325. self.summary_params = {**DatasetStatisticsTensorboardLogger.DEFAULT_SUMMARY_PARAMS, **summary_params}
  326. def analyze(self, data_loader: torch.utils.data.DataLoader, title: str, all_classes: List[str], anchors: list = None):
  327. """
  328. :param data_loader: the dataset data loader
  329. :param dataset_params: the dataset parameters
  330. :param title: the title for this dataset (i.e. Coco 2017 test set)
  331. :param anchors: the list of anchors used by the model. applicable only for detection datasets
  332. :param all_classes: the list of all classes names
  333. """
  334. # FIXME: UNCOMMENT AND APPLY TO NEW DetectionDataSet ONCE ITS MERGED
  335. # if isinstance(data_loader.dataset, DetectionDataSet):
  336. # self._analyze_detection(data_loader=data_loader, title=title,
  337. # all_classes=all_classes, anchors=anchors)
  338. # else:
  339. # DatasetStatisticsTensorboardLogger.logger.warning('only DetectionDataSet are currently supported')
  340. DatasetStatisticsTensorboardLogger.logger.warning("only DetectionDataSet are currently supported")
  341. def _analyze_detection(self, data_loader, title, all_classes, anchors=None):
  342. """
  343. Analyze a detection dataset
  344. :param data_loader: the dataset data loader
  345. :param dataset_params: the dataset parameters
  346. :param all_classes: the list of all classes names
  347. :param title: the title for this dataset (i.e. Coco 2017 test set)
  348. :param anchors: the list of anchors used by the model. if not provided, anchors coverage will not be analyzed
  349. """
  350. try:
  351. color_mean = AverageMeter()
  352. color_std = AverageMeter()
  353. all_labels = []
  354. image_size = 0
  355. for i, (images, labels) in enumerate(tqdm(data_loader)):
  356. if i >= self.summary_params["max_batches"] > 0:
  357. break
  358. if i == 0:
  359. image_size = max(images[0].shape[1], images[0].shape[2])
  360. if images.shape[0] > self.summary_params["sample_images"]:
  361. samples = images[: self.summary_params["sample_images"]]
  362. else:
  363. samples = images
  364. pred = [torch.zeros(size=(0, 6)) for _ in range(len(samples))]
  365. try:
  366. result_images = DetectionVisualization.visualize_batch(
  367. image_tensor=samples,
  368. 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. )
  375. self.sg_logger.add_images(tag=f"{title} sample images", images=np.stack(result_images).transpose([0, 3, 1, 2])[:, ::-1, :, :])
  376. except Exception as e:
  377. DatasetStatisticsTensorboardLogger.logger.error(f"Dataset Statistics failed at adding an example batch:\n{e}")
  378. return
  379. all_labels.append(labels)
  380. color_mean.update(torch.mean(images, dim=[0, 2, 3]), 1)
  381. color_std.update(torch.std(images, dim=[0, 2, 3]), 1)
  382. all_labels = torch.cat(all_labels, dim=0)[1:].numpy()
  383. try:
  384. if self.summary_params["plot_class_distribution"]:
  385. self._analyze_class_distribution(labels=all_labels, num_classes=len(all_classes), title=title)
  386. except Exception as e:
  387. DatasetStatisticsTensorboardLogger.logger.error(f"Dataset Statistics failed at analyzing class distributions.\n{e}")
  388. return
  389. try:
  390. if self.summary_params["plot_box_size_distribution"]:
  391. self._analyze_object_size_distribution(labels=all_labels, title=title)
  392. except Exception as e:
  393. DatasetStatisticsTensorboardLogger.logger.error(f"Dataset Statistics failed at analyzing object size " f"distributions.\n{e}")
  394. return
  395. summary = ""
  396. summary += f"dataset size: {len(data_loader)} \n"
  397. summary += f"color mean: {color_mean.average} \n"
  398. summary += f"color std: {color_std.average} \n"
  399. try:
  400. if anchors is not None and image_size > 0:
  401. coverage = self._analyze_anchors_coverage(anchors=anchors, image_size=image_size, title=title, labels=all_labels)
  402. summary += f"anchors: {anchors} \n"
  403. summary += f"anchors coverage: {coverage} \n"
  404. except Exception as e:
  405. DatasetStatisticsTensorboardLogger.logger.error(f"Dataset Statistics failed at analyzing anchors " f"coverage.\n{e}")
  406. return
  407. self.sg_logger.add_text(tag=f"{title} Statistics", text_string=summary)
  408. self.sg_logger.flush()
  409. except Exception as e:
  410. DatasetStatisticsTensorboardLogger.logger.error(f"dataset analysis failed!\n{e}")
  411. def _analyze_class_distribution(self, labels: list, num_classes: int, title: str):
  412. hist, edges = np.histogram(labels[:, 0], num_classes)
  413. f = plt.figure(figsize=[10, 8])
  414. plt.bar(range(num_classes), hist, width=0.5, color="#0504aa", alpha=0.7)
  415. plt.xlim(-1, num_classes)
  416. plt.grid(axis="y", alpha=0.75)
  417. plt.xlabel("Value", fontsize=STAT_LOGGER_FONT_SIZE)
  418. plt.ylabel("Frequency", fontsize=STAT_LOGGER_FONT_SIZE)
  419. plt.xticks(fontsize=STAT_LOGGER_FONT_SIZE)
  420. plt.yticks(fontsize=STAT_LOGGER_FONT_SIZE)
  421. plt.title(f"{title} class distribution", fontsize=STAT_LOGGER_FONT_SIZE)
  422. self.sg_logger.add_figure(f"{title} class distribution", figure=f)
  423. text_dist = ""
  424. for i, val in enumerate(hist):
  425. text_dist += f"[{i}]: {val}, "
  426. self.sg_logger.add_text(tag=f"{title} class distribution", text_string=text_dist)
  427. def _analyze_object_size_distribution(self, labels: list, title: str):
  428. """
  429. This function will add two plots to the tensorboard.
  430. 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
  431. is the object width (both normalized by image size)
  432. :param labels: all the labels of the dataset of the shape [class_label, x_center, y_center, w, h]
  433. :param title: the dataset title
  434. """
  435. # histogram plot
  436. hist, xedges, yedges = np.histogram2d(labels[:, 4], labels[:, 3], 50) # x and y are deliberately switched
  437. fig = plt.figure(figsize=(10, 6))
  438. fig.suptitle(f"{title} boxes w/h distribution")
  439. ax = fig.add_subplot(121)
  440. ax.set_xlabel("W", fontsize=STAT_LOGGER_FONT_SIZE)
  441. ax.set_ylabel("H", fontsize=STAT_LOGGER_FONT_SIZE)
  442. plt.imshow(np.log(hist + 1), interpolation="nearest", origin="lower", extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
  443. # scatter plot
  444. if len(labels) > 10000:
  445. # we randomly sample just 10000 objects so that the scatter plot will not get too dense
  446. labels = labels[np.random.randint(0, len(labels) - 1, 10000)]
  447. ax = fig.add_subplot(122)
  448. ax.set_xlabel("W", fontsize=STAT_LOGGER_FONT_SIZE)
  449. ax.set_ylabel("H", fontsize=STAT_LOGGER_FONT_SIZE)
  450. plt.scatter(labels[:, 3], labels[:, 4], marker=".")
  451. self.sg_logger.add_figure(tag=f"{title} boxes w/h distribution", figure=fig)
  452. @staticmethod
  453. def _get_rect(w, h):
  454. min_w = w / 4.0
  455. min_h = h / 4.0
  456. return Rectangle((min_w, min_h), w * 4 - min_w, h * 4 - min_h, linewidth=1, edgecolor="b", facecolor="none")
  457. @staticmethod
  458. def _get_score(anchors: np.ndarray, points: np.ndarray, image_size: int):
  459. """
  460. Calculate the ratio (and 1/ratio) between each anchor width and height and each point (representing a possible
  461. object width and height).
  462. 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
  463. or 10/11=0.91 and 20/25=0.8 respectively
  464. :param anchors: array of anchors of the shape [2,N]
  465. :param points: array of points of the shape [2,M]
  466. :param image_size the size of the input image
  467. :returns: an array of size [image_size - 1, image_size - 1] where each cell i,j represent the minimum ratio
  468. for that cell (point) from all anchors
  469. """
  470. ratio = (
  471. anchors[:, :, None]
  472. / points[
  473. :,
  474. ]
  475. )
  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, indexing="xy")
  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", extent=[0, image_size, 0, image_size])
  518. # calculate the coverage for the dataset labels
  519. cover_masks = []
  520. for i in range(anchors_len):
  521. w_max = (anchors_boxes[i][0] / image_size) * 4
  522. w_min = (anchors_boxes[i][0] / image_size) * 0.25
  523. h_max = (anchors_boxes[i][1] / image_size) * 4
  524. h_min = (anchors_boxes[i][1] / image_size) * 0.25
  525. cover_masks.append(
  526. np.logical_and(np.logical_and(np.logical_and(labels[:, 3] < w_max, labels[:, 3] > w_min), labels[:, 4] < h_max), labels[:, 4] > h_min)
  527. )
  528. cover_masks = np.stack(cover_masks)
  529. coverage = np.count_nonzero(np.any(cover_masks, axis=0)) / len(labels)
  530. self.sg_logger.add_figure(tag=f"{title} anchors coverage", figure=fig)
  531. return coverage
  532. def get_color_augmentation(rand_augment_config_string: str, color_jitter: tuple, crop_size=224, img_mean=[0.485, 0.456, 0.406]):
  533. """
  534. Returns color augmentation class. As these augmentation cannot work on top one another, only one is returned
  535. according to rand_augment_config_string
  536. :param rand_augment_config_string: string which defines the auto augment configurations.
  537. If none, color jitter will be returned. For possibile values see auto_augment.py
  538. :param color_jitter: tuple for color jitter value.
  539. :param crop_size: relevant only for auto augment
  540. :param img_mean: relevant only for auto augment
  541. :return: RandAugment transform or ColorJitter
  542. """
  543. if rand_augment_config_string:
  544. color_augmentation = rand_augment_transform(rand_augment_config_string, crop_size, img_mean)
  545. else: # RandAugment includes colorjitter like augmentations, both cannot be applied together.
  546. color_augmentation = transforms.ColorJitter(*color_jitter)
  547. return color_augmentation
  548. def worker_init_reset_seed(worker_id):
  549. """
  550. Make sure each process has different random seed, especially for 'fork' method.
  551. Check https://github.com/pytorch/pytorch/issues/63311 for more details.
  552. :param worker_id: placeholder (needs to be passed to DataLoader init).
  553. """
  554. seed = uuid.uuid4().int % 2**32
  555. random.seed(seed)
  556. torch.set_rng_state(torch.manual_seed(seed).get_state())
  557. np.random.seed(seed)
Discard
Tip!

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