matcher.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from scipy.optimize import linear_sum_assignment
  5. try:
  6. from .loss_utils import box_cxcywh_to_xyxy, generalized_box_iou
  7. except:
  8. from loss_utils import box_cxcywh_to_xyxy, generalized_box_iou
  9. class HungarianMatcher(nn.Module):
  10. """This class computes an assignment between the targets and the predictions of the network
  11. For efficiency reasons, the targets don't include the no_object. Because of this, in general,
  12. there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,
  13. while the others are un-matched (and thus treated as non-objects).
  14. """
  15. __share__ = ['use_focal_loss', ]
  16. def __init__(self, weight_dict, alpha=0.25, gamma=2.0):
  17. """Creates the matcher
  18. Params:
  19. cost_class: This is the relative weight of the classification error in the matching cost
  20. cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost
  21. cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost
  22. """
  23. super().__init__()
  24. self.cost_class = weight_dict['cost_class']
  25. self.cost_bbox = weight_dict['cost_bbox']
  26. self.cost_giou = weight_dict['cost_giou']
  27. self.alpha = alpha
  28. self.gamma = gamma
  29. assert self.cost_class != 0 or self.cost_bbox != 0 or self.cost_giou != 0, "all costs cant be 0"
  30. @torch.no_grad()
  31. def forward(self, outputs, targets):
  32. """ Performs the matching
  33. Params:
  34. outputs: This is a dict that contains at least these entries:
  35. "pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
  36. "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
  37. targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:
  38. "labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
  39. objects in the target) containing the class labels
  40. "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates
  41. Returns:
  42. A list of size batch_size, containing tuples of (index_i, index_j) where:
  43. - index_i is the indices of the selected predictions (in order)
  44. - index_j is the indices of the corresponding selected targets (in order)
  45. For each batch element, it holds:
  46. len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
  47. """
  48. bs, num_queries = outputs["pred_logits"].shape[:2]
  49. # We flatten to compute the cost matrices in a batch
  50. out_prob = F.sigmoid(outputs["pred_logits"].flatten(0, 1))
  51. out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4]
  52. # Also concat the target labels and boxes
  53. tgt_ids = torch.cat([v["labels"] for v in targets])
  54. tgt_bbox = torch.cat([v["boxes"] for v in targets])
  55. # Compute the classification cost
  56. out_prob = out_prob[:, tgt_ids]
  57. neg_cost_class = (1 - self.alpha) * (out_prob**self.gamma) * (-(1 - out_prob + 1e-8).log())
  58. pos_cost_class = self.alpha * ((1 - out_prob)**self.gamma) * (-(out_prob + 1e-8).log())
  59. cost_class = pos_cost_class - neg_cost_class
  60. # Compute the L1 cost between boxes
  61. cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)
  62. # Compute the giou cost betwen boxes
  63. cost_giou = -generalized_box_iou(box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox))
  64. # Final cost matrix
  65. C = self.cost_bbox * cost_bbox + self.cost_class * cost_class + self.cost_giou * cost_giou
  66. C = C.view(bs, num_queries, -1).cpu()
  67. sizes = [len(v["boxes"]) for v in targets]
  68. indices = [linear_sum_assignment(c[i]) for i, c in enumerate(C.split(sizes, -1))]
  69. return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]