matcher.py 6.8 KB

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