matcher.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. import torch
  2. import torch.nn.functional as F
  3. from utils.box_ops import *
  4. # -------------------------- YOLOX's SimOTA Assigner --------------------------
  5. ## Simple OTA
  6. class SimOTA(object):
  7. """
  8. This code referenced to https://github.com/Megvii-BaseDetection/YOLOX/blob/main/yolox/models/yolo_head.py
  9. """
  10. def __init__(self, num_classes, center_sampling_radius, topk_candidate ):
  11. self.num_classes = num_classes
  12. self.center_sampling_radius = center_sampling_radius
  13. self.topk_candidate = topk_candidate
  14. @torch.no_grad()
  15. def __call__(self,
  16. fpn_strides,
  17. anchors,
  18. pred_cls,
  19. pred_box,
  20. tgt_labels,
  21. tgt_bboxes):
  22. # [M,]
  23. strides_tensor = torch.cat([torch.ones_like(anchor_i[:, 0]) * stride_i
  24. for stride_i, anchor_i in zip(fpn_strides, anchors)], dim=-1)
  25. # List[F, M, 2] -> [M, 2]
  26. anchors = torch.cat(anchors, dim=0)
  27. num_anchor = anchors.shape[0]
  28. num_gt = len(tgt_labels)
  29. # ----------------------- Find inside points -----------------------
  30. fg_mask, is_in_boxes_and_center = self.get_in_boxes_info(
  31. tgt_bboxes, anchors, strides_tensor, num_anchor, num_gt)
  32. cls_preds = pred_cls[fg_mask].float() # [Mp, C]
  33. box_preds = pred_box[fg_mask].float() # [Mp, 4]
  34. # ----------------------- Reg cost -----------------------
  35. pair_wise_ious, _ = box_iou(tgt_bboxes, box_preds) # [N, Mp]
  36. reg_cost = -torch.log(pair_wise_ious + 1e-8) # [N, Mp]
  37. # ----------------------- Cls cost -----------------------
  38. with torch.cuda.amp.autocast(enabled=False):
  39. # [Mp, C] -> [N, Mp, C]
  40. cls_preds_expand = cls_preds.unsqueeze(0).repeat(num_gt, 1, 1)
  41. # prepare cls_target
  42. cls_targets = F.one_hot(tgt_labels.long(), self.num_classes).float()
  43. cls_targets = cls_targets.unsqueeze(1).repeat(1, cls_preds_expand.size(1), 1)
  44. cls_targets *= pair_wise_ious.unsqueeze(-1) # iou-aware
  45. # [N, Mp]
  46. cls_cost = F.binary_cross_entropy_with_logits(cls_preds_expand, cls_targets, reduction="none").sum(-1)
  47. del cls_preds_expand
  48. #----------------------- Dynamic K-Matching -----------------------
  49. cost_matrix = (
  50. cls_cost
  51. + 3.0 * reg_cost
  52. + 100000.0 * (~is_in_boxes_and_center)
  53. ) # [N, Mp]
  54. (
  55. assigned_labels, # [num_fg,]
  56. assigned_ious, # [num_fg,]
  57. assigned_indexs, # [num_fg,]
  58. ) = self.dynamic_k_matching(
  59. cost_matrix,
  60. pair_wise_ious,
  61. tgt_labels,
  62. num_gt,
  63. fg_mask
  64. )
  65. del cls_cost, cost_matrix, pair_wise_ious, reg_cost
  66. return fg_mask, assigned_labels, assigned_ious, assigned_indexs
  67. def get_in_boxes_info(
  68. self,
  69. gt_bboxes, # [N, 4]
  70. anchors, # [M, 2]
  71. strides, # [M,]
  72. num_anchors, # M
  73. num_gt, # N
  74. ):
  75. # anchor center
  76. x_centers = anchors[:, 0]
  77. y_centers = anchors[:, 1]
  78. # [M,] -> [1, M] -> [N, M]
  79. x_centers = x_centers.unsqueeze(0).repeat(num_gt, 1)
  80. y_centers = y_centers.unsqueeze(0).repeat(num_gt, 1)
  81. # [N,] -> [N, 1] -> [N, M]
  82. gt_bboxes_l = gt_bboxes[:, 0].unsqueeze(1).repeat(1, num_anchors) # x1
  83. gt_bboxes_t = gt_bboxes[:, 1].unsqueeze(1).repeat(1, num_anchors) # y1
  84. gt_bboxes_r = gt_bboxes[:, 2].unsqueeze(1).repeat(1, num_anchors) # x2
  85. gt_bboxes_b = gt_bboxes[:, 3].unsqueeze(1).repeat(1, num_anchors) # y2
  86. b_l = x_centers - gt_bboxes_l
  87. b_r = gt_bboxes_r - x_centers
  88. b_t = y_centers - gt_bboxes_t
  89. b_b = gt_bboxes_b - y_centers
  90. bbox_deltas = torch.stack([b_l, b_t, b_r, b_b], 2)
  91. is_in_boxes = bbox_deltas.min(dim=-1).values > 0.0
  92. is_in_boxes_all = is_in_boxes.sum(dim=0) > 0
  93. # in fixed center
  94. center_radius = self.center_sampling_radius
  95. # [N, 2]
  96. gt_centers = (gt_bboxes[:, :2] + gt_bboxes[:, 2:]) * 0.5
  97. # [1, M]
  98. center_radius_ = center_radius * strides.unsqueeze(0)
  99. gt_bboxes_l = gt_centers[:, 0].unsqueeze(1).repeat(1, num_anchors) - center_radius_ # x1
  100. gt_bboxes_t = gt_centers[:, 1].unsqueeze(1).repeat(1, num_anchors) - center_radius_ # y1
  101. gt_bboxes_r = gt_centers[:, 0].unsqueeze(1).repeat(1, num_anchors) + center_radius_ # x2
  102. gt_bboxes_b = gt_centers[:, 1].unsqueeze(1).repeat(1, num_anchors) + center_radius_ # y2
  103. c_l = x_centers - gt_bboxes_l
  104. c_r = gt_bboxes_r - x_centers
  105. c_t = y_centers - gt_bboxes_t
  106. c_b = gt_bboxes_b - y_centers
  107. center_deltas = torch.stack([c_l, c_t, c_r, c_b], 2)
  108. is_in_centers = center_deltas.min(dim=-1).values > 0.0
  109. is_in_centers_all = is_in_centers.sum(dim=0) > 0
  110. # in boxes and in centers
  111. is_in_boxes_anchor = is_in_boxes_all | is_in_centers_all
  112. is_in_boxes_and_center = (
  113. is_in_boxes[:, is_in_boxes_anchor] & is_in_centers[:, is_in_boxes_anchor]
  114. )
  115. return is_in_boxes_anchor, is_in_boxes_and_center
  116. def dynamic_k_matching(
  117. self,
  118. cost,
  119. pair_wise_ious,
  120. gt_classes,
  121. num_gt,
  122. fg_mask
  123. ):
  124. # Dynamic K
  125. # ---------------------------------------------------------------
  126. matching_matrix = torch.zeros_like(cost, dtype=torch.uint8)
  127. ious_in_boxes_matrix = pair_wise_ious
  128. n_candidate_k = min(self.topk_candidate, ious_in_boxes_matrix.size(1))
  129. topk_ious, _ = torch.topk(ious_in_boxes_matrix, n_candidate_k, dim=1)
  130. dynamic_ks = torch.clamp(topk_ious.sum(1).int(), min=1)
  131. dynamic_ks = dynamic_ks.tolist()
  132. for gt_idx in range(num_gt):
  133. _, pos_idx = torch.topk(
  134. cost[gt_idx], k=dynamic_ks[gt_idx], largest=False
  135. )
  136. matching_matrix[gt_idx][pos_idx] = 1
  137. del topk_ious, dynamic_ks, pos_idx
  138. anchor_matching_gt = matching_matrix.sum(0)
  139. if (anchor_matching_gt > 1).sum() > 0:
  140. _, cost_argmin = torch.min(cost[:, anchor_matching_gt > 1], dim=0)
  141. matching_matrix[:, anchor_matching_gt > 1] *= 0
  142. matching_matrix[cost_argmin, anchor_matching_gt > 1] = 1
  143. fg_mask_inboxes = matching_matrix.sum(0) > 0
  144. fg_mask[fg_mask.clone()] = fg_mask_inboxes
  145. assigned_indexs = matching_matrix[:, fg_mask_inboxes].argmax(0)
  146. assigned_labels = gt_classes[assigned_indexs]
  147. assigned_ious = (matching_matrix * pair_wise_ious).sum(0)[
  148. fg_mask_inboxes
  149. ]
  150. return assigned_labels, assigned_ious, assigned_indexs
  151. # -------------------------- RTMDet's Aligned SimOTA Assigner --------------------------
  152. ## Aligned SimOTA
  153. class AlignedSimOTA(object):
  154. """
  155. This code referenced to https://github.com/open-mmlab/mmyolo/models/task_modules/assigners/batch_dsl_assigner.py
  156. """
  157. def __init__(self, num_classes, soft_center_radius=3.0, topk=13, iou_weight=3.0):
  158. self.num_classes = num_classes
  159. self.soft_center_radius = soft_center_radius
  160. self.topk = topk
  161. self.iou_weight = iou_weight
  162. @torch.no_grad()
  163. def __call__(self,
  164. fpn_strides,
  165. anchors,
  166. pred_cls,
  167. pred_box,
  168. gt_labels,
  169. gt_bboxes):
  170. # [M,]
  171. strides = torch.cat([torch.ones_like(anchor_i[:, 0]) * stride_i
  172. for stride_i, anchor_i in zip(fpn_strides, anchors)], dim=-1)
  173. # List[F, M, 2] -> [M, 2]
  174. anchors = torch.cat(anchors, dim=0)
  175. num_gt = len(gt_labels)
  176. # check gt
  177. if num_gt == 0 or gt_bboxes.max().item() == 0.:
  178. return {
  179. 'assigned_labels': gt_labels.new_full(pred_cls[..., 0].shape,
  180. self.num_classes,
  181. dtype=torch.long),
  182. 'assigned_bboxes': gt_bboxes.new_full(pred_box.shape, 0),
  183. 'assign_metrics': gt_bboxes.new_full(pred_cls[..., 0].shape, 0)
  184. }
  185. # get inside points: [N, M]
  186. is_in_gt = self.find_inside_points(gt_bboxes, anchors)
  187. valid_mask = is_in_gt.sum(dim=0) > 0 # [M,]
  188. # ----------------------------------- Soft center prior -----------------------------------
  189. gt_center = (gt_bboxes[..., :2] + gt_bboxes[..., 2:]) / 2.0
  190. distance = (anchors.unsqueeze(0) - gt_center.unsqueeze(1)
  191. ).pow(2).sum(-1).sqrt() / strides.unsqueeze(0) # [N, M]
  192. distance = distance * valid_mask.unsqueeze(0)
  193. soft_center_prior = torch.pow(10, distance - self.soft_center_radius)
  194. # ----------------------------------- Regression cost -----------------------------------
  195. pair_wise_ious, _ = box_iou(gt_bboxes, pred_box) # [N, M]
  196. pair_wise_ious_loss = -torch.log(pair_wise_ious + 1e-8) * self.iou_weight
  197. # ----------------------------------- Classification cost -----------------------------------
  198. ## select the predicted scores corresponded to the gt_labels
  199. pairwise_pred_scores = pred_cls.permute(1, 0) # [M, C] -> [C, M]
  200. pairwise_pred_scores = pairwise_pred_scores[gt_labels.long(), :].float() # [N, M]
  201. ## scale factor
  202. scale_factor = (pair_wise_ious - pairwise_pred_scores.sigmoid()).abs().pow(2.0)
  203. ## cls cost
  204. pair_wise_cls_loss = F.binary_cross_entropy_with_logits(
  205. pairwise_pred_scores, pair_wise_ious,
  206. reduction="none") * scale_factor # [N, M]
  207. del pairwise_pred_scores
  208. ## foreground cost matrix
  209. cost_matrix = pair_wise_cls_loss + pair_wise_ious_loss + soft_center_prior
  210. max_pad_value = torch.ones_like(cost_matrix) * 1e9
  211. cost_matrix = torch.where(valid_mask[None].repeat(num_gt, 1), # [N, M]
  212. cost_matrix, max_pad_value)
  213. # ----------------------------------- dynamic label assignment -----------------------------------
  214. (
  215. matched_pred_ious,
  216. matched_gt_inds,
  217. fg_mask_inboxes
  218. ) = self.dynamic_k_matching(
  219. cost_matrix,
  220. pair_wise_ious,
  221. num_gt
  222. )
  223. del pair_wise_cls_loss, cost_matrix, pair_wise_ious, pair_wise_ious_loss
  224. # -----------------------------------process assigned labels -----------------------------------
  225. assigned_labels = gt_labels.new_full(pred_cls[..., 0].shape,
  226. self.num_classes) # [M,]
  227. assigned_labels[fg_mask_inboxes] = gt_labels[matched_gt_inds].squeeze(-1)
  228. assigned_labels = assigned_labels.long() # [M,]
  229. assigned_bboxes = gt_bboxes.new_full(pred_box.shape, 0) # [M, 4]
  230. assigned_bboxes[fg_mask_inboxes] = gt_bboxes[matched_gt_inds] # [M, 4]
  231. assign_metrics = gt_bboxes.new_full(pred_cls[..., 0].shape, 0) # [M, 4]
  232. assign_metrics[fg_mask_inboxes] = matched_pred_ious # [M, 4]
  233. assigned_dict = dict(
  234. assigned_labels=assigned_labels,
  235. assigned_bboxes=assigned_bboxes,
  236. assign_metrics=assign_metrics
  237. )
  238. return assigned_dict
  239. def find_inside_points(self, gt_bboxes, anchors):
  240. """
  241. gt_bboxes: Tensor -> [N, 2]
  242. anchors: Tensor -> [M, 2]
  243. """
  244. num_anchors = anchors.shape[0]
  245. num_gt = gt_bboxes.shape[0]
  246. anchors_expand = anchors.unsqueeze(0).repeat(num_gt, 1, 1) # [N, M, 2]
  247. gt_bboxes_expand = gt_bboxes.unsqueeze(1).repeat(1, num_anchors, 1) # [N, M, 4]
  248. # offset
  249. lt = anchors_expand - gt_bboxes_expand[..., :2]
  250. rb = gt_bboxes_expand[..., 2:] - anchors_expand
  251. bbox_deltas = torch.cat([lt, rb], dim=-1)
  252. is_in_gts = bbox_deltas.min(dim=-1).values > 0
  253. return is_in_gts
  254. def dynamic_k_matching(self, cost_matrix, pairwise_ious, num_gt):
  255. """Use IoU and matching cost to calculate the dynamic top-k positive
  256. targets.
  257. Args:
  258. cost_matrix (Tensor): Cost matrix.
  259. pairwise_ious (Tensor): Pairwise iou matrix.
  260. num_gt (int): Number of gt.
  261. valid_mask (Tensor): Mask for valid bboxes.
  262. Returns:
  263. tuple: matched ious and gt indexes.
  264. """
  265. matching_matrix = torch.zeros_like(cost_matrix, dtype=torch.uint8)
  266. # select candidate topk ious for dynamic-k calculation
  267. candidate_topk = min(self.topk, pairwise_ious.size(1))
  268. topk_ious, _ = torch.topk(pairwise_ious, candidate_topk, dim=1)
  269. # calculate dynamic k for each gt
  270. dynamic_ks = torch.clamp(topk_ious.sum(1).int(), min=1)
  271. # sorting the batch cost matirx is faster than topk
  272. _, sorted_indices = torch.sort(cost_matrix, dim=1)
  273. for gt_idx in range(num_gt):
  274. topk_ids = sorted_indices[gt_idx, :dynamic_ks[gt_idx]]
  275. matching_matrix[gt_idx, :][topk_ids] = 1
  276. del topk_ious, dynamic_ks, topk_ids
  277. prior_match_gt_mask = matching_matrix.sum(0) > 1
  278. if prior_match_gt_mask.sum() > 0:
  279. cost_min, cost_argmin = torch.min(
  280. cost_matrix[:, prior_match_gt_mask], dim=0)
  281. matching_matrix[:, prior_match_gt_mask] *= 0
  282. matching_matrix[cost_argmin, prior_match_gt_mask] = 1
  283. # get foreground mask inside box and center prior
  284. fg_mask_inboxes = matching_matrix.sum(0) > 0
  285. matched_pred_ious = (matching_matrix *
  286. pairwise_ious).sum(0)[fg_mask_inboxes]
  287. matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)
  288. return matched_pred_ious, matched_gt_inds, fg_mask_inboxes
  289. def build_matcher(cfg, num_classes):
  290. if cfg['matcher'] == "simota":
  291. matcher = SimOTA(
  292. center_sampling_radius=cfg['matcher_hpy'][cfg['matcher']]['center_sampling_radius'],
  293. topk_candidate=cfg['matcher_hpy'][cfg['matcher']]['topk_candidate'],
  294. num_classes=num_classes
  295. )
  296. elif cfg['matcher'] == "aligned_simota":
  297. matcher = AlignedSimOTA(
  298. num_classes=num_classes,
  299. soft_center_radius=cfg['matcher_hpy'][cfg['matcher']]['soft_center_radius'],
  300. topk=cfg['matcher_hpy'][cfg['matcher']]['topk_candicate'],
  301. iou_weight=cfg['matcher_hpy'][cfg['matcher']]['iou_weight']
  302. )
  303. return matcher