class_docstr: Head of DETR. DETR:End-to-End Object Detection with Transformers.
  
  More details can be found in the `paper
  <https://arxiv.org/pdf/2005.12872>`_ .
  
  Args:
      num_classes (int): Number of categories excluding the background.
      embed_dims (int): The dims of Transformer embedding.
      num_reg_fcs (int): Number of fully-connected layers used in `FFN`,
          which is then used for the regression head. Defaults to 2.
      sync_cls_avg_factor (bool): Whether to sync the `avg_factor` of
          all ranks. Default to `False`.
      loss_cls (:obj:`ConfigDict` or dict): Config of the classification
          loss. Defaults to `CrossEntropyLoss`.
      loss_bbox (:obj:`ConfigDict` or dict): Config of the regression bbox
          loss. Defaults to `L1Loss`.
      loss_iou (:obj:`ConfigDict` or dict): Config of the regression iou
          loss. Defaults to `GIoULoss`.
      train_cfg (:obj:`ConfigDict` or dict): Training config of transformer
          head.
      test_cfg (:obj:`ConfigDict` or dict): Testing config of transformer
          head.
      init_cfg (:obj:`ConfigDict` or dict, optional): the config to control
          the initialization. Defaults to None.
docstr: Loss function for outputs from a single decoder layer of a single
  feature level.
  
  Args:
      cls_scores (Tensor): Box score logits from a single decoder layer
          for all images, has shape (bs, num_queries, cls_out_channels).
      bbox_preds (Tensor): Sigmoid outputs from a single decoder layer
          for all images, with normalized coordinate (cx, cy, w, h) and
          shape (bs, num_queries, 4).
      batch_gt_instances (list[:obj:`InstanceData`]): Batch of
          gt_instance. It usually includes ``bboxes`` and ``labels``
          attributes.
      batch_img_metas (list[dict]): Meta information of each image, e.g.,
          image size, scaling factor, etc.
  
  Returns:
      Tuple[Tensor]: A tuple including `loss_cls`, `loss_box` and
      `loss_iou`.
