criterion.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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 utils.box_ops import box_cxcywh_to_xyxy, generalized_box_iou
  10. from utils.distributed_utils import get_world_size, is_dist_avail_and_initialized
  11. from .matcher import HungarianMatcher
  12. # --------------- Criterion for 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. # -------- Loss weights --------
  19. self.weight_dict = {'loss_cls': cfg.loss_cls,
  20. 'loss_box': cfg.loss_box,
  21. 'loss_giou': cfg.loss_giou}
  22. for i in range(cfg.num_dec_layers - 1):
  23. self.weight_dict.update({k + f'_aux_{i}': v for k, v in self.weight_dict.items()})
  24. # -------- Matcher --------
  25. self.matcher = HungarianMatcher(cfg.cost_class, cfg.cost_bbox, cfg.cost_giou)
  26. def loss_labels(self, outputs, targets, indices, num_boxes):
  27. assert 'pred_logits' in outputs
  28. src_logits = outputs['pred_logits']
  29. idx = self._get_src_permutation_idx(indices)
  30. target_classes_o = torch.cat([t["labels"][J] for t, (_, J) in zip(targets, indices)])
  31. target_classes = torch.full(src_logits.shape[:2], self.num_classes,
  32. dtype=torch.int64, device=src_logits.device)
  33. target_classes[idx] = target_classes_o
  34. loss_cls = F.cross_entropy(src_logits.transpose(1, 2), target_classes, self.empty_weight)
  35. return {'loss_cls': loss_cls.sum() / num_boxes}
  36. def loss_boxes(self, outputs, targets, indices, num_boxes):
  37. assert 'pred_boxes' in outputs
  38. idx = self._get_src_permutation_idx(indices)
  39. src_boxes = outputs['pred_boxes'][idx]
  40. target_boxes = torch.cat([t['boxes'][i] for t, (_, i) in zip(targets, indices)], dim=0)
  41. loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction='none')
  42. loss_giou = 1 - torch.diag(generalized_box_iou(box_cxcywh_to_xyxy(src_boxes),
  43. box_cxcywh_to_xyxy(target_boxes)))
  44. return {'loss_box': loss_bbox.sum() / num_boxes,
  45. 'loss_giou': loss_giou.sum() / num_boxes}
  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 get_loss(self, loss, outputs, targets, indices, num_boxes, **kwargs):
  57. loss_map = {
  58. 'boxes': self.loss_boxes,
  59. 'labels': self.loss_labels,
  60. }
  61. return loss_map[loss](outputs, targets, indices, num_boxes, **kwargs)
  62. def forward(self, outputs, targets):
  63. outputs_without_aux = {k: v for k, v in outputs.items() if 'aux' not in k}
  64. # Retrieve the matching between the outputs of the last layer and the targets
  65. indices = self.matcher(outputs_without_aux, targets)
  66. # Compute the average number of target boxes accross all nodes, for normalization purposes
  67. num_boxes = sum(len(t["labels"]) for t in targets)
  68. num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device)
  69. if is_dist_avail_and_initialized():
  70. torch.distributed.all_reduce(num_boxes)
  71. num_boxes = torch.clamp(num_boxes / get_world_size(), min=1).item()
  72. # Compute all the requested losses
  73. losses = {}
  74. for loss in self.losses:
  75. l_dict = self.get_loss(loss, outputs, targets, indices, num_boxes)
  76. losses.update(l_dict)
  77. # In case of auxiliary losses, we repeat this process with the output of each intermediate layer.
  78. if 'aux_outputs' in outputs:
  79. for i, aux_outputs in enumerate(outputs['aux_outputs']):
  80. indices = self.matcher(aux_outputs, targets)
  81. for loss in self.losses:
  82. l_dict = self.get_loss(loss, aux_outputs, targets, indices, num_boxes)
  83. l_dict = {k + f'_aux_{i}': v for k, v in l_dict.items()}
  84. losses.update(l_dict)
  85. return losses
  86. @staticmethod
  87. def get_cdn_matched_indices(dn_meta, targets):
  88. '''get_cdn_matched_indices
  89. '''
  90. dn_positive_idx, dn_num_group = dn_meta["dn_positive_idx"], dn_meta["dn_num_group"]
  91. num_gts = [len(t['labels']) for t in targets]
  92. device = targets[0]['labels'].device
  93. dn_match_indices = []
  94. for i, num_gt in enumerate(num_gts):
  95. if num_gt > 0:
  96. gt_idx = torch.arange(num_gt, dtype=torch.int64, device=device)
  97. gt_idx = gt_idx.tile(dn_num_group)
  98. assert len(dn_positive_idx[i]) == len(gt_idx)
  99. dn_match_indices.append((dn_positive_idx[i], gt_idx))
  100. else:
  101. dn_match_indices.append((torch.zeros(0, dtype=torch.int64, device=device), \
  102. torch.zeros(0, dtype=torch.int64, device=device)))
  103. return dn_match_indices