criterion.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import copy
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. from .matcher import HungarianMatcher
  6. from utils.misc import sigmoid_focal_loss
  7. from utils.box_ops import box_cxcywh_to_xyxy, generalized_box_iou, bbox2delta
  8. from utils.distributed_utils import is_dist_avail_and_initialized, get_world_size
  9. # build criterion
  10. def build_criterion(cfg, num_classes, aux_loss=True):
  11. criterion = Criterion(cfg, num_classes, aux_loss)
  12. return criterion
  13. class Criterion(nn.Module):
  14. def __init__(self, cfg, num_classes=80, aux_loss=False):
  15. super().__init__()
  16. # ------------ Basic parameters ------------
  17. self.cfg = cfg
  18. self.num_classes = num_classes
  19. self.k_one2many = cfg['k_one2many']
  20. self.lambda_one2many = cfg['lambda_one2many']
  21. self.aux_loss = aux_loss
  22. self.losses = ['labels', 'boxes']
  23. # ------------- Focal loss -------------
  24. self.alpha = 0.25
  25. self.gamma = 2.0
  26. # ------------ Matcher ------------
  27. self.matcher = HungarianMatcher(cost_class = cfg['matcher_hpy']['cost_class'],
  28. cost_bbox = cfg['matcher_hpy']['cost_bbox'],
  29. cost_giou = cfg['matcher_hpy']['cost_giou']
  30. )
  31. # ------------- Loss weight -------------
  32. weight_dict = {'loss_cls': cfg['loss_coeff']['class'],
  33. 'loss_box': cfg['loss_coeff']['bbox'],
  34. 'loss_giou': cfg['loss_coeff']['giou']}
  35. if aux_loss:
  36. aux_weight_dict = {}
  37. for i in range(cfg['de_num_layers'] - 1):
  38. aux_weight_dict.update({k + f"_{i}": v for k, v in weight_dict.items()})
  39. aux_weight_dict.update({k + "_enc": v for k, v in weight_dict.items()})
  40. weight_dict.update(aux_weight_dict)
  41. new_dict = dict()
  42. for key, value in weight_dict.items():
  43. new_dict[key] = value
  44. new_dict[key + "_one2many"] = value
  45. self.weight_dict = new_dict
  46. def _get_src_permutation_idx(self, indices):
  47. # permute predictions following indices
  48. batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)])
  49. src_idx = torch.cat([src for (src, _) in indices])
  50. return batch_idx, src_idx
  51. def _get_tgt_permutation_idx(self, indices):
  52. # permute targets following indices
  53. batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)])
  54. tgt_idx = torch.cat([tgt for (_, tgt) in indices])
  55. return batch_idx, tgt_idx
  56. def loss_labels(self, outputs, targets, indices, num_boxes):
  57. """Classification loss (NLL)
  58. targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes]
  59. """
  60. assert 'pred_logits' in outputs
  61. src_logits = outputs['pred_logits']
  62. # prepare class targets
  63. idx = self._get_src_permutation_idx(indices)
  64. target_classes_o = torch.cat([t["labels"][J] for t, (_, J) in zip(targets, indices)]).to(src_logits.device)
  65. target_classes = torch.full(src_logits.shape[:2],
  66. self.num_classes,
  67. dtype=torch.int64,
  68. device=src_logits.device)
  69. target_classes[idx] = target_classes_o
  70. # to one-hot labels
  71. target_classes_onehot = torch.zeros([*src_logits.shape[:2], self.num_classes + 1],
  72. dtype=src_logits.dtype,
  73. layout=src_logits.layout,
  74. device=src_logits.device)
  75. target_classes_onehot.scatter_(2, target_classes.unsqueeze(-1), 1)
  76. target_classes_onehot = target_classes_onehot[..., :-1]
  77. # focal loss
  78. loss_cls = sigmoid_focal_loss(src_logits, target_classes_onehot, self.alpha, self.gamma)
  79. losses = {}
  80. losses['loss_cls'] = loss_cls.sum() / num_boxes
  81. return losses
  82. def loss_boxes(self, outputs, targets, indices, num_boxes):
  83. """Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss
  84. targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]
  85. The target boxes are expected in format (center_x, center_y, w, h), normalized by the image size.
  86. """
  87. assert 'pred_boxes' in outputs
  88. # prepare bbox targets
  89. idx = self._get_src_permutation_idx(indices)
  90. src_boxes = outputs['pred_boxes'][idx]
  91. target_boxes = torch.cat([t['boxes'][i] for t, (_, i) in zip(targets, indices)], dim=0).to(src_boxes.device)
  92. # compute L1 loss
  93. src_deltas = outputs["pred_deltas"][idx]
  94. src_boxes_old = outputs["pred_boxes_old"][idx]
  95. target_deltas = bbox2delta(src_boxes_old, target_boxes)
  96. loss_bbox = F.l1_loss(src_deltas, target_deltas, reduction="none")
  97. # compute GIoU loss
  98. bbox_giou = generalized_box_iou(box_cxcywh_to_xyxy(src_boxes),
  99. box_cxcywh_to_xyxy(target_boxes))
  100. loss_giou = 1 - torch.diag(bbox_giou)
  101. losses = {}
  102. losses['loss_box'] = loss_bbox.sum() / num_boxes
  103. losses['loss_giou'] = loss_giou.sum() / num_boxes
  104. return losses
  105. def get_loss(self, loss, outputs, targets, indices, num_boxes, **kwargs):
  106. loss_map = {
  107. 'labels': self.loss_labels,
  108. 'boxes': self.loss_boxes,
  109. }
  110. assert loss in loss_map, f'do you really want to compute {loss} loss?'
  111. return loss_map[loss](outputs, targets, indices, num_boxes, **kwargs)
  112. def compute_loss(self, outputs, targets):
  113. """ This performs the loss computation.
  114. Parameters:
  115. outputs: dict of tensors, see the output specification of the model for the format
  116. targets: list of dicts, such that len(targets) == batch_size.
  117. The expected keys in each dict depends on the losses applied, see each loss' doc
  118. """
  119. outputs_without_aux = {
  120. k: v
  121. for k, v in outputs.items()
  122. if k != "aux_outputs" and k != "enc_outputs"
  123. }
  124. # Retrieve the matching between the outputs of the last layer and the targets
  125. indices = self.matcher(outputs_without_aux, targets)
  126. # Compute the average number of target boxes accross all nodes, for normalization purposes
  127. num_boxes = sum(len(t["labels"]) for t in targets)
  128. num_boxes = torch.as_tensor(
  129. [num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device
  130. )
  131. if is_dist_avail_and_initialized():
  132. torch.distributed.all_reduce(num_boxes)
  133. num_boxes = torch.clamp(num_boxes / get_world_size(), min=1).item()
  134. # Compute all the requested losses
  135. losses = {}
  136. for loss in self.losses:
  137. kwargs = {}
  138. l_dict = self.get_loss(loss, outputs, targets, indices, num_boxes, **kwargs)
  139. losses.update(l_dict)
  140. # In case of auxiliary losses, we repeat this process with the output of each intermediate layer.
  141. if "aux_outputs" in outputs:
  142. for i, aux_outputs in enumerate(outputs["aux_outputs"]):
  143. indices = self.matcher(aux_outputs, targets)
  144. for loss in self.losses:
  145. kwargs = {}
  146. l_dict = self.get_loss(loss, aux_outputs, targets, indices, num_boxes, **kwargs)
  147. l_dict = {k + f"_{i}": v for k, v in l_dict.items()}
  148. losses.update(l_dict)
  149. if "enc_outputs" in outputs:
  150. enc_outputs = outputs["enc_outputs"]
  151. bin_targets = copy.deepcopy(targets)
  152. for bt in bin_targets:
  153. bt["labels"] = torch.zeros_like(bt["labels"])
  154. indices = self.matcher(enc_outputs, bin_targets)
  155. for loss in self.losses:
  156. kwargs = {}
  157. l_dict = self.get_loss(loss, enc_outputs, bin_targets, indices, num_boxes, **kwargs)
  158. l_dict = {k + "_enc": v for k, v in l_dict.items()}
  159. losses.update(l_dict)
  160. return losses
  161. def forward(self, outputs, targets):
  162. # --------------------- One-to-one losses ---------------------
  163. outputs_one2one = {k: v for k, v in outputs.items() if "one2many" not in k}
  164. loss_dict = self.compute_loss(outputs_one2one, targets)
  165. # --------------------- One-to-many losses ---------------------
  166. outputs_one2many = {k[:-9]: v for k, v in outputs.items() if "one2many" in k}
  167. if len(outputs_one2many) > 0:
  168. # Copy targets
  169. multi_targets = copy.deepcopy(targets)
  170. for target in multi_targets:
  171. target["boxes"] = target["boxes"].repeat(self.k_one2many, 1)
  172. target["labels"] = target["labels"].repeat(self.k_one2many)
  173. # Compute one-to-many losses
  174. one2many_loss_dict = self.compute_loss(outputs_one2many, multi_targets)
  175. # add one2many losses in to the final loss_dict
  176. for k, v in one2many_loss_dict.items():
  177. if k + "_one2many" in loss_dict.keys():
  178. loss_dict[k + "_one2many"] += v * self.lambda_one2many
  179. else:
  180. loss_dict[k + "_one2many"] = v * self.lambda_one2many
  181. return loss_dict