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: Loss function.
  
  Args:
      all_layers_cls_scores (Tensor): Classification scores of all
          decoder layers, has shape (num_decoder_layers, bs,
          num_queries_total, cls_out_channels).
      all_layers_bbox_preds (Tensor): Bbox coordinates of all decoder
          layers. Each has shape (num_decoder_layers, bs,
          num_queries_total, 4) with normalized coordinate format
          (cx, cy, w, h).
      enc_cls_scores (Tensor): The top k score of each point on
          encoder feature map, has shape (bs, num_queries,
          cls_out_channels).
      enc_bbox_preds (Tensor): The proposal generated from points
          with top k score, has shape (bs, num_queries, 4) with the
          last dimension arranged as (cx, cy, w, h).
      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.
      dn_meta (Dict[str, int]): The dictionary saves information about
          group collation, including 'num_denoising_queries' and
          'num_denoising_groups'. It will be used for split outputs of
          denoising and matching parts and loss calculation.
      batch_gt_instances_ignore (list[:obj:`InstanceData`], optional):
          Batch of gt_instances_ignore. It includes ``bboxes`` attribute
          data that is ignored during training and testing.
          Defaults to None.
  
  Returns:
      dict[str, Tensor]: A dictionary of loss components.
docstr_tok: ["Loss","function",".","Args",":","all_layers_cls_scores","(","Tensor",")",":","Classification","scores","of","all","decoder","layers",",","has","shape","(","num_decoder_layers",",","bs",",","num_queries_total",",","cls_out_channels",")",".","all_layers_bbox_preds","(","Tensor",")",":","Bbox","coordinates","of","all","decoder","layers",".","Each","has","shape","(","num_decoder_layers",",","bs",",","num_queries_total",",","4",")","with","normalized","coordinate","format","(","cx",",","cy",",","w",",","h",")",".","enc_cls_scores","(","Tensor",")",":","The","top","k","score","of","each","point","on","encoder","feature","map",",","has","shape","(","bs",",","num_queries",",","cls_out_channels",")",".","enc_bbox_preds","(","Tensor",")",":","The","proposal","generated","from","points","with","top","k","score",",","has","shape","(","bs",",","num_queries",",","4",")","with","the","last","dimension","arranged","as","(","cx",",","cy",",","w",",","h",")",".","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",".","dn_meta","(","Dict","[","str",",","int","]",")",":","The","dictionary","saves","information","about","group","collation",",","including","'num_denoising_queries","'","and","'num_denoising_groups","'",".","It","will","be","used","for","split","outputs","of","denoising","and","matching","parts","and","loss","calculation",".","batch_gt_instances_ignore","(","list","[",":","obj",":","`","InstanceData","`","]",",","optional",")",":","Batch","of","gt_instances_ignore",".","It","includes","``","bboxes","``","attribute","data","that","is","ignored","during","training","and","testing",".","Defaults","to","None",".","Returns",":","dict","[","str",",","Tensor","]",":","A","dictionary","of","loss","components","."]
code: def loss_by_feat(
      self,
      all_layers_cls_scores: Tensor,
      all_layers_bbox_preds: Tensor,
      enc_cls_scores: Tensor,
      enc_bbox_preds: Tensor,
      batch_gt_instances: InstanceList,
      batch_img_metas: List[dict],
      dn_meta: Dict[str, int],
      batch_gt_instances_ignore: OptInstanceList = None,
  ) -> Dict[str, Tensor]:
      """Loss function.
  
      Args:
          all_layers_cls_scores (Tensor): Classification scores of all
              decoder layers, has shape (num_decoder_layers, bs,
              num_queries_total, cls_out_channels).
          all_layers_bbox_preds (Tensor): Bbox coordinates of all decoder
              layers. Each has shape (num_decoder_layers, bs,
              num_queries_total, 4) with normalized coordinate format
              (cx, cy, w, h).
          enc_cls_scores (Tensor): The top k score of each point on
              encoder feature map, has shape (bs, num_queries,
              cls_out_channels).
          enc_bbox_preds (Tensor): The proposal generated from points
              with top k score, has shape (bs, num_queries, 4) with the
              last dimension arranged as (cx, cy, w, h).
          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.
          dn_meta (Dict[str, int]): The dictionary saves information about
              group collation, including 'num_denoising_queries' and
              'num_denoising_groups'. It will be used for split outputs of
              denoising and matching parts and loss calculation.
          batch_gt_instances_ignore (list[:obj:`InstanceData`], optional):
              Batch of gt_instances_ignore. It includes ``bboxes`` attribute
              data that is ignored during training and testing.
              Defaults to None.
  
      Returns:
          dict[str, Tensor]: A dictionary of loss components.
      """
      (
          all_layers_matching_cls_scores,
          all_layers_matching_bbox_preds,
          all_layers_denoising_cls_scores,
          all_layers_denoising_bbox_preds,
      ) = self.split_outputs(
          all_layers_cls_scores, all_layers_bbox_preds, dn_meta
      )
  
      num_dense_queries = dn_meta["num_dense_queries"]
      num_layer = all_layers_matching_bbox_preds.size(0)
      dense_all_layers_matching_cls_scores = (
          all_layers_matching_cls_scores[
              :, :, -num_dense_queries:  # noqa: E501
          ]
      )  # noqa: E501
      dense_all_layers_matching_bbox_preds = (
          all_layers_matching_bbox_preds[
              :, :, -num_dense_queries:  # noqa: E501
          ]
      )  # noqa: E501
  
      all_layers_matching_cls_scores = all_layers_matching_cls_scores[
          :, :, :-num_dense_queries  # noqa: E501
      ]  # noqa: E501
      all_layers_matching_bbox_preds = all_layers_matching_bbox_preds[
          :, :, :-num_dense_queries  # noqa: E501
      ]  # noqa: E501
  
      loss_dict = self.loss_for_distinct_queries(
          all_layers_matching_cls_scores,
          all_layers_matching_bbox_preds,
          batch_gt_instances,
          batch_img_metas,
          batch_gt_instances_ignore,
      )
  
      if enc_cls_scores is not None:
          (
              enc_loss_cls,
              enc_losses_bbox,
              enc_losses_iou,
          ) = self.loss_by_feat_single(
              enc_cls_scores,
              enc_bbox_preds,
              batch_gt_instances=batch_gt_instances,
              batch_img_metas=batch_img_metas,
          )
          loss_dict["enc_loss_cls"] = enc_loss_cls
          loss_dict["enc_loss_bbox"] = enc_losses_bbox
          loss_dict["enc_loss_iou"] = enc_losses_iou
  
      if all_layers_denoising_cls_scores is not None:
          dn_losses_cls, dn_losses_bbox, dn_losses_iou = self.loss_dn(
              all_layers_denoising_cls_scores,
              all_layers_denoising_bbox_preds,
              batch_gt_instances=batch_gt_instances,
              batch_img_metas=batch_img_metas,
              dn_meta=dn_meta,
          )
          loss_dict["dn_loss_cls"] = dn_losses_cls[-1]
          loss_dict["dn_loss_bbox"] = dn_losses_bbox[-1]
          loss_dict["dn_loss_iou"] = dn_losses_iou[-1]
          for num_dec_layer, (
              loss_cls_i,
              loss_bbox_i,
              loss_iou_i,
          ) in enumerate(
              zip(
                  dn_losses_cls[:-1],
                  dn_losses_bbox[:-1],
                  dn_losses_iou[:-1],
              )
          ):
              loss_dict[f"d{num_dec_layer}.dn_loss_cls"] = loss_cls_i
              loss_dict[f"d{num_dec_layer}.dn_loss_bbox"] = loss_bbox_i
              loss_dict[f"d{num_dec_layer}.dn_loss_iou"] = loss_iou_i
  
      for l_id in range(num_layer):
          cls_scores = dense_all_layers_matching_cls_scores[
              l_id
          ].sigmoid()
          bbox_preds = dense_all_layers_matching_bbox_preds[l_id]
  
          bbox_preds = bbox_cxcywh_to_xyxy(bbox_preds)
          bbox_preds_list = []
          for img_id in range(len(bbox_preds)):
              det_bboxes = bbox_preds[img_id]
              img_shape = batch_img_metas[img_id]["img_shape"]
              det_bboxes[:, 0::2] = det_bboxes[:, 0::2] * img_shape[1]
              det_bboxes[:, 1::2] = det_bboxes[:, 1::2] * img_shape[0]
              bbox_preds_list.append(det_bboxes)
          bbox_preds = torch.stack(bbox_preds_list)
          aux_loss = self.aux_loss_for_dense.loss(
              cls_scores,
              bbox_preds,
              [item.bboxes for item in batch_gt_instances],
              [item.labels for item in batch_gt_instances],
              batch_img_metas,
          )
          for k, v in aux_loss.items():
              loss_dict[f"{l_id}_aux_{k}"] = v
  
      return loss_dict
  
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 6 for calling the DDQDETRHead obj's underlying member method code with example usage: obj.loss_by_feat(all_layers_cls_scores, all_layers_bbox_preds, enc_cls_scores, enc_bbox_preds, batch_gt_instances, batch_img_metas, dn_meta, batch_gt_instances_ignore) and returns: loss_dict