matcher.py 7.2 KB

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