matcher.py 6.9 KB

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