loss.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 Criterion(object):
  8. def __init__(self, cfg, device, num_classes=80):
  9. # --------------- Basic parameters ---------------
  10. self.cfg = cfg
  11. self.device = device
  12. self.num_classes = num_classes
  13. self.reg_max = cfg['reg_max']
  14. self.use_dfl = cfg['reg_max'] > 1
  15. # --------------- Loss config ---------------
  16. self.loss_cls_weight = cfg['loss_cls_weight']
  17. self.loss_box_weight = cfg['loss_box_weight']
  18. self.loss_dfl_weight = cfg['loss_dfl_weight']
  19. # --------------- Matcher config ---------------
  20. self.matcher_hpy = cfg['matcher_hpy']
  21. self.matcher = TaskAlignedAssigner(num_classes = num_classes,
  22. topk_candidates = self.matcher_hpy['topk_candidates'],
  23. alpha = self.matcher_hpy['alpha'],
  24. beta = self.matcher_hpy['beta']
  25. )
  26. def loss_classes(self, pred_cls, gt_score):
  27. # compute bce loss
  28. loss_cls = F.binary_cross_entropy_with_logits(pred_cls, gt_score, reduction='none')
  29. return loss_cls
  30. def loss_bboxes(self, pred_box, gt_box, bbox_weight):
  31. # regression loss
  32. ious = bbox_iou(pred_box, gt_box, xywh=False, CIoU=True)
  33. loss_box = (1.0 - ious.squeeze(-1)) * bbox_weight
  34. return loss_box
  35. def loss_dfl(self, pred_reg, gt_box, anchor, stride, bbox_weight=None):
  36. # rescale coords by stride
  37. gt_box_s = gt_box / stride
  38. anchor_s = anchor / stride
  39. # compute deltas
  40. gt_ltrb_s = bbox2dist(anchor_s, gt_box_s, self.cfg['reg_max'] - 1)
  41. gt_left = gt_ltrb_s.to(torch.long)
  42. gt_right = gt_left + 1
  43. weight_left = gt_right.to(torch.float) - gt_ltrb_s
  44. weight_right = 1 - weight_left
  45. # loss left
  46. loss_left = F.cross_entropy(
  47. pred_reg.view(-1, self.cfg['reg_max']),
  48. gt_left.view(-1),
  49. reduction='none').view(gt_left.shape) * weight_left
  50. # loss right
  51. loss_right = F.cross_entropy(
  52. pred_reg.view(-1, self.cfg['reg_max']),
  53. gt_right.view(-1),
  54. reduction='none').view(gt_left.shape) * weight_right
  55. loss_dfl = (loss_left + loss_right).mean(-1)
  56. if bbox_weight is not None:
  57. loss_dfl *= bbox_weight
  58. return loss_dfl
  59. def __call__(self, outputs, targets, epoch=0):
  60. """
  61. outputs['pred_cls']: List(Tensor) [B, M, C]
  62. outputs['pred_reg']: List(Tensor) [B, M, 4*(reg_max+1)]
  63. outputs['pred_box']: List(Tensor) [B, M, 4]
  64. outputs['anchors']: List(Tensor) [M, 2]
  65. outputs['strides']: List(Int) [8, 16, 32] output stride
  66. outputs['stride_tensor']: List(Tensor) [M, 1]
  67. targets: (List) [dict{'boxes': [...],
  68. 'labels': [...],
  69. 'orig_size': ...}, ...]
  70. """
  71. bs = outputs['pred_cls'][0].shape[0]
  72. device = outputs['pred_cls'][0].device
  73. strides = outputs['stride_tensor']
  74. anchors = outputs['anchors']
  75. anchors = torch.cat(anchors, dim=0)
  76. num_anchors = anchors.shape[0]
  77. # preds: [B, M, C]
  78. cls_preds = torch.cat(outputs['pred_cls'], dim=1)
  79. reg_preds = torch.cat(outputs['pred_reg'], dim=1)
  80. box_preds = torch.cat(outputs['pred_box'], dim=1)
  81. # --------------- label assignment ---------------
  82. gt_score_targets = []
  83. gt_bbox_targets = []
  84. fg_masks = []
  85. for batch_idx in range(bs):
  86. tgt_labels = targets[batch_idx]["labels"].to(device) # [Mp,]
  87. tgt_boxs = targets[batch_idx]["boxes"].to(device) # [Mp, 4]
  88. # check target
  89. if len(tgt_labels) == 0 or tgt_boxs.max().item() == 0.:
  90. # There is no valid gt
  91. fg_mask = cls_preds.new_zeros(1, num_anchors).bool() #[1, M,]
  92. gt_score = cls_preds.new_zeros((1, num_anchors, self.num_classes)) #[1, M, C]
  93. gt_box = cls_preds.new_zeros((1, num_anchors, 4)) #[1, M, 4]
  94. else:
  95. tgt_labels = tgt_labels[None, :, None] # [1, Mp, 1]
  96. tgt_boxs = tgt_boxs[None] # [1, Mp, 4]
  97. (
  98. _,
  99. gt_box, # [1, M, 4]
  100. gt_score, # [1, M, C]
  101. fg_mask, # [1, M,]
  102. _
  103. ) = self.matcher(
  104. pd_scores = cls_preds[batch_idx:batch_idx+1].detach().sigmoid(),
  105. pd_bboxes = box_preds[batch_idx:batch_idx+1].detach(),
  106. anc_points = anchors,
  107. gt_labels = tgt_labels,
  108. gt_bboxes = tgt_boxs
  109. )
  110. gt_score_targets.append(gt_score)
  111. gt_bbox_targets.append(gt_box)
  112. fg_masks.append(fg_mask)
  113. # List[B, 1, M, C] -> Tensor[B, M, C] -> Tensor[BM, C]
  114. fg_masks = torch.cat(fg_masks, 0).view(-1) # [BM,]
  115. gt_score_targets = torch.cat(gt_score_targets, 0).view(-1, self.num_classes) # [BM, C]
  116. gt_bbox_targets = torch.cat(gt_bbox_targets, 0).view(-1, 4) # [BM, 4]
  117. num_fgs = gt_score_targets.sum()
  118. # Average loss normalizer across all the GPUs
  119. if is_dist_avail_and_initialized():
  120. torch.distributed.all_reduce(num_fgs)
  121. num_fgs = (num_fgs / get_world_size()).clamp(1.0)
  122. # ------------------ Classification loss ------------------
  123. cls_preds = cls_preds.view(-1, self.num_classes)
  124. loss_cls = self.loss_classes(cls_preds, gt_score_targets)
  125. loss_cls = loss_cls.sum() / num_fgs
  126. # ------------------ Regression loss ------------------
  127. box_preds_pos = box_preds.view(-1, 4)[fg_masks]
  128. box_targets_pos = gt_bbox_targets.view(-1, 4)[fg_masks]
  129. bbox_weight = gt_score_targets[fg_masks].sum(-1)
  130. loss_box = self.loss_bboxes(box_preds_pos, box_targets_pos, bbox_weight)
  131. loss_box = loss_box.sum() / num_fgs
  132. # ------------------ Distribution focal loss ------------------
  133. ## process anchors
  134. anchors = torch.cat(outputs['anchors'], dim=0)
  135. anchors = anchors[None].repeat(bs, 1, 1).view(-1, 2)
  136. ## process stride tensors
  137. strides = torch.cat(outputs['stride_tensor'], dim=0)
  138. strides = strides.unsqueeze(0).repeat(bs, 1, 1).view(-1, 1)
  139. ## fg preds
  140. reg_preds_pos = reg_preds.view(-1, 4*self.cfg['reg_max'])[fg_masks]
  141. anchors_pos = anchors[fg_masks]
  142. strides_pos = strides[fg_masks]
  143. ## compute dfl
  144. loss_dfl = self.loss_dfl(reg_preds_pos, box_targets_pos, anchors_pos, strides_pos, bbox_weight)
  145. loss_dfl = loss_dfl.sum() / num_fgs
  146. # total loss
  147. if not self.use_dfl:
  148. losses = loss_cls * self.loss_cls_weight + loss_box * self.loss_box_weight
  149. loss_dict = dict(
  150. loss_cls = loss_cls,
  151. loss_box = loss_box,
  152. losses = losses
  153. )
  154. else:
  155. losses = loss_cls * self.loss_cls_weight + loss_box * self.loss_box_weight + loss_dfl * self.loss_dfl_weight
  156. loss_dict = dict(
  157. loss_cls = loss_cls,
  158. loss_box = loss_box,
  159. loss_dfl = loss_dfl,
  160. losses = losses
  161. )
  162. return loss_dict
  163. class ClassificationLoss(nn.Module):
  164. def __init__(self, cfg, reduction='none'):
  165. super(ClassificationLoss, self).__init__()
  166. self.cfg = cfg
  167. self.reduction = reduction
  168. # For VFL
  169. self.alpha = 0.75
  170. self.gamma = 2.0
  171. def binary_cross_entropy(self, pred_logits, gt_score):
  172. loss = F.binary_cross_entropy_with_logits(
  173. pred_logits.float(), gt_score.float(), reduction='none')
  174. if self.reduction == 'sum':
  175. loss = loss.sum()
  176. elif self.reduction == 'mean':
  177. loss = loss.mean()
  178. return loss
  179. def forward(self, pred_logits, gt_score):
  180. if self.cfg['cls_loss'] == 'bce':
  181. return self.binary_cross_entropy(pred_logits, gt_score)
  182. class RegressionLoss(nn.Module):
  183. def __init__(self, num_classes, reg_max, use_dfl):
  184. super(RegressionLoss, self).__init__()
  185. self.num_classes = num_classes
  186. self.reg_max = reg_max
  187. self.use_dfl = use_dfl
  188. def df_loss(self, pred_regs, target):
  189. gt_left = target.to(torch.long)
  190. gt_right = gt_left + 1
  191. weight_left = gt_right.to(torch.float) - target
  192. weight_right = 1 - weight_left
  193. # loss left
  194. loss_left = F.cross_entropy(
  195. pred_regs.view(-1, self.reg_max + 1),
  196. gt_left.view(-1),
  197. reduction='none').view(gt_left.shape) * weight_left
  198. # loss right
  199. loss_right = F.cross_entropy(
  200. pred_regs.view(-1, self.reg_max + 1),
  201. gt_right.view(-1),
  202. reduction='none').view(gt_left.shape) * weight_right
  203. loss = (loss_left + loss_right).mean(-1, keepdim=True)
  204. return loss
  205. def forward(self, pred_regs, pred_boxs, anchors, gt_boxs, bbox_weight, fg_masks, strides):
  206. """
  207. Input:
  208. pred_regs: (Tensor) [BM, 4*(reg_max + 1)]
  209. pred_boxs: (Tensor) [BM, 4]
  210. anchors: (Tensor) [BM, 2]
  211. gt_boxs: (Tensor) [BM, 4]
  212. bbox_weight: (Tensor) [BM, 1]
  213. fg_masks: (Tensor) [BM,]
  214. strides: (Tensor) [BM, 1]
  215. """
  216. # select positive samples mask
  217. num_pos = fg_masks.sum()
  218. if num_pos > 0:
  219. pred_boxs_pos = pred_boxs[fg_masks]
  220. gt_boxs_pos = gt_boxs[fg_masks]
  221. # iou loss
  222. ious = bbox_iou(pred_boxs_pos,
  223. gt_boxs_pos,
  224. xywh=False,
  225. CIoU=True)
  226. loss_iou = (1.0 - ious) * bbox_weight
  227. # dfl loss
  228. if self.use_dfl:
  229. pred_regs_pos = pred_regs[fg_masks]
  230. gt_boxs_s = gt_boxs / strides
  231. anchors_s = anchors / strides
  232. gt_ltrb_s = bbox2dist(anchors_s, gt_boxs_s, self.reg_max)
  233. gt_ltrb_s_pos = gt_ltrb_s[fg_masks]
  234. loss_dfl = self.df_loss(pred_regs_pos, gt_ltrb_s_pos)
  235. loss_dfl *= bbox_weight
  236. else:
  237. loss_dfl = pred_regs.sum() * 0.
  238. else:
  239. loss_iou = pred_regs.sum() * 0.
  240. loss_dfl = pred_regs.sum() * 0.
  241. return loss_iou, loss_dfl
  242. def build_criterion(cfg, device, num_classes):
  243. criterion = Criterion(
  244. cfg=cfg,
  245. device=device,
  246. num_classes=num_classes
  247. )
  248. return criterion
  249. if __name__ == "__main__":
  250. pass