matcher.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import torch
  2. import torch.nn.functional as F
  3. from utils.box_ops import *
  4. # -------------------------- Aligned SimOTA Assigner --------------------------
  5. class AlignedSimOTA(object):
  6. """
  7. This code referenced to https://github.com/Megvii-BaseDetection/YOLOX/blob/main/yolox/models/yolo_head.py
  8. """
  9. def __init__(self, num_classes, center_sampling_radius, topk_candidate ):
  10. self.num_classes = num_classes
  11. self.center_sampling_radius = center_sampling_radius
  12. self.topk_candidate = topk_candidate
  13. @torch.no_grad()
  14. def __call__(self,
  15. fpn_strides,
  16. anchors,
  17. pred_cls,
  18. pred_box,
  19. tgt_labels,
  20. tgt_bboxes):
  21. # [M,]
  22. strides_tensor = torch.cat([torch.ones_like(anchor_i[:, 0]) * stride_i
  23. for stride_i, anchor_i in zip(fpn_strides, anchors)], dim=-1)
  24. # List[F, M, 2] -> [M, 2]
  25. anchors = torch.cat(anchors, dim=0)
  26. num_anchor = anchors.shape[0]
  27. num_gt = len(tgt_labels)
  28. # ----------------------- Find inside points -----------------------
  29. fg_mask, is_in_boxes_and_center = self.get_in_boxes_info(
  30. tgt_bboxes, anchors, strides_tensor, num_anchor, num_gt)
  31. cls_preds = pred_cls[fg_mask].float() # [Mp, C]
  32. box_preds = pred_box[fg_mask].float() # [Mp, 4]
  33. # ----------------------- Reg cost -----------------------
  34. pair_wise_ious, _ = box_iou(tgt_bboxes, box_preds) # [N, Mp]
  35. reg_cost = -torch.log(pair_wise_ious + 1e-8) # [N, Mp]
  36. # ----------------------- Cls cost -----------------------
  37. with torch.cuda.amp.autocast(enabled=False):
  38. # [Mp, C] -> [N, Mp, C]
  39. cls_preds_expand = cls_preds.unsqueeze(0).repeat(num_gt, 1, 1)
  40. # prepare cls_target
  41. cls_targets = F.one_hot(tgt_labels.long(), self.num_classes).float()
  42. cls_targets = cls_targets.unsqueeze(1).repeat(1, cls_preds_expand.size(1), 1)
  43. cls_targets *= pair_wise_ious.unsqueeze(-1) # iou-aware
  44. # [N, Mp]
  45. cls_cost = F.binary_cross_entropy_with_logits(cls_preds_expand, cls_targets, reduction="none").sum(-1)
  46. del cls_preds_expand
  47. #----------------------- Dynamic K-Matching -----------------------
  48. cost_matrix = (
  49. cls_cost
  50. + 3.0 * reg_cost
  51. + 100000.0 * (~is_in_boxes_and_center)
  52. ) # [N, Mp]
  53. (
  54. assigned_labels, # [num_fg,]
  55. assigned_ious, # [num_fg,]
  56. assigned_indexs, # [num_fg,]
  57. ) = self.dynamic_k_matching(
  58. cost_matrix,
  59. pair_wise_ious,
  60. tgt_labels,
  61. num_gt,
  62. fg_mask
  63. )
  64. del cls_cost, cost_matrix, pair_wise_ious, reg_cost
  65. return fg_mask, assigned_labels, assigned_ious, assigned_indexs
  66. def get_in_boxes_info(
  67. self,
  68. gt_bboxes, # [N, 4]
  69. anchors, # [M, 2]
  70. strides, # [M,]
  71. num_anchors, # M
  72. num_gt, # N
  73. ):
  74. # anchor center
  75. x_centers = anchors[:, 0]
  76. y_centers = anchors[:, 1]
  77. # [M,] -> [1, M] -> [N, M]
  78. x_centers = x_centers.unsqueeze(0).repeat(num_gt, 1)
  79. y_centers = y_centers.unsqueeze(0).repeat(num_gt, 1)
  80. # [N,] -> [N, 1] -> [N, M]
  81. gt_bboxes_l = gt_bboxes[:, 0].unsqueeze(1).repeat(1, num_anchors) # x1
  82. gt_bboxes_t = gt_bboxes[:, 1].unsqueeze(1).repeat(1, num_anchors) # y1
  83. gt_bboxes_r = gt_bboxes[:, 2].unsqueeze(1).repeat(1, num_anchors) # x2
  84. gt_bboxes_b = gt_bboxes[:, 3].unsqueeze(1).repeat(1, num_anchors) # y2
  85. b_l = x_centers - gt_bboxes_l
  86. b_r = gt_bboxes_r - x_centers
  87. b_t = y_centers - gt_bboxes_t
  88. b_b = gt_bboxes_b - y_centers
  89. bbox_deltas = torch.stack([b_l, b_t, b_r, b_b], 2)
  90. is_in_boxes = bbox_deltas.min(dim=-1).values > 0.0
  91. is_in_boxes_all = is_in_boxes.sum(dim=0) > 0
  92. # in fixed center
  93. center_radius = self.center_sampling_radius
  94. # [N, 2]
  95. gt_centers = (gt_bboxes[:, :2] + gt_bboxes[:, 2:]) * 0.5
  96. # [1, M]
  97. center_radius_ = center_radius * strides.unsqueeze(0)
  98. gt_bboxes_l = gt_centers[:, 0].unsqueeze(1).repeat(1, num_anchors) - center_radius_ # x1
  99. gt_bboxes_t = gt_centers[:, 1].unsqueeze(1).repeat(1, num_anchors) - center_radius_ # y1
  100. gt_bboxes_r = gt_centers[:, 0].unsqueeze(1).repeat(1, num_anchors) + center_radius_ # x2
  101. gt_bboxes_b = gt_centers[:, 1].unsqueeze(1).repeat(1, num_anchors) + center_radius_ # y2
  102. c_l = x_centers - gt_bboxes_l
  103. c_r = gt_bboxes_r - x_centers
  104. c_t = y_centers - gt_bboxes_t
  105. c_b = gt_bboxes_b - y_centers
  106. center_deltas = torch.stack([c_l, c_t, c_r, c_b], 2)
  107. is_in_centers = center_deltas.min(dim=-1).values > 0.0
  108. is_in_centers_all = is_in_centers.sum(dim=0) > 0
  109. # in boxes and in centers
  110. is_in_boxes_anchor = is_in_boxes_all | is_in_centers_all
  111. is_in_boxes_and_center = (
  112. is_in_boxes[:, is_in_boxes_anchor] & is_in_centers[:, is_in_boxes_anchor]
  113. )
  114. return is_in_boxes_anchor, is_in_boxes_and_center
  115. def dynamic_k_matching(
  116. self,
  117. cost,
  118. pair_wise_ious,
  119. gt_classes,
  120. num_gt,
  121. fg_mask
  122. ):
  123. # Dynamic K
  124. # ---------------------------------------------------------------
  125. matching_matrix = torch.zeros_like(cost, dtype=torch.uint8)
  126. ious_in_boxes_matrix = pair_wise_ious
  127. n_candidate_k = min(self.topk_candidate, ious_in_boxes_matrix.size(1))
  128. topk_ious, _ = torch.topk(ious_in_boxes_matrix, n_candidate_k, dim=1)
  129. dynamic_ks = torch.clamp(topk_ious.sum(1).int(), min=1)
  130. dynamic_ks = dynamic_ks.tolist()
  131. for gt_idx in range(num_gt):
  132. _, pos_idx = torch.topk(
  133. cost[gt_idx], k=dynamic_ks[gt_idx], largest=False
  134. )
  135. matching_matrix[gt_idx][pos_idx] = 1
  136. del topk_ious, dynamic_ks, pos_idx
  137. anchor_matching_gt = matching_matrix.sum(0)
  138. if (anchor_matching_gt > 1).sum() > 0:
  139. _, cost_argmin = torch.min(cost[:, anchor_matching_gt > 1], dim=0)
  140. matching_matrix[:, anchor_matching_gt > 1] *= 0
  141. matching_matrix[cost_argmin, anchor_matching_gt > 1] = 1
  142. fg_mask_inboxes = matching_matrix.sum(0) > 0
  143. fg_mask[fg_mask.clone()] = fg_mask_inboxes
  144. assigned_indexs = matching_matrix[:, fg_mask_inboxes].argmax(0)
  145. assigned_labels = gt_classes[assigned_indexs]
  146. assigned_ious = (matching_matrix * pair_wise_ious).sum(0)[
  147. fg_mask_inboxes
  148. ]
  149. return assigned_labels, assigned_ious, assigned_indexs