matcher.py 7.3 KB

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