matcher.py 8.5 KB

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