loss.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from utils.box_ops import bbox2dist, bbox_iou
  5. from utils.distributed_utils import get_world_size, is_dist_avail_and_initialized
  6. from .matcher import TaskAlignedAssigner
  7. class SetCriterion(object):
  8. def __init__(self, cfg):
  9. # --------------- Basic parameters ---------------
  10. self.cfg = cfg
  11. self.reg_max = cfg.reg_max
  12. self.num_classes = cfg.num_classes
  13. # --------------- Loss config ---------------
  14. self.loss_cls_weight = cfg.loss_cls
  15. self.loss_box_weight = cfg.loss_box
  16. self.loss_dfl_weight = cfg.loss_dfl
  17. # --------------- Matcher config ---------------
  18. self.matcher = TaskAlignedAssigner(num_classes = cfg.num_classes,
  19. topk_candidates = cfg.tal_topk_candidates,
  20. alpha = cfg.tal_alpha,
  21. beta = cfg.tal_beta
  22. )
  23. def loss_classes(self, pred_cls, gt_score):
  24. # compute bce loss
  25. loss_cls = F.binary_cross_entropy_with_logits(pred_cls, gt_score, reduction='none')
  26. return loss_cls
  27. def loss_bboxes(self, pred_box, gt_box, bbox_weight):
  28. # regression loss
  29. ious = bbox_iou(pred_box, gt_box, xywh=False, CIoU=True)
  30. loss_box = (1.0 - ious.squeeze(-1)) * bbox_weight
  31. return loss_box
  32. def loss_dfl(self, pred_reg, gt_box, anchor, stride, bbox_weight=None):
  33. # rescale coords by stride
  34. gt_box_s = gt_box / stride
  35. anchor_s = anchor / stride
  36. # compute deltas
  37. gt_ltrb_s = bbox2dist(anchor_s, gt_box_s, self.reg_max - 1)
  38. gt_left = gt_ltrb_s.to(torch.long)
  39. gt_right = gt_left + 1
  40. weight_left = gt_right.to(torch.float) - gt_ltrb_s
  41. weight_right = 1 - weight_left
  42. # loss left
  43. loss_left = F.cross_entropy(
  44. pred_reg.view(-1, self.reg_max),
  45. gt_left.view(-1),
  46. reduction='none').view(gt_left.shape) * weight_left
  47. # loss right
  48. loss_right = F.cross_entropy(
  49. pred_reg.view(-1, self.reg_max),
  50. gt_right.view(-1),
  51. reduction='none').view(gt_left.shape) * weight_right
  52. loss_dfl = (loss_left + loss_right).mean(-1)
  53. if bbox_weight is not None:
  54. loss_dfl *= bbox_weight
  55. return loss_dfl
  56. def __call__(self, outputs, targets):
  57. """
  58. outputs['pred_cls']: List(Tensor) [B, M, C]
  59. outputs['pred_reg']: List(Tensor) [B, M, 4*(reg_max+1)]
  60. outputs['pred_box']: List(Tensor) [B, M, 4]
  61. outputs['anchors']: List(Tensor) [M, 2]
  62. outputs['strides']: List(Int) [8, 16, 32] output stride
  63. outputs['stride_tensor']: List(Tensor) [M, 1]
  64. targets: (List) [dict{'boxes': [...],
  65. 'labels': [...],
  66. 'orig_size': ...}, ...]
  67. """
  68. # preds: [B, M, C]
  69. cls_preds = torch.cat(outputs['pred_cls'], dim=1)
  70. reg_preds = torch.cat(outputs['pred_reg'], dim=1)
  71. box_preds = torch.cat(outputs['pred_box'], dim=1)
  72. bs, num_anchors = cls_preds.shape[:2]
  73. device = cls_preds.device
  74. anchors = torch.cat(outputs['anchors'], dim=0)
  75. # --------------- label assignment ---------------
  76. gt_score_targets = []
  77. gt_bbox_targets = []
  78. fg_masks = []
  79. for batch_idx in range(bs):
  80. tgt_labels = targets[batch_idx]["labels"].to(device) # [Mp,]
  81. tgt_boxs = targets[batch_idx]["boxes"].to(device) # [Mp, 4]
  82. if self.cfg.normalize_coords:
  83. img_h, img_w = outputs['image_size']
  84. tgt_boxs[..., [0, 2]] *= img_w
  85. tgt_boxs[..., [1, 3]] *= img_h
  86. if self.cfg.box_format == 'xywh':
  87. tgt_boxs_x1y1 = tgt_boxs[..., :2] - 0.5 * tgt_boxs[..., 2:]
  88. tgt_boxs_x2y2 = tgt_boxs[..., :2] + 0.5 * tgt_boxs[..., 2:]
  89. tgt_boxs = torch.cat([tgt_boxs_x1y1, tgt_boxs_x2y2], dim=-1)
  90. # check target
  91. if len(tgt_labels) == 0 or tgt_boxs.max().item() == 0.:
  92. # There is no valid gt
  93. fg_mask = cls_preds.new_zeros(1, num_anchors).bool() #[1, M,]
  94. gt_score = cls_preds.new_zeros((1, num_anchors, self.num_classes)) #[1, M, C]
  95. gt_box = cls_preds.new_zeros((1, num_anchors, 4)) #[1, M, 4]
  96. else:
  97. tgt_labels = tgt_labels[None, :, None] # [1, Mp, 1]
  98. tgt_boxs = tgt_boxs[None] # [1, Mp, 4]
  99. (
  100. _,
  101. gt_box, # [1, M, 4]
  102. gt_score, # [1, M, C]
  103. fg_mask, # [1, M,]
  104. _
  105. ) = self.matcher(
  106. pd_scores = cls_preds[batch_idx:batch_idx+1].detach().sigmoid(),
  107. pd_bboxes = box_preds[batch_idx:batch_idx+1].detach(),
  108. anc_points = anchors,
  109. gt_labels = tgt_labels,
  110. gt_bboxes = tgt_boxs
  111. )
  112. gt_score_targets.append(gt_score)
  113. gt_bbox_targets.append(gt_box)
  114. fg_masks.append(fg_mask)
  115. # List[B, 1, M, C] -> Tensor[B, M, C] -> Tensor[BM, C]
  116. fg_masks = torch.cat(fg_masks, 0).view(-1) # [BM,]
  117. gt_score_targets = torch.cat(gt_score_targets, 0).view(-1, self.num_classes) # [BM, C]
  118. gt_bbox_targets = torch.cat(gt_bbox_targets, 0).view(-1, 4) # [BM, 4]
  119. num_fgs = gt_score_targets.sum()
  120. # Average loss normalizer across all the GPUs
  121. if is_dist_avail_and_initialized():
  122. torch.distributed.all_reduce(num_fgs)
  123. num_fgs = (num_fgs / get_world_size()).clamp(1.0)
  124. # ------------------ Classification loss ------------------
  125. cls_preds = cls_preds.view(-1, self.num_classes)
  126. loss_cls = self.loss_classes(cls_preds, gt_score_targets)
  127. loss_cls = loss_cls.sum() / num_fgs
  128. # ------------------ Regression loss ------------------
  129. box_preds_pos = box_preds.view(-1, 4)[fg_masks]
  130. box_targets_pos = gt_bbox_targets.view(-1, 4)[fg_masks]
  131. bbox_weight = gt_score_targets[fg_masks].sum(-1)
  132. loss_box = self.loss_bboxes(box_preds_pos, box_targets_pos, bbox_weight)
  133. loss_box = loss_box.sum() / num_fgs
  134. # ------------------ Distribution focal loss ------------------
  135. ## process anchors
  136. anchors = anchors[None].repeat(bs, 1, 1).view(-1, 2)
  137. ## process stride tensors
  138. strides = torch.cat(outputs['stride_tensor'], dim=0)
  139. strides = strides.unsqueeze(0).repeat(bs, 1, 1).view(-1, 1)
  140. ## fg preds
  141. reg_preds_pos = reg_preds.view(-1, 4*self.reg_max)[fg_masks]
  142. anchors_pos = anchors[fg_masks]
  143. strides_pos = strides[fg_masks]
  144. ## compute dfl
  145. loss_dfl = self.loss_dfl(reg_preds_pos, box_targets_pos, anchors_pos, strides_pos, bbox_weight)
  146. loss_dfl = loss_dfl.sum() / num_fgs
  147. # total loss
  148. losses = loss_cls * self.loss_cls_weight + loss_box * self.loss_box_weight + loss_dfl * self.loss_dfl_weight
  149. loss_dict = dict(
  150. loss_cls = loss_cls,
  151. loss_box = loss_box,
  152. loss_dfl = loss_dfl,
  153. losses = losses
  154. )
  155. return loss_dict
  156. if __name__ == "__main__":
  157. pass