loss.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from .matcher import build_matcher
  5. from utils.misc import sigmoid_focal_loss
  6. from utils.box_ops import box_cxcywh_to_xyxy, generalized_box_iou
  7. from utils.distributed_utils import is_dist_avail_and_initialized, get_world_size
  8. class Criterion(nn.Module):
  9. """ This class computes the loss for DETR.
  10. The process happens in two steps:
  11. 1) we compute hungarian assignment between ground truth boxes and the outputs of the model
  12. 2) we supervise each pair of matched ground-truth / prediction (supervise class and box)
  13. """
  14. def __init__(self, num_classes, matcher, weight_dict, losses, focal_alpha=0.25):
  15. """ Create the criterion.
  16. Parameters:
  17. num_classes: number of object categories, omitting the special no-object category
  18. matcher: module able to compute a matching between targets and proposals
  19. weight_dict: dict containing as key the names of the losses and as values their relative weight.
  20. eos_coef: relative classification weight applied to the no-object category
  21. losses: list of all the losses to be applied. See get_loss for list of available losses.
  22. """
  23. super().__init__()
  24. self.num_classes = num_classes
  25. self.matcher = matcher
  26. self.weight_dict = weight_dict
  27. self.losses = losses
  28. self.focal_alpha = focal_alpha
  29. def _get_src_permutation_idx(self, indices):
  30. # permute predictions following indices
  31. batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)])
  32. src_idx = torch.cat([src for (src, _) in indices])
  33. return batch_idx, src_idx
  34. def _get_tgt_permutation_idx(self, indices):
  35. # permute targets following indices
  36. batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)])
  37. tgt_idx = torch.cat([tgt for (_, tgt) in indices])
  38. return batch_idx, tgt_idx
  39. def loss_labels(self, outputs, targets, indices, num_boxes):
  40. """Classification loss (NLL)
  41. targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes]
  42. """
  43. assert 'pred_logits' in outputs
  44. src_logits = outputs['pred_logits']
  45. idx = self._get_src_permutation_idx(indices)
  46. target_classes_o = torch.cat([t["labels"][J] for t, (_, J) in zip(targets, indices)]).to(src_logits.device)
  47. target_classes = torch.full(src_logits.shape[:2], self.num_classes,
  48. dtype=torch.int64, device=src_logits.device)
  49. target_classes[idx] = target_classes_o
  50. target_classes_onehot = torch.zeros([src_logits.shape[0], src_logits.shape[1], src_logits.shape[2] + 1],
  51. dtype=src_logits.dtype, layout=src_logits.layout, device=src_logits.device)
  52. target_classes_onehot.scatter_(2, target_classes.unsqueeze(-1), 1)
  53. target_classes_onehot = target_classes_onehot[:, :, :-1]
  54. loss_cls = sigmoid_focal_loss(src_logits, target_classes_onehot, num_boxes, alpha=self.focal_alpha, gamma=2) * \
  55. src_logits.shape[1]
  56. losses = {'loss_cls': loss_cls}
  57. return losses
  58. def loss_boxes(self, outputs, targets, indices, num_boxes):
  59. """Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss
  60. targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]
  61. The target boxes are expected in format (center_x, center_y, w, h), normalized by the image size.
  62. """
  63. assert 'pred_boxes' in outputs
  64. idx = self._get_src_permutation_idx(indices)
  65. src_boxes = outputs['pred_boxes'][idx]
  66. target_boxes = torch.cat([t['boxes'][i] for t, (_, i) in zip(targets, indices)], dim=0).to(src_boxes.device)
  67. loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction='none')
  68. losses = {}
  69. losses['loss_box'] = loss_bbox.sum() / num_boxes
  70. loss_giou = 1 - torch.diag(generalized_box_iou(
  71. box_cxcywh_to_xyxy(src_boxes),
  72. box_cxcywh_to_xyxy(target_boxes)))
  73. losses['loss_giou'] = loss_giou.sum() / num_boxes
  74. return losses
  75. def get_loss(self, loss, outputs, targets, indices, num_boxes, **kwargs):
  76. loss_map = {
  77. 'labels': self.loss_labels,
  78. 'boxes': self.loss_boxes,
  79. }
  80. assert loss in loss_map, f'do you really want to compute {loss} loss?'
  81. return loss_map[loss](outputs, targets, indices, num_boxes, **kwargs)
  82. def forward(self, outputs, targets, epoch=0):
  83. """ This performs the loss computation.
  84. Parameters:
  85. outputs: dict of tensors, see the output specification of the model for the format
  86. targets: list of dicts, such that len(targets) == batch_size.
  87. The expected keys in each dict depends on the losses applied, see each loss' doc
  88. """
  89. outputs_without_aux = {k: v for k, v in outputs.items() if k != 'aux_outputs'}
  90. # Retrieve the matching between the outputs of the last layer and the targets
  91. indices = self.matcher(outputs_without_aux, targets)
  92. # Compute the average number of target boxes accross all nodes, for normalization purposes
  93. num_boxes = sum(len(t["labels"]) for t in targets)
  94. num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device)
  95. if is_dist_avail_and_initialized():
  96. torch.distributed.all_reduce(num_boxes)
  97. num_boxes = torch.clamp(num_boxes / get_world_size(), min=1).item()
  98. # Compute all the requested losses
  99. losses = {}
  100. for loss in self.losses:
  101. losses.update(self.get_loss(loss, outputs, targets, indices, num_boxes))
  102. # In case of auxiliary losses, we repeat this process with the output of each intermediate layer.
  103. if 'aux_outputs' in outputs:
  104. for i, aux_outputs in enumerate(outputs['aux_outputs']):
  105. indices = self.matcher(aux_outputs, targets)
  106. for loss in self.losses:
  107. kwargs = {}
  108. l_dict = self.get_loss(loss, aux_outputs, targets, indices, num_boxes, **kwargs)
  109. l_dict = {k + f'_{i}': v for k, v in l_dict.items()}
  110. losses.update(l_dict)
  111. # compute total losses
  112. total_loss = sum(losses[k] * self.weight_dict[k] for k in losses.keys() if k in self.weight_dict)
  113. losses['losses'] = total_loss
  114. return losses
  115. # build criterion
  116. def build_criterion(cfg, num_classes, aux_loss=False):
  117. # build matcher
  118. matcher_type = cfg['matcher']
  119. matcher = build_matcher(cfg)
  120. # build criterion
  121. weight_dict = {'loss_cls': cfg['loss_weights'][matcher_type]['loss_cls_weight'],
  122. 'loss_box': cfg['loss_weights'][matcher_type]['loss_box_weight'],
  123. 'loss_giou': cfg['loss_weights'][matcher_type]['loss_giou_weight']}
  124. if aux_loss:
  125. aux_weight_dict = {}
  126. for i in range(cfg['num_decoder'] - 1):
  127. aux_weight_dict.update({k + f'_{i}': v for k, v in weight_dict.items()})
  128. weight_dict.update(aux_weight_dict)
  129. losses = ['labels', 'boxes']
  130. criterion = Criterion(num_classes, matcher, weight_dict, losses)
  131. return criterion