matcher.py 6.3 KB

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