loss.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from .matcher import TaskAlignedAssigner
  5. from utils.box_ops import bbox2dist, bbox_iou
  6. class Criterion(object):
  7. def __init__(self,
  8. cfg,
  9. device,
  10. num_classes=80):
  11. self.cfg = cfg
  12. self.device = device
  13. self.num_classes = num_classes
  14. self.reg_max = cfg['reg_max']
  15. self.use_dfl = cfg['reg_max'] > 1
  16. # loss
  17. self.cls_lossf = ClassificationLoss(cfg, reduction='none')
  18. self.reg_lossf = RegressionLoss(num_classes, cfg['reg_max'] - 1, self.use_dfl)
  19. # loss weight
  20. self.loss_cls_weight = cfg['loss_cls_weight']
  21. self.loss_iou_weight = cfg['loss_iou_weight']
  22. self.loss_dfl_weight = cfg['loss_dfl_weight']
  23. # matcher
  24. matcher_config = cfg['matcher']
  25. self.matcher = TaskAlignedAssigner(
  26. topk=matcher_config['topk'],
  27. num_classes=num_classes,
  28. alpha=matcher_config['alpha'],
  29. beta=matcher_config['beta']
  30. )
  31. def __call__(self, outputs, targets):
  32. """
  33. outputs['pred_cls']: List(Tensor) [B, M, C]
  34. outputs['pred_regs']: List(Tensor) [B, M, 4*(reg_max+1)]
  35. outputs['pred_boxs']: List(Tensor) [B, M, 4]
  36. outputs['anchors']: List(Tensor) [M, 2]
  37. outputs['strides']: List(Int) [8, 16, 32] output stride
  38. outputs['stride_tensor']: List(Tensor) [M, 1]
  39. targets: (List) [dict{'boxes': [...],
  40. 'labels': [...],
  41. 'orig_size': ...}, ...]
  42. """
  43. bs = outputs['pred_cls'][0].shape[0]
  44. device = outputs['pred_cls'][0].device
  45. strides = outputs['stride_tensor']
  46. anchors = outputs['anchors']
  47. anchors = torch.cat(anchors, dim=0)
  48. num_anchors = anchors.shape[0]
  49. # preds: [B, M, C]
  50. cls_preds = torch.cat(outputs['pred_cls'], dim=1)
  51. reg_preds = torch.cat(outputs['pred_reg'], dim=1)
  52. box_preds = torch.cat(outputs['pred_box'], dim=1)
  53. # label assignment
  54. gt_score_targets = []
  55. gt_bbox_targets = []
  56. fg_masks = []
  57. for batch_idx in range(bs):
  58. tgt_labels = targets[batch_idx]["labels"].to(device) # [Mp,]
  59. tgt_boxs = targets[batch_idx]["boxes"].to(device) # [Mp, 4]
  60. # check target
  61. if len(tgt_labels) == 0 or tgt_boxs.max().item() == 0.:
  62. # There is no valid gt
  63. fg_mask = cls_preds.new_zeros(1, num_anchors).bool() #[1, M,]
  64. gt_score = cls_preds.new_zeros((1, num_anchors, self.num_classes)) #[1, M, C]
  65. gt_box = cls_preds.new_zeros((1, num_anchors, 4)) #[1, M, 4]
  66. else:
  67. tgt_labels = tgt_labels[None, :, None] # [1, Mp, 1]
  68. tgt_boxs = tgt_boxs[None] # [1, Mp, 4]
  69. (
  70. _,
  71. gt_box, #[1, M, 4]
  72. gt_score, #[1, M, C]
  73. fg_mask, #[1, M,]
  74. _
  75. ) = self.matcher(
  76. pd_scores = cls_preds[batch_idx:batch_idx+1].detach().sigmoid(),
  77. pd_bboxes = box_preds[batch_idx:batch_idx+1].detach(),
  78. anc_points = anchors,
  79. gt_labels = tgt_labels,
  80. gt_bboxes = tgt_boxs
  81. )
  82. gt_score_targets.append(gt_score)
  83. gt_bbox_targets.append(gt_box)
  84. fg_masks.append(fg_mask)
  85. # List[B, 1, M, C] -> Tensor[B, M, C] -> Tensor[BM, C]
  86. fg_masks = torch.cat(fg_masks, 0).view(-1) # [BM,]
  87. gt_score_targets = torch.cat(gt_score_targets, 0).view(-1, self.num_classes) # [BM, C]
  88. gt_bbox_targets = torch.cat(gt_bbox_targets, 0).view(-1, 4) # [BM, 4]
  89. # cls loss
  90. cls_preds = cls_preds.view(-1, self.num_classes)
  91. loss_cls = self.cls_lossf(cls_preds, gt_score_targets)
  92. # reg loss
  93. anchors = anchors[None].repeat(bs, 1, 1).view(-1, 2) # [BM, 2]
  94. strides = torch.cat(strides, dim=0).unsqueeze(0).repeat(bs, 1, 1).view(-1, 1) # [BM, 1]
  95. bbox_weight = gt_score_targets[fg_masks].sum(-1, keepdim=True) # [BM, 1]
  96. reg_preds = reg_preds.view(-1, 4*self.reg_max) # [BM, 4*(reg_max + 1)]
  97. box_preds = box_preds.view(-1, 4) # [BM, 4]
  98. loss_iou, loss_dfl = self.reg_lossf(
  99. pred_regs = reg_preds,
  100. pred_boxs = box_preds,
  101. anchors = anchors,
  102. gt_boxs = gt_bbox_targets,
  103. bbox_weight = bbox_weight,
  104. fg_masks = fg_masks,
  105. strides = strides,
  106. )
  107. # normalize loss
  108. gt_score_targets_sum = max(gt_score_targets.sum(), 1)
  109. loss_cls = loss_cls.sum() / gt_score_targets_sum
  110. loss_iou = loss_iou.sum() / gt_score_targets_sum
  111. loss_dfl = loss_dfl.sum() / gt_score_targets_sum
  112. # total loss
  113. losses = loss_cls * self.loss_cls_weight + \
  114. loss_iou * self.loss_iou_weight
  115. if self.use_dfl:
  116. losses += loss_dfl * self.loss_dfl_weight
  117. loss_dict = dict(
  118. loss_cls = loss_cls,
  119. loss_iou = loss_iou,
  120. loss_dfl = loss_dfl,
  121. losses = losses
  122. )
  123. else:
  124. loss_dict = dict(
  125. loss_cls = loss_cls,
  126. loss_iou = loss_iou,
  127. losses = losses
  128. )
  129. return loss_dict
  130. class ClassificationLoss(nn.Module):
  131. def __init__(self, cfg, reduction='none'):
  132. super(ClassificationLoss, self).__init__()
  133. self.cfg = cfg
  134. self.reduction = reduction
  135. # For VFL
  136. self.alpha = 0.75
  137. self.gamma = 2.0
  138. def binary_cross_entropy(self, pred_logits, gt_score):
  139. loss = F.binary_cross_entropy_with_logits(
  140. pred_logits.float(), gt_score.float(), reduction='none')
  141. if self.reduction == 'sum':
  142. loss = loss.sum()
  143. elif self.reduction == 'mean':
  144. loss = loss.mean()
  145. return loss
  146. def forward(self, pred_logits, gt_score):
  147. if self.cfg['cls_loss'] == 'bce':
  148. return self.binary_cross_entropy(pred_logits, gt_score)
  149. class RegressionLoss(nn.Module):
  150. def __init__(self, num_classes, reg_max, use_dfl):
  151. super(RegressionLoss, self).__init__()
  152. self.num_classes = num_classes
  153. self.reg_max = reg_max
  154. self.use_dfl = use_dfl
  155. def df_loss(self, pred_regs, target):
  156. gt_left = target.to(torch.long)
  157. gt_right = gt_left + 1
  158. weight_left = gt_right.to(torch.float) - target
  159. weight_right = 1 - weight_left
  160. # loss left
  161. loss_left = F.cross_entropy(
  162. pred_regs.view(-1, self.reg_max + 1),
  163. gt_left.view(-1),
  164. reduction='none').view(gt_left.shape) * weight_left
  165. # loss right
  166. loss_right = F.cross_entropy(
  167. pred_regs.view(-1, self.reg_max + 1),
  168. gt_right.view(-1),
  169. reduction='none').view(gt_left.shape) * weight_right
  170. loss = (loss_left + loss_right).mean(-1, keepdim=True)
  171. return loss
  172. def forward(self, pred_regs, pred_boxs, anchors, gt_boxs, bbox_weight, fg_masks, strides):
  173. """
  174. Input:
  175. pred_regs: (Tensor) [BM, 4*(reg_max + 1)]
  176. pred_boxs: (Tensor) [BM, 4]
  177. anchors: (Tensor) [BM, 2]
  178. gt_boxs: (Tensor) [BM, 4]
  179. bbox_weight: (Tensor) [BM, 1]
  180. fg_masks: (Tensor) [BM,]
  181. strides: (Tensor) [BM, 1]
  182. """
  183. # select positive samples mask
  184. num_pos = fg_masks.sum()
  185. if num_pos > 0:
  186. pred_boxs_pos = pred_boxs[fg_masks]
  187. gt_boxs_pos = gt_boxs[fg_masks]
  188. # iou loss
  189. ious = bbox_iou(pred_boxs_pos,
  190. gt_boxs_pos,
  191. xywh=False,
  192. CIoU=True)
  193. loss_iou = (1.0 - ious) * bbox_weight
  194. # dfl loss
  195. if self.use_dfl:
  196. pred_regs_pos = pred_regs[fg_masks]
  197. gt_boxs_s = gt_boxs / strides
  198. anchors_s = anchors / strides
  199. gt_ltrb_s = bbox2dist(anchors_s, gt_boxs_s, self.reg_max)
  200. gt_ltrb_s_pos = gt_ltrb_s[fg_masks]
  201. loss_dfl = self.df_loss(pred_regs_pos, gt_ltrb_s_pos)
  202. loss_dfl *= bbox_weight
  203. else:
  204. loss_dfl = pred_regs.sum() * 0.
  205. else:
  206. loss_iou = pred_regs.sum() * 0.
  207. loss_dfl = pred_regs.sum() * 0.
  208. return loss_iou, loss_dfl
  209. def build_criterion(cfg, device, num_classes):
  210. criterion = Criterion(
  211. cfg=cfg,
  212. device=device,
  213. num_classes=num_classes
  214. )
  215. return criterion
  216. if __name__ == "__main__":
  217. pass