loss.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 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.use_ema_update = cfg['ema_update']
  13. # ---------------- Loss weight ----------------
  14. self.loss_cls_weight = cfg['loss_cls_weight']
  15. self.loss_box_weight = cfg['loss_box_weight']
  16. self.loss_dfl_weight = cfg['loss_dfl_weight']
  17. # ---------------- Matcher ----------------
  18. matcher_config = cfg['matcher']
  19. ## SimOTA assigner
  20. self.ota_matcher = AlignedSimOTA(
  21. center_sampling_radius=matcher_config['ota']['center_sampling_radius'],
  22. topk_candidate=matcher_config['ota']['topk_candidate'],
  23. num_classes=num_classes
  24. )
  25. def ema_update(self, name: str, value, initial_value, momentum=0.9):
  26. if hasattr(self, name):
  27. old = getattr(self, name)
  28. else:
  29. old = initial_value
  30. new = old * momentum + value * (1 - momentum)
  31. setattr(self, name, new)
  32. return new
  33. # ----------------- Loss functions -----------------
  34. def loss_classes(self, pred_cls, gt_score, gt_label=None, vfl=False):
  35. if vfl:
  36. assert gt_label is not None
  37. # compute varifocal loss
  38. alpha, gamma = 0.75, 2.0
  39. focal_weight = alpha * pred_cls.sigmoid().pow(gamma) * (1 - gt_label) + gt_score * gt_label
  40. bce_loss = F.binary_cross_entropy_with_logits(pred_cls, gt_score, reduction='none')
  41. loss_cls = bce_loss * focal_weight
  42. else:
  43. # compute bce loss
  44. loss_cls = F.binary_cross_entropy_with_logits(pred_cls, gt_score, reduction='none')
  45. return loss_cls
  46. def loss_bboxes(self, pred_box, gt_box, bbox_weight=None):
  47. # regression loss
  48. ious = get_ious(pred_box, gt_box, 'xyxy', 'giou')
  49. loss_box = 1.0 - ious
  50. if bbox_weight is not None:
  51. loss_box *= bbox_weight
  52. return loss_box
  53. def loss_dfl(self, pred_reg, gt_box, anchor, stride, bbox_weight=None):
  54. # rescale coords by stride
  55. gt_box_s = gt_box / stride
  56. anchor_s = anchor / stride
  57. # compute deltas
  58. gt_ltrb_s = bbox2dist(anchor_s, gt_box_s, self.cfg['reg_max'] - 1)
  59. gt_left = gt_ltrb_s.to(torch.long)
  60. gt_right = gt_left + 1
  61. weight_left = gt_right.to(torch.float) - gt_ltrb_s
  62. weight_right = 1 - weight_left
  63. # loss left
  64. loss_left = F.cross_entropy(
  65. pred_reg.view(-1, self.cfg['reg_max']),
  66. gt_left.view(-1),
  67. reduction='none').view(gt_left.shape) * weight_left
  68. # loss right
  69. loss_right = F.cross_entropy(
  70. pred_reg.view(-1, self.cfg['reg_max']),
  71. gt_right.view(-1),
  72. reduction='none').view(gt_left.shape) * weight_right
  73. loss_dfl = (loss_left + loss_right).mean(-1)
  74. if bbox_weight is not None:
  75. loss_dfl *= bbox_weight
  76. return loss_dfl
  77. # ----------------- Loss with SimOTA assigner -----------------
  78. def __call__(self, outputs, targets, epoch=0):
  79. """ Compute loss with SimOTA assigner """
  80. bs = outputs['pred_cls'][0].shape[0]
  81. device = outputs['pred_cls'][0].device
  82. fpn_strides = outputs['strides']
  83. anchors = outputs['anchors']
  84. num_anchors = sum([ab.shape[0] for ab in anchors])
  85. # preds: [B, M, C]
  86. cls_preds = torch.cat(outputs['pred_cls'], dim=1)
  87. reg_preds = torch.cat(outputs['pred_reg'], dim=1)
  88. box_preds = torch.cat(outputs['pred_box'], dim=1)
  89. # --------------- label assignment ---------------
  90. cls_targets = []
  91. box_targets = []
  92. fg_masks = []
  93. for batch_idx in range(bs):
  94. tgt_labels = targets[batch_idx]["labels"].to(device)
  95. tgt_bboxes = targets[batch_idx]["boxes"].to(device)
  96. # check target
  97. if len(tgt_labels) == 0 or tgt_bboxes.max().item() == 0.:
  98. # There is no valid gt
  99. cls_target = cls_preds.new_zeros((num_anchors, self.num_classes))
  100. box_target = cls_preds.new_zeros((0, 4))
  101. fg_mask = cls_preds.new_zeros(num_anchors).bool()
  102. else:
  103. (
  104. fg_mask,
  105. assigned_labels,
  106. assigned_ious,
  107. assigned_indexs
  108. ) = self.ota_matcher(
  109. fpn_strides = fpn_strides,
  110. anchors = anchors,
  111. pred_cls = cls_preds[batch_idx],
  112. pred_box = box_preds[batch_idx],
  113. tgt_labels = tgt_labels,
  114. tgt_bboxes = tgt_bboxes
  115. )
  116. # prepare cls targets
  117. assigned_labels = F.one_hot(assigned_labels.long(), self.num_classes)
  118. assigned_labels = assigned_labels * assigned_ious.unsqueeze(-1)
  119. cls_target = assigned_labels.new_zeros((num_anchors, self.num_classes))
  120. cls_target[fg_mask] = assigned_labels
  121. # prepare box targets
  122. box_target = tgt_bboxes[assigned_indexs]
  123. cls_targets.append(cls_target)
  124. box_targets.append(box_target)
  125. fg_masks.append(fg_mask)
  126. cls_targets = torch.cat(cls_targets, 0)
  127. box_targets = torch.cat(box_targets, 0)
  128. fg_masks = torch.cat(fg_masks, 0)
  129. num_fgs = fg_masks.sum()
  130. # average loss normalizer across all the GPUs
  131. if is_dist_avail_and_initialized():
  132. torch.distributed.all_reduce(num_fgs)
  133. num_fgs = (num_fgs / get_world_size()).clamp(1.0)
  134. # update loss normalizer with EMA
  135. if self.use_ema_update:
  136. normalizer = self.ema_update("loss_normalizer", max(num_fgs, 1), 100)
  137. else:
  138. normalizer = num_fgs
  139. # ------------------ Classification loss ------------------
  140. cls_preds = cls_preds.view(-1, self.num_classes)
  141. loss_cls = self.loss_classes(cls_preds, cls_targets)
  142. loss_cls = loss_cls.sum() / normalizer
  143. # ------------------ Regression loss ------------------
  144. box_preds_pos = box_preds.view(-1, 4)[fg_masks]
  145. loss_box = self.loss_bboxes(box_preds_pos, box_targets)
  146. loss_box = loss_box.sum() / normalizer
  147. # ------------------ Distribution focal loss ------------------
  148. ## process anchors
  149. anchors = torch.cat(anchors, dim=0)
  150. anchors = anchors[None].repeat(bs, 1, 1).view(-1, 2)
  151. ## process stride tensors
  152. strides = torch.cat(outputs['stride_tensor'], dim=0)
  153. strides = strides.unsqueeze(0).repeat(bs, 1, 1).view(-1, 1)
  154. ## fg preds
  155. reg_preds_pos = reg_preds.view(-1, 4*self.cfg['reg_max'])[fg_masks]
  156. anchors_pos = anchors[fg_masks]
  157. strides_pos = strides[fg_masks]
  158. ## compute dfl
  159. loss_dfl = self.loss_dfl(reg_preds_pos, box_targets, anchors_pos, strides_pos)
  160. loss_dfl = loss_dfl.sum() / normalizer
  161. # total loss
  162. losses = self.loss_cls_weight * loss_cls + \
  163. self.loss_box_weight * loss_box + \
  164. self.loss_dfl_weight * loss_dfl
  165. loss_dict = dict(
  166. loss_cls = loss_cls,
  167. loss_box = loss_box,
  168. loss_dfl = loss_dfl,
  169. losses = losses
  170. )
  171. return loss_dict
  172. def build_criterion(args, cfg, device, num_classes):
  173. criterion = Criterion(
  174. args=args,
  175. cfg=cfg,
  176. device=device,
  177. num_classes=num_classes
  178. )
  179. return criterion
  180. if __name__ == "__main__":
  181. pass