matcher.py 7.0 KB

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