loss.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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 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. # loss
  15. self.cls_lossf = ClassificationLoss(cfg)
  16. self.reg_lossf = RegressionLoss(num_classes)
  17. # loss weight
  18. self.loss_cls_weight = cfg['loss_cls_weight']
  19. self.loss_box_weight = cfg['loss_box_weight']
  20. # matcher
  21. matcher_config = cfg['matcher']
  22. self.matcher = TaskAlignedAssigner(
  23. topk=matcher_config['topk'],
  24. num_classes=num_classes,
  25. alpha=matcher_config['alpha'],
  26. beta=matcher_config['beta']
  27. )
  28. def __call__(self, outputs, targets, epoch=0):
  29. """
  30. outputs['pred_cls']: List(Tensor) [B, M, C]
  31. outputs['pred_regs']: List(Tensor) [B, M, 4*(reg_max+1)]
  32. outputs['pred_boxs']: List(Tensor) [B, M, 4]
  33. outputs['anchors']: List(Tensor) [M, 2]
  34. outputs['strides']: List(Int) [8, 16, 32] output stride
  35. outputs['stride_tensor']: List(Tensor) [M, 1]
  36. targets: (List) [dict{'boxes': [...],
  37. 'labels': [...],
  38. 'orig_size': ...}, ...]
  39. """
  40. bs = outputs['pred_cls'][0].shape[0]
  41. device = outputs['pred_cls'][0].device
  42. anchors = outputs['anchors']
  43. anchors = torch.cat(anchors, dim=0)
  44. num_anchors = anchors.shape[0]
  45. # preds: [B, M, C]
  46. cls_preds = torch.cat(outputs['pred_cls'], dim=1)
  47. box_preds = torch.cat(outputs['pred_box'], dim=1)
  48. # label assignment
  49. gt_label_targets = []
  50. gt_score_targets = []
  51. gt_bbox_targets = []
  52. fg_masks = []
  53. for batch_idx in range(bs):
  54. tgt_labels = targets[batch_idx]["labels"].to(device) # [Mp,]
  55. tgt_boxs = targets[batch_idx]["boxes"].to(device) # [Mp, 4]
  56. # check target
  57. if len(tgt_labels) == 0 or tgt_boxs.max().item() == 0.:
  58. # There is no valid gt
  59. fg_mask = cls_preds.new_zeros(1, num_anchors).bool() #[1, M,]
  60. gt_score = cls_preds.new_zeros((1, num_anchors, self.num_classes)) #[1, M, C]
  61. gt_box = cls_preds.new_zeros((1, num_anchors, 4)) #[1, M, 4]
  62. else:
  63. tgt_labels = tgt_labels[None, :, None] # [1, Mp, 1]
  64. tgt_boxs = tgt_boxs[None] # [1, Mp, 4]
  65. (
  66. gt_label,
  67. gt_box, #[1, M, 4]
  68. gt_score, #[1, M, C]
  69. fg_mask, #[1, M,]
  70. _
  71. ) = self.matcher(
  72. pd_scores = cls_preds[batch_idx:batch_idx+1].detach().sigmoid(),
  73. pd_bboxes = box_preds[batch_idx:batch_idx+1].detach(),
  74. anc_points = anchors,
  75. gt_labels = tgt_labels,
  76. gt_bboxes = tgt_boxs
  77. )
  78. gt_label_targets.append(gt_label)
  79. gt_score_targets.append(gt_score)
  80. gt_bbox_targets.append(gt_box)
  81. fg_masks.append(fg_mask)
  82. # List[B, 1, M, C] -> Tensor[B, M, C] -> Tensor[BM, C]
  83. fg_masks = torch.cat(fg_masks, 0).view(-1) # [BM,]
  84. gt_label_targets = torch.cat(gt_label_targets, 0).view(-1,) # [BM, 1]
  85. gt_score_targets = torch.cat(gt_score_targets, 0).view(-1, self.num_classes) # [BM, C]
  86. gt_bbox_targets = torch.cat(gt_bbox_targets, 0).view(-1, 4) # [BM, 4]
  87. # cls loss
  88. cls_preds = cls_preds.view(-1, self.num_classes)
  89. loss_cls = self.cls_lossf(cls_preds, gt_label_targets, gt_score_targets)
  90. # reg loss
  91. bbox_weight = gt_score_targets[fg_masks].sum(-1, keepdim=True) # [BM, 1]
  92. box_preds = box_preds.view(-1, 4) # [BM, 4]
  93. loss_box = self.reg_lossf(box_preds, gt_bbox_targets, bbox_weight, fg_masks)
  94. # normalize loss
  95. gt_score_targets_sum = max(gt_score_targets.sum(), 1)
  96. loss_cls = loss_cls.sum() / gt_score_targets_sum
  97. loss_box = loss_box.sum() / gt_score_targets_sum
  98. # total loss
  99. losses = loss_cls * self.loss_cls_weight + \
  100. loss_box * self.loss_box_weight
  101. loss_dict = dict(
  102. loss_cls = loss_cls,
  103. loss_box = loss_box,
  104. losses = losses
  105. )
  106. return loss_dict
  107. class ClassificationLoss(nn.Module):
  108. def __init__(self, cfg):
  109. super(ClassificationLoss, self).__init__()
  110. self.cfg = cfg
  111. def quality_focal_loss(self, pred_cls, gt_label, gt_score, beta=2.0):
  112. # Quality FocalLoss
  113. """
  114. pred_cls: (torch.Tensor): [N, C]
  115. gt_label: (torch.Tensor): [N,]
  116. gt_score: (torch.Tensor): [N, C]
  117. """
  118. gt_label = gt_label.long()
  119. gt_score = gt_score[torch.arange(gt_label.shape[0]), gt_label]
  120. pred_sigmoid = pred_cls.sigmoid()
  121. scale_factor = pred_sigmoid
  122. zerolabel = scale_factor.new_zeros(pred_cls.shape)
  123. ce_loss = F.binary_cross_entropy_with_logits(
  124. pred_cls, zerolabel, reduction='none') * scale_factor.pow(beta)
  125. bg_class_ind = pred_cls.shape[-1]
  126. pos = ((gt_label >= 0) & (gt_label < bg_class_ind)).nonzero().squeeze(1)
  127. pos_label = gt_label[pos].long()
  128. scale_factor = gt_score[pos] - pred_sigmoid[pos, pos_label]
  129. ce_loss[pos, pos_label] = F.binary_cross_entropy_with_logits(
  130. pred_cls[pos, pos_label], gt_score[pos],
  131. reduction='none') * scale_factor.abs().pow(beta)
  132. return ce_loss
  133. def binary_cross_entropy(self, pred_logits, gt_score):
  134. loss = F.binary_cross_entropy_with_logits(
  135. pred_logits, gt_score, reduction='none')
  136. return loss
  137. def forward(self, pred_logits, gt_label, gt_score):
  138. if self.cfg['cls_loss'] == 'bce':
  139. loss = self.binary_cross_entropy(pred_logits, gt_score)
  140. elif self.cfg['cls_loss'] == 'qfl':
  141. loss = self.quality_focal_loss(pred_logits, gt_label, gt_score)
  142. return loss
  143. class RegressionLoss(nn.Module):
  144. def __init__(self, num_classes):
  145. super(RegressionLoss, self).__init__()
  146. self.num_classes = num_classes
  147. def forward(self, pred_boxs, gt_boxs, bbox_weight, fg_masks):
  148. """
  149. Input:
  150. pred_boxs: (Tensor) [BM, 4]
  151. gt_boxs: (Tensor) [BM, 4]
  152. bbox_weight: (Tensor) [BM, 1]
  153. fg_masks: (Tensor) [BM,]
  154. """
  155. # select positive samples mask
  156. num_pos = fg_masks.sum()
  157. if num_pos > 0:
  158. pred_boxs_pos = pred_boxs[fg_masks]
  159. gt_boxs_pos = gt_boxs[fg_masks]
  160. # iou loss
  161. ious = bbox_iou(pred_boxs_pos,
  162. gt_boxs_pos,
  163. xywh=False,
  164. CIoU=True)
  165. loss_iou = (1.0 - ious) * bbox_weight
  166. else:
  167. loss_iou = pred_boxs.sum() * 0.
  168. return loss_iou
  169. def build_criterion(cfg, device, num_classes):
  170. criterion = Criterion(
  171. cfg=cfg,
  172. device=device,
  173. num_classes=num_classes
  174. )
  175. return criterion
  176. if __name__ == "__main__":
  177. pass