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: Compute regression and classification targets for one image.
  
  Outputs from a single decoder layer of a single feature level are used.
  AlignDETR: This method is based on `DETRHead._get_targets_single`.
  
  Args:
      cls_score (Tensor): Box score logits from a single decoder layer
          for one image. Shape [num_queries, cls_out_channels].
      bbox_pred (Tensor): Sigmoid outputs from a single decoder layer
          for one image, with normalized coordinate (cx, cy, w, h) and
          shape [num_queries, 4].
      gt_instances (:obj:`InstanceData`): Ground truth of instance
          annotations. It should includes ``bboxes`` and ``labels``
          attributes.
      img_meta (dict): Meta information for one image.
      layer_index (int): Decoder layer index for the outputs. Defaults
          to `-1`.
  
  Returns:
      tuple[Tensor]: a tuple containing the following for one image.
  
      - labels (Tensor): Labels of each image.
      - label_weights (Tensor]): Label weights of each image.
      - bbox_targets (Tensor): BBox targets of each image.
      - bbox_weights (Tensor): BBox weights of each image.
      - pos_inds (Tensor): Sampled positive indices for each image.
      - neg_inds (Tensor): Sampled negative indices for each image.
docstr_tok: ["Compute","regression","and","classification","targets","for","one","image",".","Outputs","from","a","single","decoder","layer","of","a","single","feature","level","are","used",".","AlignDETR",":","This","method","is","based","on","`","DETRHead._get_targets_single","`",".","Args",":","cls_score","(","Tensor",")",":","Box","score","logits","from","a","single","decoder","layer","for","one","image",".","Shape","[","num_queries",",","cls_out_channels","]",".","bbox_pred","(","Tensor",")",":","Sigmoid","outputs","from","a","single","decoder","layer","for","one","image",",","with","normalized","coordinate","(","cx",",","cy",",","w",",","h",")","and","shape","[","num_queries",",","4","]",".","gt_instances","(",":","obj",":","`","InstanceData","`",")",":","Ground","truth","of","instance","annotations",".","It","should","includes","``","bboxes","``","and","``","labels","``","attributes",".","img_meta","(","dict",")",":","Meta","information","for","one","image",".","layer_index","(","int",")",":","Decoder","layer","index","for","the","outputs",".","Defaults","to","`","-1","`",".","Returns",":","tuple","[","Tensor","]",":","a","tuple","containing","the","following","for","one","image",".","-","labels","(","Tensor",")",":","Labels","of","each","image",".","-","label_weights","(","Tensor","]",")",":","Label","weights","of","each","image",".","-","bbox_targets","(","Tensor",")",":","BBox","targets","of","each","image",".","-","bbox_weights","(","Tensor",")",":","BBox","weights","of","each","image",".","-","pos_inds","(","Tensor",")",":","Sampled","positive","indices","for","each","image",".","-","neg_inds","(","Tensor",")",":","Sampled","negative","indices","for","each","image","."]
code: def _get_targets_single(
      self,
      cls_score: Tensor,
      bbox_pred: Tensor,
      gt_instances: InstanceData,
      img_meta: dict,
  ) -> tuple:
      """Compute regression and classification targets for one image.
  
      Outputs from a single decoder layer of a single feature level are used.
      AlignDETR: This method is based on `DETRHead._get_targets_single`.
  
      Args:
          cls_score (Tensor): Box score logits from a single decoder layer
              for one image. Shape [num_queries, cls_out_channels].
          bbox_pred (Tensor): Sigmoid outputs from a single decoder layer
              for one image, with normalized coordinate (cx, cy, w, h) and
              shape [num_queries, 4].
          gt_instances (:obj:`InstanceData`): Ground truth of instance
              annotations. It should includes ``bboxes`` and ``labels``
              attributes.
          img_meta (dict): Meta information for one image.
          layer_index (int): Decoder layer index for the outputs. Defaults
              to `-1`.
  
      Returns:
          tuple[Tensor]: a tuple containing the following for one image.
  
          - labels (Tensor): Labels of each image.
          - label_weights (Tensor]): Label weights of each image.
          - bbox_targets (Tensor): BBox targets of each image.
          - bbox_weights (Tensor): BBox weights of each image.
          - pos_inds (Tensor): Sampled positive indices for each image.
          - neg_inds (Tensor): Sampled negative indices for each image.
      """
      img_h, img_w = img_meta["img_shape"]
      factor = bbox_pred.new_tensor(
          [img_w, img_h, img_w, img_h]
      ).unsqueeze(0)
      # convert bbox_pred from xywh, normalized to xyxy, unnormalized
      bbox_pred = bbox_cxcywh_to_xyxy(bbox_pred)
      bbox_pred = bbox_pred * factor
  
      pred_instances = InstanceData(scores=cls_score, bboxes=bbox_pred)
  
      # assigner and sampler
      # AlignDETR: Get `k` of current layer.
      layer_index = img_meta["layer_index"]
      num_gt_repeat = self.all_layers_num_gt_repeat[layer_index]
      assign_result = self.assigner.assign(
          pred_instances=pred_instances,
          gt_instances=gt_instances,
          img_meta=img_meta,
          k=num_gt_repeat,
      )
  
      gt_bboxes = gt_instances.bboxes
      gt_labels = gt_instances.labels
      pos_inds = (
          torch.nonzero(assign_result.gt_inds > 0, as_tuple=False)
          .squeeze(-1)
          .unique()
      )
      neg_inds = (
          torch.nonzero(assign_result.gt_inds == 0, as_tuple=False)
          .squeeze(-1)
          .unique()
      )
      pos_assigned_gt_inds = assign_result.gt_inds[pos_inds] - 1
      pos_gt_bboxes = gt_bboxes[pos_assigned_gt_inds.long(), :]
  
      # AlignDETR: Get label targets, label weights, and bbox weights.
      target_results = self._get_align_detr_targets_single(
          cls_score,
          bbox_pred,
          gt_labels,
          pos_gt_bboxes,
          pos_inds,
          pos_assigned_gt_inds,
          layer_index,
          is_matching_queries=True,
      )
  
      label_targets, label_weights, bbox_weights = target_results
  
      # bbox targets
      bbox_targets = torch.zeros_like(bbox_pred, dtype=gt_bboxes.dtype)
  
      # DETR regress the relative position of boxes (cxcywh) in the image.
      # Thus the learning target should be normalized by the image size, also
      # the box format should be converted from defaultly x1y1x2y2 to cxcywh.
      pos_gt_bboxes_normalized = pos_gt_bboxes / factor
      pos_gt_bboxes_targets = bbox_xyxy_to_cxcywh(
          pos_gt_bboxes_normalized
      )
      bbox_targets[pos_inds] = pos_gt_bboxes_targets
      return (
          label_targets,
          label_weights,
          bbox_targets,
          bbox_weights,
          pos_inds,
          neg_inds,
      )
  
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 5 for calling the AlignDETRHead obj's underlying member method code with example usage: obj._get_targets_single(cls_score, bbox_pred, gt_instances, img_meta) and returns: label_targets,  label_weights,  bbox_targets,  bbox_weights,  pos_inds,  neg_inds