class_docstr: Base class for DenseHeads.
  
  1. The ``init_weights`` method is used to initialize densehead's
  model parameters. After detector initialization, ``init_weights``
  is triggered when ``detector.init_weights()`` is called externally.
  
  2. The ``loss`` method is used to calculate the loss of densehead,
  which includes two steps: (1) the densehead model performs forward
  propagation to obtain the feature maps (2) The ``loss_by_feat`` method
  is called based on the feature maps to calculate the loss.
  
  .. code:: text
  
  loss(): forward() -> loss_by_feat()
  
  3. The ``predict`` method is used to predict detection results,
  which includes two steps: (1) the densehead model performs forward
  propagation to obtain the feature maps (2) The ``predict_by_feat`` method
  is called based on the feature maps to predict detection results including
  post-processing.
  
  .. code:: text
  
  predict(): forward() -> predict_by_feat()
  
  4. The ``loss_and_predict`` method is used to return loss and detection
  results at the same time. It will call densehead's ``forward``,
  ``loss_by_feat`` and ``predict_by_feat`` methods in order.  If one-stage is
  used as RPN, the densehead needs to return both losses and predictions.
  This predictions is used as the proposal of roihead.
  
  .. code:: text
  
  loss_and_predict(): forward() -> loss_by_feat() -> predict_by_feat()
class_docstr_tok: ["Base","class","for","DenseHeads",".","1",".","The","``","init_weights","``","method","is","used","to","initialize","densehead's","model","parameters",".","After","detector","initialization",",","``","init_weights","``","is","triggered","when","``","detector.init_weights","(",")","``","is","called","externally",".","2",".","The","``","loss","``","method","is","used","to","calculate","the","loss","of","densehead",",","which","includes","two","steps",":","(","1",")","the","densehead","model","performs","forward","propagation","to","obtain","the","feature","maps","(","2",")","The","``","loss_by_feat","``","method","is","called","based","on","the","feature","maps","to","calculate","the","loss",".","..","code",":",":","text","loss","(",")",":","forward","(",")","-",">","loss_by_feat","(",")","3",".","The","``","predict","``","method","is","used","to","predict","detection","results",",","which","includes","two","steps",":","(","1",")","the","densehead","model","performs","forward","propagation","to","obtain","the","feature","maps","(","2",")","The","``","predict_by_feat","``","method","is","called","based","on","the","feature","maps","to","predict","detection","results","including","post-processing",".","..","code",":",":","text","predict","(",")",":","forward","(",")","-",">","predict_by_feat","(",")","4",".","The","``","loss_and_predict","``","method","is","used","to","return","loss","and","detection","results","at","the","same","time",".","It","will","call","densehead","'s","``","forward","``",",","``","loss_by_feat","``","and","``","predict_by_feat","``","methods","in","order",".","If","one-stage","is","used","as","RPN",",","the","densehead","needs","to","return","both","losses","and","predictions",".","This","predictions","is","used","as","the","proposal","of","roihead",".","..","code",":",":","text","loss_and_predict","(",")",":","forward","(",")","-",">","loss_by_feat","(",")","-",">","predict_by_feat","(",")"]
docstr: Test function with test time augmentation.
  
  Args:
      aug_batch_feats (list[tuple[Tensor]]): The outer list
          indicates test-time augmentations and inner tuple
          indicate the multi-level feats from
          FPN, each Tensor should have a shape (B, C, H, W),
      aug_batch_img_metas (list[list[dict]]): Meta information
          of images under the different test-time augs
          (multiscale, flip, etc.). The outer list indicate
          the
      rescale (bool, optional): Whether to rescale the results.
          Defaults to False.
      with_ori_nms (bool): Whether execute the nms in original head.
          Defaults to False. It will be `True` when the head is
          adopted as `rpn_head`.
  
  Returns:
      list(obj:`InstanceData`): Detection results of the
      input images. Each item usually contains            following keys.
  
          - scores (Tensor): Classification scores, has a shape
            (num_instance,)
          - labels (Tensor): Labels of bboxes, has a shape
            (num_instances,).
          - bboxes (Tensor): Has a shape (num_instances, 4),
            the last dimension 4 arrange as (x1, y1, x2, y2).
