loss.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. from ultralytics.utils.loss import FocalLoss, VarifocalLoss
  6. from ultralytics.utils.metrics import bbox_iou
  7. from .ops import HungarianMatcher
  8. class DETRLoss(nn.Module):
  9. """
  10. DETR (DEtection TRansformer) Loss class. This class calculates and returns the different loss components for the
  11. DETR object detection model. It computes classification loss, bounding box loss, GIoU loss, and optionally auxiliary
  12. losses.
  13. Attributes:
  14. nc (int): The number of classes.
  15. loss_gain (dict): Coefficients for different loss components.
  16. aux_loss (bool): Whether to compute auxiliary losses.
  17. use_fl (bool): Use FocalLoss or not.
  18. use_vfl (bool): Use VarifocalLoss or not.
  19. use_uni_match (bool): Whether to use a fixed layer to assign labels for the auxiliary branch.
  20. uni_match_ind (int): The fixed indices of a layer to use if `use_uni_match` is True.
  21. matcher (HungarianMatcher): Object to compute matching cost and indices.
  22. fl (FocalLoss or None): Focal Loss object if `use_fl` is True, otherwise None.
  23. vfl (VarifocalLoss or None): Varifocal Loss object if `use_vfl` is True, otherwise None.
  24. device (torch.device): Device on which tensors are stored.
  25. """
  26. def __init__(
  27. self, nc=80, loss_gain=None, aux_loss=True, use_fl=True, use_vfl=False, use_uni_match=False, uni_match_ind=0
  28. ):
  29. """
  30. DETR loss function.
  31. Args:
  32. nc (int): The number of classes.
  33. loss_gain (dict): The coefficient of loss.
  34. aux_loss (bool): If 'aux_loss = True', loss at each decoder layer are to be used.
  35. use_vfl (bool): Use VarifocalLoss or not.
  36. use_uni_match (bool): Whether to use a fixed layer to assign labels for auxiliary branch.
  37. uni_match_ind (int): The fixed indices of a layer.
  38. """
  39. super().__init__()
  40. if loss_gain is None:
  41. loss_gain = {"class": 1, "bbox": 5, "giou": 2, "no_object": 0.1, "mask": 1, "dice": 1}
  42. self.nc = nc
  43. self.matcher = HungarianMatcher(cost_gain={"class": 2, "bbox": 5, "giou": 2})
  44. self.loss_gain = loss_gain
  45. self.aux_loss = aux_loss
  46. self.fl = FocalLoss() if use_fl else None
  47. self.vfl = VarifocalLoss() if use_vfl else None
  48. self.use_uni_match = use_uni_match
  49. self.uni_match_ind = uni_match_ind
  50. self.device = None
  51. def _get_loss_class(self, pred_scores, targets, gt_scores, num_gts, postfix=""):
  52. """Computes the classification loss based on predictions, target values, and ground truth scores."""
  53. # Logits: [b, query, num_classes], gt_class: list[[n, 1]]
  54. name_class = f"loss_class{postfix}"
  55. bs, nq = pred_scores.shape[:2]
  56. # one_hot = F.one_hot(targets, self.nc + 1)[..., :-1] # (bs, num_queries, num_classes)
  57. one_hot = torch.zeros((bs, nq, self.nc + 1), dtype=torch.int64, device=targets.device)
  58. one_hot.scatter_(2, targets.unsqueeze(-1), 1)
  59. one_hot = one_hot[..., :-1]
  60. gt_scores = gt_scores.view(bs, nq, 1) * one_hot
  61. if self.fl:
  62. if num_gts and self.vfl:
  63. loss_cls = self.vfl(pred_scores, gt_scores, one_hot)
  64. else:
  65. loss_cls = self.fl(pred_scores, one_hot.float())
  66. loss_cls /= max(num_gts, 1) / nq
  67. else:
  68. loss_cls = nn.BCEWithLogitsLoss(reduction="none")(pred_scores, gt_scores).mean(1).sum() # YOLO CLS loss
  69. return {name_class: loss_cls.squeeze() * self.loss_gain["class"]}
  70. def _get_loss_bbox(self, pred_bboxes, gt_bboxes, postfix=""):
  71. """Calculates and returns the bounding box loss and GIoU loss for the predicted and ground truth bounding
  72. boxes.
  73. """
  74. # Boxes: [b, query, 4], gt_bbox: list[[n, 4]]
  75. name_bbox = f"loss_bbox{postfix}"
  76. name_giou = f"loss_giou{postfix}"
  77. loss = {}
  78. if len(gt_bboxes) == 0:
  79. loss[name_bbox] = torch.tensor(0.0, device=self.device)
  80. loss[name_giou] = torch.tensor(0.0, device=self.device)
  81. return loss
  82. loss[name_bbox] = self.loss_gain["bbox"] * F.l1_loss(pred_bboxes, gt_bboxes, reduction="sum") / len(gt_bboxes)
  83. loss[name_giou] = 1.0 - bbox_iou(pred_bboxes, gt_bboxes, xywh=True, GIoU=True)
  84. loss[name_giou] = loss[name_giou].sum() / len(gt_bboxes)
  85. loss[name_giou] = self.loss_gain["giou"] * loss[name_giou]
  86. return {k: v.squeeze() for k, v in loss.items()}
  87. # This function is for future RT-DETR Segment models
  88. # def _get_loss_mask(self, masks, gt_mask, match_indices, postfix=''):
  89. # # masks: [b, query, h, w], gt_mask: list[[n, H, W]]
  90. # name_mask = f'loss_mask{postfix}'
  91. # name_dice = f'loss_dice{postfix}'
  92. #
  93. # loss = {}
  94. # if sum(len(a) for a in gt_mask) == 0:
  95. # loss[name_mask] = torch.tensor(0., device=self.device)
  96. # loss[name_dice] = torch.tensor(0., device=self.device)
  97. # return loss
  98. #
  99. # num_gts = len(gt_mask)
  100. # src_masks, target_masks = self._get_assigned_bboxes(masks, gt_mask, match_indices)
  101. # src_masks = F.interpolate(src_masks.unsqueeze(0), size=target_masks.shape[-2:], mode='bilinear')[0]
  102. # # TODO: torch does not have `sigmoid_focal_loss`, but it's not urgent since we don't use mask branch for now.
  103. # loss[name_mask] = self.loss_gain['mask'] * F.sigmoid_focal_loss(src_masks, target_masks,
  104. # torch.tensor([num_gts], dtype=torch.float32))
  105. # loss[name_dice] = self.loss_gain['dice'] * self._dice_loss(src_masks, target_masks, num_gts)
  106. # return loss
  107. # This function is for future RT-DETR Segment models
  108. # @staticmethod
  109. # def _dice_loss(inputs, targets, num_gts):
  110. # inputs = F.sigmoid(inputs).flatten(1)
  111. # targets = targets.flatten(1)
  112. # numerator = 2 * (inputs * targets).sum(1)
  113. # denominator = inputs.sum(-1) + targets.sum(-1)
  114. # loss = 1 - (numerator + 1) / (denominator + 1)
  115. # return loss.sum() / num_gts
  116. def _get_loss_aux(
  117. self,
  118. pred_bboxes,
  119. pred_scores,
  120. gt_bboxes,
  121. gt_cls,
  122. gt_groups,
  123. match_indices=None,
  124. postfix="",
  125. masks=None,
  126. gt_mask=None,
  127. ):
  128. """Get auxiliary losses."""
  129. # NOTE: loss class, bbox, giou, mask, dice
  130. loss = torch.zeros(5 if masks is not None else 3, device=pred_bboxes.device)
  131. if match_indices is None and self.use_uni_match:
  132. match_indices = self.matcher(
  133. pred_bboxes[self.uni_match_ind],
  134. pred_scores[self.uni_match_ind],
  135. gt_bboxes,
  136. gt_cls,
  137. gt_groups,
  138. masks=masks[self.uni_match_ind] if masks is not None else None,
  139. gt_mask=gt_mask,
  140. )
  141. for i, (aux_bboxes, aux_scores) in enumerate(zip(pred_bboxes, pred_scores)):
  142. aux_masks = masks[i] if masks is not None else None
  143. loss_ = self._get_loss(
  144. aux_bboxes,
  145. aux_scores,
  146. gt_bboxes,
  147. gt_cls,
  148. gt_groups,
  149. masks=aux_masks,
  150. gt_mask=gt_mask,
  151. postfix=postfix,
  152. match_indices=match_indices,
  153. )
  154. loss[0] += loss_[f"loss_class{postfix}"]
  155. loss[1] += loss_[f"loss_bbox{postfix}"]
  156. loss[2] += loss_[f"loss_giou{postfix}"]
  157. # if masks is not None and gt_mask is not None:
  158. # loss_ = self._get_loss_mask(aux_masks, gt_mask, match_indices, postfix)
  159. # loss[3] += loss_[f'loss_mask{postfix}']
  160. # loss[4] += loss_[f'loss_dice{postfix}']
  161. loss = {
  162. f"loss_class_aux{postfix}": loss[0],
  163. f"loss_bbox_aux{postfix}": loss[1],
  164. f"loss_giou_aux{postfix}": loss[2],
  165. }
  166. # if masks is not None and gt_mask is not None:
  167. # loss[f'loss_mask_aux{postfix}'] = loss[3]
  168. # loss[f'loss_dice_aux{postfix}'] = loss[4]
  169. return loss
  170. @staticmethod
  171. def _get_index(match_indices):
  172. """Returns batch indices, source indices, and destination indices from provided match indices."""
  173. batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(match_indices)])
  174. src_idx = torch.cat([src for (src, _) in match_indices])
  175. dst_idx = torch.cat([dst for (_, dst) in match_indices])
  176. return (batch_idx, src_idx), dst_idx
  177. def _get_assigned_bboxes(self, pred_bboxes, gt_bboxes, match_indices):
  178. """Assigns predicted bounding boxes to ground truth bounding boxes based on the match indices."""
  179. pred_assigned = torch.cat(
  180. [
  181. t[i] if len(i) > 0 else torch.zeros(0, t.shape[-1], device=self.device)
  182. for t, (i, _) in zip(pred_bboxes, match_indices)
  183. ]
  184. )
  185. gt_assigned = torch.cat(
  186. [
  187. t[j] if len(j) > 0 else torch.zeros(0, t.shape[-1], device=self.device)
  188. for t, (_, j) in zip(gt_bboxes, match_indices)
  189. ]
  190. )
  191. return pred_assigned, gt_assigned
  192. def _get_loss(
  193. self,
  194. pred_bboxes,
  195. pred_scores,
  196. gt_bboxes,
  197. gt_cls,
  198. gt_groups,
  199. masks=None,
  200. gt_mask=None,
  201. postfix="",
  202. match_indices=None,
  203. ):
  204. """Get losses."""
  205. if match_indices is None:
  206. match_indices = self.matcher(
  207. pred_bboxes, pred_scores, gt_bboxes, gt_cls, gt_groups, masks=masks, gt_mask=gt_mask
  208. )
  209. idx, gt_idx = self._get_index(match_indices)
  210. pred_bboxes, gt_bboxes = pred_bboxes[idx], gt_bboxes[gt_idx]
  211. bs, nq = pred_scores.shape[:2]
  212. targets = torch.full((bs, nq), self.nc, device=pred_scores.device, dtype=gt_cls.dtype)
  213. targets[idx] = gt_cls[gt_idx]
  214. gt_scores = torch.zeros([bs, nq], device=pred_scores.device)
  215. if len(gt_bboxes):
  216. gt_scores[idx] = bbox_iou(pred_bboxes.detach(), gt_bboxes, xywh=True).squeeze(-1)
  217. loss = {}
  218. loss.update(self._get_loss_class(pred_scores, targets, gt_scores, len(gt_bboxes), postfix))
  219. loss.update(self._get_loss_bbox(pred_bboxes, gt_bboxes, postfix))
  220. # if masks is not None and gt_mask is not None:
  221. # loss.update(self._get_loss_mask(masks, gt_mask, match_indices, postfix))
  222. return loss
  223. def forward(self, pred_bboxes, pred_scores, batch, postfix="", **kwargs):
  224. """
  225. Args:
  226. pred_bboxes (torch.Tensor): [l, b, query, 4]
  227. pred_scores (torch.Tensor): [l, b, query, num_classes]
  228. batch (dict): A dict includes:
  229. gt_cls (torch.Tensor) with shape [num_gts, ],
  230. gt_bboxes (torch.Tensor): [num_gts, 4],
  231. gt_groups (List(int)): a list of batch size length includes the number of gts of each image.
  232. postfix (str): postfix of loss name.
  233. """
  234. self.device = pred_bboxes.device
  235. match_indices = kwargs.get("match_indices", None)
  236. gt_cls, gt_bboxes, gt_groups = batch["cls"], batch["bboxes"], batch["gt_groups"]
  237. total_loss = self._get_loss(
  238. pred_bboxes[-1], pred_scores[-1], gt_bboxes, gt_cls, gt_groups, postfix=postfix, match_indices=match_indices
  239. )
  240. if self.aux_loss:
  241. total_loss.update(
  242. self._get_loss_aux(
  243. pred_bboxes[:-1], pred_scores[:-1], gt_bboxes, gt_cls, gt_groups, match_indices, postfix
  244. )
  245. )
  246. return total_loss
  247. class RTDETRDetectionLoss(DETRLoss):
  248. """
  249. Real-Time DeepTracker (RT-DETR) Detection Loss class that extends the DETRLoss.
  250. This class computes the detection loss for the RT-DETR model, which includes the standard detection loss as well as
  251. an additional denoising training loss when provided with denoising metadata.
  252. """
  253. def forward(self, preds, batch, dn_bboxes=None, dn_scores=None, dn_meta=None):
  254. """
  255. Forward pass to compute the detection loss.
  256. Args:
  257. preds (tuple): Predicted bounding boxes and scores.
  258. batch (dict): Batch data containing ground truth information.
  259. dn_bboxes (torch.Tensor, optional): Denoising bounding boxes. Default is None.
  260. dn_scores (torch.Tensor, optional): Denoising scores. Default is None.
  261. dn_meta (dict, optional): Metadata for denoising. Default is None.
  262. Returns:
  263. (dict): Dictionary containing the total loss and, if applicable, the denoising loss.
  264. """
  265. pred_bboxes, pred_scores = preds
  266. total_loss = super().forward(pred_bboxes, pred_scores, batch)
  267. # Check for denoising metadata to compute denoising training loss
  268. if dn_meta is not None:
  269. dn_pos_idx, dn_num_group = dn_meta["dn_pos_idx"], dn_meta["dn_num_group"]
  270. assert len(batch["gt_groups"]) == len(dn_pos_idx)
  271. # Get the match indices for denoising
  272. match_indices = self.get_dn_match_indices(dn_pos_idx, dn_num_group, batch["gt_groups"])
  273. # Compute the denoising training loss
  274. dn_loss = super().forward(dn_bboxes, dn_scores, batch, postfix="_dn", match_indices=match_indices)
  275. total_loss.update(dn_loss)
  276. else:
  277. # If no denoising metadata is provided, set denoising loss to zero
  278. total_loss.update({f"{k}_dn": torch.tensor(0.0, device=self.device) for k in total_loss.keys()})
  279. return total_loss
  280. @staticmethod
  281. def get_dn_match_indices(dn_pos_idx, dn_num_group, gt_groups):
  282. """
  283. Get the match indices for denoising.
  284. Args:
  285. dn_pos_idx (List[torch.Tensor]): List of tensors containing positive indices for denoising.
  286. dn_num_group (int): Number of denoising groups.
  287. gt_groups (List[int]): List of integers representing the number of ground truths for each image.
  288. Returns:
  289. (List[tuple]): List of tuples containing matched indices for denoising.
  290. """
  291. dn_match_indices = []
  292. idx_groups = torch.as_tensor([0, *gt_groups[:-1]]).cumsum_(0)
  293. for i, num_gt in enumerate(gt_groups):
  294. if num_gt > 0:
  295. gt_idx = torch.arange(end=num_gt, dtype=torch.long) + idx_groups[i]
  296. gt_idx = gt_idx.repeat(dn_num_group)
  297. assert len(dn_pos_idx[i]) == len(gt_idx), "Expected the same length, "
  298. f"but got {len(dn_pos_idx[i])} and {len(gt_idx)} respectively."
  299. dn_match_indices.append((dn_pos_idx[i], gt_idx))
  300. else:
  301. dn_match_indices.append((torch.zeros([0], dtype=torch.long), torch.zeros([0], dtype=torch.long)))
  302. return dn_match_indices