loss.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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_label_targets = []
  55. gt_score_targets = []
  56. gt_bbox_targets = []
  57. fg_masks = []
  58. for batch_idx in range(bs):
  59. tgt_labels = targets[batch_idx]["labels"].to(device) # [Mp,]
  60. tgt_boxs = targets[batch_idx]["boxes"].to(device) # [Mp, 4]
  61. # check target
  62. if len(tgt_labels) == 0 or tgt_boxs.max().item() == 0.:
  63. # There is no valid gt
  64. fg_mask = cls_preds.new_zeros(1, num_anchors).bool() #[1, M,]
  65. gt_label = cls_preds.new_zeros((1, num_anchors,)) #[1, M,]
  66. gt_score = cls_preds.new_zeros((1, num_anchors, self.num_classes)) #[1, M, C]
  67. gt_box = cls_preds.new_zeros((1, num_anchors, 4)) #[1, M, 4]
  68. else:
  69. tgt_labels = tgt_labels[None, :, None] # [1, Mp, 1]
  70. tgt_boxs = tgt_boxs[None] # [1, Mp, 4]
  71. (
  72. gt_label, #[1, M,]
  73. gt_box, #[1, M, 4]
  74. gt_score, #[1, M, C]
  75. fg_mask #[1, M,]
  76. ) = self.matcher(
  77. pd_scores = cls_preds[batch_idx:batch_idx+1].detach().sigmoid(),
  78. pd_bboxes = box_preds[batch_idx:batch_idx+1].detach(),
  79. anc_points = anchors,
  80. gt_labels = tgt_labels,
  81. gt_bboxes = tgt_boxs
  82. )
  83. gt_label_targets.append(gt_label)
  84. gt_score_targets.append(gt_score)
  85. gt_bbox_targets.append(gt_box)
  86. fg_masks.append(fg_mask)
  87. # List[B, 1, M, C] -> Tensor[B, M, C] -> Tensor[BM, C]
  88. fg_masks = torch.cat(fg_masks, 0).view(-1) # [BM,]
  89. gt_label_targets = torch.cat(gt_label_targets, 0).view(-1) # [BM,]
  90. gt_score_targets = torch.cat(gt_score_targets, 0).view(-1, self.num_classes) # [BM, C]
  91. gt_bbox_targets = torch.cat(gt_bbox_targets, 0).view(-1, 4) # [BM, 4]
  92. # cls loss
  93. cls_preds = cls_preds.view(-1, self.num_classes)
  94. gt_label_targets = torch.where(
  95. fg_masks > 0,
  96. gt_label_targets,
  97. torch.full_like(gt_label_targets, self.num_classes)
  98. )
  99. gt_labels_one_hot = F.one_hot(gt_label_targets.long(), self.num_classes + 1)[..., :-1]
  100. loss_cls = self.cls_lossf(cls_preds, gt_score_targets, gt_labels_one_hot)
  101. # reg loss
  102. anchors = anchors[None].repeat(bs, 1, 1).view(-1, 2) # [BM, 2]
  103. strides = torch.cat(strides, dim=0).unsqueeze(0).repeat(bs, 1, 1).view(-1, 1) # [BM, 1]
  104. bbox_weight = gt_score_targets[fg_masks].sum(-1, keepdim=True) # [BM, 1]
  105. reg_preds = reg_preds.view(-1, 4*self.reg_max) # [BM, 4*(reg_max + 1)]
  106. box_preds = box_preds.view(-1, 4) # [BM, 4]
  107. loss_iou, loss_dfl = self.reg_lossf(
  108. pred_regs = reg_preds,
  109. pred_boxs = box_preds,
  110. anchors = anchors,
  111. gt_boxs = gt_bbox_targets,
  112. bbox_weight = bbox_weight,
  113. fg_masks = fg_masks,
  114. strides = strides,
  115. )
  116. loss_cls = loss_cls.sum()
  117. loss_iou = loss_iou.sum()
  118. loss_dfl = loss_dfl.sum()
  119. gt_score_targets_sum = gt_score_targets.sum()
  120. # normalize loss
  121. if gt_score_targets_sum > 0:
  122. loss_cls /= gt_score_targets_sum
  123. loss_iou /= gt_score_targets_sum
  124. loss_dfl /= gt_score_targets_sum
  125. # total loss
  126. losses = loss_cls * self.loss_cls_weight + \
  127. loss_iou * self.loss_iou_weight
  128. if self.use_dfl:
  129. losses += loss_dfl * self.loss_dfl_weight
  130. loss_dict = dict(
  131. loss_cls = loss_cls,
  132. loss_iou = loss_iou,
  133. loss_dfl = loss_dfl,
  134. losses = losses
  135. )
  136. else:
  137. loss_dict = dict(
  138. loss_cls = loss_cls,
  139. loss_iou = loss_iou,
  140. losses = losses
  141. )
  142. return loss_dict
  143. class ClassificationLoss(nn.Module):
  144. def __init__(self, cfg, reduction='none'):
  145. super(ClassificationLoss, self).__init__()
  146. self.cfg = cfg
  147. self.reduction = reduction
  148. # For VFL
  149. self.alpha = 0.75
  150. self.gamma = 2.0
  151. def varifocalloss(self, pred_logits, gt_score, gt_label, alpha=0.75, gamma=2.0):
  152. focal_weight = alpha * pred_logits.sigmoid().pow(gamma) * (1 - gt_label) + gt_score * gt_label
  153. with torch.cuda.amp.autocast(enabled=False):
  154. bce_loss = F.binary_cross_entropy_with_logits(
  155. pred_logits.float(), gt_score.float(), reduction='none')
  156. loss = bce_loss * focal_weight
  157. if self.reduction == 'sum':
  158. loss = loss.sum()
  159. elif self.reduction == 'mean':
  160. loss = loss.mean()
  161. return loss
  162. def binary_cross_entropy(self, pred_logits, gt_score):
  163. loss = F.binary_cross_entropy_with_logits(
  164. pred_logits.float(), gt_score.float(), reduction='none')
  165. if self.reduction == 'sum':
  166. loss = loss.sum()
  167. elif self.reduction == 'mean':
  168. loss = loss.mean()
  169. return loss
  170. def forward(self, pred_logits, gt_score, gt_label):
  171. if self.cfg['cls_loss'] == 'vfl':
  172. return self.varifocalloss(pred_logits, gt_score, gt_label, self.alpha, self.gamma)
  173. elif self.cfg['cls_loss'] == 'bce':
  174. return self.binary_cross_entropy(pred_logits, gt_score)
  175. class RegressionLoss(nn.Module):
  176. def __init__(self, num_classes, reg_max, use_dfl):
  177. super(RegressionLoss, self).__init__()
  178. self.num_classes = num_classes
  179. self.reg_max = reg_max
  180. self.use_dfl = use_dfl
  181. def df_loss(self, pred_regs, target):
  182. gt_left = target.to(torch.long)
  183. gt_right = gt_left + 1
  184. weight_left = gt_right.to(torch.float) - target
  185. weight_right = 1 - weight_left
  186. # loss left
  187. loss_left = F.cross_entropy(
  188. pred_regs.view(-1, self.reg_max + 1),
  189. gt_left.view(-1),
  190. reduction='none').view(gt_left.shape) * weight_left
  191. # loss right
  192. loss_right = F.cross_entropy(
  193. pred_regs.view(-1, self.reg_max + 1),
  194. gt_right.view(-1),
  195. reduction='none').view(gt_left.shape) * weight_right
  196. loss = (loss_left + loss_right).mean(-1, keepdim=True)
  197. return loss
  198. def forward(self, pred_regs, pred_boxs, anchors, gt_boxs, bbox_weight, fg_masks, strides):
  199. """
  200. Input:
  201. pred_regs: (Tensor) [BM, 4*(reg_max + 1)]
  202. pred_boxs: (Tensor) [BM, 4]
  203. anchors: (Tensor) [BM, 2]
  204. gt_boxs: (Tensor) [BM, 4]
  205. bbox_weight: (Tensor) [BM, 1]
  206. fg_masks: (Tensor) [BM,]
  207. strides: (Tensor) [BM, 1]
  208. """
  209. # select positive samples mask
  210. num_pos = fg_masks.sum()
  211. if num_pos > 0:
  212. pred_boxs_pos = pred_boxs[fg_masks]
  213. gt_boxs_pos = gt_boxs[fg_masks]
  214. # iou loss
  215. ious = bbox_iou(pred_boxs_pos,
  216. gt_boxs_pos,
  217. xywh=False,
  218. CIoU=True)
  219. loss_iou = (1.0 - ious) * bbox_weight
  220. # dfl loss
  221. if self.use_dfl:
  222. pred_regs_pos = pred_regs[fg_masks]
  223. gt_boxs_s = gt_boxs / strides
  224. anchors_s = anchors / strides
  225. gt_ltrb_s = bbox2dist(anchors_s, gt_boxs_s, self.reg_max)
  226. gt_ltrb_s_pos = gt_ltrb_s[fg_masks]
  227. loss_dfl = self.df_loss(pred_regs_pos, gt_ltrb_s_pos)
  228. loss_dfl *= bbox_weight
  229. else:
  230. loss_dfl = pred_regs.sum() * 0.
  231. else:
  232. loss_iou = pred_regs.sum() * 0.
  233. loss_dfl = pred_regs.sum() * 0.
  234. return loss_iou, loss_dfl
  235. def build_criterion(cfg, device, num_classes):
  236. criterion = Criterion(
  237. cfg=cfg,
  238. device=device,
  239. num_classes=num_classes
  240. )
  241. return criterion
  242. if __name__ == "__main__":
  243. pass