tal.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import torch
  3. import torch.nn as nn
  4. from .checks import check_version
  5. from .metrics import bbox_iou
  6. TORCH_1_10 = check_version(torch.__version__, '1.10.0')
  7. def select_candidates_in_gts(xy_centers, gt_bboxes, eps=1e-9):
  8. """
  9. Select the positive anchor center in gt.
  10. Args:
  11. xy_centers (Tensor): shape(h*w, 4)
  12. gt_bboxes (Tensor): shape(b, n_boxes, 4)
  13. Returns:
  14. (Tensor): shape(b, n_boxes, h*w)
  15. """
  16. n_anchors = xy_centers.shape[0]
  17. bs, n_boxes, _ = gt_bboxes.shape
  18. lt, rb = gt_bboxes.view(-1, 1, 4).chunk(2, 2) # left-top, right-bottom
  19. bbox_deltas = torch.cat((xy_centers[None] - lt, rb - xy_centers[None]), dim=2).view(bs, n_boxes, n_anchors, -1)
  20. # return (bbox_deltas.min(3)[0] > eps).to(gt_bboxes.dtype)
  21. return bbox_deltas.amin(3).gt_(eps)
  22. def select_highest_overlaps(mask_pos, overlaps, n_max_boxes):
  23. """
  24. If an anchor box is assigned to multiple gts, the one with the highest IoI will be selected.
  25. Args:
  26. mask_pos (Tensor): shape(b, n_max_boxes, h*w)
  27. overlaps (Tensor): shape(b, n_max_boxes, h*w)
  28. Returns:
  29. target_gt_idx (Tensor): shape(b, h*w)
  30. fg_mask (Tensor): shape(b, h*w)
  31. mask_pos (Tensor): shape(b, n_max_boxes, h*w)
  32. """
  33. # (b, n_max_boxes, h*w) -> (b, h*w)
  34. fg_mask = mask_pos.sum(-2)
  35. if fg_mask.max() > 1: # one anchor is assigned to multiple gt_bboxes
  36. mask_multi_gts = (fg_mask.unsqueeze(1) > 1).expand(-1, n_max_boxes, -1) # (b, n_max_boxes, h*w)
  37. max_overlaps_idx = overlaps.argmax(1) # (b, h*w)
  38. is_max_overlaps = torch.zeros(mask_pos.shape, dtype=mask_pos.dtype, device=mask_pos.device)
  39. is_max_overlaps.scatter_(1, max_overlaps_idx.unsqueeze(1), 1)
  40. mask_pos = torch.where(mask_multi_gts, is_max_overlaps, mask_pos).float() # (b, n_max_boxes, h*w)
  41. fg_mask = mask_pos.sum(-2)
  42. # Find each grid serve which gt(index)
  43. target_gt_idx = mask_pos.argmax(-2) # (b, h*w)
  44. return target_gt_idx, fg_mask, mask_pos
  45. class TaskAlignedAssigner(nn.Module):
  46. """
  47. A task-aligned assigner for object detection.
  48. This class assigns ground-truth (gt) objects to anchors based on the task-aligned metric,
  49. which combines both classification and localization information.
  50. Attributes:
  51. topk (int): The number of top candidates to consider.
  52. num_classes (int): The number of object classes.
  53. alpha (float): The alpha parameter for the classification component of the task-aligned metric.
  54. beta (float): The beta parameter for the localization component of the task-aligned metric.
  55. eps (float): A small value to prevent division by zero.
  56. """
  57. def __init__(self, topk=13, num_classes=80, alpha=1.0, beta=6.0, eps=1e-9):
  58. """Initialize a TaskAlignedAssigner object with customizable hyperparameters."""
  59. super().__init__()
  60. self.topk = topk
  61. self.num_classes = num_classes
  62. self.bg_idx = num_classes
  63. self.alpha = alpha
  64. self.beta = beta
  65. self.eps = eps
  66. @torch.no_grad()
  67. def forward(self, pd_scores, pd_bboxes, anc_points, gt_labels, gt_bboxes, mask_gt):
  68. """
  69. Compute the task-aligned assignment.
  70. Reference https://github.com/Nioolek/PPYOLOE_pytorch/blob/master/ppyoloe/assigner/tal_assigner.py
  71. Args:
  72. pd_scores (Tensor): shape(bs, num_total_anchors, num_classes)
  73. pd_bboxes (Tensor): shape(bs, num_total_anchors, 4)
  74. anc_points (Tensor): shape(num_total_anchors, 2)
  75. gt_labels (Tensor): shape(bs, n_max_boxes, 1)
  76. gt_bboxes (Tensor): shape(bs, n_max_boxes, 4)
  77. mask_gt (Tensor): shape(bs, n_max_boxes, 1)
  78. Returns:
  79. target_labels (Tensor): shape(bs, num_total_anchors)
  80. target_bboxes (Tensor): shape(bs, num_total_anchors, 4)
  81. target_scores (Tensor): shape(bs, num_total_anchors, num_classes)
  82. fg_mask (Tensor): shape(bs, num_total_anchors)
  83. target_gt_idx (Tensor): shape(bs, num_total_anchors)
  84. """
  85. self.bs = pd_scores.size(0)
  86. self.n_max_boxes = gt_bboxes.size(1)
  87. if self.n_max_boxes == 0:
  88. device = gt_bboxes.device
  89. return (torch.full_like(pd_scores[..., 0], self.bg_idx).to(device), torch.zeros_like(pd_bboxes).to(device),
  90. torch.zeros_like(pd_scores).to(device), torch.zeros_like(pd_scores[..., 0]).to(device),
  91. torch.zeros_like(pd_scores[..., 0]).to(device))
  92. mask_pos, align_metric, overlaps = self.get_pos_mask(pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points,
  93. mask_gt)
  94. target_gt_idx, fg_mask, mask_pos = select_highest_overlaps(mask_pos, overlaps, self.n_max_boxes)
  95. # Assigned target
  96. target_labels, target_bboxes, target_scores = self.get_targets(gt_labels, gt_bboxes, target_gt_idx, fg_mask)
  97. # Normalize
  98. align_metric *= mask_pos
  99. pos_align_metrics = align_metric.amax(axis=-1, keepdim=True) # b, max_num_obj
  100. pos_overlaps = (overlaps * mask_pos).amax(axis=-1, keepdim=True) # b, max_num_obj
  101. norm_align_metric = (align_metric * pos_overlaps / (pos_align_metrics + self.eps)).amax(-2).unsqueeze(-1)
  102. target_scores = target_scores * norm_align_metric
  103. return target_labels, target_bboxes, target_scores, fg_mask.bool(), target_gt_idx
  104. def get_pos_mask(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points, mask_gt):
  105. """Get in_gts mask, (b, max_num_obj, h*w)."""
  106. mask_in_gts = select_candidates_in_gts(anc_points, gt_bboxes)
  107. # Get anchor_align metric, (b, max_num_obj, h*w)
  108. align_metric, overlaps = self.get_box_metrics(pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_in_gts * mask_gt)
  109. # Get topk_metric mask, (b, max_num_obj, h*w)
  110. mask_topk = self.select_topk_candidates(align_metric, topk_mask=mask_gt.expand(-1, -1, self.topk).bool())
  111. # Merge all mask to a final mask, (b, max_num_obj, h*w)
  112. mask_pos = mask_topk * mask_in_gts * mask_gt
  113. return mask_pos, align_metric, overlaps
  114. def get_box_metrics(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_gt):
  115. """Compute alignment metric given predicted and ground truth bounding boxes."""
  116. na = pd_bboxes.shape[-2]
  117. mask_gt = mask_gt.bool() # b, max_num_obj, h*w
  118. overlaps = torch.zeros([self.bs, self.n_max_boxes, na], dtype=pd_bboxes.dtype, device=pd_bboxes.device)
  119. bbox_scores = torch.zeros([self.bs, self.n_max_boxes, na], dtype=pd_scores.dtype, device=pd_scores.device)
  120. ind = torch.zeros([2, self.bs, self.n_max_boxes], dtype=torch.long) # 2, b, max_num_obj
  121. ind[0] = torch.arange(end=self.bs).view(-1, 1).expand(-1, self.n_max_boxes) # b, max_num_obj
  122. ind[1] = gt_labels.squeeze(-1) # b, max_num_obj
  123. # Get the scores of each grid for each gt cls
  124. bbox_scores[mask_gt] = pd_scores[ind[0], :, ind[1]][mask_gt] # b, max_num_obj, h*w
  125. # (b, max_num_obj, 1, 4), (b, 1, h*w, 4)
  126. pd_boxes = pd_bboxes.unsqueeze(1).expand(-1, self.n_max_boxes, -1, -1)[mask_gt]
  127. gt_boxes = gt_bboxes.unsqueeze(2).expand(-1, -1, na, -1)[mask_gt]
  128. overlaps[mask_gt] = bbox_iou(gt_boxes, pd_boxes, xywh=False, CIoU=True).squeeze(-1).clamp_(0)
  129. align_metric = bbox_scores.pow(self.alpha) * overlaps.pow(self.beta)
  130. return align_metric, overlaps
  131. def select_topk_candidates(self, metrics, largest=True, topk_mask=None):
  132. """
  133. Select the top-k candidates based on the given metrics.
  134. Args:
  135. metrics (Tensor): A tensor of shape (b, max_num_obj, h*w), where b is the batch size,
  136. max_num_obj is the maximum number of objects, and h*w represents the
  137. total number of anchor points.
  138. largest (bool): If True, select the largest values; otherwise, select the smallest values.
  139. topk_mask (Tensor): An optional boolean tensor of shape (b, max_num_obj, topk), where
  140. topk is the number of top candidates to consider. If not provided,
  141. the top-k values are automatically computed based on the given metrics.
  142. Returns:
  143. (Tensor): A tensor of shape (b, max_num_obj, h*w) containing the selected top-k candidates.
  144. """
  145. # (b, max_num_obj, topk)
  146. topk_metrics, topk_idxs = torch.topk(metrics, self.topk, dim=-1, largest=largest)
  147. if topk_mask is None:
  148. topk_mask = (topk_metrics.max(-1, keepdim=True)[0] > self.eps).expand_as(topk_idxs)
  149. # (b, max_num_obj, topk)
  150. topk_idxs.masked_fill_(~topk_mask, 0)
  151. # (b, max_num_obj, topk, h*w) -> (b, max_num_obj, h*w)
  152. count_tensor = torch.zeros(metrics.shape, dtype=torch.int8, device=topk_idxs.device)
  153. ones = torch.ones_like(topk_idxs[:, :, :1], dtype=torch.int8, device=topk_idxs.device)
  154. for k in range(self.topk):
  155. # Expand topk_idxs for each value of k and add 1 at the specified positions
  156. count_tensor.scatter_add_(-1, topk_idxs[:, :, k:k + 1], ones)
  157. # count_tensor.scatter_add_(-1, topk_idxs, torch.ones_like(topk_idxs, dtype=torch.int8, device=topk_idxs.device))
  158. # filter invalid bboxes
  159. count_tensor.masked_fill_(count_tensor > 1, 0)
  160. return count_tensor.to(metrics.dtype)
  161. def get_targets(self, gt_labels, gt_bboxes, target_gt_idx, fg_mask):
  162. """
  163. Compute target labels, target bounding boxes, and target scores for the positive anchor points.
  164. Args:
  165. gt_labels (Tensor): Ground truth labels of shape (b, max_num_obj, 1), where b is the
  166. batch size and max_num_obj is the maximum number of objects.
  167. gt_bboxes (Tensor): Ground truth bounding boxes of shape (b, max_num_obj, 4).
  168. target_gt_idx (Tensor): Indices of the assigned ground truth objects for positive
  169. anchor points, with shape (b, h*w), where h*w is the total
  170. number of anchor points.
  171. fg_mask (Tensor): A boolean tensor of shape (b, h*w) indicating the positive
  172. (foreground) anchor points.
  173. Returns:
  174. (Tuple[Tensor, Tensor, Tensor]): A tuple containing the following tensors:
  175. - target_labels (Tensor): Shape (b, h*w), containing the target labels for
  176. positive anchor points.
  177. - target_bboxes (Tensor): Shape (b, h*w, 4), containing the target bounding boxes
  178. for positive anchor points.
  179. - target_scores (Tensor): Shape (b, h*w, num_classes), containing the target scores
  180. for positive anchor points, where num_classes is the number
  181. of object classes.
  182. """
  183. # Assigned target labels, (b, 1)
  184. batch_ind = torch.arange(end=self.bs, dtype=torch.int64, device=gt_labels.device)[..., None]
  185. target_gt_idx = target_gt_idx + batch_ind * self.n_max_boxes # (b, h*w)
  186. target_labels = gt_labels.long().flatten()[target_gt_idx] # (b, h*w)
  187. # Assigned target boxes, (b, max_num_obj, 4) -> (b, h*w)
  188. target_bboxes = gt_bboxes.view(-1, 4)[target_gt_idx]
  189. # Assigned target scores
  190. target_labels.clamp_(0)
  191. # 10x faster than F.one_hot()
  192. target_scores = torch.zeros((target_labels.shape[0], target_labels.shape[1], self.num_classes),
  193. dtype=torch.int64,
  194. device=target_labels.device) # (b, h*w, 80)
  195. target_scores.scatter_(2, target_labels.unsqueeze(-1), 1)
  196. fg_scores_mask = fg_mask[:, :, None].repeat(1, 1, self.num_classes) # (b, h*w, 80)
  197. target_scores = torch.where(fg_scores_mask > 0, target_scores, 0)
  198. return target_labels, target_bboxes, target_scores
  199. def make_anchors(feats, strides, grid_cell_offset=0.5):
  200. """Generate anchors from features."""
  201. anchor_points, stride_tensor = [], []
  202. assert feats is not None
  203. dtype, device = feats[0].dtype, feats[0].device
  204. for i, stride in enumerate(strides):
  205. _, _, h, w = feats[i].shape
  206. sx = torch.arange(end=w, device=device, dtype=dtype) + grid_cell_offset # shift x
  207. sy = torch.arange(end=h, device=device, dtype=dtype) + grid_cell_offset # shift y
  208. sy, sx = torch.meshgrid(sy, sx, indexing='ij') if TORCH_1_10 else torch.meshgrid(sy, sx)
  209. anchor_points.append(torch.stack((sx, sy), -1).view(-1, 2))
  210. stride_tensor.append(torch.full((h * w, 1), stride, dtype=dtype, device=device))
  211. return torch.cat(anchor_points), torch.cat(stride_tensor)
  212. def dist2bbox(distance, anchor_points, xywh=True, dim=-1):
  213. """Transform distance(ltrb) to box(xywh or xyxy)."""
  214. lt, rb = distance.chunk(2, dim)
  215. x1y1 = anchor_points - lt
  216. x2y2 = anchor_points + rb
  217. if xywh:
  218. c_xy = (x1y1 + x2y2) / 2
  219. wh = x2y2 - x1y1
  220. return torch.cat((c_xy, wh), dim) # xywh bbox
  221. return torch.cat((x1y1, x2y2), dim) # xyxy bbox
  222. def bbox2dist(anchor_points, bbox, reg_max):
  223. """Transform bbox(xyxy) to dist(ltrb)."""
  224. x1y1, x2y2 = bbox.chunk(2, -1)
  225. return torch.cat((anchor_points - x1y1, x2y2 - anchor_points), -1).clamp_(0, reg_max - 0.01) # dist (lt, rb)