matcher.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. import torch
  2. import torch.nn.functional as F
  3. from utils.box_ops import box_iou
  4. class AlignedOTAMatcher(object):
  5. """
  6. This code referenced to https://github.com/open-mmlab/mmyolo/models/task_modules/assigners/batch_dsl_assigner.py
  7. """
  8. def __init__(self,
  9. num_classes,
  10. soft_center_radius=3.0,
  11. topk_candidates=13,
  12. ):
  13. self.num_classes = num_classes
  14. self.soft_center_radius = soft_center_radius
  15. self.topk_candidates = topk_candidates
  16. @torch.no_grad()
  17. def __call__(self,
  18. fpn_strides,
  19. anchors,
  20. pred_cls,
  21. pred_box,
  22. gt_labels,
  23. gt_bboxes):
  24. # [M,]
  25. strides = 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. num_gt = len(gt_labels)
  29. anchors = torch.cat(anchors, dim=0)
  30. # check gt
  31. if num_gt == 0 or gt_bboxes.max().item() == 0.:
  32. return {
  33. 'assigned_labels': gt_labels.new_full(pred_cls[..., 0].shape, self.num_classes).long(),
  34. 'assigned_bboxes': gt_bboxes.new_full(pred_box.shape, 0),
  35. 'assign_metrics': gt_bboxes.new_full(pred_cls[..., 0].shape, 0),
  36. 'assigned_pss': gt_labels.new_full(pred_cls[..., 0].shape, 0).float(),
  37. }
  38. # get inside points: [N, M]
  39. is_in_gt = self.find_inside_points(gt_bboxes, anchors)
  40. valid_mask = is_in_gt.sum(dim=0) > 0 # [M,]
  41. # ----------------------- Soft center prior -----------------------
  42. gt_center = (gt_bboxes[..., :2] + gt_bboxes[..., 2:]) / 2.0
  43. distance = (anchors.unsqueeze(0) - gt_center.unsqueeze(1)
  44. ).pow(2).sum(-1).sqrt() / strides.unsqueeze(0) # [N, M]
  45. distance = distance * valid_mask.unsqueeze(0)
  46. soft_center_prior = torch.pow(10, distance - self.soft_center_radius)
  47. # ----------------------- Regression cost -----------------------
  48. pair_wise_ious, _ = box_iou(gt_bboxes, pred_box) # [N, M]
  49. pair_wise_ious_loss = -torch.log(pair_wise_ious + 1e-8) * 3.0
  50. # ----------------------- Classification cost -----------------------
  51. ## select the predicted scores corresponded to the gt_labels
  52. pairwise_pred_scores = pred_cls.permute(1, 0) # [M, C] -> [C, M]
  53. pairwise_pred_scores = pairwise_pred_scores[gt_labels.long(), :].float() # [N, M]
  54. ## scale factor
  55. scale_factor = (pair_wise_ious - pairwise_pred_scores.sigmoid()).abs().pow(2.0)
  56. ## cls cost
  57. pair_wise_cls_loss = F.binary_cross_entropy_with_logits(
  58. pairwise_pred_scores, pair_wise_ious,
  59. reduction="none") * scale_factor # [N, M]
  60. del pairwise_pred_scores
  61. ## foreground cost matrix
  62. cost_matrix = pair_wise_cls_loss + pair_wise_ious_loss + soft_center_prior
  63. max_pad_value = torch.ones_like(cost_matrix) * 1e9
  64. cost_matrix = torch.where(valid_mask[None].repeat(num_gt, 1), # [N, M]
  65. cost_matrix, max_pad_value)
  66. # ----------------------- Dynamic label assignment -----------------------
  67. matched_pred_ious, matched_gt_inds, fg_mask_inboxes = self.dynamic_k_matching(
  68. cost_matrix, pair_wise_ious, num_gt)
  69. matched_pss_inds, fg_mask_top1 = self.topk_one_matching(cost_matrix, pair_wise_ious, num_gt)
  70. del pair_wise_cls_loss, cost_matrix, pair_wise_ious, pair_wise_ious_loss
  71. # ----------------------- Process assigned labels -----------------------
  72. assigned_labels = gt_labels.new_full(pred_cls[..., 0].shape,
  73. self.num_classes) # [M,]
  74. assigned_labels[fg_mask_inboxes] = gt_labels[matched_gt_inds].squeeze(-1)
  75. assigned_labels = assigned_labels.long() # [M,]
  76. assigned_bboxes = gt_bboxes.new_full(pred_box.shape, 0) # [M, 4]
  77. assigned_bboxes[fg_mask_inboxes] = gt_bboxes[matched_gt_inds] # [M, 4]
  78. assign_metrics = gt_bboxes.new_full(pred_cls[..., 0].shape, 0) # [M,]
  79. assign_metrics[fg_mask_inboxes] = matched_pred_ious # [M,]
  80. assigned_pss = gt_labels.new_zeros(pred_cls[..., 0].shape) # [M,]
  81. assigned_pss[fg_mask_top1] = torch.ones_like(gt_labels)[matched_pss_inds].squeeze(-1)
  82. assigned_pss = assigned_pss.float()
  83. assigned_dict = dict(
  84. assigned_labels = assigned_labels,
  85. assigned_bboxes = assigned_bboxes,
  86. assign_metrics = assign_metrics,
  87. assigned_pss = assigned_pss,
  88. )
  89. return assigned_dict
  90. def find_inside_points(self, gt_bboxes, anchors):
  91. """
  92. gt_bboxes: Tensor -> [N, 2]
  93. anchors: Tensor -> [M, 2]
  94. """
  95. num_anchors = anchors.shape[0]
  96. num_gt = gt_bboxes.shape[0]
  97. anchors_expand = anchors.unsqueeze(0).repeat(num_gt, 1, 1) # [N, M, 2]
  98. gt_bboxes_expand = gt_bboxes.unsqueeze(1).repeat(1, num_anchors, 1) # [N, M, 4]
  99. # offset
  100. lt = anchors_expand - gt_bboxes_expand[..., :2]
  101. rb = gt_bboxes_expand[..., 2:] - anchors_expand
  102. bbox_deltas = torch.cat([lt, rb], dim=-1)
  103. is_in_gts = bbox_deltas.min(dim=-1).values > 0
  104. return is_in_gts
  105. def dynamic_k_matching(self, cost_matrix, pairwise_ious, num_gt):
  106. matching_matrix = torch.zeros_like(cost_matrix, dtype=torch.uint8)
  107. # select candidate topk ious for dynamic-k calculation
  108. candidate_topk = min(self.topk_candidates, pairwise_ious.size(1))
  109. topk_ious, _ = torch.topk(pairwise_ious, candidate_topk, dim=1)
  110. # calculate dynamic k for each gt
  111. dynamic_ks = torch.clamp(topk_ious.sum(1).int(), min=1)
  112. # sorting the batch cost matirx is faster than topk
  113. _, sorted_indices = torch.sort(cost_matrix, dim=1)
  114. for gt_idx in range(num_gt):
  115. topk_ids = sorted_indices[gt_idx, :dynamic_ks[gt_idx]]
  116. matching_matrix[gt_idx, :][topk_ids] = 1
  117. del topk_ious, dynamic_ks, topk_ids
  118. prior_match_gt_mask = matching_matrix.sum(0) > 1
  119. if prior_match_gt_mask.sum() > 0:
  120. cost_min, cost_argmin = torch.min(
  121. cost_matrix[:, prior_match_gt_mask], dim=0)
  122. matching_matrix[:, prior_match_gt_mask] *= 0
  123. matching_matrix[cost_argmin, prior_match_gt_mask] = 1
  124. # get foreground mask inside box and center prior
  125. fg_mask_inboxes = matching_matrix.sum(0) > 0
  126. matched_pred_ious = (matching_matrix *
  127. pairwise_ious).sum(0)[fg_mask_inboxes]
  128. matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)
  129. return matched_pred_ious, matched_gt_inds, fg_mask_inboxes
  130. def topk_one_matching(self, cost_matrix, pairwise_ious, num_gt):
  131. matching_matrix = torch.zeros_like(cost_matrix, dtype=torch.uint8)
  132. # select candidate topk ious for dynamic-k calculation
  133. candidate_topk = min(1, pairwise_ious.size(1))
  134. topk_ious, _ = torch.topk(pairwise_ious, candidate_topk, dim=1)
  135. # calculate dynamic k for each gt
  136. dynamic_ks = torch.clamp(topk_ious.sum(1).int(), min=1)
  137. # sorting the batch cost matirx is faster than topk
  138. _, sorted_indices = torch.sort(cost_matrix, dim=1)
  139. for gt_idx in range(num_gt):
  140. topk_ids = sorted_indices[gt_idx, :dynamic_ks[gt_idx]]
  141. matching_matrix[gt_idx, :][topk_ids] = 1
  142. del topk_ious, dynamic_ks, topk_ids
  143. prior_match_gt_mask = matching_matrix.sum(0) > 1
  144. if prior_match_gt_mask.sum() > 0:
  145. cost_min, cost_argmin = torch.min(
  146. cost_matrix[:, prior_match_gt_mask], dim=0)
  147. matching_matrix[:, prior_match_gt_mask] *= 0
  148. matching_matrix[cost_argmin, prior_match_gt_mask] = 1
  149. # get foreground mask inside box and center prior
  150. fg_mask_inboxes = matching_matrix.sum(0) > 0
  151. matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)
  152. return matched_gt_inds, fg_mask_inboxes