class_docstr: Implement query generator of the Contrastive denoising (CDN) proposed in
  `DINO: DETR with Improved DeNoising Anchor Boxes for End-to-End Object
  Detection <https://arxiv.org/abs/2203.03605>`_
  
  Code is modified from the `official github repo
  <https://github.com/IDEA-Research/DINO>`_.
  
  Args:
      num_classes (int): Number of object classes.
      embed_dims (int): The embedding dimensions of the generated queries.
      num_matching_queries (int): The queries number of the matching part.
          Used for generating dn_mask.
      label_noise_scale (float): The scale of label noise, defaults to 0.5.
      box_noise_scale (float): The scale of box noise, defaults to 1.0.
      group_cfg (:obj:`ConfigDict` or dict, optional): The config of the
          denoising queries grouping, includes `dynamic`, `num_dn_queries`,
          and `num_groups`. Two grouping strategies, 'static dn groups' and
          'dynamic dn groups', are supported. When `dynamic` is `False`,
          the `num_groups` should be set, and the number of denoising query
          groups will always be `num_groups`. When `dynamic` is `True`, the
          `num_dn_queries` should be set, and the group number will be
          dynamic to ensure that the denoising queries number will not exceed
          `num_dn_queries` to prevent large fluctuations of memory. Defaults
          to `None`.
docstr: Generate contrastive denoising (cdn) queries with ground truth.
  
  Descriptions of the Number Values in code and comments:
      - num_target_total: the total target number of the input batch
        samples.
      - max_num_target: the max target number of the input batch samples.
      - num_noisy_targets: the total targets number after adding noise,
        i.e., num_target_total * num_groups * 2.
      - num_denoising_queries: the length of the output batched queries,
        i.e., max_num_target * num_groups * 2.
  
  NOTE The format of input bboxes in batch_data_samples is unnormalized
  (x, y, x, y), and the output bbox queries are embedded by normalized
  (cx, cy, w, h) format bboxes going through inverse_sigmoid.
  
  Args:
      batch_data_samples (list[:obj:`DetDataSample`]): List of the batch
          data samples, each includes `gt_instance` which has attributes
          `bboxes` and `labels`. The `bboxes` has unnormalized coordinate
          format (x, y, x, y).
  
  Returns:
      tuple: The outputs of the dn query generator.
  
      - dn_label_query (Tensor): The output content queries for denoising
        part, has shape (bs, num_denoising_queries, dim), where
        `num_denoising_queries = max_num_target * num_groups * 2`.
      - dn_bbox_query (Tensor): The output reference bboxes as positions
        of queries for denoising part, which are embedded by normalized
        (cx, cy, w, h) format bboxes going through inverse_sigmoid, has
        shape (bs, num_denoising_queries, 4) with the last dimension
        arranged as (cx, cy, w, h).
      - attn_mask (Tensor): The attention mask to prevent information
        leakage from different denoising groups and matching parts,
        will be used as `self_attn_mask` of the `decoder`, has shape
        (num_queries_total, num_queries_total), where `num_queries_total`
        is the sum of `num_denoising_queries` and `num_matching_queries`.
      - 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.
