class_docstr: Head of DDQDETR: Dense Distinct Query for
      End-to-End Object Detection.
  
  Code is modified from the `official github repo
      <https://github.com/jshilong/DDQ>`_.
  
  More details can be found in the `paper
      <https://arxiv.org/abs/2303.12776>`_ .
  
  Args:
      aux_num_pos (int): Number of positive targets assigned to a
          perdicted object. Defaults to 4.
docstr: Calculate the loss for outputs from a single decoder layer of
  distinct queries, that is, excluding denoising and dense queries. Only
  select the distinct queries in decoder for loss.
  
  Args:
      cls_scores (Tensor): Classification scores of a single
          decoder layer, has shape (bs, num_queries, cls_out_channels).
      bbox_preds (Tensor): Bbox coordinates of a single decoder
          layer. It has shape (bs, num_queries, 4) with the last
          dimension arranged as (cx, cy, w, h).
      l_id (int): Decoder layer index for these outputs.
      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: ["Calculate","the","loss","for","outputs","from","a","single","decoder","layer","of","distinct","queries",",","that","is",",","excluding","denoising","and","dense","queries",".","Only","select","the","distinct","queries","in","decoder","for","loss",".","Args",":","cls_scores","(","Tensor",")",":","Classification","scores","of","a","single","decoder","layer",",","has","shape","(","bs",",","num_queries",",","cls_out_channels",")",".","bbox_preds","(","Tensor",")",":","Bbox","coordinates","of","a","single","decoder","layer",".","It","has","shape","(","bs",",","num_queries",",","4",")","with","the","last","dimension","arranged","as","(","cx",",","cy",",","w",",","h",")",".","l_id","(","int",")",":","Decoder","layer","index","for","these","outputs",".","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_for_distinct_queries_single(
      self,
      cls_scores,
      bbox_preds,
      l_id,
      batch_gt_instances,
      batch_img_metas,
  ):
      """Calculate the loss for outputs from a single decoder layer of
      distinct queries, that is, excluding denoising and dense queries. Only
      select the distinct queries in decoder for loss.
  
      Args:
          cls_scores (Tensor): Classification scores of a single
              decoder layer, has shape (bs, num_queries, cls_out_channels).
          bbox_preds (Tensor): Bbox coordinates of a single decoder
              layer. It has shape (bs, num_queries, 4) with the last
              dimension arranged as (cx, cy, w, h).
          l_id (int): Decoder layer index for these outputs.
          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)
      if 0 < l_id:
          batch_mask = [
              self.cache_dict["distinct_query_mask"][l_id - 1][
                  img_id * self.cache_dict["num_heads"]
              ][0]
              for img_id in range(num_imgs)
          ]
      else:
          batch_mask = [
              torch.ones(
                  len(cls_scores[i]), device=cls_scores.device
              ).bool()
              for i in range(num_imgs)
          ]
      # only select the distinct queries in decoder for loss
      cls_scores_list = [
          cls_scores[i][batch_mask[i]] for i in range(num_imgs)
      ]
      bbox_preds_list = [
          bbox_preds[i][batch_mask[i]] for i in range(num_imgs)
      ]
      cls_scores = torch.cat(cls_scores_list)
  
      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)
  
      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_list):
          (
              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 = torch.cat(bbox_preds_list)
      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 copy
  from typing import Dict, List, Tuple
  import torch
  from mmengine.model import bias_init_with_prob, constant_init
  from torch import Tensor, nn
  from mmdet.registry import MODELS
  from mmdet.structures import SampleList
  from mmdet.structures.bbox import bbox_cxcywh_to_xyxy
  from mmdet.utils import InstanceList, OptInstanceList, reduce_mean
  from ..layers import inverse_sigmoid
  from ..losses import DDQAuxLoss
  from ..utils import multi_apply
  from .dino_head import DINOHead
label_desc: Use image node_id 8 for calling the DDQDETRHead obj's underlying member method code with example usage: obj._loss_for_distinct_queries_single(cls_scores, bbox_preds, l_id, batch_gt_instances, batch_img_metas) and returns: loss_cls,  loss_bbox,  loss_iou