docstr_tok: ["Loss","function","for","outputs","from","a","single","decoder","layer","of","a","single","feature","level",".","Args",":","cls_scores","(","Tensor",")",":","Box","score","logits","from","a","single","decoder","layer","for","all","images",",","has","shape","(","bs",",","num_queries",",","cls_out_channels",")",".","bbox_preds","(","Tensor",")",":","Sigmoid","outputs","from","a","single","decoder","layer","for","all","images",",","with","normalized","coordinate","(","cx",",","cy",",","w",",","h",")","and","shape","(","bs",",","num_queries",",","4",")",".","batch_gt_instances","(","list","[",":","obj",":","`","InstanceData","`","]",")",":","Batch","of","gt_instance",".","It","usually","includes","``","bboxes","``","and","``","labels","``","attributes",".","batch_img_metas","(","list","[","dict","]",")",":","Meta","information","of","each","image",",","e.g.",",","image","size",",","scaling","factor",",","etc",".","Returns",":","Tuple","[","Tensor","]",":","A","tuple","including","`","loss_cls","`",",","`","loss_box","`","and","`","loss_iou","`","."]
code: def loss_by_feat_single(
      self,
      cls_scores: Tensor,
      bbox_preds: Tensor,
      batch_gt_instances: InstanceList,
      batch_img_metas: List[dict],
  ) -> Tuple[Tensor]:
      """Loss function for outputs from a single decoder layer of a single
      feature level.
  
      Args:
          cls_scores (Tensor): Box score logits from a single decoder layer
              for all images, has shape (bs, num_queries, cls_out_channels).
          bbox_preds (Tensor): Sigmoid outputs from a single decoder layer
              for all images, with normalized coordinate (cx, cy, w, h) and
              shape (bs, num_queries, 4).
          batch_gt_instances (list[:obj:`InstanceData`]): Batch of
              gt_instance. It usually includes ``bboxes`` and ``labels``
              attributes.
          batch_img_metas (list[dict]): Meta information of each image, e.g.,
              image size, scaling factor, etc.
  
      Returns:
          Tuple[Tensor]: A tuple including `loss_cls`, `loss_box` and
          `loss_iou`.
      """
      num_imgs = cls_scores.size(0)
      cls_scores_list = [cls_scores[i] for i in range(num_imgs)]
      bbox_preds_list = [bbox_preds[i] for i in range(num_imgs)]
      cls_reg_targets = self.get_targets(
          cls_scores_list,
          bbox_preds_list,
          batch_gt_instances,
          batch_img_metas,
      )
      (
          labels_list,
          label_weights_list,
          bbox_targets_list,
          bbox_weights_list,
          num_total_pos,
          num_total_neg,
      ) = cls_reg_targets
      labels = torch.cat(labels_list, 0)
      label_weights = torch.cat(label_weights_list, 0)
      bbox_targets = torch.cat(bbox_targets_list, 0)
      bbox_weights = torch.cat(bbox_weights_list, 0)
  
      # classification loss
      cls_scores = cls_scores.reshape(-1, self.cls_out_channels)
      # construct weighted avg_factor to match with the official DETR repo
      cls_avg_factor = (
          num_total_pos * 1.0 + num_total_neg * self.bg_cls_weight
      )
      if self.sync_cls_avg_factor:
          cls_avg_factor = reduce_mean(
              cls_scores.new_tensor([cls_avg_factor])
          )
      cls_avg_factor = max(cls_avg_factor, 1)
  
      if isinstance(self.loss_cls, QualityFocalLoss):
          bg_class_ind = self.num_classes
          pos_inds = (
              ((labels >= 0) & (labels < bg_class_ind))
              .nonzero()
              .squeeze(1)
          )
          scores = label_weights.new_zeros(labels.shape)
          pos_bbox_targets = bbox_targets[pos_inds]
          pos_decode_bbox_targets = bbox_cxcywh_to_xyxy(
              pos_bbox_targets
          )
          pos_bbox_pred = bbox_preds.reshape(-1, 4)[pos_inds]
          pos_decode_bbox_pred = bbox_cxcywh_to_xyxy(pos_bbox_pred)
          scores[pos_inds] = bbox_overlaps(
              pos_decode_bbox_pred.detach(),
              pos_decode_bbox_targets,
              is_aligned=True,
          )
          loss_cls = self.loss_cls(
              cls_scores,
              (labels, scores),
              label_weights,
              avg_factor=cls_avg_factor,
          )
      else:
          loss_cls = self.loss_cls(
              cls_scores,
              labels,
              label_weights,
              avg_factor=cls_avg_factor,
          )
  
      # Compute the average number of gt boxes across all gpus, for
      # normalization purposes
      num_total_pos = loss_cls.new_tensor([num_total_pos])
      num_total_pos = torch.clamp(
          reduce_mean(num_total_pos), min=1
      ).item()
  
      # construct factors used for rescale bboxes
      factors = []
      for img_meta, bbox_pred in zip(batch_img_metas, bbox_preds):
          (
              img_h,
              img_w,
          ) = img_meta["img_shape"]
          factor = (
              bbox_pred.new_tensor([img_w, img_h, img_w, img_h])
              .unsqueeze(0)
              .repeat(bbox_pred.size(0), 1)
          )
          factors.append(factor)
      factors = torch.cat(factors, 0)
  
      # DETR regress the relative position of boxes (cxcywh) in the image,
      # thus the learning target is normalized by the image size. So here
      # we need to re-scale them for calculating IoU loss
      bbox_preds = bbox_preds.reshape(-1, 4)
      bboxes = bbox_cxcywh_to_xyxy(bbox_preds) * factors
      bboxes_gt = bbox_cxcywh_to_xyxy(bbox_targets) * factors
  
      # regression IoU loss, defaultly GIoU loss
      loss_iou = self.loss_iou(
          bboxes, bboxes_gt, bbox_weights, avg_factor=num_total_pos
      )
  
      # regression L1 loss
      loss_bbox = self.loss_bbox(
          bbox_preds,
          bbox_targets,
          bbox_weights,
          avg_factor=num_total_pos,
      )
      return loss_cls, loss_bbox, loss_iou
  
imports: from typing import Dict, List, Tuple
  import torch
  import torch.nn
  import torch.nn.functional
  from mmcv.cnn import Linear
  from mmcv.cnn.bricks.transformer import FFN
  from mmengine.model import BaseModule
  from mmengine.structures import InstanceData
  from torch import Tensor
  from mmdet.registry import MODELS, TASK_UTILS
  from mmdet.structures import SampleList
  from mmdet.structures.bbox import bbox_cxcywh_to_xyxy, bbox_overlaps, bbox_xyxy_to_cxcywh
  from mmdet.utils import ConfigType, InstanceList, OptInstanceList, OptMultiConfig, reduce_mean
  from ..losses import QualityFocalLoss
  from ..utils import multi_apply
label_desc: Use image node_id 6 for calling the DETRHead obj's underlying member method code with example usage: obj.loss_by_feat_single(cls_scores, bbox_preds, batch_gt_instances, batch_img_metas) and returns: loss_cls,  loss_bbox,  loss_iou