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 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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. # logger.info("labels.shape:{}".format(labels.shape))
  178. # logger.info("torch.cat(outputs, 1).shape:{}".format(torch.cat(outputs, 1).shape))
  179. # if torch.isnan(torch.cat(outputs, 1)).sum().item():
  180. # logger.info('There is Nan value in outputs {}'.format(torch.isnan(torch.cat(outputs, 1)).sum().item()))
  181. return self.get_losses(
  182. imgs,
  183. x_shifts,
  184. y_shifts,
  185. expanded_strides,
  186. labels,
  187. torch.cat(outputs, 1),
  188. origin_preds,
  189. dtype=xin[0].dtype,
  190. )
  191. else:
  192. self.hw = [x.shape[-2:] for x in outputs]
  193. # [batch, n_anchors_all, 85]
  194. outputs = torch.cat(
  195. [x.flatten(start_dim=2) for x in outputs], dim=2
  196. ).permute(0, 2, 1)
  197. if self.decode_in_inference:
  198. return self.decode_outputs(outputs, dtype=xin[0].type())
  199. else:
  200. return outputs
  201. def get_output_and_grid(self, output, k, stride, dtype):
  202. grid = self.grids[k]
  203. batch_size = output.shape[0]
  204. n_ch = 5 + self.num_classes
  205. hsize, wsize = output.shape[-2:]
  206. if grid.shape[2:4] != output.shape[2:4]:
  207. yv, xv = torch.meshgrid([torch.arange(hsize), torch.arange(wsize)])
  208. grid = torch.stack((xv, yv), 2).view(1, 1, hsize, wsize, 2).type(dtype)
  209. self.grids[k] = grid
  210. output = output.view(batch_size, self.n_anchors, n_ch, hsize, wsize)
  211. output = output.permute(0, 1, 3, 4, 2).reshape(
  212. batch_size, self.n_anchors * hsize * wsize, -1
  213. )
  214. grid = grid.view(1, -1, 2)
  215. output[..., :2] = (output[..., :2] + grid) * stride
  216. output[..., 2:4] = torch.exp(output[..., 2:4]) * stride
  217. return output, grid
  218. def decode_outputs(self, outputs, dtype):
  219. grids = []
  220. strides = []
  221. for (hsize, wsize), stride in zip(self.hw, self.strides):
  222. yv, xv = torch.meshgrid([torch.arange(hsize), torch.arange(wsize)])
  223. grid = torch.stack((xv, yv), 2).view(1, -1, 2)
  224. grids.append(grid)
  225. shape = grid.shape[:2]
  226. strides.append(torch.full((*shape, 1), stride))
  227. grids = torch.cat(grids, dim=1).type(dtype)
  228. strides = torch.cat(strides, dim=1).type(dtype)
  229. outputs[..., :2] = (outputs[..., :2] + grids) * strides
  230. outputs[..., 2:4] = torch.exp(outputs[..., 2:4]) * strides
  231. return outputs
  232. def get_losses(
  233. self,
  234. imgs,
  235. x_shifts,
  236. y_shifts,
  237. expanded_strides,
  238. labels,
  239. outputs,
  240. origin_preds,
  241. dtype,
  242. ):
  243. bbox_preds = outputs[:, :, :4] # [batch, n_anchors_all, 4]
  244. obj_preds = outputs[:, :, 4].unsqueeze(-1) # [batch, n_anchors_all, 1]
  245. cls_preds = outputs[:, :, 5:] # [batch, n_anchors_all, n_cls]
  246. # calculate targets
  247. mixup = labels.shape[2] > 5
  248. if mixup:
  249. label_cut = labels[..., :5]
  250. else:
  251. label_cut = labels
  252. nlabel = (label_cut.sum(dim=2) > 0).sum(dim=1) # number of objects
  253. total_num_anchors = outputs.shape[1]
  254. x_shifts = torch.cat(x_shifts, 1) # [1, n_anchors_all]
  255. y_shifts = torch.cat(y_shifts, 1) # [1, n_anchors_all]
  256. expanded_strides = torch.cat(expanded_strides, 1)
  257. if self.use_l1:
  258. origin_preds = torch.cat(origin_preds, 1)
  259. cls_targets = []
  260. reg_targets = []
  261. l1_targets = []
  262. obj_targets = []
  263. fg_masks = []
  264. num_fg = 0.0
  265. num_gts = 0.0
  266. for batch_idx in range(outputs.shape[0]):
  267. num_gt = int(nlabel[batch_idx])
  268. num_gts += num_gt
  269. if num_gt == 0:
  270. cls_target = outputs.new_zeros((0, self.num_classes))
  271. reg_target = outputs.new_zeros((0, 4))
  272. l1_target = outputs.new_zeros((0, 4))
  273. obj_target = outputs.new_zeros((total_num_anchors, 1))
  274. fg_mask = outputs.new_zeros(total_num_anchors).bool()
  275. else:
  276. gt_bboxes_per_image = labels[batch_idx, :num_gt, 1:5]
  277. gt_classes = labels[batch_idx, :num_gt, 0]
  278. bboxes_preds_per_image = bbox_preds[batch_idx]
  279. try:
  280. (
  281. gt_matched_classes,
  282. fg_mask,
  283. pred_ious_this_matching,
  284. matched_gt_inds,
  285. num_fg_img,
  286. ) = self.get_assignments( # noqa
  287. batch_idx,
  288. num_gt,
  289. total_num_anchors,
  290. gt_bboxes_per_image,
  291. gt_classes,
  292. bboxes_preds_per_image,
  293. expanded_strides,
  294. x_shifts,
  295. y_shifts,
  296. cls_preds,
  297. bbox_preds,
  298. obj_preds,
  299. labels,
  300. imgs,
  301. )
  302. except RuntimeError as e:
  303. logger.info(
  304. "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. " + str(e)
  307. )
  308. print("OOM RuntimeError is raised due to the huge memory cost during label assignment. \
  309. CPU mode is applied in this batch. If you want to avoid this issue, \
  310. try to reduce the batch size or image size. " + str(e))
  311. torch.cuda.empty_cache()
  312. (
  313. gt_matched_classes,
  314. fg_mask,
  315. pred_ious_this_matching,
  316. matched_gt_inds,
  317. num_fg_img,
  318. ) = self.get_assignments( # noqa
  319. batch_idx,
  320. num_gt,
  321. total_num_anchors,
  322. gt_bboxes_per_image,
  323. gt_classes,
  324. bboxes_preds_per_image,
  325. expanded_strides,
  326. x_shifts,
  327. y_shifts,
  328. cls_preds,
  329. bbox_preds,
  330. obj_preds,
  331. labels,
  332. imgs,
  333. "cpu",
  334. )
  335. torch.cuda.empty_cache()
  336. num_fg += num_fg_img
  337. cls_target = F.one_hot(
  338. gt_matched_classes.to(torch.int64), self.num_classes
  339. ) * pred_ious_this_matching.unsqueeze(-1)
  340. obj_target = fg_mask.unsqueeze(-1)
  341. reg_target = gt_bboxes_per_image[matched_gt_inds]
  342. if self.use_l1:
  343. l1_target = self.get_l1_target(
  344. outputs.new_zeros((num_fg_img, 4)),
  345. gt_bboxes_per_image[matched_gt_inds],
  346. expanded_strides[0][fg_mask],
  347. x_shifts=x_shifts[0][fg_mask],
  348. y_shifts=y_shifts[0][fg_mask],
  349. )
  350. cls_targets.append(cls_target)
  351. reg_targets.append(reg_target)
  352. obj_targets.append(obj_target.to(dtype))
  353. fg_masks.append(fg_mask)
  354. if self.use_l1:
  355. l1_targets.append(l1_target)
  356. cls_targets = torch.cat(cls_targets, 0)
  357. reg_targets = torch.cat(reg_targets, 0)
  358. obj_targets = torch.cat(obj_targets, 0)
  359. fg_masks = torch.cat(fg_masks, 0)
  360. if self.use_l1:
  361. l1_targets = torch.cat(l1_targets, 0)
  362. # TODO: check loss parts shapes
  363. num_fg = max(num_fg, 1)
  364. # if bbox_preds.view(-1, 4)[fg_masks].shape != reg_targets.shape:
  365. # logger.info("some shape mismatch")
  366. # logger.info("bbox_preds.view(-1, 4)[fg_masks].shape {}".format(bbox_preds.view(-1, 4)[fg_masks].shape))
  367. # logger.info("reg_targets {}".format(reg_targets.shape))
  368. # logger.info("--------------------")
  369. loss_iou = (
  370. self.iou_loss(bbox_preds.view(-1, 4)[fg_masks], reg_targets)
  371. ).sum() / num_fg
  372. # if obj_preds.view(-1, 1).shape != obj_targets.shape:
  373. # logger.info("some shape mismatch")
  374. # logger.info("obj_preds.view(-1, 1).shape {}".format(obj_preds.view(-1, 1).shape))
  375. # logger.info("obj_targets.shape {}".format(obj_targets.shape))
  376. # logger.info("--------------------")
  377. loss_obj = (
  378. self.bcewithlog_loss(obj_preds.view(-1, 1), obj_targets)
  379. ).sum() / num_fg
  380. # if cls_preds.view(-1, self.num_classes)[fg_masks].shape != cls_targets.shape:
  381. # logger.info("some shape mismatch")
  382. # logger.info("cls_preds.view(-1, self.num_classes)[fg_masks].shape {}".format(
  383. # cls_preds.view(-1, self.num_classes)[fg_masks].shape))
  384. # logger.info("cls_targets.shape {}".format(cls_targets.shape))
  385. # logger.info("--------------------")
  386. loss_cls = (
  387. self.bcewithlog_loss(
  388. cls_preds.view(-1, self.num_classes)[fg_masks], cls_targets
  389. )
  390. ).sum() / num_fg
  391. if self.use_l1:
  392. # if origin_preds.view(-1, 4)[fg_masks].shape != l1_targets.shape:
  393. # logger.info("some shape mismatch")
  394. # logger.info("origin_preds.view(-1, 4)[fg_masks].shape {}".format(
  395. # origin_preds.view(-1, 4)[fg_masks].shape))
  396. # logger.info("l1_targets.shape {}".format(l1_targets.shape))
  397. # logger.info("--------------------")
  398. loss_l1 = (
  399. self.l1_loss(origin_preds.view(-1, 4)[fg_masks], l1_targets)
  400. ).sum() / num_fg
  401. else:
  402. loss_l1 = 0.0
  403. reg_weight = 5.0
  404. loss = reg_weight * loss_iou + loss_obj + loss_cls + loss_l1
  405. return (
  406. loss,
  407. reg_weight * loss_iou,
  408. loss_obj,
  409. loss_cls,
  410. loss_l1,
  411. num_fg / max(num_gts, 1),
  412. )
  413. def get_l1_target(self, l1_target, gt, stride, x_shifts, y_shifts, eps=1e-8):
  414. l1_target[:, 0] = gt[:, 0] / stride - x_shifts
  415. l1_target[:, 1] = gt[:, 1] / stride - y_shifts
  416. l1_target[:, 2] = torch.log(gt[:, 2] / stride + eps)
  417. l1_target[:, 3] = torch.log(gt[:, 3] / stride + eps)
  418. return l1_target
  419. @torch.no_grad()
  420. def get_assignments(
  421. self,
  422. batch_idx,
  423. num_gt,
  424. total_num_anchors,
  425. gt_bboxes_per_image,
  426. gt_classes,
  427. bboxes_preds_per_image,
  428. expanded_strides,
  429. x_shifts,
  430. y_shifts,
  431. cls_preds,
  432. bbox_preds,
  433. obj_preds,
  434. labels,
  435. imgs,
  436. mode="gpu",
  437. ):
  438. # TODO: check loss mismatches here
  439. if mode == "cpu":
  440. print("------------CPU Mode for This Batch-------------")
  441. gt_bboxes_per_image = gt_bboxes_per_image.cpu().float()
  442. bboxes_preds_per_image = bboxes_preds_per_image.cpu().float()
  443. gt_classes = gt_classes.cpu().float()
  444. expanded_strides = expanded_strides.cpu().float()
  445. x_shifts = x_shifts.cpu()
  446. y_shifts = y_shifts.cpu()
  447. img_size = imgs.shape[2:]
  448. fg_mask, is_in_boxes_and_center = self.get_in_boxes_info(
  449. gt_bboxes_per_image,
  450. expanded_strides,
  451. x_shifts,
  452. y_shifts,
  453. total_num_anchors,
  454. num_gt,
  455. img_size
  456. )
  457. # if torch.isnan(cls_preds).sum().item() or torch.isnan(obj_preds).sum().item() or torch.isnan(
  458. # bboxes_preds_per_image).sum().item():
  459. # logger.info("cls_preds is Nan {}".format(torch.isnan(cls_preds).sum().item()))
  460. # logger.info("obj_preds is Nan {}".format(torch.isnan(obj_preds).sum().item()))
  461. # logger.info("bboxes_preds_per_image is Nan {}".format(torch.isnan(bboxes_preds_per_image).sum().item()))
  462. bboxes_preds_per_image = bboxes_preds_per_image[fg_mask]
  463. cls_preds_ = cls_preds[batch_idx][fg_mask]
  464. obj_preds_ = obj_preds[batch_idx][fg_mask]
  465. num_in_boxes_anchor = bboxes_preds_per_image.shape[0]
  466. if mode == "cpu":
  467. gt_bboxes_per_image = gt_bboxes_per_image.cpu()
  468. bboxes_preds_per_image = bboxes_preds_per_image.cpu()
  469. pair_wise_ious = bboxes_iou(gt_bboxes_per_image, bboxes_preds_per_image, False)
  470. gt_cls_per_image = (
  471. F.one_hot(gt_classes.to(torch.int64), self.num_classes)
  472. .float()
  473. .unsqueeze(1)
  474. .repeat(1, num_in_boxes_anchor, 1)
  475. )
  476. pair_wise_ious_loss = -torch.log(pair_wise_ious + 1e-8)
  477. # if torch.isnan(pair_wise_ious_loss).sum().item():
  478. # logger.info("pair_wise_ious_loss is Nan {}".format(torch.isnan(pair_wise_ious_loss).sum().item()))
  479. if mode == "cpu":
  480. cls_preds_, obj_preds_ = cls_preds_.cpu(), obj_preds_.cpu()
  481. with torch.cuda.amp.autocast(enabled=False):
  482. cls_preds_ = (
  483. cls_preds_.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
  484. * obj_preds_.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()
  485. )
  486. pair_wise_cls_loss = F.binary_cross_entropy(
  487. cls_preds_.sqrt_(), gt_cls_per_image, reduction="none"
  488. ).sum(-1)
  489. del cls_preds_
  490. cost = (
  491. pair_wise_cls_loss
  492. + 3.0 * pair_wise_ious_loss
  493. + 100000.0 * (~is_in_boxes_and_center)
  494. )
  495. (
  496. num_fg,
  497. gt_matched_classes,
  498. pred_ious_this_matching,
  499. matched_gt_inds,
  500. ) = self.dynamic_k_matching(cost, pair_wise_ious, gt_classes, num_gt, fg_mask)
  501. del pair_wise_cls_loss, cost, pair_wise_ious, pair_wise_ious_loss
  502. if mode == "cpu":
  503. gt_matched_classes = gt_matched_classes.cuda()
  504. fg_mask = fg_mask.cuda()
  505. pred_ious_this_matching = pred_ious_this_matching.cuda()
  506. matched_gt_inds = matched_gt_inds.cuda()
  507. return (
  508. gt_matched_classes,
  509. fg_mask,
  510. pred_ious_this_matching,
  511. matched_gt_inds,
  512. num_fg,
  513. )
  514. def get_in_boxes_info(
  515. self,
  516. gt_bboxes_per_image,
  517. expanded_strides,
  518. x_shifts,
  519. y_shifts,
  520. total_num_anchors,
  521. num_gt,
  522. img_size
  523. ):
  524. expanded_strides_per_image = expanded_strides[0]
  525. x_shifts_per_image = x_shifts[0] * expanded_strides_per_image
  526. y_shifts_per_image = y_shifts[0] * expanded_strides_per_image
  527. x_centers_per_image = (
  528. (x_shifts_per_image + 0.5 * expanded_strides_per_image)
  529. .unsqueeze(0)
  530. .repeat(num_gt, 1)
  531. ) # [n_anchor] -> [n_gt, n_anchor]
  532. y_centers_per_image = (
  533. (y_shifts_per_image + 0.5 * expanded_strides_per_image)
  534. .unsqueeze(0)
  535. .repeat(num_gt, 1)
  536. )
  537. gt_bboxes_per_image_l = (
  538. (gt_bboxes_per_image[:, 0] - 0.5 * gt_bboxes_per_image[:, 2])
  539. .unsqueeze(1)
  540. .repeat(1, total_num_anchors)
  541. )
  542. gt_bboxes_per_image_r = (
  543. (gt_bboxes_per_image[:, 0] + 0.5 * gt_bboxes_per_image[:, 2])
  544. .unsqueeze(1)
  545. .repeat(1, total_num_anchors)
  546. )
  547. gt_bboxes_per_image_t = (
  548. (gt_bboxes_per_image[:, 1] - 0.5 * gt_bboxes_per_image[:, 3])
  549. .unsqueeze(1)
  550. .repeat(1, total_num_anchors)
  551. )
  552. gt_bboxes_per_image_b = (
  553. (gt_bboxes_per_image[:, 1] + 0.5 * gt_bboxes_per_image[:, 3])
  554. .unsqueeze(1)
  555. .repeat(1, total_num_anchors)
  556. )
  557. b_l = x_centers_per_image - gt_bboxes_per_image_l
  558. b_r = gt_bboxes_per_image_r - x_centers_per_image
  559. b_t = y_centers_per_image - gt_bboxes_per_image_t
  560. b_b = gt_bboxes_per_image_b - y_centers_per_image
  561. bbox_deltas = torch.stack([b_l, b_t, b_r, b_b], 2)
  562. is_in_boxes = bbox_deltas.min(dim=-1).values > 0.0
  563. is_in_boxes_all = is_in_boxes.sum(dim=0) > 0
  564. # in fixed center
  565. center_radius = 2.5
  566. # clip center inside image
  567. gt_bboxes_per_image_clip = gt_bboxes_per_image[:, 0:2].clone()
  568. gt_bboxes_per_image_clip[:, 0] = torch.clamp(gt_bboxes_per_image_clip[:, 0], min=0, max=img_size[1])
  569. gt_bboxes_per_image_clip[:, 1] = torch.clamp(gt_bboxes_per_image_clip[:, 1], min=0, max=img_size[0])
  570. gt_bboxes_per_image_l = (gt_bboxes_per_image_clip[:, 0]).unsqueeze(1).repeat(
  571. 1, total_num_anchors
  572. ) - center_radius * expanded_strides_per_image.unsqueeze(0)
  573. gt_bboxes_per_image_r = (gt_bboxes_per_image_clip[:, 0]).unsqueeze(1).repeat(
  574. 1, total_num_anchors
  575. ) + center_radius * expanded_strides_per_image.unsqueeze(0)
  576. gt_bboxes_per_image_t = (gt_bboxes_per_image_clip[:, 1]).unsqueeze(1).repeat(
  577. 1, total_num_anchors
  578. ) - center_radius * expanded_strides_per_image.unsqueeze(0)
  579. gt_bboxes_per_image_b = (gt_bboxes_per_image_clip[:, 1]).unsqueeze(1).repeat(
  580. 1, total_num_anchors
  581. ) + center_radius * expanded_strides_per_image.unsqueeze(0)
  582. c_l = x_centers_per_image - gt_bboxes_per_image_l
  583. c_r = gt_bboxes_per_image_r - x_centers_per_image
  584. c_t = y_centers_per_image - gt_bboxes_per_image_t
  585. c_b = gt_bboxes_per_image_b - y_centers_per_image
  586. center_deltas = torch.stack([c_l, c_t, c_r, c_b], 2)
  587. is_in_centers = center_deltas.min(dim=-1).values > 0.0
  588. is_in_centers_all = is_in_centers.sum(dim=0) > 0
  589. # in boxes and in centers
  590. is_in_boxes_anchor = is_in_boxes_all | is_in_centers_all
  591. is_in_boxes_and_center = (
  592. is_in_boxes[:, is_in_boxes_anchor] & is_in_centers[:, is_in_boxes_anchor]
  593. )
  594. del gt_bboxes_per_image_clip
  595. return is_in_boxes_anchor, is_in_boxes_and_center
  596. def dynamic_k_matching(self, cost, pair_wise_ious, gt_classes, num_gt, fg_mask):
  597. # Dynamic K
  598. # ---------------------------------------------------------------
  599. matching_matrix = torch.zeros_like(cost)
  600. ious_in_boxes_matrix = pair_wise_ious
  601. n_candidate_k = min(10, ious_in_boxes_matrix.size(1))
  602. topk_ious, _ = torch.topk(ious_in_boxes_matrix, n_candidate_k, dim=1)
  603. dynamic_ks = torch.clamp(topk_ious.sum(1).int(), min=1)
  604. for gt_idx in range(num_gt):
  605. _, pos_idx = torch.topk(
  606. cost[gt_idx], k=dynamic_ks[gt_idx].item(), largest=False
  607. )
  608. matching_matrix[gt_idx][pos_idx] = 1.0
  609. del topk_ious, dynamic_ks, pos_idx
  610. anchor_matching_gt = matching_matrix.sum(0)
  611. if (anchor_matching_gt > 1).sum() > 0:
  612. cost_min, cost_argmin = torch.min(cost[:, anchor_matching_gt > 1], dim=0)
  613. matching_matrix[:, anchor_matching_gt > 1] *= 0.0
  614. matching_matrix[cost_argmin, anchor_matching_gt > 1] = 1.0
  615. fg_mask_inboxes = matching_matrix.sum(0) > 0.0
  616. num_fg = fg_mask_inboxes.sum().item()
  617. fg_mask[fg_mask.clone()] = fg_mask_inboxes
  618. matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)
  619. gt_matched_classes = gt_classes[matched_gt_inds]
  620. pred_ious_this_matching = (matching_matrix * pair_wise_ious).sum(0)[
  621. fg_mask_inboxes
  622. ]
  623. return num_fg, gt_matched_classes, pred_ious_this_matching, matched_gt_inds