loss_rt_detr.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. # Copyright 2020 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import torch
  15. import torch.nn as nn
  16. import torch.nn.functional as F
  17. from ..utils import is_scipy_available, is_vision_available, requires_backends
  18. from .loss_for_object_detection import (
  19. box_iou,
  20. dice_loss,
  21. generalized_box_iou,
  22. nested_tensor_from_tensor_list,
  23. sigmoid_focal_loss,
  24. )
  25. if is_scipy_available():
  26. from scipy.optimize import linear_sum_assignment
  27. if is_vision_available():
  28. from transformers.image_transforms import center_to_corners_format
  29. # different for RT-DETR: not slicing the last element like in DETR one
  30. @torch.jit.unused
  31. def _set_aux_loss(outputs_class, outputs_coord):
  32. # this is a workaround to make torchscript happy, as torchscript
  33. # doesn't support dictionary with non-homogeneous values, such
  34. # as a dict having both a Tensor and a list.
  35. return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class, outputs_coord)]
  36. class RTDetrHungarianMatcher(nn.Module):
  37. """This class computes an assignment between the targets and the predictions of the network
  38. For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more
  39. predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, while the others are
  40. un-matched (and thus treated as non-objects).
  41. Args:
  42. config: RTDetrConfig
  43. """
  44. def __init__(self, config):
  45. super().__init__()
  46. requires_backends(self, ["scipy"])
  47. self.class_cost = config.matcher_class_cost
  48. self.bbox_cost = config.matcher_bbox_cost
  49. self.giou_cost = config.matcher_giou_cost
  50. self.use_focal_loss = config.use_focal_loss
  51. self.alpha = config.matcher_alpha
  52. self.gamma = config.matcher_gamma
  53. if self.class_cost == self.bbox_cost == self.giou_cost == 0:
  54. raise ValueError("All costs of the Matcher can't be 0")
  55. @torch.no_grad()
  56. def forward(self, outputs, targets):
  57. """Performs the matching
  58. Params:
  59. outputs: This is a dict that contains at least these entries:
  60. "logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
  61. "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
  62. targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:
  63. "class_labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
  64. objects in the target) containing the class labels
  65. "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates
  66. Returns:
  67. A list of size batch_size, containing tuples of (index_i, index_j) where:
  68. - index_i is the indices of the selected predictions (in order)
  69. - index_j is the indices of the corresponding selected targets (in order)
  70. For each batch element, it holds:
  71. len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
  72. """
  73. batch_size, num_queries = outputs["logits"].shape[:2]
  74. # We flatten to compute the cost matrices in a batch
  75. out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4]
  76. # Also concat the target labels and boxes
  77. target_ids = torch.cat([v["class_labels"] for v in targets])
  78. target_bbox = torch.cat([v["boxes"] for v in targets])
  79. # Compute the classification cost. Contrary to the loss, we don't use the NLL,
  80. # but approximate it in 1 - proba[target class].
  81. # The 1 is a constant that doesn't change the matching, it can be omitted.
  82. if self.use_focal_loss:
  83. out_prob = F.sigmoid(outputs["logits"].flatten(0, 1))
  84. out_prob = out_prob[:, target_ids]
  85. neg_cost_class = (1 - self.alpha) * (out_prob**self.gamma) * (-(1 - out_prob + 1e-8).log())
  86. pos_cost_class = self.alpha * ((1 - out_prob) ** self.gamma) * (-(out_prob + 1e-8).log())
  87. class_cost = pos_cost_class - neg_cost_class
  88. else:
  89. out_prob = outputs["logits"].flatten(0, 1).softmax(-1) # [batch_size * num_queries, num_classes]
  90. class_cost = -out_prob[:, target_ids]
  91. # Compute the L1 cost between boxes
  92. bbox_cost = torch.cdist(out_bbox, target_bbox, p=1)
  93. # Compute the giou cost between boxes
  94. giou_cost = -generalized_box_iou(center_to_corners_format(out_bbox), center_to_corners_format(target_bbox))
  95. # Compute the final cost matrix
  96. cost_matrix = self.bbox_cost * bbox_cost + self.class_cost * class_cost + self.giou_cost * giou_cost
  97. cost_matrix = cost_matrix.view(batch_size, num_queries, -1).cpu()
  98. sizes = [len(v["boxes"]) for v in targets]
  99. indices = [linear_sum_assignment(c[i]) for i, c in enumerate(cost_matrix.split(sizes, -1))]
  100. return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]
  101. class RTDetrLoss(nn.Module):
  102. """
  103. This class computes the losses for RTDetr. The process happens in two steps: 1) we compute hungarian assignment
  104. between ground truth boxes and the outputs of the model 2) we supervise each pair of matched ground-truth /
  105. prediction (supervise class and box).
  106. Args:
  107. matcher (`DetrHungarianMatcher`):
  108. Module able to compute a matching between targets and proposals.
  109. weight_dict (`Dict`):
  110. Dictionary relating each loss with its weights. These losses are configured in RTDetrConf as
  111. `weight_loss_vfl`, `weight_loss_bbox`, `weight_loss_giou`
  112. losses (`list[str]`):
  113. List of all the losses to be applied. See `get_loss` for a list of all available losses.
  114. alpha (`float`):
  115. Parameter alpha used to compute the focal loss.
  116. gamma (`float`):
  117. Parameter gamma used to compute the focal loss.
  118. eos_coef (`float`):
  119. Relative classification weight applied to the no-object category.
  120. num_classes (`int`):
  121. Number of object categories, omitting the special no-object category.
  122. """
  123. def __init__(self, config):
  124. super().__init__()
  125. self.matcher = RTDetrHungarianMatcher(config)
  126. self.num_classes = config.num_labels
  127. self.weight_dict = {
  128. "loss_vfl": config.weight_loss_vfl,
  129. "loss_bbox": config.weight_loss_bbox,
  130. "loss_giou": config.weight_loss_giou,
  131. }
  132. self.losses = ["vfl", "boxes"]
  133. self.eos_coef = config.eos_coefficient
  134. empty_weight = torch.ones(config.num_labels + 1)
  135. empty_weight[-1] = self.eos_coef
  136. self.register_buffer("empty_weight", empty_weight)
  137. self.alpha = config.focal_loss_alpha
  138. self.gamma = config.focal_loss_gamma
  139. def loss_labels_vfl(self, outputs, targets, indices, num_boxes, log=True):
  140. if "pred_boxes" not in outputs:
  141. raise KeyError("No predicted boxes found in outputs")
  142. if "logits" not in outputs:
  143. raise KeyError("No predicted logits found in outputs")
  144. idx = self._get_source_permutation_idx(indices)
  145. src_boxes = outputs["pred_boxes"][idx]
  146. target_boxes = torch.cat([_target["boxes"][i] for _target, (_, i) in zip(targets, indices)], dim=0)
  147. ious, _ = box_iou(center_to_corners_format(src_boxes.detach()), center_to_corners_format(target_boxes))
  148. ious = torch.diag(ious)
  149. src_logits = outputs["logits"]
  150. target_classes_original = torch.cat([_target["class_labels"][i] for _target, (_, i) in zip(targets, indices)])
  151. target_classes = torch.full(
  152. src_logits.shape[:2], self.num_classes, dtype=torch.int64, device=src_logits.device
  153. )
  154. target_classes[idx] = target_classes_original
  155. target = F.one_hot(target_classes, num_classes=self.num_classes + 1)[..., :-1]
  156. target_score_original = torch.zeros_like(target_classes, dtype=src_logits.dtype)
  157. target_score_original[idx] = ious.to(target_score_original.dtype)
  158. target_score = target_score_original.unsqueeze(-1) * target
  159. pred_score = F.sigmoid(src_logits.detach())
  160. weight = self.alpha * pred_score.pow(self.gamma) * (1 - target) + target_score
  161. loss = F.binary_cross_entropy_with_logits(src_logits, target_score, weight=weight, reduction="none")
  162. loss = loss.mean(1).sum() * src_logits.shape[1] / num_boxes
  163. return {"loss_vfl": loss}
  164. def loss_labels(self, outputs, targets, indices, num_boxes, log=True):
  165. """Classification loss (NLL)
  166. targets dicts must contain the key "class_labels" containing a tensor of dim [nb_target_boxes]
  167. """
  168. if "logits" not in outputs:
  169. raise KeyError("No logits were found in the outputs")
  170. src_logits = outputs["logits"]
  171. idx = self._get_source_permutation_idx(indices)
  172. target_classes_original = torch.cat([_target["class_labels"][i] for _target, (_, i) in zip(targets, indices)])
  173. target_classes = torch.full(
  174. src_logits.shape[:2], self.num_classes, dtype=torch.int64, device=src_logits.device
  175. )
  176. target_classes[idx] = target_classes_original
  177. loss_ce = F.cross_entropy(src_logits.transpose(1, 2), target_classes, self.class_weight)
  178. losses = {"loss_ce": loss_ce}
  179. return losses
  180. @torch.no_grad()
  181. def loss_cardinality(self, outputs, targets, indices, num_boxes):
  182. """
  183. Compute the cardinality error, i.e. the absolute error in the number of predicted non-empty boxes. This is not
  184. really a loss, it is intended for logging purposes only. It doesn't propagate gradients.
  185. """
  186. logits = outputs["logits"]
  187. device = logits.device
  188. target_lengths = torch.as_tensor([len(v["class_labels"]) for v in targets], device=device)
  189. # Count the number of predictions that are NOT "no-object" (which is the last class)
  190. card_pred = (logits.argmax(-1) != logits.shape[-1] - 1).sum(1)
  191. card_err = nn.functional.l1_loss(card_pred.float(), target_lengths.float())
  192. losses = {"cardinality_error": card_err}
  193. return losses
  194. def loss_boxes(self, outputs, targets, indices, num_boxes):
  195. """
  196. Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss. Targets dicts must
  197. contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]. The target boxes are expected in
  198. format (center_x, center_y, w, h), normalized by the image size.
  199. """
  200. if "pred_boxes" not in outputs:
  201. raise KeyError("No predicted boxes found in outputs")
  202. idx = self._get_source_permutation_idx(indices)
  203. src_boxes = outputs["pred_boxes"][idx]
  204. target_boxes = torch.cat([t["boxes"][i] for t, (_, i) in zip(targets, indices)], dim=0)
  205. losses = {}
  206. loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction="none")
  207. losses["loss_bbox"] = loss_bbox.sum() / num_boxes
  208. loss_giou = 1 - torch.diag(
  209. generalized_box_iou(center_to_corners_format(src_boxes), center_to_corners_format(target_boxes))
  210. )
  211. losses["loss_giou"] = loss_giou.sum() / num_boxes
  212. return losses
  213. def loss_masks(self, outputs, targets, indices, num_boxes):
  214. """
  215. Compute the losses related to the masks: the focal loss and the dice loss. Targets dicts must contain the key
  216. "masks" containing a tensor of dim [nb_target_boxes, h, w].
  217. """
  218. if "pred_masks" not in outputs:
  219. raise KeyError("No predicted masks found in outputs")
  220. source_idx = self._get_source_permutation_idx(indices)
  221. target_idx = self._get_target_permutation_idx(indices)
  222. source_masks = outputs["pred_masks"]
  223. source_masks = source_masks[source_idx]
  224. masks = [t["masks"] for t in targets]
  225. target_masks, valid = nested_tensor_from_tensor_list(masks).decompose()
  226. target_masks = target_masks.to(source_masks)
  227. target_masks = target_masks[target_idx]
  228. # upsample predictions to the target size
  229. source_masks = nn.functional.interpolate(
  230. source_masks[:, None], size=target_masks.shape[-2:], mode="bilinear", align_corners=False
  231. )
  232. source_masks = source_masks[:, 0].flatten(1)
  233. target_masks = target_masks.flatten(1)
  234. target_masks = target_masks.view(source_masks.shape)
  235. losses = {
  236. "loss_mask": sigmoid_focal_loss(source_masks, target_masks, num_boxes),
  237. "loss_dice": dice_loss(source_masks, target_masks, num_boxes),
  238. }
  239. return losses
  240. def loss_labels_bce(self, outputs, targets, indices, num_boxes, log=True):
  241. src_logits = outputs["logits"]
  242. idx = self._get_source_permutation_idx(indices)
  243. target_classes_original = torch.cat([_target["class_labels"][i] for _target, (_, i) in zip(targets, indices)])
  244. target_classes = torch.full(
  245. src_logits.shape[:2], self.num_classes, dtype=torch.int64, device=src_logits.device
  246. )
  247. target_classes[idx] = target_classes_original
  248. target = F.one_hot(target_classes, num_classes=self.num_classes + 1)[..., :-1]
  249. loss = F.binary_cross_entropy_with_logits(src_logits, target * 1.0, reduction="none")
  250. loss = loss.mean(1).sum() * src_logits.shape[1] / num_boxes
  251. return {"loss_bce": loss}
  252. def _get_source_permutation_idx(self, indices):
  253. # permute predictions following indices
  254. batch_idx = torch.cat([torch.full_like(source, i) for i, (source, _) in enumerate(indices)])
  255. source_idx = torch.cat([source for (source, _) in indices])
  256. return batch_idx, source_idx
  257. def _get_target_permutation_idx(self, indices):
  258. # permute targets following indices
  259. batch_idx = torch.cat([torch.full_like(target, i) for i, (_, target) in enumerate(indices)])
  260. target_idx = torch.cat([target for (_, target) in indices])
  261. return batch_idx, target_idx
  262. def loss_labels_focal(self, outputs, targets, indices, num_boxes, log=True):
  263. if "logits" not in outputs:
  264. raise KeyError("No logits found in outputs")
  265. src_logits = outputs["logits"]
  266. idx = self._get_source_permutation_idx(indices)
  267. target_classes_original = torch.cat([_target["class_labels"][i] for _target, (_, i) in zip(targets, indices)])
  268. target_classes = torch.full(
  269. src_logits.shape[:2], self.num_classes, dtype=torch.int64, device=src_logits.device
  270. )
  271. target_classes[idx] = target_classes_original
  272. target = F.one_hot(target_classes, num_classes=self.num_classes + 1)[..., :-1]
  273. loss = sigmoid_focal_loss(src_logits, target, self.alpha, self.gamma)
  274. loss = loss.mean(1).sum() * src_logits.shape[1] / num_boxes
  275. return {"loss_focal": loss}
  276. def get_loss(self, loss, outputs, targets, indices, num_boxes):
  277. loss_map = {
  278. "labels": self.loss_labels,
  279. "cardinality": self.loss_cardinality,
  280. "boxes": self.loss_boxes,
  281. "masks": self.loss_masks,
  282. "bce": self.loss_labels_bce,
  283. "focal": self.loss_labels_focal,
  284. "vfl": self.loss_labels_vfl,
  285. }
  286. if loss not in loss_map:
  287. raise ValueError(f"Loss {loss} not supported")
  288. return loss_map[loss](outputs, targets, indices, num_boxes)
  289. @staticmethod
  290. def get_cdn_matched_indices(dn_meta, targets):
  291. dn_positive_idx, dn_num_group = dn_meta["dn_positive_idx"], dn_meta["dn_num_group"]
  292. num_gts = [len(t["class_labels"]) for t in targets]
  293. device = targets[0]["class_labels"].device
  294. dn_match_indices = []
  295. for i, num_gt in enumerate(num_gts):
  296. if num_gt > 0:
  297. gt_idx = torch.arange(num_gt, dtype=torch.int64, device=device)
  298. gt_idx = gt_idx.tile(dn_num_group)
  299. assert len(dn_positive_idx[i]) == len(gt_idx)
  300. dn_match_indices.append((dn_positive_idx[i], gt_idx))
  301. else:
  302. dn_match_indices.append(
  303. (
  304. torch.zeros(0, dtype=torch.int64, device=device),
  305. torch.zeros(0, dtype=torch.int64, device=device),
  306. )
  307. )
  308. return dn_match_indices
  309. def forward(self, outputs, targets):
  310. """
  311. This performs the loss computation.
  312. Args:
  313. outputs (`dict`, *optional*):
  314. Dictionary of tensors, see the output specification of the model for the format.
  315. targets (`list[dict]`, *optional*):
  316. List of dicts, such that `len(targets) == batch_size`. The expected keys in each dict depends on the
  317. losses applied, see each loss' doc.
  318. """
  319. outputs_without_aux = {k: v for k, v in outputs.items() if "auxiliary_outputs" not in k}
  320. # Retrieve the matching between the outputs of the last layer and the targets
  321. indices = self.matcher(outputs_without_aux, targets)
  322. # Compute the average number of target boxes across all nodes, for normalization purposes
  323. num_boxes = sum(len(t["class_labels"]) for t in targets)
  324. num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device)
  325. num_boxes = torch.clamp(num_boxes, min=1).item()
  326. # Compute all the requested losses
  327. losses = {}
  328. for loss in self.losses:
  329. l_dict = self.get_loss(loss, outputs, targets, indices, num_boxes)
  330. l_dict = {k: l_dict[k] * self.weight_dict[k] for k in l_dict if k in self.weight_dict}
  331. losses.update(l_dict)
  332. # In case of auxiliary losses, we repeat this process with the output of each intermediate layer.
  333. if "auxiliary_outputs" in outputs:
  334. for i, auxiliary_outputs in enumerate(outputs["auxiliary_outputs"]):
  335. indices = self.matcher(auxiliary_outputs, targets)
  336. for loss in self.losses:
  337. if loss == "masks":
  338. # Intermediate masks losses are too costly to compute, we ignore them.
  339. continue
  340. l_dict = self.get_loss(loss, auxiliary_outputs, targets, indices, num_boxes)
  341. l_dict = {k: l_dict[k] * self.weight_dict[k] for k in l_dict if k in self.weight_dict}
  342. l_dict = {k + f"_aux_{i}": v for k, v in l_dict.items()}
  343. losses.update(l_dict)
  344. # In case of cdn auxiliary losses. For rtdetr
  345. if "dn_auxiliary_outputs" in outputs:
  346. if "denoising_meta_values" not in outputs:
  347. raise ValueError(
  348. "The output must have the 'denoising_meta_values` key. Please, ensure that 'outputs' includes a 'denoising_meta_values' entry."
  349. )
  350. indices = self.get_cdn_matched_indices(outputs["denoising_meta_values"], targets)
  351. num_boxes = num_boxes * outputs["denoising_meta_values"]["dn_num_group"]
  352. for i, auxiliary_outputs in enumerate(outputs["dn_auxiliary_outputs"]):
  353. # indices = self.matcher(auxiliary_outputs, targets)
  354. for loss in self.losses:
  355. if loss == "masks":
  356. # Intermediate masks losses are too costly to compute, we ignore them.
  357. continue
  358. kwargs = {}
  359. l_dict = self.get_loss(loss, auxiliary_outputs, targets, indices, num_boxes, **kwargs)
  360. l_dict = {k: l_dict[k] * self.weight_dict[k] for k in l_dict if k in self.weight_dict}
  361. l_dict = {k + f"_dn_{i}": v for k, v in l_dict.items()}
  362. losses.update(l_dict)
  363. return losses
  364. def RTDetrForObjectDetectionLoss(
  365. logits,
  366. labels,
  367. device,
  368. pred_boxes,
  369. config,
  370. outputs_class=None,
  371. outputs_coord=None,
  372. enc_topk_logits=None,
  373. enc_topk_bboxes=None,
  374. denoising_meta_values=None,
  375. **kwargs,
  376. ):
  377. criterion = RTDetrLoss(config)
  378. criterion.to(device)
  379. # Second: compute the losses, based on outputs and labels
  380. outputs_loss = {}
  381. outputs_loss["logits"] = logits
  382. outputs_loss["pred_boxes"] = pred_boxes
  383. if config.auxiliary_loss:
  384. if denoising_meta_values is not None:
  385. dn_out_coord, outputs_coord = torch.split(outputs_coord, denoising_meta_values["dn_num_split"], dim=2)
  386. dn_out_class, outputs_class = torch.split(outputs_class, denoising_meta_values["dn_num_split"], dim=2)
  387. auxiliary_outputs = _set_aux_loss(outputs_class[:, :-1].transpose(0, 1), outputs_coord[:, :-1].transpose(0, 1))
  388. outputs_loss["auxiliary_outputs"] = auxiliary_outputs
  389. outputs_loss["auxiliary_outputs"].extend(_set_aux_loss([enc_topk_logits], [enc_topk_bboxes]))
  390. if denoising_meta_values is not None:
  391. outputs_loss["dn_auxiliary_outputs"] = _set_aux_loss(
  392. dn_out_class.transpose(0, 1), dn_out_coord.transpose(0, 1)
  393. )
  394. outputs_loss["denoising_meta_values"] = denoising_meta_values
  395. loss_dict = criterion(outputs_loss, labels)
  396. loss = sum(loss_dict.values())
  397. return loss, loss_dict, auxiliary_outputs