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

#716 Fix mapilliary_dataset yaml

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:hotfix/SG-000-fix_mapilliary_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
  1. from typing import Mapping, Tuple, Union
  2. import numpy as np
  3. import torch
  4. import torch.nn.functional as F
  5. from torch import nn, Tensor
  6. import super_gradients
  7. from super_gradients.training.datasets.data_formats.bbox_formats.cxcywh import cxcywh_to_xyxy
  8. from super_gradients.training.utils.bbox_utils import batch_distance2bbox
  9. from super_gradients.training.utils.distributed_training_utils import (
  10. get_world_size,
  11. )
  12. def batch_iou_similarity(box1, box2, eps=1e-9):
  13. """Calculate iou of box1 and box2 in batch. Bboxes are expected to be in x1y1x2y2 format.
  14. Args:
  15. box1 (Tensor): box with the shape [N, M1, 4]
  16. box2 (Tensor): box with the shape [N, M2, 4]
  17. Return:
  18. iou (Tensor): iou between box1 and box2 with the shape [N, M1, M2]
  19. """
  20. box1 = box1.unsqueeze(2) # [N, M1, 4] -> [N, M1, 1, 4]
  21. box2 = box2.unsqueeze(1) # [N, M2, 4] -> [N, 1, M2, 4]
  22. px1y1, px2y2 = box1[:, :, :, 0:2], box1[:, :, :, 2:4]
  23. gx1y1, gx2y2 = box2[:, :, :, 0:2], box2[:, :, :, 2:4]
  24. x1y1 = torch.maximum(px1y1, gx1y1)
  25. x2y2 = torch.minimum(px2y2, gx2y2)
  26. overlap = (x2y2 - x1y1).clip(0).prod(-1)
  27. area1 = (px2y2 - px1y1).clip(0).prod(-1)
  28. area2 = (gx2y2 - gx1y1).clip(0).prod(-1)
  29. union = area1 + area2 - overlap + eps
  30. return overlap / union
  31. def iou_similarity(box1, box2, eps=1e-10):
  32. """
  33. Calculate iou of box1 and box2. Bboxes are expected to be in x1y1x2y2 format.
  34. Args:
  35. box1 (Tensor): box with the shape [M1, 4]
  36. box2 (Tensor): box with the shape [M2, 4]
  37. Return:
  38. iou (Tensor): iou between box1 and box2 with the shape [M1, M2]
  39. """
  40. box1 = box1.unsqueeze(1) # [M1, 4] -> [M1, 1, 4]
  41. box2 = box2.unsqueeze(0) # [M2, 4] -> [1, M2, 4]
  42. px1y1, px2y2 = box1[:, :, 0:2], box1[:, :, 2:4]
  43. gx1y1, gx2y2 = box2[:, :, 0:2], box2[:, :, 2:4]
  44. x1y1 = torch.maximum(px1y1, gx1y1)
  45. x2y2 = torch.minimum(px2y2, gx2y2)
  46. overlap = (x2y2 - x1y1).clip(0).prod(-1)
  47. area1 = (px2y2 - px1y1).clip(0).prod(-1)
  48. area2 = (gx2y2 - gx1y1).clip(0).prod(-1)
  49. union = area1 + area2 - overlap + eps
  50. return overlap / union
  51. def bbox_overlaps(bboxes1, bboxes2, mode="iou", is_aligned=False, eps=1e-6):
  52. """Calculate overlap between two set of bboxes.
  53. If ``is_aligned `` is ``False``, then calculate the overlaps between each
  54. bbox of bboxes1 and bboxes2, otherwise the overlaps between each aligned
  55. pair of bboxes1 and bboxes2.
  56. Args:
  57. bboxes1 (Tensor): shape (B, m, 4) in <x1, y1, x2, y2> format or empty.
  58. bboxes2 (Tensor): shape (B, n, 4) in <x1, y1, x2, y2> format or empty.
  59. B indicates the batch dim, in shape (B1, B2, ..., Bn).
  60. If ``is_aligned `` is ``True``, then m and n must be equal.
  61. mode (str): "iou" (intersection over union) or "iof" (intersection over
  62. foreground).
  63. is_aligned (bool, optional): If True, then m and n must be equal.
  64. Default False.
  65. eps (float, optional): A value added to the denominator for numerical
  66. stability. Default 1e-6.
  67. Returns:
  68. Tensor: shape (m, n) if ``is_aligned `` is False else shape (m,)
  69. """
  70. assert mode in ["iou", "iof", "giou"], "Unsupported mode {}".format(mode)
  71. # Either the boxes are empty or the length of boxes's last dimenstion is 4
  72. assert bboxes1.shape[-1] == 4 or bboxes1.shape[0] == 0
  73. assert bboxes2.shape[-1] == 4 or bboxes2.shape[0] == 0
  74. # Batch dim must be the same
  75. # Batch dim: (B1, B2, ... Bn)
  76. assert bboxes1.shape[:-2] == bboxes2.shape[:-2]
  77. batch_shape = bboxes1.shape[:-2]
  78. rows = bboxes1.shape[-2] if bboxes1.shape[0] > 0 else 0
  79. cols = bboxes2.shape[-2] if bboxes2.shape[0] > 0 else 0
  80. if is_aligned:
  81. assert rows == cols
  82. if rows * cols == 0:
  83. if is_aligned:
  84. return np.random.random(batch_shape + (rows,))
  85. else:
  86. return np.random.random(batch_shape + (rows, cols))
  87. area1 = (bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] - bboxes1[..., 1])
  88. area2 = (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] - bboxes2[..., 1])
  89. if is_aligned:
  90. lt = np.maximum(bboxes1[..., :2], bboxes2[..., :2]) # [B, rows, 2]
  91. rb = np.minimum(bboxes1[..., 2:], bboxes2[..., 2:]) # [B, rows, 2]
  92. wh = (rb - lt).clip(min=0) # [B, rows, 2]
  93. overlap = wh[..., 0] * wh[..., 1]
  94. if mode in ["iou", "giou"]:
  95. union = area1 + area2 - overlap
  96. else:
  97. union = area1
  98. if mode == "giou":
  99. enclosed_lt = np.minimum(bboxes1[..., :2], bboxes2[..., :2])
  100. enclosed_rb = np.maximum(bboxes1[..., 2:], bboxes2[..., 2:])
  101. else:
  102. lt = np.maximum(bboxes1[..., :, None, :2], bboxes2[..., None, :, :2]) # [B, rows, cols, 2]
  103. rb = np.minimum(bboxes1[..., :, None, 2:], bboxes2[..., None, :, 2:]) # [B, rows, cols, 2]
  104. wh = (rb - lt).clip(min=0) # [B, rows, cols, 2]
  105. overlap = wh[..., 0] * wh[..., 1]
  106. if mode in ["iou", "giou"]:
  107. union = area1[..., None] + area2[..., None, :] - overlap
  108. else:
  109. union = area1[..., None]
  110. if mode == "giou":
  111. enclosed_lt = np.minimum(bboxes1[..., :, None, :2], bboxes2[..., None, :, :2])
  112. enclosed_rb = np.maximum(bboxes1[..., :, None, 2:], bboxes2[..., None, :, 2:])
  113. eps = np.array([eps])
  114. union = np.maximum(union, eps)
  115. ious = overlap / union
  116. if mode in ["iou", "iof"]:
  117. return ious
  118. # calculate gious
  119. enclose_wh = (enclosed_rb - enclosed_lt).clip(min=0)
  120. enclose_area = enclose_wh[..., 0] * enclose_wh[..., 1]
  121. enclose_area = np.maximum(enclose_area, eps)
  122. gious = ious - (enclose_area - union) / enclose_area
  123. return gious
  124. def topk_(input, k, axis=1, largest=True):
  125. x = -input if largest else input
  126. if axis == 0:
  127. row_index = np.arange(input.shape[1 - axis])
  128. topk_index = np.argpartition(x, k, axis=axis)[0:k, :]
  129. topk_data = x[topk_index, row_index]
  130. topk_index_sort = np.argsort(topk_data, axis=axis)
  131. topk_data_sort = topk_data[topk_index_sort, row_index]
  132. topk_index_sort = topk_index[0:k, :][topk_index_sort, row_index]
  133. else:
  134. column_index = np.arange(x.shape[1 - axis])[:, None]
  135. topk_index = np.argpartition(x, k, axis=axis)[:, 0:k]
  136. topk_data = x[column_index, topk_index]
  137. topk_data = -topk_data if largest else topk_data
  138. topk_index_sort = np.argsort(topk_data, axis=axis)
  139. topk_data_sort = topk_data[column_index, topk_index_sort]
  140. topk_index_sort = topk_index[:, 0:k][column_index, topk_index_sort]
  141. return topk_data_sort, topk_index_sort
  142. def compute_max_iou_anchor(ious: Tensor) -> Tensor:
  143. r"""
  144. For each anchor, find the GT with the largest IOU.
  145. Args:
  146. ious (Tensor, float32): shape[B, n, L], n: num_gts, L: num_anchors
  147. Returns:
  148. is_max_iou (Tensor, float32): shape[B, n, L], value=1. means selected
  149. """
  150. num_max_boxes = ious.shape[-2]
  151. max_iou_index = ious.argmax(dim=-2)
  152. is_max_iou: Tensor = torch.nn.functional.one_hot(max_iou_index, num_max_boxes).permute([0, 2, 1])
  153. return is_max_iou.type_as(ious)
  154. def check_points_inside_bboxes(points: Tensor, bboxes, center_radius_tensor=None, eps=1e-9):
  155. r"""
  156. Args:
  157. points (Tensor, float32): shape[L, 2], "xy" format, L: num_anchors
  158. bboxes (Tensor, float32): shape[B, n, 4], "xmin, ymin, xmax, ymax" format
  159. center_radius_tensor (Tensor, float32): shape [L, 1]. Default: None.
  160. eps (float): Default: 1e-9
  161. Returns:
  162. is_in_bboxes (Tensor, float32): shape[B, n, L], value=1. means selected
  163. """
  164. points = points.unsqueeze(0).unsqueeze(0)
  165. x, y = points.chunk(2, dim=-1)
  166. xmin, ymin, xmax, ymax = bboxes.unsqueeze(2).chunk(4, dim=-1)
  167. # check whether `points` is in `bboxes`
  168. left = x - xmin
  169. top = y - ymin
  170. right = xmax - x
  171. bottom = ymax - y
  172. delta_ltrb = torch.cat([left, top, right, bottom], dim=-1)
  173. is_in_bboxes = delta_ltrb.min(dim=-1).values > eps
  174. if center_radius_tensor is not None:
  175. # check whether `points` is in `center_radius`
  176. center_radius_tensor = center_radius_tensor.unsqueeze(0).unsqueeze(0)
  177. cx = (xmin + xmax) * 0.5
  178. cy = (ymin + ymax) * 0.5
  179. left = x - (cx - center_radius_tensor)
  180. top = y - (cy - center_radius_tensor)
  181. right = (cx + center_radius_tensor) - x
  182. bottom = (cy + center_radius_tensor) - y
  183. delta_ltrb_c = torch.cat([left, top, right, bottom], dim=-1)
  184. is_in_center = delta_ltrb_c.min(dim=-1) > eps
  185. return (torch.logical_and(is_in_bboxes, is_in_center), torch.logical_or(is_in_bboxes, is_in_center))
  186. return is_in_bboxes.type_as(bboxes)
  187. def gather_topk_anchors(metrics, topk, largest=True, topk_mask=None, eps=1e-9):
  188. r"""
  189. Args:
  190. metrics (Tensor, float32): shape[B, n, L], n: num_gts, L: num_anchors
  191. topk (int): The number of top elements to look for along the axis.
  192. largest (bool) : largest is a flag, if set to true,
  193. algorithm will sort by descending order, otherwise sort by
  194. ascending order. Default: True
  195. topk_mask (Tensor, float32): shape[B, n, 1], ignore bbox mask,
  196. Default: None
  197. eps (float): Default: 1e-9
  198. Returns:
  199. is_in_topk (Tensor, float32): shape[B, n, L], value=1. means selected
  200. """
  201. num_anchors = metrics.shape[-1]
  202. topk_metrics, topk_idxs = torch.topk(metrics, topk, dim=-1, largest=largest)
  203. if topk_mask is None:
  204. topk_mask = (topk_metrics.max(dim=-1, keepdim=True).values > eps).type_as(metrics)
  205. is_in_topk = torch.nn.functional.one_hot(topk_idxs, num_anchors).sum(dim=-2).type_as(metrics)
  206. return is_in_topk * topk_mask
  207. def bbox_center(boxes):
  208. """Get bbox centers from boxes.
  209. Args:
  210. boxes (Tensor): boxes with shape (..., 4), "xmin, ymin, xmax, ymax" format.
  211. Returns:
  212. Tensor: boxes centers with shape (..., 2), "cx, cy" format.
  213. """
  214. boxes_cx = (boxes[..., 0] + boxes[..., 2]) / 2
  215. boxes_cy = (boxes[..., 1] + boxes[..., 3]) / 2
  216. return torch.stack([boxes_cx, boxes_cy], dim=-1)
  217. def compute_max_iou_gt(ious):
  218. r"""
  219. For each GT, find the anchor with the largest IOU.
  220. Args:
  221. ious (Tensor, float32): shape[B, n, L], n: num_gts, L: num_anchors
  222. Returns:
  223. is_max_iou (Tensor, float32): shape[B, n, L], value=1. means selected
  224. """
  225. num_anchors = ious.shape[-1]
  226. max_iou_index = ious.argmax(dim=-1)
  227. is_max_iou = torch.nn.functional.one_hot(max_iou_index, num_anchors)
  228. return is_max_iou.astype(ious.dtype)
  229. class ATSSAssigner(nn.Module):
  230. """Bridging the Gap Between Anchor-based and Anchor-free Detection
  231. via Adaptive Training Sample Selection
  232. """
  233. __shared__ = ["num_classes"]
  234. def __init__(self, topk=9, num_classes=80, force_gt_matching=False, eps=1e-9):
  235. """
  236. :param topk: Maximum number of achors that is selected for each gt box
  237. :param num_classes:
  238. :param force_gt_matching: Guarantee that each gt box is matched to at least one anchor.
  239. If two gt boxes match to the same anchor, the one with the larger area will be selected.
  240. And the second-best achnor will be assigned to the other gt box.
  241. :param eps: Small constant for numerical stability
  242. """
  243. super(ATSSAssigner, self).__init__()
  244. self.topk = topk
  245. self.num_classes = num_classes
  246. self.force_gt_matching = force_gt_matching
  247. self.eps = eps
  248. def _gather_topk_pyramid(self, gt2anchor_distances, num_anchors_list, pad_gt_mask):
  249. gt2anchor_distances_list = torch.split(gt2anchor_distances, num_anchors_list, dim=-1)
  250. num_anchors_index = np.cumsum(num_anchors_list).tolist()
  251. num_anchors_index = [
  252. 0,
  253. ] + num_anchors_index[:-1]
  254. is_in_topk_list = []
  255. topk_idxs_list = []
  256. for distances, anchors_index in zip(gt2anchor_distances_list, num_anchors_index):
  257. num_anchors = distances.shape[-1]
  258. _, topk_idxs = torch.topk(distances, self.topk, dim=-1, largest=False)
  259. topk_idxs_list.append(topk_idxs + anchors_index)
  260. is_in_topk = torch.nn.functional.one_hot(topk_idxs, num_anchors).sum(dim=-2).type_as(gt2anchor_distances)
  261. is_in_topk_list.append(is_in_topk * pad_gt_mask)
  262. is_in_topk_list = torch.cat(is_in_topk_list, dim=-1)
  263. topk_idxs_list = torch.cat(topk_idxs_list, dim=-1)
  264. return is_in_topk_list, topk_idxs_list
  265. @torch.no_grad()
  266. def forward(
  267. self,
  268. anchor_bboxes,
  269. num_anchors_list,
  270. gt_labels,
  271. gt_bboxes,
  272. pad_gt_mask,
  273. bg_index,
  274. gt_scores=None,
  275. pred_bboxes=None,
  276. ):
  277. r"""This code is based on
  278. https://github.com/fcjian/TOOD/blob/master/mmdet/core/bbox/assigners/atss_assigner.py
  279. The assignment is done in following steps
  280. 1. compute iou between all bbox (bbox of all pyramid levels) and gt
  281. 2. compute center distance between all bbox and gt
  282. 3. on each pyramid level, for each gt, select k bbox whose center
  283. are closest to the gt center, so we total select k*l bbox as
  284. candidates for each gt
  285. 4. get corresponding iou for the these candidates, and compute the
  286. mean and std, set mean + std as the iou threshold
  287. 5. select these candidates whose iou are greater than or equal to
  288. the threshold as positive
  289. 6. limit the positive sample's center in gt
  290. 7. if an anchor box is assigned to multiple gts, the one with the
  291. highest iou will be selected.
  292. Args:
  293. anchor_bboxes (Tensor, float32): pre-defined anchors, shape(L, 4),
  294. "xmin, xmax, ymin, ymax" format
  295. num_anchors_list (List): num of anchors in each level
  296. gt_labels (Tensor, int64|int32): Label of gt_bboxes, shape(B, n, 1)
  297. gt_bboxes (Tensor, float32): Ground truth bboxes, shape(B, n, 4)
  298. pad_gt_mask (Tensor, float32): 1 means bbox, 0 means no bbox, shape(B, n, 1)
  299. bg_index (int): background index
  300. gt_scores (Tensor|None, float32) Score of gt_bboxes,
  301. shape(B, n, 1), if None, then it will initialize with one_hot label
  302. pred_bboxes (Tensor, float32, optional): predicted bounding boxes, shape(B, L, 4)
  303. Returns:
  304. assigned_labels (Tensor): (B, L)
  305. assigned_bboxes (Tensor): (B, L, 4)
  306. assigned_scores (Tensor): (B, L, C), if pred_bboxes is not None, then output ious
  307. """
  308. assert gt_labels.ndim == gt_bboxes.ndim and gt_bboxes.ndim == 3
  309. num_anchors, _ = anchor_bboxes.shape
  310. batch_size, num_max_boxes, _ = gt_bboxes.shape
  311. # negative batch
  312. if num_max_boxes == 0:
  313. assigned_labels = torch.full([batch_size, num_anchors], bg_index, dtype=torch.long, device=anchor_bboxes.device)
  314. assigned_bboxes = torch.zeros([batch_size, num_anchors, 4], device=anchor_bboxes.device)
  315. assigned_scores = torch.zeros([batch_size, num_anchors, self.num_classes], device=anchor_bboxes.device)
  316. return assigned_labels, assigned_bboxes, assigned_scores
  317. # 1. compute iou between gt and anchor bbox, [B, n, L]
  318. ious = iou_similarity(gt_bboxes.reshape([-1, 4]), anchor_bboxes)
  319. ious = ious.reshape([batch_size, -1, num_anchors])
  320. # 2. compute center distance between all anchors and gt, [B, n, L]
  321. gt_centers = bbox_center(gt_bboxes.reshape([-1, 4])).unsqueeze(1)
  322. anchor_centers = bbox_center(anchor_bboxes)
  323. # gt2anchor_distances = (
  324. # (gt_centers - anchor_centers.unsqueeze(0)).norm(2, dim=-1).reshape([batch_size, -1, num_anchors])
  325. # )
  326. gt2anchor_distances = torch.norm(gt_centers - anchor_centers.unsqueeze(0), p=2, dim=-1).reshape([batch_size, -1, num_anchors])
  327. # 3. on each pyramid level, selecting top-k closest candidates
  328. # based on the center distance, [B, n, L]
  329. is_in_topk, topk_idxs = self._gather_topk_pyramid(gt2anchor_distances, num_anchors_list, pad_gt_mask)
  330. # 4. get corresponding iou for the these candidates, and compute the
  331. # mean and std, 5. set mean + std as the iou threshold
  332. iou_candidates = ious * is_in_topk
  333. iou_threshold = torch.gather(iou_candidates.flatten(end_dim=-2), dim=1, index=topk_idxs.flatten(end_dim=-2))
  334. iou_threshold = iou_threshold.reshape([batch_size, num_max_boxes, -1])
  335. iou_threshold = iou_threshold.mean(dim=-1, keepdim=True) + iou_threshold.std(dim=-1, keepdim=True)
  336. is_in_topk = torch.where(iou_candidates > iou_threshold, is_in_topk, torch.zeros_like(is_in_topk))
  337. # 6. check the positive sample's center in gt, [B, n, L]
  338. is_in_gts = check_points_inside_bboxes(anchor_centers, gt_bboxes)
  339. # select positive sample, [B, n, L]
  340. mask_positive = is_in_topk * is_in_gts * pad_gt_mask
  341. # 7. if an anchor box is assigned to multiple gts,
  342. # the one with the highest iou will be selected.
  343. mask_positive_sum = mask_positive.sum(dim=-2)
  344. if mask_positive_sum.max() > 1:
  345. mask_multiple_gts = (mask_positive_sum.unsqueeze(1) > 1).tile([1, num_max_boxes, 1])
  346. is_max_iou = compute_max_iou_anchor(ious)
  347. mask_positive = torch.where(mask_multiple_gts, is_max_iou, mask_positive)
  348. mask_positive_sum = mask_positive.sum(dim=-2)
  349. # 8. make sure every gt_bbox matches the anchor
  350. if self.force_gt_matching:
  351. is_max_iou = compute_max_iou_gt(ious) * pad_gt_mask
  352. mask_max_iou = (is_max_iou.sum(-2, keepdim=True) == 1).tile([1, num_max_boxes, 1])
  353. mask_positive = torch.where(mask_max_iou, is_max_iou, mask_positive)
  354. mask_positive_sum = mask_positive.sum(dim=-2)
  355. assigned_gt_index = mask_positive.argmax(dim=-2)
  356. # assigned target
  357. batch_ind = torch.arange(end=batch_size, dtype=gt_labels.dtype, device=gt_labels.device).unsqueeze(-1)
  358. assigned_gt_index = assigned_gt_index + batch_ind * num_max_boxes
  359. assigned_labels = torch.gather(gt_labels.flatten(), index=assigned_gt_index.flatten(), dim=0)
  360. assigned_labels = assigned_labels.reshape([batch_size, num_anchors])
  361. assigned_labels = torch.where(mask_positive_sum > 0, assigned_labels, torch.full_like(assigned_labels, bg_index))
  362. # assigned_bboxes = torch.gather(gt_bboxes.reshape([-1, 4]), index=assigned_gt_index.flatten(), dim=0)
  363. assigned_bboxes = gt_bboxes.reshape([-1, 4])[assigned_gt_index.flatten(), :]
  364. assigned_bboxes = assigned_bboxes.reshape([batch_size, num_anchors, 4])
  365. assigned_scores = torch.nn.functional.one_hot(assigned_labels, self.num_classes + 1).float()
  366. ind = list(range(self.num_classes + 1))
  367. ind.remove(bg_index)
  368. assigned_scores = torch.index_select(assigned_scores, index=torch.tensor(ind, device=assigned_scores.device), dim=-1)
  369. if pred_bboxes is not None:
  370. # assigned iou
  371. ious = batch_iou_similarity(gt_bboxes, pred_bboxes) * mask_positive
  372. ious = ious.max(dim=-2).values.unsqueeze(-1)
  373. assigned_scores *= ious
  374. elif gt_scores is not None:
  375. gather_scores = torch.gather(gt_scores.flatten(), assigned_gt_index.flatten(), dim=0)
  376. gather_scores = gather_scores.reshape([batch_size, num_anchors])
  377. gather_scores = torch.where(mask_positive_sum > 0, gather_scores, torch.zeros_like(gather_scores))
  378. assigned_scores *= gather_scores.unsqueeze(-1)
  379. return assigned_labels, assigned_bboxes, assigned_scores
  380. class TaskAlignedAssigner(nn.Module):
  381. """TOOD: Task-aligned One-stage Object Detection"""
  382. def __init__(self, topk=13, alpha=1.0, beta=6.0, eps=1e-9):
  383. """
  384. :param topk: Maximum number of achors that is selected for each gt box
  385. :param alpha: Power factor for class probabilities of predicted boxes (Used compute alignment metric)
  386. :param beta: Power factor for IoU score of predicted boxes (Used compute alignment metric)
  387. :param eps: Small constant for numerical stability
  388. """
  389. super(TaskAlignedAssigner, self).__init__()
  390. self.topk = topk
  391. self.alpha = alpha
  392. self.beta = beta
  393. self.eps = eps
  394. @torch.no_grad()
  395. def forward(
  396. self,
  397. pred_scores,
  398. pred_bboxes,
  399. anchor_points,
  400. num_anchors_list,
  401. gt_labels,
  402. gt_bboxes,
  403. pad_gt_mask,
  404. bg_index,
  405. gt_scores=None,
  406. ):
  407. r"""This code is based on
  408. https://github.com/fcjian/TOOD/blob/master/mmdet/core/bbox/assigners/task_aligned_assigner.py
  409. The assignment is done in following steps
  410. 1. compute alignment metric between all bbox (bbox of all pyramid levels) and gt
  411. 2. select top-k bbox as candidates for each gt
  412. 3. limit the positive sample's center in gt (because the anchor-free detector
  413. only can predict positive distance)
  414. 4. if an anchor box is assigned to multiple gts, the one with the
  415. highest iou will be selected.
  416. Args:
  417. pred_scores (Tensor, float32): predicted class probability, shape(B, L, C)
  418. pred_bboxes (Tensor, float32): predicted bounding boxes, shape(B, L, 4)
  419. anchor_points (Tensor, float32): pre-defined anchors, shape(L, 2), "cxcy" format
  420. num_anchors_list (List): num of anchors in each level, shape(L)
  421. gt_labels (Tensor, int64|int32): Label of gt_bboxes, shape(B, n, 1)
  422. gt_bboxes (Tensor, float32): Ground truth bboxes, shape(B, n, 4)
  423. pad_gt_mask (Tensor, float32): 1 means bbox, 0 means no bbox, shape(B, n, 1)
  424. bg_index (int): background index
  425. gt_scores (Tensor|None, float32) Score of gt_bboxes, shape(B, n, 1)
  426. Returns:
  427. assigned_labels (Tensor): (B, L)
  428. assigned_bboxes (Tensor): (B, L, 4)
  429. assigned_scores (Tensor): (B, L, C)
  430. """
  431. assert pred_scores.ndim == pred_bboxes.ndim
  432. assert gt_labels.ndim == gt_bboxes.ndim and gt_bboxes.ndim == 3
  433. batch_size, num_anchors, num_classes = pred_scores.shape
  434. _, num_max_boxes, _ = gt_bboxes.shape
  435. # negative batch
  436. if num_max_boxes == 0:
  437. assigned_labels = torch.full([batch_size, num_anchors], bg_index, dtype="int32")
  438. assigned_bboxes = torch.zeros([batch_size, num_anchors, 4])
  439. assigned_scores = torch.zeros([batch_size, num_anchors, num_classes])
  440. return assigned_labels, assigned_bboxes, assigned_scores
  441. # compute iou between gt and pred bbox, [B, n, L]
  442. ious = batch_iou_similarity(gt_bboxes, pred_bboxes)
  443. # gather pred bboxes class score
  444. pred_scores = torch.permute(pred_scores, [0, 2, 1])
  445. batch_ind = torch.arange(end=batch_size, dtype=gt_labels.dtype, device=gt_labels.device).unsqueeze(-1)
  446. gt_labels_ind = torch.stack([batch_ind.tile([1, num_max_boxes]), gt_labels.squeeze(-1)], dim=-1)
  447. bbox_cls_scores = pred_scores[gt_labels_ind[..., 0], gt_labels_ind[..., 1]]
  448. # compute alignment metrics, [B, n, L]
  449. alignment_metrics = bbox_cls_scores.pow(self.alpha) * ious.pow(self.beta)
  450. # check the positive sample's center in gt, [B, n, L]
  451. is_in_gts = check_points_inside_bboxes(anchor_points, gt_bboxes)
  452. # select topk largest alignment metrics pred bbox as candidates
  453. # for each gt, [B, n, L]
  454. is_in_topk = gather_topk_anchors(alignment_metrics * is_in_gts, self.topk, topk_mask=pad_gt_mask)
  455. # select positive sample, [B, n, L]
  456. mask_positive = is_in_topk * is_in_gts * pad_gt_mask
  457. # if an anchor box is assigned to multiple gts,
  458. # the one with the highest iou will be selected, [B, n, L]
  459. mask_positive_sum = mask_positive.sum(dim=-2)
  460. if mask_positive_sum.max() > 1:
  461. mask_multiple_gts = (mask_positive_sum.unsqueeze(1) > 1).tile([1, num_max_boxes, 1])
  462. is_max_iou = compute_max_iou_anchor(ious)
  463. mask_positive = torch.where(mask_multiple_gts, is_max_iou, mask_positive)
  464. mask_positive_sum = mask_positive.sum(dim=-2)
  465. assigned_gt_index = mask_positive.argmax(dim=-2)
  466. # assigned target
  467. assigned_gt_index = assigned_gt_index + batch_ind * num_max_boxes
  468. assigned_labels = torch.gather(gt_labels.flatten(), index=assigned_gt_index.flatten(), dim=0)
  469. assigned_labels = assigned_labels.reshape([batch_size, num_anchors])
  470. assigned_labels = torch.where(mask_positive_sum > 0, assigned_labels, torch.full_like(assigned_labels, bg_index))
  471. assigned_bboxes = gt_bboxes.reshape([-1, 4])[assigned_gt_index.flatten(), :]
  472. assigned_bboxes = assigned_bboxes.reshape([batch_size, num_anchors, 4])
  473. assigned_scores = torch.nn.functional.one_hot(assigned_labels, num_classes + 1)
  474. ind = list(range(num_classes + 1))
  475. ind.remove(bg_index)
  476. assigned_scores = torch.index_select(assigned_scores, index=torch.tensor(ind, device=assigned_scores.device, dtype=torch.long), dim=-1)
  477. # rescale alignment metrics
  478. alignment_metrics *= mask_positive
  479. max_metrics_per_instance = alignment_metrics.max(dim=-1, keepdim=True).values
  480. max_ious_per_instance = (ious * mask_positive).max(dim=-1, keepdim=True).values
  481. alignment_metrics = alignment_metrics / (max_metrics_per_instance + self.eps) * max_ious_per_instance
  482. alignment_metrics = alignment_metrics.max(dim=-2).values.unsqueeze(-1)
  483. assigned_scores = assigned_scores * alignment_metrics
  484. return assigned_labels, assigned_bboxes, assigned_scores
  485. class GIoULoss(object):
  486. """
  487. Generalized Intersection over Union, see https://arxiv.org/abs/1902.09630
  488. Args:
  489. loss_weight (float): giou loss weight, default as 1
  490. eps (float): epsilon to avoid divide by zero, default as 1e-10
  491. reduction (string): Options are "none", "mean" and "sum". default as none
  492. """
  493. def __init__(self, loss_weight=1.0, eps=1e-10, reduction="none"):
  494. self.loss_weight = loss_weight
  495. self.eps = eps
  496. assert reduction in ("none", "mean", "sum")
  497. self.reduction = reduction
  498. def bbox_overlap(self, box1, box2, eps=1e-10):
  499. """calculate the iou of box1 and box2
  500. Args:
  501. box1 (Tensor): box1 with the shape (..., 4)
  502. box2 (Tensor): box1 with the shape (..., 4)
  503. eps (float): epsilon to avoid divide by zero
  504. Return:
  505. iou (Tensor): iou of box1 and box2
  506. overlap (Tensor): overlap of box1 and box2
  507. union (Tensor): union of box1 and box2
  508. """
  509. x1, y1, x2, y2 = box1
  510. x1g, y1g, x2g, y2g = box2
  511. xkis1 = torch.maximum(x1, x1g)
  512. ykis1 = torch.maximum(y1, y1g)
  513. xkis2 = torch.minimum(x2, x2g)
  514. ykis2 = torch.minimum(y2, y2g)
  515. w_inter = (xkis2 - xkis1).clip(0)
  516. h_inter = (ykis2 - ykis1).clip(0)
  517. overlap = w_inter * h_inter
  518. area1 = (x2 - x1) * (y2 - y1)
  519. area2 = (x2g - x1g) * (y2g - y1g)
  520. union = area1 + area2 - overlap + eps
  521. iou = overlap / union
  522. return iou, overlap, union
  523. def __call__(self, pbox: Tensor, gbox: Tensor, iou_weight=1.0, loc_reweight=None):
  524. # x1, y1, x2, y2 = torch.split(pbox, split_size_or_sections=4, dim=-1)
  525. # x1g, y1g, x2g, y2g = torch.split(gbox, split_size_or_sections=4, dim=-1)
  526. x1, y1, x2, y2 = pbox.chunk(4, dim=-1)
  527. x1g, y1g, x2g, y2g = gbox.chunk(4, dim=-1)
  528. box1 = [x1, y1, x2, y2]
  529. box2 = [x1g, y1g, x2g, y2g]
  530. iou, overlap, union = self.bbox_overlap(box1, box2, self.eps)
  531. xc1 = torch.minimum(x1, x1g)
  532. yc1 = torch.minimum(y1, y1g)
  533. xc2 = torch.maximum(x2, x2g)
  534. yc2 = torch.maximum(y2, y2g)
  535. area_c = (xc2 - xc1) * (yc2 - yc1) + self.eps
  536. miou = iou - ((area_c - union) / area_c)
  537. if loc_reweight is not None:
  538. loc_reweight = torch.reshape(loc_reweight, shape=(-1, 1))
  539. loc_thresh = 0.9
  540. giou = 1 - (1 - loc_thresh) * miou - loc_thresh * miou * loc_reweight
  541. else:
  542. giou = 1 - miou
  543. if self.reduction == "none":
  544. loss = giou
  545. elif self.reduction == "sum":
  546. loss = torch.sum(giou * iou_weight)
  547. else:
  548. loss = torch.mean(giou * iou_weight)
  549. return loss * self.loss_weight
  550. class PPYoloELoss(nn.Module):
  551. def __init__(
  552. self,
  553. num_classes: int,
  554. use_varifocal_loss: bool = True,
  555. use_static_assigner: bool = True,
  556. reg_max: int = 16,
  557. classification_loss_weight: float = 1.0,
  558. iou_loss_weight: float = 2.5,
  559. dfl_loss_weight: float = 0.5,
  560. ):
  561. """
  562. :param num_classes: Number of classes
  563. :param use_varifocal_loss: Whether to use Varifocal loss for classification loss; otherwise use Focal loss
  564. :param static_assigner_epoch: Whether to use static assigner or Task-Aligned assigner
  565. :param classification_loss_weight: Classification loss weight
  566. :param iou_loss_weight: IoU loss weight
  567. :param dfl_loss_weight: DFL loss weight
  568. :param reg_max: Number of regression bins (Must match the number of bins in the PPYoloE head)
  569. """
  570. super().__init__()
  571. self.use_varifocal_loss = use_varifocal_loss
  572. self.classification_loss_weight = classification_loss_weight
  573. self.dfl_loss_weight = dfl_loss_weight
  574. self.iou_loss_weight = iou_loss_weight
  575. self.iou_loss = GIoULoss()
  576. self.static_assigner = ATSSAssigner(topk=9, num_classes=num_classes)
  577. self.assigner = TaskAlignedAssigner(topk=13, alpha=1.0, beta=6.0)
  578. self.use_static_assigner = use_static_assigner
  579. self.reg_max = reg_max
  580. self.num_classes = num_classes
  581. # Same as in PPYoloE head
  582. proj = torch.linspace(0, self.reg_max, self.reg_max + 1).reshape([1, self.reg_max + 1, 1, 1])
  583. self.register_buffer("proj_conv", proj)
  584. @torch.no_grad()
  585. def _yolox_targets_to_ppyolo(self, targets: torch.Tensor, batch_size: int) -> Mapping[str, torch.Tensor]:
  586. """
  587. Convert targets from YoloX format to PPYolo since its the easiest (not the cleanest) way to
  588. have PP Yolo training & metrics computed
  589. :param targets: (N, 6) format of bboxes is meant to be LABEL_CXCYWH (index, c, cx, cy, w, h)
  590. :return: (Dictionary [str,Tensor]) with keys:
  591. - gt_class: (Tensor, int64|int32): Label of gt_bboxes, shape(B, n, 1)
  592. - gt_bbox: (Tensor, float32): Ground truth bboxes, shape(B, n, 4) in x1y1x2y2 format
  593. - pad_gt_mask (Tensor, float32): 1 means bbox, 0 means no bbox, shape(B, n, 1)
  594. """
  595. image_index = targets[:, 0]
  596. gt_class = targets[:, 1:2].long()
  597. gt_bbox = cxcywh_to_xyxy(targets[:, 2:6], image_shape=None)
  598. per_image_class = []
  599. per_image_bbox = []
  600. per_image_pad_mask = []
  601. max_boxes = 0
  602. for i in range(batch_size):
  603. mask = image_index == i
  604. image_labels = gt_class[mask]
  605. image_bboxes = gt_bbox[mask, :]
  606. valid_bboxes = image_bboxes.sum(dim=1, keepdims=True) > 0
  607. per_image_class.append(image_labels)
  608. per_image_bbox.append(image_bboxes)
  609. per_image_pad_mask.append(valid_bboxes)
  610. max_boxes = max(max_boxes, mask.sum().item())
  611. for i in range(batch_size):
  612. elements_to_pad = max_boxes - len(per_image_class[i])
  613. padding_left = 0
  614. padding_right = 0
  615. padding_top = 0
  616. padding_bottom = elements_to_pad
  617. pad = padding_left, padding_right, padding_top, padding_bottom
  618. per_image_class[i] = F.pad(per_image_class[i], pad, mode="constant", value=0)
  619. per_image_bbox[i] = F.pad(per_image_bbox[i], pad, mode="constant", value=0)
  620. per_image_pad_mask[i] = F.pad(per_image_pad_mask[i], pad, mode="constant", value=0)
  621. return {
  622. "gt_class": torch.stack(per_image_class, dim=0),
  623. "gt_bbox": torch.stack(per_image_bbox, dim=0),
  624. "pad_gt_mask": torch.stack(per_image_pad_mask, dim=0),
  625. }
  626. def forward(
  627. self,
  628. outputs: Union[
  629. Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor], Tuple[Tuple[Tensor, Tensor], Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]]
  630. ],
  631. targets: Tensor,
  632. ) -> Mapping[str, Tensor]:
  633. """
  634. :param outputs: Tuple of pred_scores, pred_distri, anchors, anchor_points, num_anchors_list, stride_tensor
  635. :param targets: (Dictionary [str,Tensor]) with keys:
  636. - gt_class: (Tensor, int64|int32): Label of gt_bboxes, shape(B, n, 1)
  637. - gt_bbox: (Tensor, float32): Ground truth bboxes, shape(B, n, 4) in x1y1x2y2 format
  638. - pad_gt_mask (Tensor, float32): 1 means bbox, 0 means no bbox, shape(B, n, 1)
  639. :return:
  640. """
  641. # in test/eval mode the model outputs a tuple where the second item is the raw predictions
  642. if isinstance(outputs, tuple) and len(outputs) == 2:
  643. # in test/eval mode the Yolo model outputs a tuple where the second item is the raw predictions
  644. _, predictions = outputs
  645. else:
  646. predictions = outputs
  647. (
  648. pred_scores,
  649. pred_distri,
  650. anchors,
  651. anchor_points,
  652. num_anchors_list,
  653. stride_tensor,
  654. ) = predictions
  655. targets = self._yolox_targets_to_ppyolo(targets, batch_size=pred_scores.size(0)) # yolox -> ppyolo
  656. anchor_points_s = anchor_points / stride_tensor
  657. pred_bboxes = self._bbox_decode(anchor_points_s, pred_distri)
  658. gt_labels = targets["gt_class"]
  659. gt_bboxes = targets["gt_bbox"]
  660. pad_gt_mask = targets["pad_gt_mask"]
  661. # label assignment
  662. if self.use_static_assigner:
  663. assigned_labels, assigned_bboxes, assigned_scores = self.static_assigner(
  664. anchor_bboxes=anchors,
  665. num_anchors_list=num_anchors_list,
  666. gt_labels=gt_labels,
  667. gt_bboxes=gt_bboxes,
  668. pad_gt_mask=pad_gt_mask,
  669. bg_index=self.num_classes,
  670. pred_bboxes=pred_bboxes.detach() * stride_tensor,
  671. )
  672. alpha_l = 0.25
  673. else:
  674. assigned_labels, assigned_bboxes, assigned_scores = self.assigner(
  675. pred_scores=pred_scores.detach().sigmoid(), # Pred scores are logits on training for numerical stability
  676. pred_bboxes=pred_bboxes.detach() * stride_tensor,
  677. anchor_points=anchor_points,
  678. num_anchors_list=num_anchors_list,
  679. gt_labels=gt_labels,
  680. gt_bboxes=gt_bboxes,
  681. pad_gt_mask=pad_gt_mask,
  682. bg_index=self.num_classes,
  683. )
  684. alpha_l = -1
  685. # rescale bbox
  686. assigned_bboxes /= stride_tensor
  687. # cls loss
  688. if self.use_varifocal_loss:
  689. one_hot_label = torch.nn.functional.one_hot(assigned_labels, self.num_classes + 1)[..., :-1]
  690. loss_cls = self._varifocal_loss(pred_scores, assigned_scores, one_hot_label)
  691. else:
  692. loss_cls = self._focal_loss(pred_scores, assigned_scores, alpha_l)
  693. assigned_scores_sum = assigned_scores.sum()
  694. if super_gradients.is_distributed():
  695. torch.distributed.all_reduce(assigned_scores_sum, op=torch.distributed.ReduceOp.SUM)
  696. assigned_scores_sum /= get_world_size()
  697. assigned_scores_sum = torch.clip(assigned_scores_sum, min=1.0)
  698. loss_cls /= assigned_scores_sum
  699. loss_iou, loss_dfl = self._bbox_loss(
  700. pred_distri,
  701. pred_bboxes,
  702. anchor_points_s,
  703. assigned_labels,
  704. assigned_bboxes,
  705. assigned_scores,
  706. assigned_scores_sum,
  707. )
  708. loss = self.classification_loss_weight * loss_cls + self.iou_loss_weight * loss_iou + self.dfl_loss_weight * loss_dfl
  709. log_losses = torch.stack([loss_cls.detach(), loss_iou.detach(), loss_dfl.detach(), loss.detach()])
  710. return loss, log_losses
  711. @property
  712. def component_names(self):
  713. return ["loss_cls", "loss_iou", "loss_dfl", "loss"]
  714. def _df_loss(self, pred_dist: Tensor, target: Tensor) -> Tensor:
  715. target_left = target.long()
  716. target_right = target_left + 1
  717. weight_left = target_right.float() - target
  718. weight_right = 1 - weight_left
  719. # [B,L,C] -> [B,C,L] to make compatible with torch.nn.functional.cross_entropy
  720. # which expects channel dim to be at index 1
  721. pred_dist = torch.moveaxis(pred_dist, -1, 1)
  722. loss_left = torch.nn.functional.cross_entropy(pred_dist, target_left, reduction="none") * weight_left
  723. loss_right = torch.nn.functional.cross_entropy(pred_dist, target_right, reduction="none") * weight_right
  724. return (loss_left + loss_right).mean(dim=-1, keepdim=True)
  725. def _bbox_loss(
  726. self,
  727. pred_dist,
  728. pred_bboxes,
  729. anchor_points,
  730. assigned_labels,
  731. assigned_bboxes,
  732. assigned_scores,
  733. assigned_scores_sum,
  734. ):
  735. # select positive samples mask
  736. mask_positive = assigned_labels != self.num_classes
  737. num_pos = mask_positive.sum()
  738. # pos/neg loss
  739. if num_pos > 0:
  740. # l1 + iou
  741. bbox_mask = mask_positive.unsqueeze(-1).tile([1, 1, 4])
  742. pred_bboxes_pos = torch.masked_select(pred_bboxes, bbox_mask).reshape([-1, 4])
  743. assigned_bboxes_pos = torch.masked_select(assigned_bboxes, bbox_mask).reshape([-1, 4])
  744. bbox_weight = torch.masked_select(assigned_scores.sum(-1), mask_positive).unsqueeze(-1)
  745. loss_iou = self.iou_loss(pred_bboxes_pos, assigned_bboxes_pos) * bbox_weight
  746. loss_iou = loss_iou.sum() / assigned_scores_sum
  747. dist_mask = mask_positive.unsqueeze(-1).tile([1, 1, (self.reg_max + 1) * 4])
  748. pred_dist_pos = torch.masked_select(pred_dist, dist_mask).reshape([-1, 4, self.reg_max + 1])
  749. assigned_ltrb = self._bbox2distance(anchor_points, assigned_bboxes)
  750. assigned_ltrb_pos = torch.masked_select(assigned_ltrb, bbox_mask).reshape([-1, 4])
  751. loss_dfl = self._df_loss(pred_dist_pos, assigned_ltrb_pos) * bbox_weight
  752. loss_dfl = loss_dfl.sum() / assigned_scores_sum
  753. else:
  754. loss_iou = torch.zeros([], device=pred_bboxes.device)
  755. loss_dfl = pred_dist.sum() * 0.0
  756. return loss_iou, loss_dfl
  757. def _bbox_decode(self, anchor_points: Tensor, pred_dist: Tensor):
  758. b, l, *_ = pred_dist.size()
  759. pred_dist = torch.softmax(pred_dist.reshape([b, l, 4, self.reg_max + 1]), dim=-1)
  760. pred_dist = torch.nn.functional.conv2d(pred_dist.permute(0, 3, 1, 2), self.proj_conv).squeeze(1)
  761. return batch_distance2bbox(anchor_points, pred_dist)
  762. def _bbox2distance(self, points, bbox):
  763. x1y1, x2y2 = torch.split(bbox, 2, -1)
  764. lt = points - x1y1
  765. rb = x2y2 - points
  766. return torch.cat([lt, rb], dim=-1).clip(0, self.reg_max - 0.01)
  767. @staticmethod
  768. def _focal_loss(pred_logits: Tensor, label: Tensor, alpha=0.25, gamma=2.0) -> Tensor:
  769. pred_score = pred_logits.sigmoid()
  770. weight = (pred_score - label).pow(gamma)
  771. if alpha > 0:
  772. alpha_t = alpha * label + (1 - alpha) * (1 - label)
  773. weight *= alpha_t
  774. loss = -weight * (label * torch.nn.functional.logsigmoid(pred_logits) + (1 - label) * torch.nn.functional.logsigmoid(-pred_logits))
  775. return loss.sum()
  776. @staticmethod
  777. def _varifocal_loss(pred_logits: Tensor, gt_score: Tensor, label: Tensor, alpha=0.75, gamma=2.0) -> Tensor:
  778. pred_score = pred_logits.sigmoid()
  779. weight = alpha * pred_score.pow(gamma) * (1 - label) + gt_score * label
  780. loss = -weight * (gt_score * torch.nn.functional.logsigmoid(pred_logits) + (1 - gt_score) * torch.nn.functional.logsigmoid(-pred_logits))
  781. return loss.sum()
Discard
Tip!

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