loss.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. import torch
  2. import torch.nn.functional as F
  3. from utils.box_ops import bbox2dist, get_ious
  4. from utils.distributed_utils import get_world_size, is_dist_avail_and_initialized
  5. from .matcher import TaskAlignedAssigner, AlignedSimOTA
  6. class Criterion(object):
  7. def __init__(self, args, cfg, device, num_classes=80):
  8. self.cfg = cfg
  9. self.args = args
  10. self.device = device
  11. self.num_classes = num_classes
  12. self.max_epoch = args.max_epoch
  13. self.no_aug_epoch = args.no_aug_epoch
  14. self.use_ema_update = cfg['ema_update']
  15. # ---------------- Loss weight ----------------
  16. self.loss_cls_weight = cfg['loss_cls_weight']
  17. self.loss_box_weight = cfg['loss_box_weight']
  18. self.loss_dfl_weight = cfg['loss_dfl_weight']
  19. # ---------------- Matcher ----------------
  20. matcher_config = cfg['matcher']
  21. ## TAL assigner
  22. self.tal_matcher = TaskAlignedAssigner(
  23. topk=matcher_config['tal']['topk'],
  24. alpha=matcher_config['tal']['alpha'],
  25. beta=matcher_config['tal']['beta'],
  26. num_classes=num_classes
  27. )
  28. ## SimOTA assigner
  29. self.ota_matcher = AlignedSimOTA(
  30. center_sampling_radius=matcher_config['ota']['center_sampling_radius'],
  31. topk_candidate=matcher_config['ota']['topk_candidate'],
  32. num_classes=num_classes
  33. )
  34. def __call__(self, outputs, targets, epoch=0):
  35. if epoch < self.args.max_epoch // 2:
  36. return self.ota_loss(outputs, targets)
  37. else:
  38. return self.tal_loss(outputs, targets)
  39. def ema_update(self, name: str, value, initial_value, momentum=0.9):
  40. if hasattr(self, name):
  41. old = getattr(self, name)
  42. else:
  43. old = initial_value
  44. new = old * momentum + value * (1 - momentum)
  45. setattr(self, name, new)
  46. return new
  47. # ----------------- Loss functions -----------------
  48. def loss_classes(self, pred_cls, gt_score, gt_label=None, vfl=False):
  49. if vfl:
  50. assert gt_label is not None
  51. # compute varifocal loss
  52. alpha, gamma = 0.75, 2.0
  53. focal_weight = alpha * pred_cls.sigmoid().pow(gamma) * (1 - gt_label) + gt_score * gt_label
  54. bce_loss = F.binary_cross_entropy_with_logits(pred_cls, gt_score, reduction='none')
  55. loss_cls = bce_loss * focal_weight
  56. else:
  57. # compute bce loss
  58. loss_cls = F.binary_cross_entropy_with_logits(pred_cls, gt_score, reduction='none')
  59. return loss_cls
  60. def loss_bboxes(self, pred_box, gt_box, bbox_weight=None):
  61. # regression loss
  62. ious = get_ious(pred_box, gt_box, 'xyxy', 'giou')
  63. loss_box = 1.0 - ious
  64. if bbox_weight is not None:
  65. loss_box *= bbox_weight
  66. return loss_box
  67. def loss_dfl(self, pred_reg, gt_box, anchor, stride, bbox_weight=None):
  68. # rescale coords by stride
  69. gt_box_s = gt_box / stride
  70. anchor_s = anchor / stride
  71. # compute deltas
  72. gt_ltrb_s = bbox2dist(anchor_s, gt_box_s, self.cfg['reg_max'] - 1)
  73. gt_left = gt_ltrb_s.to(torch.long)
  74. gt_right = gt_left + 1
  75. weight_left = gt_right.to(torch.float) - gt_ltrb_s
  76. weight_right = 1 - weight_left
  77. # loss left
  78. loss_left = F.cross_entropy(
  79. pred_reg.view(-1, self.cfg['reg_max']),
  80. gt_left.view(-1),
  81. reduction='none').view(gt_left.shape) * weight_left
  82. # loss right
  83. loss_right = F.cross_entropy(
  84. pred_reg.view(-1, self.cfg['reg_max']),
  85. gt_right.view(-1),
  86. reduction='none').view(gt_left.shape) * weight_right
  87. loss_dfl = (loss_left + loss_right).mean(-1)
  88. if bbox_weight is not None:
  89. loss_dfl *= bbox_weight
  90. return loss_dfl
  91. def loss_bboxes_aux(self, pred_delta, gt_box, anchors, stride_tensors):
  92. gt_delta_tl = (anchors - gt_box[..., :2]) / stride_tensors
  93. gt_delta_rb = (gt_box[..., 2:] - anchors) / stride_tensors
  94. gt_delta = torch.cat([gt_delta_tl, gt_delta_rb], dim=1)
  95. loss_box_aux = F.l1_loss(pred_delta, gt_delta, reduction='none')
  96. return loss_box_aux
  97. # ----------------- Loss with TAL assigner -----------------
  98. def tal_loss(self, outputs, targets, epoch=0):
  99. """ Compute loss with TAL assigner """
  100. bs = outputs['pred_cls'][0].shape[0]
  101. device = outputs['pred_cls'][0].device
  102. anchors = torch.cat(outputs['anchors'], dim=0)
  103. num_anchors = anchors.shape[0]
  104. # preds: [B, M, C]
  105. cls_preds = torch.cat(outputs['pred_cls'], dim=1)
  106. reg_preds = torch.cat(outputs['pred_reg'], dim=1)
  107. box_preds = torch.cat(outputs['pred_box'], dim=1)
  108. # --------------- label assignment ---------------
  109. gt_label_targets = []
  110. gt_score_targets = []
  111. gt_bbox_targets = []
  112. fg_masks = []
  113. for batch_idx in range(bs):
  114. tgt_labels = targets[batch_idx]["labels"].to(device)
  115. tgt_bboxes = targets[batch_idx]["boxes"].to(device)
  116. # check target
  117. if len(tgt_labels) == 0 or tgt_bboxes.max().item() == 0.:
  118. # There is no valid gt
  119. fg_mask = cls_preds.new_zeros(1, num_anchors).bool() #[1, M,]
  120. gt_label = cls_preds.new_zeros((1, num_anchors,)) #[1, M,]
  121. gt_score = cls_preds.new_zeros((1, num_anchors, self.num_classes)) #[1, M, C]
  122. gt_box = cls_preds.new_zeros((1, num_anchors, 4)) #[1, M, 4]
  123. else:
  124. tgt_labels = tgt_labels[None, :, None] # [1, Mp, 1]
  125. tgt_bboxes = tgt_bboxes[None] # [1, Mp, 4]
  126. (
  127. gt_label, #[1, M]
  128. gt_box, #[1, M, 4]
  129. gt_score, #[1, M, C]
  130. fg_mask, #[1, M,]
  131. _
  132. ) = self.tal_matcher(
  133. pd_scores = cls_preds[batch_idx:batch_idx+1].detach().sigmoid(),
  134. pd_bboxes = box_preds[batch_idx:batch_idx+1].detach(),
  135. anc_points = anchors,
  136. gt_labels = tgt_labels,
  137. gt_bboxes = tgt_bboxes
  138. )
  139. gt_label_targets.append(gt_label)
  140. gt_score_targets.append(gt_score)
  141. gt_bbox_targets.append(gt_box)
  142. fg_masks.append(fg_mask)
  143. # List[B, 1, M, C] -> Tensor[B, M, C] -> Tensor[BM, C]
  144. fg_masks = torch.cat(fg_masks, 0).view(-1) # [BM,]
  145. gt_score_targets = torch.cat(gt_score_targets, 0).view(-1, self.num_classes) # [BM, C]
  146. gt_bbox_targets = torch.cat(gt_bbox_targets, 0).view(-1, 4) # [BM, 4]
  147. gt_label_targets = torch.cat(gt_label_targets, 0).view(-1) # [BM,]
  148. gt_label_targets = torch.where(fg_masks > 0, gt_label_targets, torch.full_like(gt_label_targets, self.num_classes))
  149. gt_labels_one_hot = F.one_hot(gt_label_targets.long(), self.num_classes + 1)[..., :-1]
  150. bbox_weight = gt_score_targets[fg_masks].sum(-1)
  151. num_fgs = max(gt_score_targets.sum(), 1)
  152. # average loss normalizer across all the GPUs
  153. if is_dist_avail_and_initialized():
  154. torch.distributed.all_reduce(num_fgs)
  155. num_fgs = max(num_fgs / get_world_size(), 1.0)
  156. # update loss normalizer with EMA
  157. if self.use_ema_update:
  158. normalizer = self.ema_update("loss_normalizer", max(num_fgs, 1), 100)
  159. else:
  160. normalizer = num_fgs
  161. # ------------------ Classification loss ------------------
  162. cls_preds = cls_preds.view(-1, self.num_classes)
  163. loss_cls = self.loss_classes(cls_preds, gt_score_targets, gt_labels_one_hot, vfl=False)
  164. loss_cls = loss_cls.sum() / normalizer
  165. # ------------------ Regression loss ------------------
  166. box_preds_pos = box_preds.view(-1, 4)[fg_masks]
  167. box_targets_pos = gt_bbox_targets[fg_masks]
  168. loss_box = self.loss_bboxes(box_preds_pos, box_targets_pos, bbox_weight)
  169. loss_box = loss_box.sum() / normalizer
  170. # ------------------ Distribution focal loss ------------------
  171. ## process anchors
  172. anchors = anchors[None].repeat(bs, 1, 1).view(-1, 2)
  173. ## process stride tensors
  174. strides = torch.cat(outputs['stride_tensor'], dim=0)
  175. strides = strides.unsqueeze(0).repeat(bs, 1, 1).view(-1, 1)
  176. ## fg preds
  177. reg_preds_pos = reg_preds.view(-1, 4*self.cfg['reg_max'])[fg_masks]
  178. anchors_pos = anchors[fg_masks]
  179. strides_pos = strides[fg_masks]
  180. ## compute dfl
  181. loss_dfl = self.loss_dfl(reg_preds_pos, box_targets_pos, anchors_pos, strides_pos, bbox_weight)
  182. loss_dfl = loss_dfl.sum() / normalizer
  183. # total loss
  184. losses = self.loss_cls_weight['tal'] * loss_cls + \
  185. self.loss_box_weight['tal'] * loss_box + \
  186. self.loss_dfl_weight['tal'] * loss_dfl
  187. loss_dict = dict(
  188. loss_cls = loss_cls,
  189. loss_box = loss_box,
  190. loss_dfl = loss_dfl,
  191. losses = losses
  192. )
  193. # ------------------ Aux regression loss ------------------
  194. if epoch >= (self.max_epoch - self.no_aug_epoch - 1):
  195. ## delta_preds
  196. delta_preds = torch.cat(outputs['pred_delta'], dim=1)
  197. delta_preds_pos = delta_preds.view(-1, 4)[fg_masks]
  198. ## anchor tensors
  199. anchors_tensors = torch.cat(outputs['anchors'], dim=0)[None].repeat(bs, 1, 1)
  200. anchors_tensors_pos = anchors_tensors.view(-1, 2)[fg_masks]
  201. ## stride tensors
  202. stride_tensors = torch.cat(outputs['stride_tensors'], dim=0)[None].repeat(bs, 1, 1)
  203. stride_tensors_pos = stride_tensors.view(-1, 1)[fg_masks]
  204. ## aux loss
  205. loss_box_aux = self.loss_bboxes_aux(delta_preds_pos, box_targets_pos, anchors_pos, strides_pos)
  206. loss_box_aux = loss_box_aux.sum() / num_fgs
  207. losses += loss_box_aux
  208. loss_dict['loss_box_aux'] = loss_box_aux
  209. return loss_dict
  210. # ----------------- Loss with SimOTA assigner -----------------
  211. def ota_loss(self, outputs, targets, epoch=0):
  212. """ Compute loss with SimOTA assigner """
  213. bs = outputs['pred_cls'][0].shape[0]
  214. device = outputs['pred_cls'][0].device
  215. fpn_strides = outputs['strides']
  216. anchors = outputs['anchors']
  217. num_anchors = sum([ab.shape[0] for ab in anchors])
  218. # preds: [B, M, C]
  219. cls_preds = torch.cat(outputs['pred_cls'], dim=1)
  220. reg_preds = torch.cat(outputs['pred_reg'], dim=1)
  221. box_preds = torch.cat(outputs['pred_box'], dim=1)
  222. # --------------- label assignment ---------------
  223. cls_targets = []
  224. box_targets = []
  225. fg_masks = []
  226. for batch_idx in range(bs):
  227. tgt_labels = targets[batch_idx]["labels"].to(device)
  228. tgt_bboxes = targets[batch_idx]["boxes"].to(device)
  229. # check target
  230. if len(tgt_labels) == 0 or tgt_bboxes.max().item() == 0.:
  231. # There is no valid gt
  232. cls_target = cls_preds.new_zeros((num_anchors, self.num_classes))
  233. box_target = cls_preds.new_zeros((0, 4))
  234. fg_mask = cls_preds.new_zeros(num_anchors).bool()
  235. else:
  236. (
  237. fg_mask,
  238. assigned_labels,
  239. assigned_ious,
  240. assigned_indexs
  241. ) = self.ota_matcher(
  242. fpn_strides = fpn_strides,
  243. anchors = anchors,
  244. pred_cls = cls_preds[batch_idx],
  245. pred_box = box_preds[batch_idx],
  246. tgt_labels = tgt_labels,
  247. tgt_bboxes = tgt_bboxes
  248. )
  249. # prepare cls targets
  250. assigned_labels = F.one_hot(assigned_labels.long(), self.num_classes)
  251. assigned_labels = assigned_labels * assigned_ious.unsqueeze(-1)
  252. cls_target = assigned_labels.new_zeros((num_anchors, self.num_classes))
  253. cls_target[fg_mask] = assigned_labels
  254. # prepare box targets
  255. box_target = tgt_bboxes[assigned_indexs]
  256. cls_targets.append(cls_target)
  257. box_targets.append(box_target)
  258. fg_masks.append(fg_mask)
  259. cls_targets = torch.cat(cls_targets, 0)
  260. box_targets = torch.cat(box_targets, 0)
  261. fg_masks = torch.cat(fg_masks, 0)
  262. num_fgs = fg_masks.sum()
  263. # average loss normalizer across all the GPUs
  264. if is_dist_avail_and_initialized():
  265. torch.distributed.all_reduce(num_fgs)
  266. num_fgs = (num_fgs / get_world_size()).clamp(1.0)
  267. # update loss normalizer with EMA
  268. if self.use_ema_update:
  269. normalizer = self.ema_update("loss_normalizer", max(num_fgs, 1), 100)
  270. else:
  271. normalizer = num_fgs
  272. # ------------------ Classification loss ------------------
  273. cls_preds = cls_preds.view(-1, self.num_classes)
  274. loss_cls = self.loss_classes(cls_preds, cls_targets)
  275. loss_cls = loss_cls.sum() / normalizer
  276. # ------------------ Regression loss ------------------
  277. box_preds_pos = box_preds.view(-1, 4)[fg_masks]
  278. loss_box = self.loss_bboxes(box_preds_pos, box_targets)
  279. loss_box = loss_box.sum() / normalizer
  280. # ------------------ Distribution focal loss ------------------
  281. ## process anchors
  282. anchors = torch.cat(anchors, dim=0)
  283. anchors = anchors[None].repeat(bs, 1, 1).view(-1, 2)
  284. ## process stride tensors
  285. strides = torch.cat(outputs['stride_tensor'], dim=0)
  286. strides = strides.unsqueeze(0).repeat(bs, 1, 1).view(-1, 1)
  287. ## fg preds
  288. reg_preds_pos = reg_preds.view(-1, 4*self.cfg['reg_max'])[fg_masks]
  289. anchors_pos = anchors[fg_masks]
  290. strides_pos = strides[fg_masks]
  291. ## compute dfl
  292. loss_dfl = self.loss_dfl(reg_preds_pos, box_targets, anchors_pos, strides_pos)
  293. loss_dfl = loss_dfl.sum() / normalizer
  294. # total loss
  295. losses = self.loss_cls_weight['ota'] * loss_cls + \
  296. self.loss_box_weight['ota'] * loss_box + \
  297. self.loss_dfl_weight['ota'] * loss_dfl
  298. loss_dict = dict(
  299. loss_cls = loss_cls,
  300. loss_box = loss_box,
  301. loss_dfl = loss_dfl,
  302. losses = losses
  303. )
  304. # ------------------ Aux regression loss ------------------
  305. if epoch >= (self.max_epoch - self.no_aug_epoch - 1):
  306. ## delta_preds
  307. delta_preds = torch.cat(outputs['pred_delta'], dim=1)
  308. delta_preds_pos = delta_preds.view(-1, 4)[fg_masks]
  309. ## aux loss
  310. loss_box_aux = self.loss_bboxes_aux(delta_preds_pos, box_targets, anchors_pos, strides_pos)
  311. loss_box_aux = loss_box_aux.sum() / num_fgs
  312. losses += loss_box_aux
  313. loss_dict['loss_box_aux'] = loss_box_aux
  314. return loss_dict
  315. def build_criterion(args, cfg, device, num_classes):
  316. criterion = Criterion(
  317. args=args,
  318. cfg=cfg,
  319. device=device,
  320. num_classes=num_classes
  321. )
  322. return criterion
  323. if __name__ == "__main__":
  324. pass