docstr_tok: ["Generate","contrastive","denoising","(","cdn",")","queries","with","ground","truth",".","Descriptions","of","the","Number","Values","in","code","and","comments",":","-","num_target_total",":","the","total","target","number","of","the","input","batch","samples",".","-","max_num_target",":","the","max","target","number","of","the","input","batch","samples",".","-","num_noisy_targets",":","the","total","targets","number","after","adding","noise",",","i.e.",",","num_target_total","*","num_groups","*","2",".","-","num_denoising_queries",":","the","length","of","the","output","batched","queries",",","i.e.",",","max_num_target","*","num_groups","*","2",".","NOTE","The","format","of","input","bboxes","in","batch_data_samples","is","unnormalized","(","x",",","y",",","x",",","y",")",",","and","the","output","bbox","queries","are","embedded","by","normalized","(","cx",",","cy",",","w",",","h",")","format","bboxes","going","through","inverse_sigmoid",".","Args",":","batch_data_samples","(","list","[",":","obj",":","`","DetDataSample","`","]",")",":","List","of","the","batch","data","samples",",","each","includes","`","gt_instance","`","which","has","attributes","`","bboxes","`","and","`","labels","`",".","The","`","bboxes","`","has","unnormalized","coordinate","format","(","x",",","y",",","x",",","y",")",".","Returns",":","tuple",":","The","outputs","of","the","dn","query","generator",".","-","dn_label_query","(","Tensor",")",":","The","output","content","queries","for","denoising","part",",","has","shape","(","bs",",","num_denoising_queries",",","dim",")",",","where","`","num_denoising_queries","=","max_num_target","*","num_groups","*","2","`",".","-","dn_bbox_query","(","Tensor",")",":","The","output","reference","bboxes","as","positions","of","queries","for","denoising","part",",","which","are","embedded","by","normalized","(","cx",",","cy",",","w",",","h",")","format","bboxes","going","through","inverse_sigmoid",",","has","shape","(","bs",",","num_denoising_queries",",","4",")","with","the","last","dimension","arranged","as","(","cx",",","cy",",","w",",","h",")",".","-","attn_mask","(","Tensor",")",":","The","attention","mask","to","prevent","information","leakage","from","different","denoising","groups","and","matching","parts",",","will","be","used","as","`","self_attn_mask","`","of","the","`","decoder","`",",","has","shape","(","num_queries_total",",","num_queries_total",")",",","where","`","num_queries_total","`","is","the","sum","of","`","num_denoising_queries","`","and","`","num_matching_queries","`",".","-","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","."]
code: def __call__(self, batch_data_samples: SampleList) -> tuple:
      """Generate contrastive denoising (cdn) queries with ground truth.
  
      Descriptions of the Number Values in code and comments:
          - num_target_total: the total target number of the input batch
            samples.
          - max_num_target: the max target number of the input batch samples.
          - num_noisy_targets: the total targets number after adding noise,
            i.e., num_target_total * num_groups * 2.
          - num_denoising_queries: the length of the output batched queries,
            i.e., max_num_target * num_groups * 2.
  
      NOTE The format of input bboxes in batch_data_samples is unnormalized
      (x, y, x, y), and the output bbox queries are embedded by normalized
      (cx, cy, w, h) format bboxes going through inverse_sigmoid.
  
      Args:
          batch_data_samples (list[:obj:`DetDataSample`]): List of the batch
              data samples, each includes `gt_instance` which has attributes
              `bboxes` and `labels`. The `bboxes` has unnormalized coordinate
              format (x, y, x, y).
  
      Returns:
          tuple: The outputs of the dn query generator.
  
          - dn_label_query (Tensor): The output content queries for denoising
            part, has shape (bs, num_denoising_queries, dim), where
            `num_denoising_queries = max_num_target * num_groups * 2`.
          - dn_bbox_query (Tensor): The output reference bboxes as positions
            of queries for denoising part, which are embedded by normalized
            (cx, cy, w, h) format bboxes going through inverse_sigmoid, has
            shape (bs, num_denoising_queries, 4) with the last dimension
            arranged as (cx, cy, w, h).
          - attn_mask (Tensor): The attention mask to prevent information
            leakage from different denoising groups and matching parts,
            will be used as `self_attn_mask` of the `decoder`, has shape
            (num_queries_total, num_queries_total), where `num_queries_total`
            is the sum of `num_denoising_queries` and `num_matching_queries`.
          - 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.
      """
      # normalize bbox and collate ground truth (gt)
      gt_labels_list = []
      gt_bboxes_list = []
      for sample in batch_data_samples:
          img_h, img_w = sample.img_shape
          bboxes = sample.gt_instances.bboxes
          factor = bboxes.new_tensor(
              [img_w, img_h, img_w, img_h]
          ).unsqueeze(0)
          bboxes_normalized = bboxes / factor
          gt_bboxes_list.append(bboxes_normalized)
          gt_labels_list.append(sample.gt_instances.labels)
      gt_labels = torch.cat(gt_labels_list)  # (num_target_total, 4)
      gt_bboxes = torch.cat(gt_bboxes_list)
  
      num_target_list = [len(bboxes) for bboxes in gt_bboxes_list]
      max_num_target = max(num_target_list)
      num_groups = self.get_num_groups(max_num_target)
  
      dn_label_query = self.generate_dn_label_query(
          gt_labels, num_groups
      )
      dn_bbox_query = self.generate_dn_bbox_query(gt_bboxes, num_groups)
  
      # The `batch_idx` saves the batch index of the corresponding sample
      # for each target, has shape (num_target_total).
      batch_idx = torch.cat(
          [
              torch.full_like(t.long(), i)
              for i, t in enumerate(gt_labels_list)
          ]
      )
      dn_label_query, dn_bbox_query = self.collate_dn_queries(
          dn_label_query,
          dn_bbox_query,
          batch_idx,
          len(batch_data_samples),
          num_groups,
      )
  
      attn_mask = self.generate_dn_mask(
          max_num_target, num_groups, device=dn_label_query.device
      )
  
      dn_meta = dict(
          num_denoising_queries=int(max_num_target * 2 * num_groups),
          num_denoising_groups=num_groups,
      )
  
      return dn_label_query, dn_bbox_query, attn_mask, dn_meta
  
imports: import warnings
  from typing import Tuple, Union
  import torch
  from mmengine.model import BaseModule
  from torch import Tensor, nn
  from mmdet.structures import SampleList
  from mmdet.structures.bbox import bbox_xyxy_to_cxcywh
  from mmdet.utils import OptConfigType
  from .deformable_detr_layers import DeformableDetrTransformerDecoder
  from .utils import MLP, coordinate_to_encoding, inverse_sigmoid
label_desc: Use image node_id 2 for calling the CdnQueryGenerator obj's underlying member method code with example usage: obj.__call__(batch_data_samples) and returns: dn_label_query,  dn_bbox_query,  attn_mask,  dn_meta