matcher.py 7.9 KB

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