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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
  1. """
  2. Based on https://github.com/Megvii-BaseDetection/YOLOX (Apache-2.0 license)
  3. """
  4. import logging
  5. from typing import List, Tuple, Union
  6. import torch
  7. import torch.distributed as dist
  8. from torch import nn
  9. from torch.nn.modules.loss import _Loss
  10. import torch.nn.functional as F
  11. from super_gradients.common.abstractions.abstract_logger import get_logger
  12. from super_gradients.training.utils import torch_version_is_greater_or_equal
  13. from super_gradients.training.utils.detection_utils import calculate_bbox_iou_matrix
  14. logger = get_logger(__name__)
  15. class IOUloss(nn.Module):
  16. """
  17. IoU loss with the following supported loss types:
  18. Attributes:
  19. reduction: str: One of ["mean", "sum", "none"] reduction to apply to the computed loss (Default="none")
  20. loss_type: str: One of ["iou", "giou"] where:
  21. * 'iou' for
  22. (1 - iou^2)
  23. * 'giou' according to "Generalized Intersection over Union: A Metric and A Loss for Bounding Box Regression"
  24. (1 - giou), where giou = iou - (cover_box - union_box)/cover_box
  25. """
  26. def __init__(self, reduction: str = "none", loss_type: str = "iou"):
  27. super(IOUloss, self).__init__()
  28. self._validate_args(loss_type, reduction)
  29. self.reduction = reduction
  30. self.loss_type = loss_type
  31. @staticmethod
  32. def _validate_args(loss_type, reduction):
  33. supported_losses = ["iou", "giou"]
  34. supported_reductions = ["mean", "sum", "none"]
  35. if loss_type not in supported_losses:
  36. raise ValueError("Illegal loss_type value: " + loss_type + ", expected one of: " + str(supported_losses))
  37. if reduction not in supported_reductions:
  38. raise ValueError("Illegal reduction value: " + reduction + ", expected one of: " + str(supported_reductions))
  39. def forward(self, pred, target):
  40. assert pred.shape[0] == target.shape[0]
  41. pred = pred.view(-1, 4)
  42. target = target.view(-1, 4)
  43. tl = torch.max((pred[:, :2] - pred[:, 2:] / 2), (target[:, :2] - target[:, 2:] / 2))
  44. br = torch.min((pred[:, :2] + pred[:, 2:] / 2), (target[:, :2] + target[:, 2:] / 2))
  45. area_p = torch.prod(pred[:, 2:], 1)
  46. area_g = torch.prod(target[:, 2:], 1)
  47. en = (tl < br).type(tl.type()).prod(dim=1)
  48. area_i = torch.prod(br - tl, 1) * en
  49. area_u = area_p + area_g - area_i
  50. iou = (area_i) / (area_u + 1e-16)
  51. if self.loss_type == "iou":
  52. loss = 1 - iou**2
  53. elif self.loss_type == "giou":
  54. c_tl = torch.min((pred[:, :2] - pred[:, 2:] / 2), (target[:, :2] - target[:, 2:] / 2))
  55. c_br = torch.max((pred[:, :2] + pred[:, 2:] / 2), (target[:, :2] + target[:, 2:] / 2))
  56. area_c = torch.prod(c_br - c_tl, 1)
  57. giou = iou - (area_c - area_u) / area_c.clamp(1e-16)
  58. loss = 1 - giou.clamp(min=-1.0, max=1.0)
  59. if self.reduction == "mean":
  60. loss = loss.mean()
  61. elif self.reduction == "sum":
  62. loss = loss.sum()
  63. return loss
  64. class YoloXDetectionLoss(_Loss):
  65. """
  66. Calculate YOLOX loss:
  67. L = L_objectivness + L_iou + L_classification + 1[use_l1]*L_l1
  68. where:
  69. * L_iou, L_classification and L_l1 are calculated only between cells and targets that suit them;
  70. * L_objectivness is calculated for all cells.
  71. L_classification:
  72. for cells that have suitable ground truths in their grid locations add BCEs
  73. to force a prediction of IoU with a GT in a multi-label way
  74. Coef: 1.
  75. L_iou:
  76. for cells that have suitable ground truths in their grid locations
  77. add (1 - IoU^2), IoU between a predicted box and each GT box, force maximum IoU
  78. Coef: 5.
  79. L_l1:
  80. for cells that have suitable ground truths in their grid locations
  81. l1 distance between the logits and GTs in “logits” format (the inverse of “logits to predictions” ops)
  82. Coef: 1[use_l1]
  83. L_objectness:
  84. for each cell add BCE with a label of 1 if there is GT assigned to the cell
  85. Coef: 1
  86. Attributes:
  87. strides: list: List of Yolo levels output grid sizes (i.e [8, 16, 32]).
  88. num_classes: int: Number of classes.
  89. use_l1: bool: Controls the L_l1 Coef as discussed above (default=False).
  90. center_sampling_radius: float: Sampling radius used for center sampling when creating the fg mask (default=2.5).
  91. iou_type: str: Iou loss type, one of ["iou","giou"] (deafult="iou").
  92. """
  93. def __init__(self, strides: list, num_classes: int, use_l1: bool = False, center_sampling_radius: float = 2.5, iou_type="iou"):
  94. super().__init__()
  95. self.grids = [torch.zeros(1)] * len(strides)
  96. self.strides = strides
  97. self.num_classes = num_classes
  98. self.center_sampling_radius = center_sampling_radius
  99. self.use_l1 = use_l1
  100. self.l1_loss = nn.L1Loss(reduction="none")
  101. self.bcewithlog_loss = nn.BCEWithLogitsLoss(reduction="none")
  102. self.iou_loss = IOUloss(reduction="none", loss_type=iou_type)
  103. @property
  104. def component_names(self):
  105. """
  106. Component names for logging during training.
  107. These correspond to 2nd item in the tuple returned in self.forward(...).
  108. See super_gradients.Trainer.train() docs for more info.
  109. """
  110. return ["iou", "obj", "cls", "l1", "num_fg", "Loss"]
  111. def forward(self, model_output: Union[list, Tuple[torch.Tensor, List]], targets: torch.Tensor):
  112. """
  113. :param model_output: Union[list, Tuple[torch.Tensor, List]]:
  114. When list-
  115. output from all Yolo levels, each of shape [Batch x 1 x GridSizeY x GridSizeX x (4 + 1 + Num_classes)]
  116. And when tuple- the second item is the described list (first item is discarded)
  117. :param targets: torch.Tensor: Num_targets x (4 + 2)], values on dim 1 are: image id in a batch, class, box x y w h
  118. :return: loss, all losses separately in a detached tensor
  119. """
  120. if isinstance(model_output, tuple) and len(model_output) == 2:
  121. # in test/eval mode the Yolo model outputs a tuple where the second item is the raw predictions
  122. _, predictions = model_output
  123. else:
  124. predictions = model_output
  125. return self._compute_loss(predictions, targets)
  126. @staticmethod
  127. def _make_grid(nx=20, ny=20):
  128. """
  129. Creates a tensor of xy coordinates of size (1,1,nx,ny,2)
  130. :param nx: int: cells along x axis (default=20)
  131. :param ny: int: cells along the y axis (default=20)
  132. :return: torch.tensor of xy coordinates of size (1,1,nx,ny,2)
  133. """
  134. if torch_version_is_greater_or_equal(1, 10):
  135. # https://github.com/pytorch/pytorch/issues/50276
  136. yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)], indexing="ij")
  137. else:
  138. yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
  139. return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
  140. def _compute_loss(self, predictions: List[torch.Tensor], targets: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
  141. """
  142. :param predictions: output from all Yolo levels, each of shape
  143. [Batch x 1 x GridSizeY x GridSizeX x (4 + 1 + Num_classes)]
  144. :param targets: [Num_targets x (4 + 2)], values on dim 1 are: image id in a batch, class, box x y w h
  145. :return: loss, all losses separately in a detached tensor
  146. """
  147. x_shifts, y_shifts, expanded_strides, transformed_outputs, raw_outputs = self.prepare_predictions(predictions)
  148. bbox_preds = transformed_outputs[:, :, :4] # [batch, n_anchors_all, 4]
  149. obj_preds = transformed_outputs[:, :, 4:5] # [batch, n_anchors_all, 1]
  150. cls_preds = transformed_outputs[:, :, 5:] # [batch, n_anchors_all, n_cls]
  151. # calculate targets
  152. total_num_anchors = transformed_outputs.shape[1]
  153. cls_targets = []
  154. reg_targets = []
  155. l1_targets = []
  156. obj_targets = []
  157. fg_masks = []
  158. num_fg, num_gts = 0.0, 0.0
  159. for image_idx in range(transformed_outputs.shape[0]):
  160. labels_im = targets[targets[:, 0] == image_idx]
  161. num_gt = labels_im.shape[0]
  162. num_gts += num_gt
  163. if num_gt == 0:
  164. cls_target = transformed_outputs.new_zeros((0, self.num_classes))
  165. reg_target = transformed_outputs.new_zeros((0, 4))
  166. l1_target = transformed_outputs.new_zeros((0, 4))
  167. obj_target = transformed_outputs.new_zeros((total_num_anchors, 1))
  168. fg_mask = transformed_outputs.new_zeros(total_num_anchors).bool()
  169. else:
  170. # GT boxes to image coordinates
  171. gt_bboxes_per_image = labels_im[:, 2:6].clone()
  172. gt_classes = labels_im[:, 1]
  173. bboxes_preds_per_image = bbox_preds[image_idx]
  174. try:
  175. # assign cells to ground truths, at most one GT per cell
  176. gt_matched_classes, fg_mask, pred_ious_this_matching, matched_gt_inds, num_fg_img = self.get_assignments(
  177. image_idx,
  178. num_gt,
  179. total_num_anchors,
  180. gt_bboxes_per_image,
  181. gt_classes,
  182. bboxes_preds_per_image,
  183. expanded_strides,
  184. x_shifts,
  185. y_shifts,
  186. cls_preds,
  187. obj_preds,
  188. )
  189. # TODO: CHECK IF ERROR IS CUDA OUT OF MEMORY
  190. except RuntimeError:
  191. logging.error(
  192. "OOM RuntimeError is raised due to the huge memory cost during label assignment. \
  193. CPU mode is applied in this batch. If you want to avoid this issue, \
  194. try to reduce the batch size or image size."
  195. )
  196. torch.cuda.empty_cache()
  197. gt_matched_classes, fg_mask, pred_ious_this_matching, matched_gt_inds, num_fg_img = self.get_assignments(
  198. image_idx,
  199. num_gt,
  200. total_num_anchors,
  201. gt_bboxes_per_image,
  202. gt_classes,
  203. bboxes_preds_per_image,
  204. expanded_strides,
  205. x_shifts,
  206. y_shifts,
  207. cls_preds,
  208. obj_preds,
  209. "cpu",
  210. )
  211. torch.cuda.empty_cache()
  212. num_fg += num_fg_img
  213. cls_target = F.one_hot(gt_matched_classes.to(torch.int64), self.num_classes) * pred_ious_this_matching.unsqueeze(-1)
  214. obj_target = fg_mask.unsqueeze(-1)
  215. reg_target = gt_bboxes_per_image[matched_gt_inds]
  216. if self.use_l1:
  217. l1_target = self.get_l1_target(
  218. transformed_outputs.new_zeros((num_fg_img, 4)),
  219. gt_bboxes_per_image[matched_gt_inds],
  220. expanded_strides[0][fg_mask],
  221. x_shifts=x_shifts[0][fg_mask],
  222. y_shifts=y_shifts[0][fg_mask],
  223. )
  224. # collect targets for all loss terms over the whole batch
  225. cls_targets.append(cls_target)
  226. reg_targets.append(reg_target)
  227. obj_targets.append(obj_target.to(transformed_outputs.dtype))
  228. fg_masks.append(fg_mask)
  229. if self.use_l1:
  230. l1_targets.append(l1_target)
  231. # concat all targets over the batch (get rid of batch dim)
  232. cls_targets = torch.cat(cls_targets, 0)
  233. reg_targets = torch.cat(reg_targets, 0)
  234. obj_targets = torch.cat(obj_targets, 0)
  235. fg_masks = torch.cat(fg_masks, 0)
  236. if self.use_l1:
  237. l1_targets = torch.cat(l1_targets, 0)
  238. num_fg = max(num_fg, 1)
  239. # loss terms divided by the total number of foregrounds
  240. loss_iou = self.iou_loss(bbox_preds.view(-1, 4)[fg_masks], reg_targets).sum() / num_fg
  241. loss_obj = self.bcewithlog_loss(obj_preds.view(-1, 1), obj_targets).sum() / num_fg
  242. loss_cls = self.bcewithlog_loss(cls_preds.view(-1, self.num_classes)[fg_masks], cls_targets).sum() / num_fg
  243. if self.use_l1:
  244. loss_l1 = self.l1_loss(raw_outputs.view(-1, 4)[fg_masks], l1_targets).sum() / num_fg
  245. else:
  246. loss_l1 = 0.0
  247. reg_weight = 5.0
  248. loss = reg_weight * loss_iou + loss_obj + loss_cls + loss_l1
  249. return (
  250. loss,
  251. torch.cat(
  252. (
  253. loss_iou.unsqueeze(0),
  254. loss_obj.unsqueeze(0),
  255. loss_cls.unsqueeze(0),
  256. torch.tensor(loss_l1).unsqueeze(0).to(loss.device),
  257. torch.tensor(num_fg / max(num_gts, 1)).unsqueeze(0).to(loss.device),
  258. loss.unsqueeze(0),
  259. )
  260. ).detach(),
  261. )
  262. def prepare_predictions(self, predictions: List[torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
  263. """
  264. Convert raw outputs of the network into a format that merges outputs from all levels
  265. :param predictions: output from all Yolo levels, each of shape
  266. [Batch x 1 x GridSizeY x GridSizeX x (4 + 1 + Num_classes)]
  267. :return: 5 tensors representing predictions:
  268. * x_shifts: shape [1 x * num_cells x 1],
  269. where num_cells = grid1X * grid1Y + grid2X * grid2Y + grid3X * grid3Y,
  270. x coordinate on the grid cell the prediction is coming from
  271. * y_shifts: shape [1 x num_cells x 1],
  272. y coordinate on the grid cell the prediction is coming from
  273. * expanded_strides: shape [1 x num_cells x 1],
  274. stride of the output grid the prediction is coming from
  275. * transformed_outputs: shape [batch_size x num_cells x (num_classes + 5)],
  276. predictions with boxes in real coordinates and logprobabilities
  277. * raw_outputs: shape [batch_size x num_cells x (num_classes + 5)],
  278. raw predictions with boxes and confidences as logits
  279. """
  280. raw_outputs = []
  281. transformed_outputs = []
  282. x_shifts = []
  283. y_shifts = []
  284. expanded_strides = []
  285. for k, output in enumerate(predictions):
  286. batch_size, num_anchors, h, w, num_outputs = output.shape
  287. # IN FIRST PASS CREATE GRIDS ACCORDING TO OUTPUT SHAPE (BATCH,1,IMAGE_H/STRIDE,IMAGE_2/STRIDE,NUM_CLASSES+5)
  288. if self.grids[k].shape[2:4] != output.shape[2:4]:
  289. self.grids[k] = self._make_grid(w, h).type_as(output)
  290. # e.g. [batch_size, 1, 28, 28, 85] -> [batch_size, 784, 85]
  291. output_raveled = output.reshape(batch_size, num_anchors * h * w, num_outputs)
  292. # e.g [1, 784, 2]
  293. grid_raveled = self.grids[k].view(1, num_anchors * h * w, 2)
  294. if self.use_l1:
  295. # e.g [1, 784, 4]
  296. raw_outputs.append(output_raveled[:, :, :4].clone())
  297. # box logits to coordinates
  298. centers = (output_raveled[..., :2] + grid_raveled) * self.strides[k]
  299. wh = torch.exp(output_raveled[..., 2:4]) * self.strides[k]
  300. classes = output_raveled[..., 4:]
  301. output_raveled = torch.cat([centers, wh, classes], -1)
  302. # outputs with boxes in real coordinates, probs as logits
  303. transformed_outputs.append(output_raveled)
  304. # x cell coordinates of all 784 predictions, 0, 0, 0, ..., 1, 1, 1, ...
  305. x_shifts.append(grid_raveled[:, :, 0])
  306. # y cell coordinates of all 784 predictions, 0, 1, 2, ..., 0, 1, 2, ...
  307. y_shifts.append(grid_raveled[:, :, 1])
  308. # e.g. [1, 784, stride of this level (one of [8, 16, 32])]
  309. expanded_strides.append(torch.zeros(1, grid_raveled.shape[1]).fill_(self.strides[k]).type_as(output))
  310. # all 4 below have shapes of [batch_size , num_cells, num_values_pre_cell]
  311. # where num_anchors * num_cells is e.g. 1 * (28 * 28 + 14 * 14 + 17 * 17)
  312. transformed_outputs = torch.cat(transformed_outputs, 1)
  313. x_shifts = torch.cat(x_shifts, 1)
  314. y_shifts = torch.cat(y_shifts, 1)
  315. expanded_strides = torch.cat(expanded_strides, 1)
  316. if self.use_l1:
  317. raw_outputs = torch.cat(raw_outputs, 1)
  318. return x_shifts, y_shifts, expanded_strides, transformed_outputs, raw_outputs
  319. def get_l1_target(self, l1_target, gt, stride, x_shifts, y_shifts, eps=1e-8):
  320. """
  321. :param l1_target: tensor of zeros of shape [Num_cell_gt_pairs x 4]
  322. :param gt: targets in coordinates [Num_cell_gt_pairs x (4 + 1 + num_classes)]
  323. :return: targets in the format corresponding to logits
  324. """
  325. l1_target[:, 0] = gt[:, 0] / stride - x_shifts
  326. l1_target[:, 1] = gt[:, 1] / stride - y_shifts
  327. l1_target[:, 2] = torch.log(gt[:, 2] / stride + eps)
  328. l1_target[:, 3] = torch.log(gt[:, 3] / stride + eps)
  329. return l1_target
  330. @torch.no_grad()
  331. def get_assignments(
  332. self,
  333. image_idx,
  334. num_gt,
  335. total_num_anchors,
  336. gt_bboxes_per_image,
  337. gt_classes,
  338. bboxes_preds_per_image,
  339. expanded_strides,
  340. x_shifts,
  341. y_shifts,
  342. cls_preds,
  343. obj_preds,
  344. mode="gpu",
  345. ious_loss_cost_coeff=3.0,
  346. outside_boxes_and_center_cost_coeff=100000.0,
  347. ):
  348. """
  349. Match cells to ground truth:
  350. * at most 1 GT per cell
  351. * dynamic number of cells per GT
  352. :param outside_boxes_and_center_cost_coeff: float: Cost coefficiant of cells the radius and bbox of gts in dynamic
  353. matching (default=100000).
  354. :param ious_loss_cost_coeff: float: Cost coefficiant for iou loss in dynamic matching (default=3).
  355. :param image_idx: int: Image index in batch.
  356. :param num_gt: int: Number of ground trunth targets in the image.
  357. :param total_num_anchors: int: Total number of possible bboxes = sum of all grid cells.
  358. :param gt_bboxes_per_image: torch.Tensor: Tensor of gt bboxes for the image, shape: (num_gt, 4).
  359. :param gt_classes: torch.Tesnor: Tensor of the classes in the image, shape: (num_preds,4).
  360. :param bboxes_preds_per_image: Tensor of the classes in the image, shape: (num_preds).
  361. :param expanded_strides: torch.Tensor: Stride of the output grid the prediction is coming from,
  362. shape (1 x num_cells x 1).
  363. :param x_shifts: torch.Tensor: X's in cell coordinates, shape (1,num_cells,1).
  364. :param y_shifts: torch.Tensor: Y's in cell coordinates, shape (1,num_cells,1).
  365. :param cls_preds: torch.Tensor: Class predictions in all cells, shape (batch_size, num_cells).
  366. :param obj_preds: torch.Tensor: Objectness predictions in all cells, shape (batch_size, num_cells).
  367. :param mode: str: One of ["gpu","cpu"], Controls the device the assignment operation should be taken place on (deafult="gpu")
  368. """
  369. if mode == "cpu":
  370. print("------------CPU Mode for This Batch-------------")
  371. gt_bboxes_per_image = gt_bboxes_per_image.cpu().float()
  372. bboxes_preds_per_image = bboxes_preds_per_image.cpu().float()
  373. gt_classes = gt_classes.cpu().float()
  374. expanded_strides = expanded_strides.cpu().float()
  375. x_shifts = x_shifts.cpu()
  376. y_shifts = y_shifts.cpu()
  377. # create a mask for foreground cells
  378. fg_mask, is_in_boxes_and_center = self.get_in_boxes_info(gt_bboxes_per_image, expanded_strides, x_shifts, y_shifts, total_num_anchors, num_gt)
  379. bboxes_preds_per_image = bboxes_preds_per_image[fg_mask]
  380. cls_preds_ = cls_preds[image_idx][fg_mask]
  381. obj_preds_ = obj_preds[image_idx][fg_mask]
  382. num_in_boxes_anchor = bboxes_preds_per_image.shape[0]
  383. if mode == "cpu":
  384. gt_bboxes_per_image = gt_bboxes_per_image.cpu()
  385. bboxes_preds_per_image = bboxes_preds_per_image.cpu()
  386. # calculate cost between all foregrounds and all ground truths (used only for matching)
  387. pair_wise_ious = calculate_bbox_iou_matrix(gt_bboxes_per_image, bboxes_preds_per_image, x1y1x2y2=False)
  388. gt_cls_per_image = F.one_hot(gt_classes.to(torch.int64), self.num_classes)
  389. gt_cls_per_image = gt_cls_per_image.float().unsqueeze(1).repeat(1, num_in_boxes_anchor, 1)
  390. pair_wise_ious_loss = -torch.log(pair_wise_ious + 1e-8)
  391. if mode == "cpu":
  392. cls_preds_, obj_preds_ = cls_preds_.cpu(), obj_preds_.cpu()
  393. with torch.cuda.amp.autocast(enabled=False):
  394. cls_preds_ = cls_preds_.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_() * obj_preds_.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
  395. pair_wise_cls_loss = F.binary_cross_entropy(cls_preds_.sqrt_(), gt_cls_per_image, reduction="none").sum(-1)
  396. del cls_preds_
  397. cost = pair_wise_cls_loss + ious_loss_cost_coeff * pair_wise_ious_loss + outside_boxes_and_center_cost_coeff * (~is_in_boxes_and_center)
  398. # further filter foregrounds: create pairs between cells and ground truth, based on cost and IoUs
  399. num_fg, gt_matched_classes, pred_ious_this_matching, matched_gt_inds = self.dynamic_k_matching(cost, pair_wise_ious, gt_classes, num_gt, fg_mask)
  400. # discard tensors related to cost
  401. del pair_wise_cls_loss, cost, pair_wise_ious, pair_wise_ious_loss
  402. if mode == "cpu":
  403. gt_matched_classes = gt_matched_classes.cuda()
  404. fg_mask = fg_mask.cuda()
  405. pred_ious_this_matching = pred_ious_this_matching.cuda()
  406. matched_gt_inds = matched_gt_inds.cuda()
  407. return gt_matched_classes, fg_mask, pred_ious_this_matching, matched_gt_inds, num_fg
  408. def get_in_boxes_info(self, gt_bboxes_per_image, expanded_strides, x_shifts, y_shifts, total_num_anchors, num_gt):
  409. """
  410. Create a mask for all cells, mask in only foreground: cells that have a center located:
  411. * withing a GT box;
  412. OR
  413. * within a fixed radius around a GT box (center sampling);
  414. :param num_gt: int: Number of ground trunth targets in the image.
  415. :param total_num_anchors: int: Sum of all grid cells.
  416. :param gt_bboxes_per_image: torch.Tensor: Tensor of gt bboxes for the image, shape: (num_gt, 4).
  417. :param expanded_strides: torch.Tensor: Stride of the output grid the prediction is coming from,
  418. shape (1 x num_cells x 1).
  419. :param x_shifts: torch.Tensor: X's in cell coordinates, shape (1,num_cells,1).
  420. :param y_shifts: torch.Tensor: Y's in cell coordinates, shape (1,num_cells,1).
  421. :return is_in_boxes_anchor, is_in_boxes_and_center
  422. where:
  423. - is_in_boxes_anchor masks the cells that their cell center is inside a gt bbox and within
  424. self.center_sampling_radius cells away, without reduction (i.e shape=(num_gts, num_fgs))
  425. - is_in_boxes_and_center masks the cells that their center is either inside a gt bbox or within
  426. self.center_sampling_radius cells away, shape (num_fgs)
  427. """
  428. expanded_strides_per_image = expanded_strides[0]
  429. # cell coordinates, shape [n_predictions] -> repeated to [n_gts, n_predictions]
  430. x_shifts_per_image = x_shifts[0] * expanded_strides_per_image
  431. y_shifts_per_image = y_shifts[0] * expanded_strides_per_image
  432. x_centers_per_image = (x_shifts_per_image + 0.5 * expanded_strides_per_image).unsqueeze(0).repeat(num_gt, 1)
  433. y_centers_per_image = (y_shifts_per_image + 0.5 * expanded_strides_per_image).unsqueeze(0).repeat(num_gt, 1)
  434. # FIND CELL CENTERS THAT ARE WITHIN GROUND TRUTH BOXES
  435. # ground truth boxes, shape [n_gts] -> repeated to [n_gts, n_predictions]
  436. # from (c1, c2, w, h) to left, right, top, bottom
  437. gt_bboxes_per_image_l = (gt_bboxes_per_image[:, 0] - 0.5 * gt_bboxes_per_image[:, 2]).unsqueeze(1).repeat(1, total_num_anchors)
  438. gt_bboxes_per_image_r = (gt_bboxes_per_image[:, 0] + 0.5 * gt_bboxes_per_image[:, 2]).unsqueeze(1).repeat(1, total_num_anchors)
  439. gt_bboxes_per_image_t = (gt_bboxes_per_image[:, 1] - 0.5 * gt_bboxes_per_image[:, 3]).unsqueeze(1).repeat(1, total_num_anchors)
  440. gt_bboxes_per_image_b = (gt_bboxes_per_image[:, 1] + 0.5 * gt_bboxes_per_image[:, 3]).unsqueeze(1).repeat(1, total_num_anchors)
  441. # check which cell centers lay within the ground truth boxes
  442. b_l = x_centers_per_image - gt_bboxes_per_image_l # x - l > 0 when l is on the lest from x
  443. b_r = gt_bboxes_per_image_r - x_centers_per_image
  444. b_t = y_centers_per_image - gt_bboxes_per_image_t
  445. b_b = gt_bboxes_per_image_b - y_centers_per_image
  446. bbox_deltas = torch.stack([b_l, b_t, b_r, b_b], 2) # shape [n_gts, n_predictions]
  447. # to claim that a cell center is inside a gt box all 4 differences calculated above should be positive
  448. is_in_boxes = bbox_deltas.min(dim=-1).values > 0.0 # shape [n_gts, n_predictions]
  449. is_in_boxes_all = is_in_boxes.sum(dim=0) > 0 # shape [n_predictions], whether a cell is inside at least one gt
  450. # FIND CELL CENTERS THAT ARE WITHIN +- self.center_sampling_radius CELLS FROM GROUND TRUTH BOXES CENTERS
  451. # define fake boxes: instead of ground truth boxes step +- self.center_sampling_radius from their centers
  452. gt_bboxes_per_image_l = (gt_bboxes_per_image[:, 0]).unsqueeze(1).repeat(
  453. 1, total_num_anchors
  454. ) - self.center_sampling_radius * expanded_strides_per_image.unsqueeze(0)
  455. gt_bboxes_per_image_r = (gt_bboxes_per_image[:, 0]).unsqueeze(1).repeat(
  456. 1, total_num_anchors
  457. ) + self.center_sampling_radius * expanded_strides_per_image.unsqueeze(0)
  458. gt_bboxes_per_image_t = (gt_bboxes_per_image[:, 1]).unsqueeze(1).repeat(
  459. 1, total_num_anchors
  460. ) - self.center_sampling_radius * expanded_strides_per_image.unsqueeze(0)
  461. gt_bboxes_per_image_b = (gt_bboxes_per_image[:, 1]).unsqueeze(1).repeat(
  462. 1, total_num_anchors
  463. ) + self.center_sampling_radius * expanded_strides_per_image.unsqueeze(0)
  464. c_l = x_centers_per_image - gt_bboxes_per_image_l
  465. c_r = gt_bboxes_per_image_r - x_centers_per_image
  466. c_t = y_centers_per_image - gt_bboxes_per_image_t
  467. c_b = gt_bboxes_per_image_b - y_centers_per_image
  468. center_deltas = torch.stack([c_l, c_t, c_r, c_b], 2)
  469. is_in_centers = center_deltas.min(dim=-1).values > 0.0
  470. is_in_centers_all = is_in_centers.sum(dim=0) > 0
  471. # in boxes OR in centers
  472. is_in_boxes_anchor = is_in_boxes_all | is_in_centers_all
  473. # in boxes AND in centers, preserving a shape [num_GTs x num_FGs]
  474. is_in_boxes_and_center = is_in_boxes[:, is_in_boxes_anchor] & is_in_centers[:, is_in_boxes_anchor]
  475. return is_in_boxes_anchor, is_in_boxes_and_center
  476. def dynamic_k_matching(self, cost, pair_wise_ious, gt_classes, num_gt, fg_mask):
  477. """
  478. :param cost: pairwise cost, [num_FGs x num_GTs]
  479. :param pair_wise_ious: pairwise IoUs, [num_FGs x num_GTs]
  480. :param gt_classes: class of each GT
  481. :param num_gt: number of GTs
  482. :return num_fg, (number of foregrounds)
  483. gt_matched_classes, (the classes that have been matched with fgs)
  484. pred_ious_this_matching
  485. matched_gt_inds
  486. """
  487. # create a matrix with shape [num_GTs x num_FGs]
  488. matching_matrix = torch.zeros_like(cost, dtype=torch.uint8)
  489. # for each GT get a dynamic k of foregrounds with a minimum cost: k = int(sum[top 10 IoUs])
  490. ious_in_boxes_matrix = pair_wise_ious
  491. n_candidate_k = min(10, ious_in_boxes_matrix.size(1))
  492. topk_ious, _ = torch.topk(ious_in_boxes_matrix, n_candidate_k, dim=1)
  493. dynamic_ks = torch.clamp(topk_ious.sum(1).int(), min=1)
  494. dynamic_ks = dynamic_ks.tolist()
  495. for gt_idx in range(num_gt):
  496. try:
  497. _, pos_idx = torch.topk(cost[gt_idx], k=dynamic_ks[gt_idx], largest=False)
  498. except Exception:
  499. logger.warning("cost[gt_idx]: " + str(cost[gt_idx]) + " dynamic_ks[gt_idx]L " + str(dynamic_ks[gt_idx]))
  500. matching_matrix[gt_idx][pos_idx] = 1
  501. del topk_ious, dynamic_ks, pos_idx
  502. # leave at most one GT per foreground, chose the one with the smallest cost
  503. anchor_matching_gt = matching_matrix.sum(0)
  504. if (anchor_matching_gt > 1).sum() > 0:
  505. _, cost_argmin = torch.min(cost[:, anchor_matching_gt > 1], dim=0)
  506. matching_matrix[:, anchor_matching_gt > 1] *= 0
  507. matching_matrix[cost_argmin, anchor_matching_gt > 1] = 1
  508. fg_mask_inboxes = matching_matrix.sum(0) > 0
  509. num_fg = fg_mask_inboxes.sum().item()
  510. fg_mask[fg_mask.clone()] = fg_mask_inboxes
  511. matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)
  512. gt_matched_classes = gt_classes[matched_gt_inds]
  513. pred_ious_this_matching = (matching_matrix * pair_wise_ious).sum(0)[fg_mask_inboxes]
  514. return num_fg, gt_matched_classes, pred_ious_this_matching, matched_gt_inds
  515. class YoloXFastDetectionLoss(YoloXDetectionLoss):
  516. """
  517. A completely new implementation of YOLOX loss.
  518. This is NOT an equivalent implementation to the regular yolox loss.
  519. * Completely avoids using loops compared to the nested loops in the original implementation.
  520. As a result runs much faster (speedup depends on the type of GPUs, their count, the batch size, etc.).
  521. * Tensors format is very different the original implementation.
  522. Tensors contain image ids, ground truth ids and anchor ids as values to support variable length data.
  523. * There are differences in terms of the algorithm itself:
  524. 1. When computing a dynamic k for a ground truth,
  525. in the original implementation they consider the sum of top 10 predictions sorted by ious among the initial
  526. foregrounds of any ground truth in the image,
  527. while in our implementation we consider only the initial foreground of that particular ground truth.
  528. To compensate for that difference we introduce the dynamic_ks_bias hyperparamter which makes the dynamic ks larger.
  529. 2. When computing the k matched detections for a ground truth,
  530. in the original implementation they consider the initial foregrounds of any ground truth in the image as candidates,
  531. while in our implementation we consider only the initial foreground of that particular ground truth as candidates.
  532. We believe that this difference is minor.
  533. :param dynamic_ks_bias: hyperparameter to compensate for the discrepancies between the regular loss and this loss.
  534. :param sync_num_fgs: sync num of fgs.
  535. Can be used for DDP training.
  536. :param obj_loss_fix: devide by total of num anchors instead num of matching fgs.
  537. Can be used for objectness loss.
  538. """
  539. def __init__(
  540. self, strides, num_classes, use_l1=False, center_sampling_radius=2.5, iou_type="iou", dynamic_ks_bias=1.1, sync_num_fgs=False, obj_loss_fix=False
  541. ):
  542. super().__init__(strides=strides, num_classes=num_classes, use_l1=use_l1, center_sampling_radius=center_sampling_radius, iou_type=iou_type)
  543. self.dynamic_ks_bias = dynamic_ks_bias
  544. self.sync_num_fgs = sync_num_fgs
  545. self.obj_loss_fix = obj_loss_fix
  546. def _compute_loss(self, predictions: List[torch.Tensor], targets: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
  547. """
  548. L = L_objectness + L_iou + L_classification + 1[no_aug_epoch]*L_l1
  549. where:
  550. * L_iou, L_classification and L_l1 are calculated only between cells and targets that suit them;
  551. * L_objectness is calculated for all cells.
  552. L_classification:
  553. for cells that have suitable ground truths in their grid locations add BCEs
  554. to force a prediction of IoU with a GT in a multi-label way
  555. Coef: 1.
  556. L_iou:
  557. for cells that have suitable ground truths in their grid locations
  558. add (1 - IoU^2), IoU between a predicted box and each GT box, force maximum IoU
  559. Coef: 1.
  560. L_l1:
  561. for cells that have suitable ground truths in their grid locations
  562. l1 distance between the logits and GTs in “logits” format (the inverse of “logits to predictions” ops)
  563. Coef: 1[no_aug_epoch]
  564. L_objectness:
  565. for each cell add BCE with a label of 1 if there is GT assigned to the cell
  566. Coef: 5
  567. :param predictions: output from all Yolo levels, each of shape
  568. [Batch x Num_Anchors x GridSizeY x GridSizeX x (4 + 1 + Num_classes)]
  569. :param targets: [Num_targets x (4 + 2)], values on dim 1 are: image id in a batch, class, box x y w h
  570. :return: loss, all losses separately in a detached tensor
  571. """
  572. x_shifts, y_shifts, expanded_strides, transformed_outputs, raw_outputs = self.prepare_predictions(predictions)
  573. bbox_preds = transformed_outputs[:, :, :4] # [batch, n_anchors_all, 4]
  574. obj_preds = transformed_outputs[:, :, 4:5] # [batch, n_anchors_all, 1]
  575. cls_preds = transformed_outputs[:, :, 5:] # [batch, n_anchors_all, n_cls]
  576. # assign cells to ground truths, at most one GT per cell
  577. matched_fg_ids, matched_gt_classes, matched_gt_ids, matched_img_ids, matched_ious, flattened_gts = self._compute_matching(
  578. bbox_preds, cls_preds, obj_preds, expanded_strides, x_shifts, y_shifts, targets
  579. )
  580. num_gts = max(flattened_gts.shape[0], 1)
  581. num_fg = max(matched_gt_ids.shape[0], 1)
  582. total_num_anchors = max(transformed_outputs.shape[0] * transformed_outputs.shape[1], 1)
  583. cls_targets = F.one_hot(matched_gt_classes.to(torch.int64), self.num_classes) * matched_ious.unsqueeze(dim=1)
  584. obj_targets = transformed_outputs.new_zeros((transformed_outputs.shape[0], transformed_outputs.shape[1]))
  585. obj_targets[matched_img_ids, matched_fg_ids] = 1
  586. reg_targets = flattened_gts[matched_gt_ids][:, 1:]
  587. if self.use_l1:
  588. l1_targets = self.get_l1_target(
  589. transformed_outputs.new_zeros((num_fg, 4)),
  590. flattened_gts[matched_gt_ids][:, 1:],
  591. expanded_strides.squeeze()[matched_fg_ids],
  592. x_shifts=x_shifts.squeeze()[matched_fg_ids],
  593. y_shifts=y_shifts.squeeze()[matched_fg_ids],
  594. )
  595. if self.sync_num_fgs and dist.group.WORLD is not None:
  596. num_fg = torch.scalar_tensor(num_fg).to(matched_gt_ids.device)
  597. dist.all_reduce(num_fg, op=torch._C._distributed_c10d.ReduceOp.AVG)
  598. loss_iou = self.iou_loss(bbox_preds[matched_img_ids, matched_fg_ids], reg_targets).sum() / num_fg
  599. loss_obj = self.bcewithlog_loss(obj_preds.squeeze(-1), obj_targets).sum() / (total_num_anchors if self.obj_loss_fix else num_fg)
  600. loss_cls = self.bcewithlog_loss(cls_preds[matched_img_ids, matched_fg_ids], cls_targets).sum() / num_fg
  601. if self.use_l1:
  602. loss_l1 = self.l1_loss(raw_outputs[matched_img_ids, matched_fg_ids], l1_targets).sum() / num_fg
  603. else:
  604. loss_l1 = 0.0
  605. reg_weight = 5.0
  606. loss = reg_weight * loss_iou + loss_obj + loss_cls + loss_l1
  607. return (
  608. loss,
  609. torch.cat(
  610. (
  611. loss_iou.unsqueeze(0),
  612. loss_obj.unsqueeze(0),
  613. loss_cls.unsqueeze(0),
  614. torch.tensor(loss_l1).unsqueeze(0).to(transformed_outputs.device),
  615. torch.tensor(num_fg / max(num_gts, 1)).unsqueeze(0).to(transformed_outputs.device),
  616. loss.unsqueeze(0),
  617. )
  618. ).detach(),
  619. )
  620. def _get_initial_matching(
  621. self, gt_bboxes: torch.Tensor, expanded_strides: torch.Tensor, x_shifts: torch.Tensor, y_shifts: torch.Tensor
  622. ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
  623. """
  624. Get candidates using a mask for all cells.
  625. Mask in only foreground cells that have a center located:
  626. * withing a GT box (param: is_in_boxes);
  627. OR
  628. * within a fixed radius around a GT box (center sampling) (param: is_in_centers);
  629. return:
  630. initial_matching: get a list of candidates pairs of (gt box id, anchor box id) based on cell = is_in_boxes | is_in_centers.
  631. shape: [num_candidates, 2]
  632. strong candidate mask: get a list whether a candidate is a strong one or not.
  633. strong candidate is a cell from is_in_boxes & is_in_centers.
  634. shape: [num_candidates].
  635. """
  636. cell_x_centers = (x_shifts + 0.5) * expanded_strides
  637. cell_y_centers = (y_shifts + 0.5) * expanded_strides
  638. gt_bboxes_x_centers = gt_bboxes[:, 0].unsqueeze(1)
  639. gt_bboxes_y_centers = gt_bboxes[:, 1].unsqueeze(1)
  640. gt_bboxes_half_w = (0.5 * gt_bboxes[:, 2]).unsqueeze(1)
  641. gt_bboxes_half_h = (0.5 * gt_bboxes[:, 3]).unsqueeze(1)
  642. is_in_boxes = (
  643. (cell_x_centers > gt_bboxes_x_centers - gt_bboxes_half_w)
  644. & (gt_bboxes_x_centers + gt_bboxes_half_w > cell_x_centers)
  645. & (cell_y_centers > gt_bboxes_y_centers - gt_bboxes_half_h)
  646. & (gt_bboxes_y_centers + gt_bboxes_half_h > cell_y_centers)
  647. )
  648. radius_shifts = 2.5 * expanded_strides
  649. is_in_centers = (
  650. (cell_x_centers + radius_shifts > gt_bboxes_x_centers)
  651. & (gt_bboxes_x_centers > cell_x_centers - radius_shifts)
  652. & (cell_y_centers + radius_shifts > gt_bboxes_y_centers)
  653. & (gt_bboxes_y_centers > cell_y_centers - radius_shifts)
  654. )
  655. initial_mask = is_in_boxes | is_in_centers
  656. initial_matching = initial_mask.nonzero()
  657. strong_candidate_mask = (is_in_boxes & is_in_centers)[initial_mask]
  658. return initial_matching[:, 0], initial_matching[:, 1], strong_candidate_mask
  659. @torch.no_grad()
  660. def _compute_matching(
  661. self,
  662. bbox_preds: torch.Tensor,
  663. cls_preds: torch.Tensor,
  664. obj_preds: torch.Tensor,
  665. expanded_strides: torch.Tensor,
  666. x_shifts: torch.Tensor,
  667. y_shifts: torch.Tensor,
  668. labels: torch.Tensor,
  669. ious_loss_cost_coeff: float = 3.0,
  670. outside_boxes_and_center_cost_coeff: float = 100000.0,
  671. ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
  672. """
  673. Match cells to ground truth:
  674. * at most 1 GT per cell
  675. * dynamic number of cells per GT
  676. :param bbox_preds: predictions of bounding boxes. shape [batch, n_anchors_all, 4]
  677. :param cls_preds: predictions of class. shape [batch, n_anchors_all, n_cls]
  678. :param obj_preds: predictions for objectness. shape [batch, n_anchors_all, 1]
  679. :param expanded_strides: stride of the output grid the prediction is coming from. shape [1, n_anchors_all]
  680. :param x_shifts: x coordinate on the grid cell the prediction is coming from. shape [1, n_anchors_all]
  681. :param y_shifts: y coordinate on the grid cell the prediction is coming from. shape [1, n_anchors_all]
  682. :param labels: labels for each grid cell. shape [n_anchors_all, (4 + 2)]
  683. :return: candidate_fg_ids shape [num_fg]
  684. candidate_gt_classes shape [num_fg]
  685. candidate_gt_ids shape [num_fg]
  686. candidate_img_ids shape [num_fg]
  687. candidate_ious shape [num_fg]
  688. flattened_gts shape [num_gts, 5]
  689. """
  690. flattened_gts, gt_id_to_img_id = labels[:, 1:], labels[:, 0].type(torch.int64)
  691. # COMPUTE CANDIDATES
  692. candidate_gt_ids, candidate_fg_ids, strong_candidate_mask = self._get_initial_matching(flattened_gts[:, 1:], expanded_strides, x_shifts, y_shifts)
  693. candidate_img_ids = gt_id_to_img_id[candidate_gt_ids]
  694. candidate_gts_bbox = flattened_gts[candidate_gt_ids, 1:]
  695. candidate_det_bbox = bbox_preds[candidate_img_ids, candidate_fg_ids]
  696. # COMPUTE DYNAMIC KS
  697. candidate_ious = self._calculate_pairwise_bbox_iou(candidate_gts_bbox, candidate_det_bbox, xyxy=False)
  698. dynamic_ks, matching_index_to_dynamic_k_index = self._compute_dynamic_ks(candidate_gt_ids, candidate_ious, self.dynamic_ks_bias)
  699. del candidate_gts_bbox, candidate_det_bbox
  700. # ORDER CANDIDATES BY COST
  701. candidate_gt_classes = flattened_gts[candidate_gt_ids, 0]
  702. cost_order = self._compute_cost_order(
  703. self.num_classes,
  704. candidate_img_ids,
  705. candidate_gt_classes,
  706. candidate_fg_ids,
  707. candidate_ious,
  708. cls_preds,
  709. obj_preds,
  710. strong_candidate_mask,
  711. ious_loss_cost_coeff,
  712. outside_boxes_and_center_cost_coeff,
  713. )
  714. candidate_gt_ids = candidate_gt_ids[cost_order]
  715. candidate_gt_classes = candidate_gt_classes[cost_order]
  716. candidate_img_ids = candidate_img_ids[cost_order]
  717. candidate_fg_ids = candidate_fg_ids[cost_order]
  718. candidate_ious = candidate_ious[cost_order]
  719. matching_index_to_dynamic_k_index = matching_index_to_dynamic_k_index[cost_order]
  720. del cost_order
  721. # FILTER MATCHING TO LOWEST K COST MATCHES PER GT
  722. ranks = self._compute_ranks(candidate_gt_ids)
  723. corresponding_dynamic_ks = dynamic_ks[matching_index_to_dynamic_k_index]
  724. topk_mask = ranks < corresponding_dynamic_ks
  725. candidate_gt_ids = candidate_gt_ids[topk_mask]
  726. candidate_gt_classes = candidate_gt_classes[topk_mask]
  727. candidate_img_ids = candidate_img_ids[topk_mask]
  728. candidate_fg_ids = candidate_fg_ids[topk_mask]
  729. candidate_ious = candidate_ious[topk_mask]
  730. del ranks, topk_mask, dynamic_ks, matching_index_to_dynamic_k_index, corresponding_dynamic_ks
  731. # FILTER MATCHING TO AT MOST 1 MATCH FOR DET BY TAKING THE LOWEST COST MATCH
  732. candidate_img_and_fg_ids_combined = self._combine_candidates_img_id_fg_id(candidate_img_ids, candidate_fg_ids)
  733. top1_mask = self._compute_is_first_mask(candidate_img_and_fg_ids_combined)
  734. candidate_gt_ids = candidate_gt_ids[top1_mask]
  735. candidate_gt_classes = candidate_gt_classes[top1_mask]
  736. candidate_fg_ids = candidate_fg_ids[top1_mask]
  737. candidate_img_ids = candidate_img_ids[top1_mask]
  738. candidate_ious = candidate_ious[top1_mask]
  739. return candidate_fg_ids, candidate_gt_classes, candidate_gt_ids, candidate_img_ids, candidate_ious, flattened_gts
  740. def _combine_candidates_img_id_fg_id(self, candidate_img_ids, candidate_anchor_ids):
  741. """
  742. Create one dim tensor with unique pairs of img_id and fg_id.
  743. e.g: candidate_img_ids = [0,1,0,0]
  744. candidate_fg_ids = [0,0,0,1]
  745. result = [0,1,0,2]
  746. """
  747. candidate_img_and_fg_ids_combined = torch.stack((candidate_img_ids, candidate_anchor_ids), dim=1).unique(dim=0, return_inverse=True)[1]
  748. return candidate_img_and_fg_ids_combined
  749. def _compute_dynamic_ks(self, ids: torch.Tensor, ious: torch.Tensor, dynamic_ks_bias) -> torch.Tensor:
  750. """
  751. :param ids: ids of GTs, shape: [num_candidates]
  752. :param ious: pairwise IoUs, shape: [num_candidates]
  753. :param dynamic_ks_bias: multiply the resulted k to compensate the regular loss
  754. """
  755. assert len(ids.shape) == 1, "ids must be of shape [num_candidates]"
  756. assert len(ious.shape) == 1, "ious must be of shape [num_candidates]"
  757. assert ids.shape[0] == ious.shape[0], "num of ids.shape[0] must be the same as num of ious.shape[0]"
  758. # sort ious and ids by ious
  759. ious, ious_argsort = ious.sort(descending=True)
  760. ids = ids[ious_argsort]
  761. # stable sort indices, so that ious are first sorted by id and second by value
  762. ids, ids_argsort = ids.sort(stable=True)
  763. ious = ious[ids_argsort]
  764. unique_ids, ids_index_to_unique_ids_index = ids.unique_consecutive(dim=0, return_inverse=True)
  765. num_unique_ids = unique_ids.shape[0]
  766. if ids.shape[0] > 10:
  767. is_in_top_10 = torch.cat((torch.ones((10,), dtype=torch.bool, device=ids.device), ids[10:] != ids[:-10]))
  768. else:
  769. is_in_top_10 = torch.ones_like(ids, dtype=torch.bool)
  770. dynamic_ks = torch.zeros((num_unique_ids,), dtype=ious.dtype, device=ious.device)
  771. dynamic_ks.index_put_((ids_index_to_unique_ids_index,), is_in_top_10 * ious, accumulate=True)
  772. if dynamic_ks_bias is not None:
  773. dynamic_ks *= dynamic_ks_bias
  774. dynamic_ks = dynamic_ks.long().clamp(min=1)
  775. all_argsort = ious_argsort[ids_argsort]
  776. inverse_all_argsort = torch.zeros_like(ious_argsort)
  777. inverse_all_argsort[all_argsort] = torch.arange(all_argsort.shape[0], dtype=all_argsort.dtype, device=all_argsort.device)
  778. return dynamic_ks, ids_index_to_unique_ids_index[inverse_all_argsort]
  779. def _compute_cost_order(
  780. self,
  781. num_classes,
  782. candidate_gt_img_ids: torch.Tensor,
  783. candidate_gt_classes: torch.Tensor,
  784. candidate_anchor_ids: torch.Tensor,
  785. candidate_ious: torch.Tensor,
  786. cls_preds: torch.Tensor,
  787. obj_preds: torch.Tensor,
  788. strong_candidate_mask: torch.Tensor,
  789. ious_loss_cost_coeff: float,
  790. outside_boxes_and_center_cost_coeff: float,
  791. ) -> torch.Tensor:
  792. gt_cls_per_image = F.one_hot(candidate_gt_classes.to(torch.int64), num_classes).float()
  793. with torch.cuda.amp.autocast(enabled=False):
  794. cls_preds_ = (
  795. cls_preds[candidate_gt_img_ids, candidate_anchor_ids].float().sigmoid_()
  796. * obj_preds[candidate_gt_img_ids, candidate_anchor_ids].float().sigmoid_()
  797. )
  798. pair_wise_cls_cost = F.binary_cross_entropy(cls_preds_.sqrt_(), gt_cls_per_image, reduction="none").sum(-1)
  799. ious_cost = -torch.log(candidate_ious + 1e-8)
  800. cost = pair_wise_cls_cost + ious_loss_cost_coeff * ious_cost + outside_boxes_and_center_cost_coeff * strong_candidate_mask.logical_not()
  801. return cost.argsort()
  802. def _calculate_pairwise_bbox_iou(self, bboxes_a: torch.Tensor, bboxes_b: torch.Tensor, xyxy=True) -> torch.Tensor:
  803. if bboxes_a.shape[1] != 4 or bboxes_b.shape[1] != 4:
  804. raise IndexError
  805. if xyxy:
  806. tl = torch.max(bboxes_a[:, :2], bboxes_b[:, :2])
  807. br = torch.min(bboxes_a[:, 2:], bboxes_b[:, 2:])
  808. area_a = torch.prod(bboxes_a[:, 2:] - bboxes_a[:, :2], 1)
  809. area_b = torch.prod(bboxes_b[:, 2:] - bboxes_b[:, :2], 1)
  810. else:
  811. tl = torch.max(
  812. (bboxes_a[:, :2] - bboxes_a[:, 2:] / 2),
  813. (bboxes_b[:, :2] - bboxes_b[:, 2:] / 2),
  814. )
  815. br = torch.min(
  816. (bboxes_a[:, :2] + bboxes_a[:, 2:] / 2),
  817. (bboxes_b[:, :2] + bboxes_b[:, 2:] / 2),
  818. )
  819. area_a = torch.prod(bboxes_a[:, 2:], 1)
  820. area_b = torch.prod(bboxes_b[:, 2:], 1)
  821. en = (tl < br).prod(dim=1)
  822. area_i = torch.prod(br - tl, 1) * en
  823. return area_i / (area_a + area_b - area_i)
  824. def _compute_ranks(self, ids: torch.Tensor) -> torch.Tensor:
  825. ids, ids_argsort = ids.sort(stable=True)
  826. if ids.shape[0] > 1:
  827. is_not_first = torch.cat((torch.zeros((1,), dtype=torch.bool, device=ids.device), ids[1:] == ids[:-1]))
  828. else:
  829. is_not_first = torch.zeros_like(ids, dtype=torch.bool)
  830. subtract = torch.arange(ids.shape[0], dtype=ids_argsort.dtype, device=ids.device)
  831. subtract[is_not_first] = 0
  832. subtract = subtract.cummax(dim=0)[0]
  833. rank = torch.arange(ids.shape[0], dtype=ids_argsort.dtype, device=ids.device) - subtract
  834. inverse_argsort = torch.zeros_like(ids_argsort)
  835. inverse_argsort[ids_argsort] = torch.arange(ids_argsort.shape[0], dtype=ids_argsort.dtype, device=ids_argsort.device)
  836. return rank[inverse_argsort]
  837. def _compute_is_first_mask(self, ids: torch.Tensor) -> torch.Tensor:
  838. """
  839. Filter fg that matches two gts.
  840. """
  841. ids, ids_argsort = ids.sort(stable=True)
  842. if ids.shape[0] > 1:
  843. is_first = torch.cat((torch.ones((1,), dtype=torch.bool, device=ids.device), ids[1:] != ids[:-1]))
  844. else:
  845. is_first = torch.ones_like(ids, dtype=torch.bool)
  846. inverse_argsort = torch.zeros_like(ids_argsort)
  847. inverse_argsort[ids_argsort] = torch.arange(ids_argsort.shape[0], dtype=ids_argsort.dtype, device=ids_argsort.device)
  848. return is_first[inverse_argsort]
Discard
Tip!

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