matcher.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import torch
  2. import torch.nn as nn
  3. from scipy.optimize import linear_sum_assignment
  4. from utils.box_ops import box_cxcywh_to_xyxy, generalized_box_iou
  5. class HungarianMatcher(nn.Module):
  6. """This class computes an assignment between the targets and the predictions of the network
  7. For efficiency reasons, the targets don't include the no_object. Because of this, in general,
  8. there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,
  9. while the others are un-matched (and thus treated as non-objects).
  10. """
  11. def __init__(self, cost_class: float = 1, cost_bbox: float = 1, cost_giou: float = 1):
  12. """Creates the matcher
  13. Params:
  14. cost_class: This is the relative weight of the classification error in the matching cost
  15. cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost
  16. cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost
  17. """
  18. super().__init__()
  19. self.cost_class = cost_class
  20. self.cost_bbox = cost_bbox
  21. self.cost_giou = cost_giou
  22. assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, "all costs cant be 0"
  23. @torch.no_grad()
  24. def forward(self, outputs, targets):
  25. """ Performs the matching
  26. Params:
  27. outputs: This is a dict that contains at least these entries:
  28. "pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
  29. "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
  30. targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:
  31. "labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
  32. objects in the target) containing the class labels
  33. "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates
  34. Returns:
  35. A list of size batch_size, containing tuples of (index_i, index_j) where:
  36. - index_i is the indices of the selected predictions (in order)
  37. - index_j is the indices of the corresponding selected targets (in order)
  38. For each batch element, it holds:
  39. len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
  40. """
  41. bs, num_queries = outputs["pred_logits"].shape[:2]
  42. # We flatten to compute the cost matrices in a batch
  43. # [B * num_queries, C] = [N, C], where N is B * num_queries
  44. out_prob = outputs["pred_logits"].flatten(0, 1).sigmoid()
  45. # [B * num_queries, 4] = [N, 4]
  46. out_bbox = outputs["pred_boxes"].flatten(0, 1)
  47. # Also concat the target labels and boxes
  48. # [M,] where M is number of all targets in this batch
  49. tgt_ids = torch.cat([v["labels"] for v in targets])
  50. # [M, 4] where M is number of all targets in this batch
  51. tgt_bbox = torch.cat([v["boxes"] for v in targets])
  52. # Compute the classification cost.
  53. alpha = 0.25
  54. gamma = 2.0
  55. neg_cost_class = (1 - alpha) * (out_prob ** gamma) * (-(1 - out_prob + 1e-8).log())
  56. pos_cost_class = alpha * ((1 - out_prob) ** gamma) * (-(out_prob + 1e-8).log())
  57. cost_class = pos_cost_class[:, tgt_ids] - neg_cost_class[:, tgt_ids]
  58. # Compute the L1 cost between boxes
  59. # [N, M]
  60. cost_bbox = torch.cdist(out_bbox, tgt_bbox.to(out_bbox.device), p=1)
  61. # Compute the giou cost betwen boxes
  62. # [N, M]
  63. cost_giou = -generalized_box_iou(
  64. box_cxcywh_to_xyxy(out_bbox),
  65. box_cxcywh_to_xyxy(tgt_bbox.to(out_bbox.device)))
  66. # Final cost matrix: [N, M]
  67. C = self.cost_bbox * cost_bbox + self.cost_class * cost_class + self.cost_giou * cost_giou
  68. # [N, M] -> [B, num_queries, M]
  69. C = C.view(bs, num_queries, -1).cpu()
  70. # The number of boxes in each image
  71. sizes = [len(v["boxes"]) for v in targets]
  72. # In the last dimension of C, we divide it into B costs, and each cost is [B, num_querys, M_i]
  73. # where sum(Mi) = M.
  74. # i is the batch index and c is cost_i = [B, num_querys, M_i].
  75. # Therefore c[i] is the cost between the i-th sample and i-th prediction.
  76. indices = [linear_sum_assignment(c[i]) for i, c in enumerate(C.split(sizes, -1))]
  77. # As for each (i, j) in indices, i is the prediction indexes and j is the target indexes
  78. # i contains row indexes of cost matrix: array([row_1, row_2, row_3])
  79. # j contains col indexes of cost matrix: array([col_1, col_2, col_3])
  80. # len(i) == len(j)
  81. # len(indices) = batch_size
  82. return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]
  83. def build_matcher(cfg):
  84. return HungarianMatcher(
  85. cost_class=cfg['set_cost_class'],
  86. cost_bbox=cfg['set_cost_bbox'],
  87. cost_giou=cfg['set_cost_giou']
  88. )