class_docstr: Implements the DETR transformer head.
  
  See `paper: End-to-End Object Detection with Transformers
  <https://arxiv.org/pdf/2005.12872>`_ for details.
  
  Args:
      num_classes (int): Number of categories excluding the background.
      in_channels (int): Number of channels in the input feature map.
      num_fcs (int, optional): Number of fully-connected layers used in
          `FFN`, which is then used for the regression head. Default 2.
      transformer (dict, optional): Config for transformer.
      positional_encoding (dict, optional): Config for position encoding.
      loss_cls (dict, optional): Config of the classification loss.
          Default `CrossEntropyLoss`.
      loss_bbox (dict, optional): Config of the regression loss.
          Default `L1Loss`.
      loss_iou (dict, optional): Config of the regression iou loss.
          Default `GIoULoss`.
      tran_cfg (dict, optional): Training config of transformer head.
      test_cfg (dict, optional): Testing config of transformer head.
  
  Example:
      >>> import torch
      >>> self = TransformerHead(80, 2048)
      >>> x = torch.rand(1, 2048, 32, 32)
      >>> mask = torch.ones(1, 32, 32).to(x.dtype)
      >>> mask[:, :16, :15] = 0
      >>> all_cls_scores, all_bbox_preds = self(x, mask)
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. Shape [bs, num_query, 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_query, 4].
      gt_bboxes_list (list[Tensor]): Ground truth bboxes for each image
          with shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.
      gt_labels_list (list[Tensor]): Ground truth class indices for each
          image with shape (num_gts, ).
      img_metas (list[dict]): List of image meta information.
      gt_bboxes_ignore_list (list[Tensor], optional): Bounding
          boxes which can be ignored for each image. Default None.
  
  Returns:
      dict[str, Tensor]: A dictionary of loss components for outputs from
          a single decoder layer.
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",".","Shape","[","bs",",","num_query",",","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_query",",","4","]",".","gt_bboxes_list","(","list","[","Tensor","]",")",":","Ground","truth","bboxes","for","each","image","with","shape","(","num_gts",",","4",")","in","[","tl_x",",","tl_y",",","br_x",",","br_y","]","format",".","gt_labels_list","(","list","[","Tensor","]",")",":","Ground","truth","class","indices","for","each","image","with","shape","(","num_gts",",",")",".","img_metas","(","list","[","dict","]",")",":","List","of","image","meta","information",".","gt_bboxes_ignore_list","(","list","[","Tensor","]",",","optional",")",":","Bounding","boxes","which","can","be","ignored","for","each","image",".","Default","None",".","Returns",":","dict","[","str",",","Tensor","]",":","A","dictionary","of","loss","components","for","outputs","from","a","single","decoder","layer","."]
code: def loss_single(
      self,
      cls_scores,
      bbox_preds,
      gt_bboxes_list,
      gt_labels_list,
      img_metas,
      gt_bboxes_ignore_list=None,
  ):
      """ "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. Shape [bs, num_query, 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_query, 4].
          gt_bboxes_list (list[Tensor]): Ground truth bboxes for each image
              with shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.
          gt_labels_list (list[Tensor]): Ground truth class indices for each
              image with shape (num_gts, ).
          img_metas (list[dict]): List of image meta information.
          gt_bboxes_ignore_list (list[Tensor], optional): Bounding
              boxes which can be ignored for each image. Default None.
  
      Returns:
          dict[str, Tensor]: A dictionary of loss components for outputs from
              a single decoder layer.
      """
      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,
          gt_bboxes_list,
          gt_labels_list,
          img_metas,
          gt_bboxes_ignore_list,
      )
      (
          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
      )
      loss_cls = self.loss_cls(
          cls_scores, labels, label_weights, avg_factor=cls_avg_factor
      )
  
      # Compute the average number of gt boxes accross 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(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: import torch
  import torch.nn
  import torch.nn.functional
  from mmcv.cnn import Conv2d, Linear, build_activation_layer
  from mmcv.runner import force_fp32
  from mmdet.core import bbox_cxcywh_to_xyxy, bbox_xyxy_to_cxcywh, build_assigner, build_sampler, multi_apply, reduce_mean
  from mmdet.models.utils import FFN, build_positional_encoding, build_transformer
  from ..builder import HEADS, build_loss
  from .anchor_free_head import AnchorFreeHead
label_desc: Use image node_id 8 for calling the TransformerHead obj's underlying member method code with example usage: obj.loss_single(cls_scores, bbox_preds, gt_bboxes_list, gt_labels_list, img_metas, gt_bboxes_ignore_list) and returns: loss_cls,  loss_bbox,  loss_iou