Meta Byte Track
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

yolo_head.py 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. #!/usr/bin/env python3
  2. # -*- coding:utf-8 -*-
  3. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  4. from loguru import logger
  5. import torch
  6. import torch.nn as nn
  7. import torch.nn.functional as F
  8. from yolox.utils import bboxes_iou
  9. import math
  10. from .losses import IOUloss
  11. from .network_blocks import BaseConv, DWConv
  12. class YOLOXHead(nn.Module):
  13. def __init__(
  14. self,
  15. num_classes,
  16. width=1.0,
  17. strides=[8, 16, 32],
  18. in_channels=[256, 512, 1024],
  19. act="silu",
  20. depthwise=False,
  21. ):
  22. """
  23. Args:
  24. act (str): activation type of conv. Defalut value: "silu".
  25. depthwise (bool): wheather apply depthwise conv in conv branch. Defalut value: False.
  26. """
  27. super().__init__()
  28. self.n_anchors = 1
  29. self.num_classes = num_classes
  30. self.decode_in_inference = True # for deploy, set to False
  31. self.cls_convs = nn.ModuleList()
  32. self.reg_convs = nn.ModuleList()
  33. self.cls_preds = nn.ModuleList()
  34. self.reg_preds = nn.ModuleList()
  35. self.obj_preds = nn.ModuleList()
  36. self.stems = nn.ModuleList()
  37. Conv = DWConv if depthwise else BaseConv
  38. for i in range(len(in_channels)):
  39. self.stems.append(
  40. BaseConv(
  41. in_channels=int(in_channels[i] * width),
  42. out_channels=int(256 * width),
  43. ksize=1,
  44. stride=1,
  45. act=act,
  46. )
  47. )
  48. self.cls_convs.append(
  49. nn.Sequential(
  50. *[
  51. Conv(
  52. in_channels=int(256 * width),
  53. out_channels=int(256 * width),
  54. ksize=3,
  55. stride=1,
  56. act=act,
  57. ),
  58. Conv(
  59. in_channels=int(256 * width),
  60. out_channels=int(256 * width),
  61. ksize=3,
  62. stride=1,
  63. act=act,
  64. ),
  65. ]
  66. )
  67. )
  68. self.reg_convs.append(
  69. nn.Sequential(
  70. *[
  71. Conv(
  72. in_channels=int(256 * width),
  73. out_channels=int(256 * width),
  74. ksize=3,
  75. stride=1,
  76. act=act,
  77. ),
  78. Conv(
  79. in_channels=int(256 * width),
  80. out_channels=int(256 * width),
  81. ksize=3,
  82. stride=1,
  83. act=act,
  84. ),
  85. ]
  86. )
  87. )
  88. self.cls_preds.append(
  89. nn.Conv2d(
  90. in_channels=int(256 * width),
  91. out_channels=self.n_anchors * self.num_classes,
  92. kernel_size=1,
  93. stride=1,
  94. padding=0,
  95. )
  96. )
  97. self.reg_preds.append(
  98. nn.Conv2d(
  99. in_channels=int(256 * width),
  100. out_channels=4,
  101. kernel_size=1,
  102. stride=1,
  103. padding=0,
  104. )
  105. )
  106. self.obj_preds.append(
  107. nn.Conv2d(
  108. in_channels=int(256 * width),
  109. out_channels=self.n_anchors * 1,
  110. kernel_size=1,
  111. stride=1,
  112. padding=0,
  113. )
  114. )
  115. self.use_l1 = False
  116. self.l1_loss = nn.L1Loss(reduction="none")
  117. self.bcewithlog_loss = nn.BCEWithLogitsLoss(reduction="none")
  118. self.iou_loss = IOUloss(reduction="none")
  119. self.strides = strides
  120. self.grids = [torch.zeros(1)] * len(in_channels)
  121. self.expanded_strides = [None] * len(in_channels)
  122. def initialize_biases(self, prior_prob):
  123. for conv in self.cls_preds:
  124. b = conv.bias.view(self.n_anchors, -1)
  125. b.data.fill_(-math.log((1 - prior_prob) / prior_prob))
  126. conv.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  127. for conv in self.obj_preds:
  128. b = conv.bias.view(self.n_anchors, -1)
  129. b.data.fill_(-math.log((1 - prior_prob) / prior_prob))
  130. conv.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
  131. def forward(self, xin, labels=None, imgs=None):
  132. outputs = []
  133. origin_preds = []
  134. x_shifts = []
  135. y_shifts = []
  136. expanded_strides = []
  137. for k, (cls_conv, reg_conv, stride_this_level, x) in enumerate(
  138. zip(self.cls_convs, self.reg_convs, self.strides, xin)
  139. ):
  140. x = self.stems[k](x)
  141. cls_x = x
  142. reg_x = x
  143. cls_feat = cls_conv(cls_x)
  144. cls_output = self.cls_preds[k](cls_feat)
  145. reg_feat = reg_conv(reg_x)
  146. reg_output = self.reg_preds[k](reg_feat)
  147. obj_output = self.obj_preds[k](reg_feat)
  148. if self.training:
  149. output = torch.cat([reg_output, obj_output, cls_output], 1)
  150. output, grid = self.get_output_and_grid(
  151. output, k, stride_this_level, xin[0].type()
  152. )
  153. x_shifts.append(grid[:, :, 0])
  154. y_shifts.append(grid[:, :, 1])
  155. expanded_strides.append(
  156. torch.zeros(1, grid.shape[1])
  157. .fill_(stride_this_level)
  158. .type_as(xin[0])
  159. )
  160. if self.use_l1:
  161. batch_size = reg_output.shape[0]
  162. hsize, wsize = reg_output.shape[-2:]
  163. reg_output = reg_output.view(
  164. batch_size, self.n_anchors, 4, hsize, wsize
  165. )
  166. reg_output = reg_output.permute(0, 1, 3, 4, 2).reshape(
  167. batch_size, -1, 4
  168. )
  169. origin_preds.append(reg_output.clone())
  170. else:
  171. output = torch.cat(
  172. [reg_output, obj_output.sigmoid(), cls_output.sigmoid()], 1
  173. )
  174. # TODO: have to see output shape to know whats going on in head
  175. outputs.append(output)
  176. if self.training:
  177. return self.get_losses(
  178. imgs,
  179. x_shifts,
  180. y_shifts,
  181. expanded_strides,
  182. labels,
  183. torch.cat(outputs, 1),
  184. origin_preds,
  185. dtype=xin[0].dtype,
  186. )
  187. else:
  188. self.hw = [x.shape[-2:] for x in outputs]
  189. # [batch, n_anchors_all, 85]
  190. outputs = torch.cat(
  191. [x.flatten(start_dim=2) for x in outputs], dim=2
  192. ).permute(0, 2, 1)
  193. if self.decode_in_inference:
  194. return self.decode_outputs(outputs, dtype=xin[0].type())
  195. else:
  196. return outputs
  197. def get_output_and_grid(self, output, k, stride, dtype):
  198. grid = self.grids[k]
  199. batch_size = output.shape[0]
  200. n_ch = 5 + self.num_classes
  201. hsize, wsize = output.shape[-2:]
  202. if grid.shape[2:4] != output.shape[2:4]:
  203. yv, xv = torch.meshgrid([torch.arange(hsize), torch.arange(wsize)])
  204. grid = torch.stack((xv, yv), 2).view(1, 1, hsize, wsize, 2).type(dtype)
  205. self.grids[k] = grid
  206. output = output.view(batch_size, self.n_anchors, n_ch, hsize, wsize)
  207. output = output.permute(0, 1, 3, 4, 2).reshape(
  208. batch_size, self.n_anchors * hsize * wsize, -1
  209. )
  210. grid = grid.view(1, -1, 2)
  211. output[..., :2] = (output[..., :2] + grid) * stride
  212. output[..., 2:4] = torch.exp(output[..., 2:4]) * stride
  213. return output, grid
  214. def decode_outputs(self, outputs, dtype):
  215. grids = []
  216. strides = []
  217. for (hsize, wsize), stride in zip(self.hw, self.strides):
  218. yv, xv = torch.meshgrid([torch.arange(hsize), torch.arange(wsize)])
  219. grid = torch.stack((xv, yv), 2).view(1, -1, 2)
  220. grids.append(grid)
  221. shape = grid.shape[:2]
  222. strides.append(torch.full((*shape, 1), stride))
  223. grids = torch.cat(grids, dim=1).type(dtype)
  224. strides = torch.cat(strides, dim=1).type(dtype)
  225. outputs[..., :2] = (outputs[..., :2] + grids) * strides
  226. outputs[..., 2:4] = torch.exp(outputs[..., 2:4]) * strides
  227. return outputs
  228. def get_losses(
  229. self,
  230. imgs,
  231. x_shifts,
  232. y_shifts,
  233. expanded_strides,
  234. labels,
  235. outputs,
  236. origin_preds,
  237. dtype,
  238. ):
  239. bbox_preds = outputs[:, :, :4] # [batch, n_anchors_all, 4]
  240. obj_preds = outputs[:, :, 4].unsqueeze(-1) # [batch, n_anchors_all, 1]
  241. cls_preds = outputs[:, :, 5:] # [batch, n_anchors_all, n_cls]
  242. # calculate targets
  243. mixup = labels.shape[2] > 5
  244. if mixup:
  245. label_cut = labels[..., :5]
  246. else:
  247. label_cut = labels
  248. nlabel = (label_cut.sum(dim=2) > 0).sum(dim=1) # number of objects
  249. total_num_anchors = outputs.shape[1]
  250. x_shifts = torch.cat(x_shifts, 1) # [1, n_anchors_all]
  251. y_shifts = torch.cat(y_shifts, 1) # [1, n_anchors_all]
  252. expanded_strides = torch.cat(expanded_strides, 1)
  253. if self.use_l1:
  254. origin_preds = torch.cat(origin_preds, 1)
  255. cls_targets = []
  256. reg_targets = []
  257. l1_targets = []
  258. obj_targets = []
  259. fg_masks = []
  260. num_fg = 0.0
  261. num_gts = 0.0
  262. for batch_idx in range(outputs.shape[0]):
  263. num_gt = int(nlabel[batch_idx])
  264. num_gts += num_gt
  265. if num_gt == 0:
  266. cls_target = outputs.new_zeros((0, self.num_classes))
  267. reg_target = outputs.new_zeros((0, 4))
  268. l1_target = outputs.new_zeros((0, 4))
  269. obj_target = outputs.new_zeros((total_num_anchors, 1))
  270. fg_mask = outputs.new_zeros(total_num_anchors).bool()
  271. else:
  272. gt_bboxes_per_image = labels[batch_idx, :num_gt, 1:5]
  273. gt_classes = labels[batch_idx, :num_gt, 0]
  274. bboxes_preds_per_image = bbox_preds[batch_idx]
  275. try:
  276. (
  277. gt_matched_classes,
  278. fg_mask,
  279. pred_ious_this_matching,
  280. matched_gt_inds,
  281. num_fg_img,
  282. ) = self.get_assignments( # noqa
  283. batch_idx,
  284. num_gt,
  285. total_num_anchors,
  286. gt_bboxes_per_image,
  287. gt_classes,
  288. bboxes_preds_per_image,
  289. expanded_strides,
  290. x_shifts,
  291. y_shifts,
  292. cls_preds,
  293. bbox_preds,
  294. obj_preds,
  295. labels,
  296. imgs,
  297. )
  298. except RuntimeError:
  299. logger.info(
  300. "OOM RuntimeError is raised due to the huge memory cost during label assignment. \
  301. CPU mode is applied in this batch. If you want to avoid this issue, \
  302. try to reduce the batch size or image size."
  303. )
  304. print("OOM RuntimeError is raised due to the huge memory cost during label assignment. \
  305. CPU mode is applied in this batch. If you want to avoid this issue, \
  306. try to reduce the batch size or image size.")
  307. torch.cuda.empty_cache()
  308. (
  309. gt_matched_classes,
  310. fg_mask,
  311. pred_ious_this_matching,
  312. matched_gt_inds,
  313. num_fg_img,
  314. ) = self.get_assignments( # noqa
  315. batch_idx,
  316. num_gt,
  317. total_num_anchors,
  318. gt_bboxes_per_image,
  319. gt_classes,
  320. bboxes_preds_per_image,
  321. expanded_strides,
  322. x_shifts,
  323. y_shifts,
  324. cls_preds,
  325. bbox_preds,
  326. obj_preds,
  327. labels,
  328. imgs,
  329. "cpu",
  330. )
  331. torch.cuda.empty_cache()
  332. num_fg += num_fg_img
  333. cls_target = F.one_hot(
  334. gt_matched_classes.to(torch.int64), self.num_classes
  335. ) * pred_ious_this_matching.unsqueeze(-1)
  336. obj_target = fg_mask.unsqueeze(-1)
  337. reg_target = gt_bboxes_per_image[matched_gt_inds]
  338. if self.use_l1:
  339. l1_target = self.get_l1_target(
  340. outputs.new_zeros((num_fg_img, 4)),
  341. gt_bboxes_per_image[matched_gt_inds],
  342. expanded_strides[0][fg_mask],
  343. x_shifts=x_shifts[0][fg_mask],
  344. y_shifts=y_shifts[0][fg_mask],
  345. )
  346. cls_targets.append(cls_target)
  347. reg_targets.append(reg_target)
  348. obj_targets.append(obj_target.to(dtype))
  349. fg_masks.append(fg_mask)
  350. if self.use_l1:
  351. l1_targets.append(l1_target)
  352. cls_targets = torch.cat(cls_targets, 0)
  353. reg_targets = torch.cat(reg_targets, 0)
  354. obj_targets = torch.cat(obj_targets, 0)
  355. fg_masks = torch.cat(fg_masks, 0)
  356. if self.use_l1:
  357. l1_targets = torch.cat(l1_targets, 0)
  358. num_fg = max(num_fg, 1)
  359. loss_iou = (
  360. self.iou_loss(bbox_preds.view(-1, 4)[fg_masks], reg_targets)
  361. ).sum() / num_fg
  362. loss_obj = (
  363. self.bcewithlog_loss(obj_preds.view(-1, 1), obj_targets)
  364. ).sum() / num_fg
  365. loss_cls = (
  366. self.bcewithlog_loss(
  367. cls_preds.view(-1, self.num_classes)[fg_masks], cls_targets
  368. )
  369. ).sum() / num_fg
  370. if self.use_l1:
  371. loss_l1 = (
  372. self.l1_loss(origin_preds.view(-1, 4)[fg_masks], l1_targets)
  373. ).sum() / num_fg
  374. else:
  375. loss_l1 = 0.0
  376. reg_weight = 5.0
  377. loss = reg_weight * loss_iou + loss_obj + loss_cls + loss_l1
  378. return (
  379. loss,
  380. reg_weight * loss_iou,
  381. loss_obj,
  382. loss_cls,
  383. loss_l1,
  384. num_fg / max(num_gts, 1),
  385. )
  386. def get_l1_target(self, l1_target, gt, stride, x_shifts, y_shifts, eps=1e-8):
  387. l1_target[:, 0] = gt[:, 0] / stride - x_shifts
  388. l1_target[:, 1] = gt[:, 1] / stride - y_shifts
  389. l1_target[:, 2] = torch.log(gt[:, 2] / stride + eps)
  390. l1_target[:, 3] = torch.log(gt[:, 3] / stride + eps)
  391. return l1_target
  392. @torch.no_grad()
  393. def get_assignments(
  394. self,
  395. batch_idx,
  396. num_gt,
  397. total_num_anchors,
  398. gt_bboxes_per_image,
  399. gt_classes,
  400. bboxes_preds_per_image,
  401. expanded_strides,
  402. x_shifts,
  403. y_shifts,
  404. cls_preds,
  405. bbox_preds,
  406. obj_preds,
  407. labels,
  408. imgs,
  409. mode="gpu",
  410. ):
  411. if mode == "cpu":
  412. print("------------CPU Mode for This Batch-------------")
  413. gt_bboxes_per_image = gt_bboxes_per_image.cpu().float()
  414. bboxes_preds_per_image = bboxes_preds_per_image.cpu().float()
  415. gt_classes = gt_classes.cpu().float()
  416. expanded_strides = expanded_strides.cpu().float()
  417. x_shifts = x_shifts.cpu()
  418. y_shifts = y_shifts.cpu()
  419. img_size = imgs.shape[2:]
  420. fg_mask, is_in_boxes_and_center = self.get_in_boxes_info(
  421. gt_bboxes_per_image,
  422. expanded_strides,
  423. x_shifts,
  424. y_shifts,
  425. total_num_anchors,
  426. num_gt,
  427. img_size
  428. )
  429. bboxes_preds_per_image = bboxes_preds_per_image[fg_mask]
  430. cls_preds_ = cls_preds[batch_idx][fg_mask]
  431. obj_preds_ = obj_preds[batch_idx][fg_mask]
  432. num_in_boxes_anchor = bboxes_preds_per_image.shape[0]
  433. if mode == "cpu":
  434. gt_bboxes_per_image = gt_bboxes_per_image.cpu()
  435. bboxes_preds_per_image = bboxes_preds_per_image.cpu()
  436. pair_wise_ious = bboxes_iou(gt_bboxes_per_image, bboxes_preds_per_image, False)
  437. gt_cls_per_image = (
  438. F.one_hot(gt_classes.to(torch.int64), self.num_classes)
  439. .float()
  440. .unsqueeze(1)
  441. .repeat(1, num_in_boxes_anchor, 1)
  442. )
  443. pair_wise_ious_loss = -torch.log(pair_wise_ious + 1e-8)
  444. if mode == "cpu":
  445. cls_preds_, obj_preds_ = cls_preds_.cpu(), obj_preds_.cpu()
  446. with torch.cuda.amp.autocast(enabled=False):
  447. cls_preds_ = (
  448. cls_preds_.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
  449. * obj_preds_.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
  450. )
  451. pair_wise_cls_loss = F.binary_cross_entropy(
  452. cls_preds_.sqrt_(), gt_cls_per_image, reduction="none"
  453. ).sum(-1)
  454. del cls_preds_
  455. cost = (
  456. pair_wise_cls_loss
  457. + 3.0 * pair_wise_ious_loss
  458. + 100000.0 * (~is_in_boxes_and_center)
  459. )
  460. (
  461. num_fg,
  462. gt_matched_classes,
  463. pred_ious_this_matching,
  464. matched_gt_inds,
  465. ) = self.dynamic_k_matching(cost, pair_wise_ious, gt_classes, num_gt, fg_mask)
  466. del pair_wise_cls_loss, cost, pair_wise_ious, pair_wise_ious_loss
  467. if mode == "cpu":
  468. gt_matched_classes = gt_matched_classes.cuda()
  469. fg_mask = fg_mask.cuda()
  470. pred_ious_this_matching = pred_ious_this_matching.cuda()
  471. matched_gt_inds = matched_gt_inds.cuda()
  472. return (
  473. gt_matched_classes,
  474. fg_mask,
  475. pred_ious_this_matching,
  476. matched_gt_inds,
  477. num_fg,
  478. )
  479. def get_in_boxes_info(
  480. self,
  481. gt_bboxes_per_image,
  482. expanded_strides,
  483. x_shifts,
  484. y_shifts,
  485. total_num_anchors,
  486. num_gt,
  487. img_size
  488. ):
  489. expanded_strides_per_image = expanded_strides[0]
  490. x_shifts_per_image = x_shifts[0] * expanded_strides_per_image
  491. y_shifts_per_image = y_shifts[0] * expanded_strides_per_image
  492. x_centers_per_image = (
  493. (x_shifts_per_image + 0.5 * expanded_strides_per_image)
  494. .unsqueeze(0)
  495. .repeat(num_gt, 1)
  496. ) # [n_anchor] -> [n_gt, n_anchor]
  497. y_centers_per_image = (
  498. (y_shifts_per_image + 0.5 * expanded_strides_per_image)
  499. .unsqueeze(0)
  500. .repeat(num_gt, 1)
  501. )
  502. gt_bboxes_per_image_l = (
  503. (gt_bboxes_per_image[:, 0] - 0.5 * gt_bboxes_per_image[:, 2])
  504. .unsqueeze(1)
  505. .repeat(1, total_num_anchors)
  506. )
  507. gt_bboxes_per_image_r = (
  508. (gt_bboxes_per_image[:, 0] + 0.5 * gt_bboxes_per_image[:, 2])
  509. .unsqueeze(1)
  510. .repeat(1, total_num_anchors)
  511. )
  512. gt_bboxes_per_image_t = (
  513. (gt_bboxes_per_image[:, 1] - 0.5 * gt_bboxes_per_image[:, 3])
  514. .unsqueeze(1)
  515. .repeat(1, total_num_anchors)
  516. )
  517. gt_bboxes_per_image_b = (
  518. (gt_bboxes_per_image[:, 1] + 0.5 * gt_bboxes_per_image[:, 3])
  519. .unsqueeze(1)
  520. .repeat(1, total_num_anchors)
  521. )
  522. b_l = x_centers_per_image - gt_bboxes_per_image_l
  523. b_r = gt_bboxes_per_image_r - x_centers_per_image
  524. b_t = y_centers_per_image - gt_bboxes_per_image_t
  525. b_b = gt_bboxes_per_image_b - y_centers_per_image
  526. bbox_deltas = torch.stack([b_l, b_t, b_r, b_b], 2)
  527. is_in_boxes = bbox_deltas.min(dim=-1).values > 0.0
  528. is_in_boxes_all = is_in_boxes.sum(dim=0) > 0
  529. # in fixed center
  530. center_radius = 2.5
  531. # clip center inside image
  532. gt_bboxes_per_image_clip = gt_bboxes_per_image[:, 0:2].clone()
  533. gt_bboxes_per_image_clip[:, 0] = torch.clamp(gt_bboxes_per_image_clip[:, 0], min=0, max=img_size[1])
  534. gt_bboxes_per_image_clip[:, 1] = torch.clamp(gt_bboxes_per_image_clip[:, 1], min=0, max=img_size[0])
  535. gt_bboxes_per_image_l = (gt_bboxes_per_image_clip[:, 0]).unsqueeze(1).repeat(
  536. 1, total_num_anchors
  537. ) - center_radius * expanded_strides_per_image.unsqueeze(0)
  538. gt_bboxes_per_image_r = (gt_bboxes_per_image_clip[:, 0]).unsqueeze(1).repeat(
  539. 1, total_num_anchors
  540. ) + center_radius * expanded_strides_per_image.unsqueeze(0)
  541. gt_bboxes_per_image_t = (gt_bboxes_per_image_clip[:, 1]).unsqueeze(1).repeat(
  542. 1, total_num_anchors
  543. ) - center_radius * expanded_strides_per_image.unsqueeze(0)
  544. gt_bboxes_per_image_b = (gt_bboxes_per_image_clip[:, 1]).unsqueeze(1).repeat(
  545. 1, total_num_anchors
  546. ) + center_radius * expanded_strides_per_image.unsqueeze(0)
  547. c_l = x_centers_per_image - gt_bboxes_per_image_l
  548. c_r = gt_bboxes_per_image_r - x_centers_per_image
  549. c_t = y_centers_per_image - gt_bboxes_per_image_t
  550. c_b = gt_bboxes_per_image_b - y_centers_per_image
  551. center_deltas = torch.stack([c_l, c_t, c_r, c_b], 2)
  552. is_in_centers = center_deltas.min(dim=-1).values > 0.0
  553. is_in_centers_all = is_in_centers.sum(dim=0) > 0
  554. # in boxes and in centers
  555. is_in_boxes_anchor = is_in_boxes_all | is_in_centers_all
  556. is_in_boxes_and_center = (
  557. is_in_boxes[:, is_in_boxes_anchor] & is_in_centers[:, is_in_boxes_anchor]
  558. )
  559. del gt_bboxes_per_image_clip
  560. return is_in_boxes_anchor, is_in_boxes_and_center
  561. def dynamic_k_matching(self, cost, pair_wise_ious, gt_classes, num_gt, fg_mask):
  562. # Dynamic K
  563. # ---------------------------------------------------------------
  564. matching_matrix = torch.zeros_like(cost)
  565. ious_in_boxes_matrix = pair_wise_ious
  566. n_candidate_k = min(10, ious_in_boxes_matrix.size(1))
  567. topk_ious, _ = torch.topk(ious_in_boxes_matrix, n_candidate_k, dim=1)
  568. dynamic_ks = torch.clamp(topk_ious.sum(1).int(), min=1)
  569. for gt_idx in range(num_gt):
  570. _, pos_idx = torch.topk(
  571. cost[gt_idx], k=dynamic_ks[gt_idx].item(), largest=False
  572. )
  573. matching_matrix[gt_idx][pos_idx] = 1.0
  574. del topk_ious, dynamic_ks, pos_idx
  575. anchor_matching_gt = matching_matrix.sum(0)
  576. if (anchor_matching_gt > 1).sum() > 0:
  577. cost_min, cost_argmin = torch.min(cost[:, anchor_matching_gt > 1], dim=0)
  578. matching_matrix[:, anchor_matching_gt > 1] *= 0.0
  579. matching_matrix[cost_argmin, anchor_matching_gt > 1] = 1.0
  580. fg_mask_inboxes = matching_matrix.sum(0) > 0.0
  581. num_fg = fg_mask_inboxes.sum().item()
  582. fg_mask[fg_mask.clone()] = fg_mask_inboxes
  583. matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)
  584. gt_matched_classes = gt_classes[matched_gt_inds]
  585. pred_ious_this_matching = (matching_matrix * pair_wise_ious).sum(0)[
  586. fg_mask_inboxes
  587. ]
  588. return num_fg, gt_matched_classes, pred_ious_this_matching, matched_gt_inds