matcher.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from utils.box_ops import bbox_iou
  5. # -------------------------- Task Aligned Assigner --------------------------
  6. class TaskAlignedAssigner(nn.Module):
  7. """
  8. This code referenced to https://github.com/ultralytics/ultralytics
  9. """
  10. def __init__(self,
  11. num_classes = 80,
  12. topk_candidates = 10,
  13. alpha = 0.5,
  14. beta = 6.0,
  15. eps = 1e-9):
  16. super(TaskAlignedAssigner, self).__init__()
  17. self.topk_candidates = topk_candidates
  18. self.num_classes = num_classes
  19. self.bg_idx = num_classes
  20. self.alpha = alpha
  21. self.beta = beta
  22. self.eps = eps
  23. @torch.no_grad()
  24. def forward(self,
  25. pd_scores,
  26. pd_bboxes,
  27. anc_points,
  28. gt_labels,
  29. gt_bboxes):
  30. self.bs = pd_scores.size(0)
  31. self.n_max_boxes = gt_bboxes.size(1)
  32. mask_pos, align_metric, overlaps = self.get_pos_mask(
  33. pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points)
  34. target_gt_idx, fg_mask, mask_pos = select_highest_overlaps(
  35. mask_pos, overlaps, self.n_max_boxes)
  36. # Assigned target
  37. target_labels, target_bboxes, target_scores = self.get_targets(
  38. gt_labels, gt_bboxes, target_gt_idx, fg_mask)
  39. # normalize
  40. align_metric *= mask_pos
  41. pos_align_metrics = align_metric.amax(axis=-1, keepdim=True) # b, max_num_obj
  42. pos_overlaps = (overlaps * mask_pos).amax(axis=-1, keepdim=True) # b, max_num_obj
  43. norm_align_metric = (align_metric * pos_overlaps / (pos_align_metrics + self.eps)).amax(-2).unsqueeze(-1)
  44. target_scores = target_scores * norm_align_metric
  45. return target_labels, target_bboxes, target_scores, fg_mask.bool(), target_gt_idx
  46. def get_pos_mask(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points):
  47. # get in_gts mask, (b, max_num_obj, h*w)
  48. mask_in_gts = select_candidates_in_gts(anc_points, gt_bboxes)
  49. # get anchor_align metric, (b, max_num_obj, h*w)
  50. align_metric, overlaps = self.get_box_metrics(pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_in_gts)
  51. # get topk_metric mask, (b, max_num_obj, h*w)
  52. mask_topk = self.select_topk_candidates(align_metric)
  53. # merge all mask to a final mask, (b, max_num_obj, h*w)
  54. mask_pos = mask_topk * mask_in_gts
  55. return mask_pos, align_metric, overlaps
  56. def get_box_metrics(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_in_gts):
  57. """Compute alignment metric given predicted and ground truth bounding boxes."""
  58. na = pd_bboxes.shape[-2]
  59. mask_in_gts = mask_in_gts.bool() # b, max_num_obj, h*w
  60. overlaps = torch.zeros([self.bs, self.n_max_boxes, na], dtype=pd_bboxes.dtype, device=pd_bboxes.device)
  61. bbox_scores = torch.zeros([self.bs, self.n_max_boxes, na], dtype=pd_scores.dtype, device=pd_scores.device)
  62. ind = torch.zeros([2, self.bs, self.n_max_boxes], dtype=torch.long) # 2, b, max_num_obj
  63. ind[0] = torch.arange(end=self.bs).view(-1, 1).expand(-1, self.n_max_boxes) # b, max_num_obj
  64. ind[1] = gt_labels.squeeze(-1) # b, max_num_obj
  65. # Get the scores of each grid for each gt cls
  66. bbox_scores[mask_in_gts] = pd_scores[ind[0], :, ind[1]][mask_in_gts] # b, max_num_obj, h*w
  67. # (b, max_num_obj, 1, 4), (b, 1, h*w, 4)
  68. pd_boxes = pd_bboxes.unsqueeze(1).expand(-1, self.n_max_boxes, -1, -1)[mask_in_gts]
  69. gt_boxes = gt_bboxes.unsqueeze(2).expand(-1, -1, na, -1)[mask_in_gts]
  70. overlaps[mask_in_gts] = bbox_iou(gt_boxes, pd_boxes, xywh=False, CIoU=True).squeeze(-1).clamp_(0)
  71. align_metric = bbox_scores.pow(self.alpha) * overlaps.pow(self.beta)
  72. return align_metric, overlaps
  73. def select_topk_candidates(self, metrics, largest=True):
  74. """
  75. Args:
  76. metrics: (b, max_num_obj, h*w).
  77. topk_mask: (b, max_num_obj, topk) or None
  78. """
  79. # (b, max_num_obj, topk)
  80. topk_metrics, topk_idxs = torch.topk(metrics, self.topk_candidates, dim=-1, largest=largest)
  81. topk_mask = (topk_metrics.max(-1, keepdim=True)[0] > self.eps).expand_as(topk_idxs)
  82. # (b, max_num_obj, topk)
  83. topk_idxs.masked_fill_(~topk_mask, 0)
  84. # (b, max_num_obj, topk, h*w) -> (b, max_num_obj, h*w)
  85. count_tensor = torch.zeros(metrics.shape, dtype=torch.int8, device=topk_idxs.device)
  86. ones = torch.ones_like(topk_idxs[:, :, :1], dtype=torch.int8, device=topk_idxs.device)
  87. for k in range(self.topk_candidates):
  88. # Expand topk_idxs for each value of k and add 1 at the specified positions
  89. count_tensor.scatter_add_(-1, topk_idxs[:, :, k:k + 1], ones)
  90. # count_tensor.scatter_add_(-1, topk_idxs, torch.ones_like(topk_idxs, dtype=torch.int8, device=topk_idxs.device))
  91. # Filter invalid bboxes
  92. count_tensor.masked_fill_(count_tensor > 1, 0)
  93. return count_tensor.to(metrics.dtype)
  94. def get_targets(self, gt_labels, gt_bboxes, target_gt_idx, fg_mask):
  95. # Assigned target labels, (b, 1)
  96. batch_ind = torch.arange(end=self.bs, dtype=torch.int64, device=gt_labels.device)[..., None]
  97. target_gt_idx = target_gt_idx + batch_ind * self.n_max_boxes # (b, h*w)
  98. target_labels = gt_labels.long().flatten()[target_gt_idx] # (b, h*w)
  99. # Assigned target boxes, (b, max_num_obj, 4) -> (b, h*w, 4)
  100. target_bboxes = gt_bboxes.view(-1, 4)[target_gt_idx]
  101. # Assigned target scores
  102. target_labels.clamp_(0)
  103. # 10x faster than F.one_hot()
  104. target_scores = torch.zeros((target_labels.shape[0], target_labels.shape[1], self.num_classes),
  105. dtype=torch.int64,
  106. device=target_labels.device) # (b, h*w, 80)
  107. target_scores.scatter_(2, target_labels.unsqueeze(-1), 1)
  108. fg_scores_mask = fg_mask[:, :, None].repeat(1, 1, self.num_classes) # (b, h*w, 80)
  109. target_scores = torch.where(fg_scores_mask > 0, target_scores, 0)
  110. return target_labels, target_bboxes, target_scores
  111. # -------------------------- Basic Functions --------------------------
  112. def select_candidates_in_gts(xy_centers, gt_bboxes, eps=1e-9):
  113. """select the positive anchors's center in gt
  114. Args:
  115. xy_centers (Tensor): shape(bs*n_max_boxes, num_total_anchors, 4)
  116. gt_bboxes (Tensor): shape(bs, n_max_boxes, 4)
  117. Return:
  118. (Tensor): shape(bs, n_max_boxes, num_total_anchors)
  119. """
  120. n_anchors = xy_centers.size(0)
  121. bs, n_max_boxes, _ = gt_bboxes.size()
  122. _gt_bboxes = gt_bboxes.reshape([-1, 4])
  123. xy_centers = xy_centers.unsqueeze(0).repeat(bs * n_max_boxes, 1, 1)
  124. gt_bboxes_lt = _gt_bboxes[:, 0:2].unsqueeze(1).repeat(1, n_anchors, 1)
  125. gt_bboxes_rb = _gt_bboxes[:, 2:4].unsqueeze(1).repeat(1, n_anchors, 1)
  126. b_lt = xy_centers - gt_bboxes_lt
  127. b_rb = gt_bboxes_rb - xy_centers
  128. bbox_deltas = torch.cat([b_lt, b_rb], dim=-1)
  129. bbox_deltas = bbox_deltas.reshape([bs, n_max_boxes, n_anchors, -1])
  130. return (bbox_deltas.min(axis=-1)[0] > eps).to(gt_bboxes.dtype)
  131. def select_highest_overlaps(mask_pos, overlaps, n_max_boxes):
  132. """if an anchor box is assigned to multiple gts,
  133. the one with the highest iou will be selected.
  134. Args:
  135. mask_pos (Tensor): shape(bs, n_max_boxes, num_total_anchors)
  136. overlaps (Tensor): shape(bs, n_max_boxes, num_total_anchors)
  137. Return:
  138. target_gt_idx (Tensor): shape(bs, num_total_anchors)
  139. fg_mask (Tensor): shape(bs, num_total_anchors)
  140. mask_pos (Tensor): shape(bs, n_max_boxes, num_total_anchors)
  141. """
  142. fg_mask = mask_pos.sum(-2)
  143. if fg_mask.max() > 1: # one anchor is assigned to multiple gt_bboxes
  144. mask_multi_gts = (fg_mask.unsqueeze(1) > 1).expand(-1, n_max_boxes, -1) # (b, n_max_boxes, h*w)
  145. max_overlaps_idx = overlaps.argmax(1) # (b, h*w)
  146. is_max_overlaps = torch.zeros(mask_pos.shape, dtype=mask_pos.dtype, device=mask_pos.device)
  147. is_max_overlaps.scatter_(1, max_overlaps_idx.unsqueeze(1), 1)
  148. mask_pos = torch.where(mask_multi_gts, is_max_overlaps, mask_pos).float() # (b, n_max_boxes, h*w)
  149. fg_mask = mask_pos.sum(-2)
  150. # Find each grid serve which gt(index)
  151. target_gt_idx = mask_pos.argmax(-2) # (b, h*w)
  152. return target_gt_idx, fg_mask, mask_pos
  153. def iou_calculator(box1, box2, eps=1e-9):
  154. """Calculate iou for batch
  155. Args:
  156. box1 (Tensor): shape(bs, n_max_boxes, 1, 4)
  157. box2 (Tensor): shape(bs, 1, num_total_anchors, 4)
  158. Return:
  159. (Tensor): shape(bs, n_max_boxes, num_total_anchors)
  160. """
  161. box1 = box1.unsqueeze(2) # [N, M1, 4] -> [N, M1, 1, 4]
  162. box2 = box2.unsqueeze(1) # [N, M2, 4] -> [N, 1, M2, 4]
  163. px1y1, px2y2 = box1[:, :, :, 0:2], box1[:, :, :, 2:4]
  164. gx1y1, gx2y2 = box2[:, :, :, 0:2], box2[:, :, :, 2:4]
  165. x1y1 = torch.maximum(px1y1, gx1y1)
  166. x2y2 = torch.minimum(px2y2, gx2y2)
  167. overlap = (x2y2 - x1y1).clip(0).prod(-1)
  168. area1 = (px2y2 - px1y1).clip(0).prod(-1)
  169. area2 = (gx2y2 - gx1y1).clip(0).prod(-1)
  170. union = area1 + area2 - overlap + eps
  171. return overlap / union