loss.py 11 KB

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