docstr_tok: ["Test","function","with","test","time","augmentation",".","Args",":","aug_batch_feats","(","list","[","tuple","[","Tensor","]","]",")",":","The","outer","list","indicates","test-time","augmentations","and","inner","tuple","indicate","the","multi-level","feats","from","FPN",",","each","Tensor","should","have","a","shape","(","B",",","C",",","H",",","W",")",",","aug_batch_img_metas","(","list","[","list","[","dict","]","]",")",":","Meta","information","of","images","under","the","different","test-time","augs","(","multiscale",",","flip",",","etc.",")",".","The","outer","list","indicate","the","rescale","(","bool",",","optional",")",":","Whether","to","rescale","the","results",".","Defaults","to","False",".","with_ori_nms","(","bool",")",":","Whether","execute","the","nms","in","original","head",".","Defaults","to","False",".","It","will","be","`","True","`","when","the","head","is","adopted","as","`","rpn_head","`",".","Returns",":","list","(","obj",":","`","InstanceData","`",")",":","Detection","results","of","the","input","images",".","Each","item","usually","contains","following","keys",".","-","scores","(","Tensor",")",":","Classification","scores",",","has","a","shape","(","num_instance",",",")","-","labels","(","Tensor",")",":","Labels","of","bboxes",",","has","a","shape","(","num_instances",",",")",".","-","bboxes","(","Tensor",")",":","Has","a","shape","(","num_instances",",","4",")",",","the","last","dimension","4","arrange","as","(","x1",",","y1",",","x2",",","y2",")","."]
code: def aug_test(
      self,
      aug_batch_feats,
      aug_batch_img_metas,
      rescale=False,
      with_ori_nms=False,
      **kwargs,
  ):
      """Test function with test time augmentation.
  
          Args:
              aug_batch_feats (list[tuple[Tensor]]): The outer list
                  indicates test-time augmentations and inner tuple
                  indicate the multi-level feats from
                  FPN, each Tensor should have a shape (B, C, H, W),
              aug_batch_img_metas (list[list[dict]]): Meta information
                  of images under the different test-time augs
                  (multiscale, flip, etc.). The outer list indicate
                  the
              rescale (bool, optional): Whether to rescale the results.
                  Defaults to False.
              with_ori_nms (bool): Whether execute the nms in original head.
                  Defaults to False. It will be `True` when the head is
                  adopted as `rpn_head`.
  
          Returns:
              list(obj:`InstanceData`): Detection results of the
              input images. Each item usually contains\
              following keys.
  
                  - scores (Tensor): Classification scores, has a shape
                    (num_instance,)
                  - labels (Tensor): Labels of bboxes, has a shape
                    (num_instances,).
                  - bboxes (Tensor): Has a shape (num_instances, 4),
                    the last dimension 4 arrange as (x1, y1, x2, y2).
          """
      # TODO: remove this for detr and deformdetr
      sig_of_get_results = signature(self.get_results)
      get_results_args = [
          p.name for p in sig_of_get_results.parameters.values()
      ]
      get_results_single_sig = signature(self._get_results_single)
      get_results_single_sig_args = [
          p.name for p in get_results_single_sig.parameters.values()
      ]
      assert ("with_nms" in get_results_args) and (
          "with_nms" in get_results_single_sig_args
      ), (
          f"{self.__class__.__name__}"
          "does not support test-time augmentation "
      )
  
      num_imgs = len(aug_batch_img_metas[0])
      aug_batch_results = []
      for x, img_metas in zip(aug_batch_feats, aug_batch_img_metas):
          outs = self.forward(x)
          batch_instance_results = self.get_results(
              *outs,
              img_metas=img_metas,
              cfg=self.test_cfg,
              rescale=False,
              with_nms=with_ori_nms,
              **kwargs,
          )
          aug_batch_results.append(batch_instance_results)
  
      # after merging, bboxes will be rescaled to the original image
      batch_results = merge_aug_results(
          aug_batch_results, aug_batch_img_metas
      )
  
      final_results = []
      for img_id in range(num_imgs):
          results = batch_results[img_id]
          det_bboxes, keep_idxs = batched_nms(
              results.bboxes,
              results.scores,
              results.labels,
              self.test_cfg.nms,
          )
          results = results[keep_idxs]
          # some nms operation may reweight the score such as softnms
          results.scores = det_bboxes[:, -1]
          results = results[: self.test_cfg.max_per_img]
          if rescale:
              # all results have been mapped to the original scale
              # in `merge_aug_results`, so just pass
              pass
          else:
              # map to the first aug image scale
              scale_factor = results.bboxes.new_tensor(
                  aug_batch_img_metas[0][img_id]["scale_factor"]
              )
              results.bboxes = results.bboxes * scale_factor
  
          final_results.append(results)
  
      return final_results
  
imports: import copy
  from abc import ABCMeta, abstractmethod
  from inspect import signature
  from typing import List, Optional, Tuple
  import torch
  from mmcv.ops import batched_nms
  from mmengine.config import ConfigDict
  from mmengine.model import BaseModule, constant_init
  from mmengine.structures import InstanceData
  from torch import Tensor
  from mmdet.structures import SampleList
  from mmdet.structures.bbox import cat_boxes, get_box_tensor, get_box_wh, scale_boxes
  from mmdet.utils import InstanceList, OptMultiConfig
  from ..test_time_augs import merge_aug_results
  from ..utils import filter_scores_and_topk, select_single_mlvl, unpack_gt_instances
label_desc: Use image node_id 11 for calling the BaseDenseHead obj's underlying member method code with example usage: obj.aug_test(aug_batch_feats, aug_batch_img_metas, rescale, with_ori_nms) and returns: final_results