class_docstr: Head of the Align-DETR: Improving DETR with Simple IoU-aware BCE loss
  
  Code is modified from the `official github repo
  <https://github.com/FelixCaae/AlignDETR>`_.
  
  More details can be found in the `paper
  <https://arxiv.org/abs/2304.07527>`_ .
  
  Args:
      all_layers_num_gt_repeat List[int]: Number to repeat gt for 1-to-k
          matching between ground truth and predictions of each decoder
          layer. Only used for matching queries, not for denoising queries.
          Element count is `num_pred_layer`. If `as_two_stage` is True, then
          the last element is for encoder output, and the others for
          decoder layers. Otherwise, all elements are for decoder layers.
          Defaults to a list of `1` for the last decoder layer and `2` for
          the others.
      alpha (float): Hyper-parameter of classification loss that controls
          the proportion of each item to calculate `t`, the weighted
          geometric average of the confident score and the IoU score, to
          align classification and regression scores. Defaults to `0.25`.
      gamma (float): Hyper-parameter of classification loss to do the hard
          negative mining. Defaults to `2.0`.
      tau (float): Hyper-parameter of classification and regression losses,
          it is the temperature controlling the sharpness of the function
          to calculate positive sample weight. Defaults to `1.5`.
class_docstr_tok: ["Head","of","the","Align-DETR",":","Improving","DETR","with","Simple","IoU-aware","BCE","loss","Code","is","modified","from","the","`","official","github","repo","<","https",":","\/\/github.com\/FelixCaae\/AlignDETR",">","`","_",".","More","details","can","be","found","in","the","`","paper","<","https",":","\/\/arxiv.org\/abs\/2304.07527",">","`","_",".","Args",":","all_layers_num_gt_repeat","List","[","int","]",":","Number","to","repeat","gt","for","1-to-k","matching","between","ground","truth","and","predictions","of","each","decoder","layer",".","Only","used","for","matching","queries",",","not","for","denoising","queries",".","Element","count","is","`","num_pred_layer","`",".","If","`","as_two_stage","`","is","True",",","then","the","last","element","is","for","encoder","output",",","and","the","others","for","decoder","layers",".","Otherwise",",","all","elements","are","for","decoder","layers",".","Defaults","to","a","list","of","`","1","`","for","the","last","decoder","layer","and","`","2","`","for","the","others",".","alpha","(","float",")",":","Hyper-parameter","of","classification","loss","that","controls","the","proportion","of","each","item","to","calculate","`","t","`",",","the","weighted","geometric","average","of","the","confident","score","and","the","IoU","score",",","to","align","classification","and","regression","scores",".","Defaults","to","`","0.25","`",".","gamma","(","float",")",":","Hyper-parameter","of","classification","loss","to","do","the","hard","negative","mining",".","Defaults","to","`","2.0","`",".","tau","(","float",")",":","Hyper-parameter","of","classification","and","regression","losses",",","it","is","the","temperature","controlling","the","sharpness","of","the","function","to","calculate","positive","sample","weight",".","Defaults","to","`","1.5","`","."]
docstr: Loss function for outputs from a single decoder layer of a single
  feature level.
      AlignDETR: This method is based on `DINOHead.loss_by_feat_single`.
  
  Args:
      cls_scores (Union[KeysRecorder, 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",".","AlignDETR",":","This","method","is","based","on","`","DINOHead.loss_by_feat_single","`",".","Args",":","cls_scores","(","Union","[","KeysRecorder",",","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: Union[KeysRecorder, 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.
          AlignDETR: This method is based on `DINOHead.loss_by_feat_single`.
  
      Args:
          cls_scores (Union[KeysRecorder, 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`.
      """
      # AlignDETR: Get layer_index.
      if isinstance(cls_scores, KeysRecorder):
          # Outputs are from decoder layer. Get layer_index from
          #   `__getitem__` keys history.
          keys = [
              key for key in cls_scores.keys if isinstance(key, int)
          ]
          assert (
              len(keys) == 1
          ), "Failed to extract key from cls_scores.keys: {}".format(
              keys
          )
          layer_index = keys[0]
          # Get dn_cls_scores tensor.
          cls_scores = cls_scores.obj
      else:
          # Outputs are from encoder layer.
          layer_index = self.num_pred_layer - 1
  
      for img_meta in batch_img_metas:
          img_meta["layer_index"] = layer_index
  
      results = super(AlignDETRHead, self).loss_by_feat_single(
          cls_scores,
          bbox_preds,
          batch_gt_instances=batch_gt_instances,
          batch_img_metas=batch_img_metas,
      )
      return results
  
file_path: mmdetection/projects/AlignDETR/align_detr/align_detr_head.py
imports: from typing import Any, Dict, List, Tuple, Union
  import torch
  from mmengine.structures import InstanceData
  from torch import Tensor
  from mmdet.models.dense_heads import DINOHead
  from mmdet.registry import MODELS
  from mmdet.structures.bbox import bbox_cxcywh_to_xyxy, bbox_overlaps, bbox_xyxy_to_cxcywh
  from mmdet.utils import InstanceList
  from .utils import KeysRecorder
label_desc: Use image node_id 3 for calling the AlignDETRHead 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: results