loss.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. """
  2. reference:
  3. https://github.com/facebookresearch/detr/blob/main/models/detr.py
  4. by lyuwenyu
  5. """
  6. import torch
  7. import torch.nn as nn
  8. import torch.nn.functional as F
  9. from .loss_utils import box_cxcywh_to_xyxy, box_iou, generalized_box_iou
  10. from .loss_utils import is_dist_avail_and_initialized, get_world_size
  11. from .matcher import HungarianMatcher
  12. # --------------- Criterion for RT-DETR ---------------
  13. class SetCriterion(nn.Module):
  14. def __init__(self, cfg):
  15. super().__init__()
  16. self.num_classes = cfg.num_classes
  17. self.losses = ['labels', 'boxes']
  18. self.alpha = 0.75 # For VFL
  19. self.gamma = 2.0
  20. self.matcher = HungarianMatcher(cfg.cost_class, cfg.cost_bbox, cfg.cost_giou, alpha=0.25, gamma=2.0)
  21. self.weight_dict = {'loss_cls': cfg.loss_cls,
  22. 'loss_box': cfg.loss_box,
  23. 'loss_giou': cfg.loss_giou}
  24. def loss_labels(self, outputs, targets, indices, num_boxes):
  25. "Compute variable focal loss"
  26. assert 'pred_boxes' in outputs
  27. idx = self._get_src_permutation_idx(indices)
  28. # Compute IoU between pred and target
  29. src_boxes = outputs['pred_boxes'][idx]
  30. target_boxes = torch.cat([t['boxes'][i] for t, (_, i) in zip(targets, indices)], dim=0)
  31. ious, _ = box_iou(box_cxcywh_to_xyxy(src_boxes), box_cxcywh_to_xyxy(target_boxes))
  32. ious = torch.diag(ious).detach()
  33. # One-hot class label
  34. src_logits = outputs['pred_logits']
  35. target_classes_o = torch.cat([t["labels"][J] for t, (_, J) in zip(targets, indices)])
  36. target_classes = torch.full(src_logits.shape[:2], self.num_classes,
  37. dtype=torch.int64, device=src_logits.device)
  38. target_classes[idx] = target_classes_o
  39. target = F.one_hot(target_classes, num_classes=self.num_classes + 1)[..., :-1]
  40. # Iou-aware class label
  41. target_score_o = torch.zeros_like(target_classes, dtype=src_logits.dtype)
  42. target_score_o[idx] = ious.to(target_score_o.dtype)
  43. target_score = target_score_o.unsqueeze(-1) * target
  44. # Compute VFL
  45. pred_score = F.sigmoid(src_logits).detach()
  46. weight = self.alpha * pred_score.pow(self.gamma) * (1 - target) + target_score
  47. loss = F.binary_cross_entropy_with_logits(src_logits, target_score, weight=weight, reduction='none')
  48. loss = loss.mean(1).sum() * src_logits.shape[1] / num_boxes
  49. return {'loss_cls': loss}
  50. def loss_boxes(self, outputs, targets, indices, num_boxes):
  51. """Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss
  52. targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]
  53. The target boxes are expected in format (center_x, center_y, w, h), normalized by the image size.
  54. """
  55. assert 'pred_boxes' in outputs
  56. idx = self._get_src_permutation_idx(indices)
  57. src_boxes = outputs['pred_boxes'][idx]
  58. target_boxes = torch.cat([t['boxes'][i] for t, (_, i) in zip(targets, indices)], dim=0)
  59. losses = {}
  60. loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction='none')
  61. losses['loss_box'] = loss_bbox.sum() / num_boxes
  62. loss_giou = 1 - torch.diag(generalized_box_iou(
  63. box_cxcywh_to_xyxy(src_boxes),
  64. box_cxcywh_to_xyxy(target_boxes)))
  65. losses['loss_giou'] = loss_giou.sum() / num_boxes
  66. return losses
  67. def _get_src_permutation_idx(self, indices):
  68. # permute predictions following indices
  69. batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)])
  70. src_idx = torch.cat([src for (src, _) in indices])
  71. return batch_idx, src_idx
  72. def _get_tgt_permutation_idx(self, indices):
  73. # permute targets following indices
  74. batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)])
  75. tgt_idx = torch.cat([tgt for (_, tgt) in indices])
  76. return batch_idx, tgt_idx
  77. def get_loss(self, loss, outputs, targets, indices, num_boxes, **kwargs):
  78. loss_map = {
  79. 'boxes': self.loss_boxes,
  80. 'labels': self.loss_labels,
  81. }
  82. assert loss in loss_map, f'do you really want to compute {loss} loss?'
  83. return loss_map[loss](outputs, targets, indices, num_boxes, **kwargs)
  84. def forward(self, outputs, targets):
  85. outputs_without_aux = {k: v for k, v in outputs.items() if 'aux' not in k}
  86. # Retrieve the matching between the outputs of the last layer and the targets
  87. indices = self.matcher(outputs_without_aux, targets)
  88. # Compute the average number of target boxes accross all nodes, for normalization purposes
  89. num_boxes = sum(len(t["labels"]) for t in targets)
  90. num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device)
  91. if is_dist_avail_and_initialized():
  92. torch.distributed.all_reduce(num_boxes)
  93. num_boxes = torch.clamp(num_boxes / get_world_size(), min=1).item()
  94. # Compute all the requested losses
  95. losses = {}
  96. for loss in self.losses:
  97. l_dict = self.get_loss(loss, outputs, targets, indices, num_boxes)
  98. l_dict = {k: l_dict[k] * self.weight_dict[k] for k in l_dict if k in self.weight_dict}
  99. losses.update(l_dict)
  100. # In case of auxiliary losses, we repeat this process with the output of each intermediate layer.
  101. if 'aux_outputs' in outputs:
  102. for i, aux_outputs in enumerate(outputs['aux_outputs']):
  103. indices = self.matcher(aux_outputs, targets)
  104. for loss in self.losses:
  105. l_dict = self.get_loss(loss, aux_outputs, targets, indices, num_boxes)
  106. l_dict = {k: l_dict[k] * self.weight_dict[k] for k in l_dict if k in self.weight_dict}
  107. l_dict = {k + f'_aux_{i}': v for k, v in l_dict.items()}
  108. losses.update(l_dict)
  109. # In case of cdn auxiliary losses. For rtdetr
  110. if 'dn_aux_outputs' in outputs:
  111. assert 'dn_meta' in outputs, ''
  112. indices = self.get_cdn_matched_indices(outputs['dn_meta'], targets)
  113. num_boxes = num_boxes * outputs['dn_meta']['dn_num_group']
  114. for i, aux_outputs in enumerate(outputs['dn_aux_outputs']):
  115. # indices = self.matcher(aux_outputs, targets)
  116. for loss in self.losses:
  117. l_dict = self.get_loss(loss, aux_outputs, targets, indices, num_boxes)
  118. l_dict = {k: l_dict[k] * self.weight_dict[k] for k in l_dict if k in self.weight_dict}
  119. l_dict = {k + f'_dn_{i}': v for k, v in l_dict.items()}
  120. losses.update(l_dict)
  121. return losses
  122. @staticmethod
  123. def get_cdn_matched_indices(dn_meta, targets):
  124. '''get_cdn_matched_indices
  125. '''
  126. dn_positive_idx, dn_num_group = dn_meta["dn_positive_idx"], dn_meta["dn_num_group"]
  127. num_gts = [len(t['labels']) for t in targets]
  128. device = targets[0]['labels'].device
  129. dn_match_indices = []
  130. for i, num_gt in enumerate(num_gts):
  131. if num_gt > 0:
  132. gt_idx = torch.arange(num_gt, dtype=torch.int64, device=device)
  133. gt_idx = gt_idx.tile(dn_num_group)
  134. assert len(dn_positive_idx[i]) == len(gt_idx)
  135. dn_match_indices.append((dn_positive_idx[i], gt_idx))
  136. else:
  137. dn_match_indices.append((torch.zeros(0, dtype=torch.int64, device=device), \
  138. torch.zeros(0, dtype=torch.int64, device=device)))
  139. return dn_match_indices