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: Transform a batch of output features extracted from the head into
  bbox results.
  
  Note: When score_factors is not None, the cls_scores are
  usually multiplied by it then obtain the real score used in NMS,
  such as CenterNess in FCOS, IoU branch in ATSS.
  
  Args:
      cls_scores (list[Tensor]): Classification scores for all
          scale levels, each is a 4D-tensor, has shape
          (batch_size, num_priors * num_classes, H, W).
      bbox_preds (list[Tensor]): Box energies / deltas for all
          scale levels, each is a 4D-tensor, has shape
          (batch_size, num_priors * 4, H, W).
      score_factors (list[Tensor], optional): Score factor for
          all scale level, each is a 4D-tensor, has shape
          (batch_size, num_priors * 1, H, W). Defaults to None.
      batch_img_metas (list[dict], Optional): Batch image meta info.
          Defaults to None.
      cfg (ConfigDict, optional): Test / postprocessing
          configuration, if None, test_cfg would be used.
          Defaults to None.
      rescale (bool): If True, return boxes in original image space.
          Defaults to False.
      with_nms (bool): If True, do nms before return boxes.
          Defaults to True.
  
  Returns:
      list[:obj:`InstanceData`]: Object detection results of each image
      after the post process. 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: ["Transform","a","batch","of","output","features","extracted","from","the","head","into","bbox","results",".","Note",":","When","score_factors","is","not","None",",","the","cls_scores","are","usually","multiplied","by","it","then","obtain","the","real","score","used","in","NMS",",","such","as","CenterNess","in","FCOS",",","IoU","branch","in","ATSS",".","Args",":","cls_scores","(","list","[","Tensor","]",")",":","Classification","scores","for","all","scale","levels",",","each","is","a","4D-tensor",",","has","shape","(","batch_size",",","num_priors","*","num_classes",",","H",",","W",")",".","bbox_preds","(","list","[","Tensor","]",")",":","Box","energies","\/","deltas","for","all","scale","levels",",","each","is","a","4D-tensor",",","has","shape","(","batch_size",",","num_priors","*","4",",","H",",","W",")",".","score_factors","(","list","[","Tensor","]",",","optional",")",":","Score","factor","for","all","scale","level",",","each","is","a","4D-tensor",",","has","shape","(","batch_size",",","num_priors","*","1",",","H",",","W",")",".","Defaults","to","None",".","batch_img_metas","(","list","[","dict","]",",","Optional",")",":","Batch","image","meta","info",".","Defaults","to","None",".","cfg","(","ConfigDict",",","optional",")",":","Test","\/","postprocessing","configuration",",","if","None",",","test_cfg","would","be","used",".","Defaults","to","None",".","rescale","(","bool",")",":","If","True",",","return","boxes","in","original","image","space",".","Defaults","to","False",".","with_nms","(","bool",")",":","If","True",",","do","nms","before","return","boxes",".","Defaults","to","True",".","Returns",":","list","[",":","obj",":","`","InstanceData","`","]",":","Object","detection","results","of","each","image","after","the","post","process",".","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 predict_by_feat(
      self,
      cls_scores: List[Tensor],
      bbox_preds: List[Tensor],
      score_factors: Optional[List[Tensor]] = None,
      batch_img_metas: Optional[List[dict]] = None,
      cfg: Optional[ConfigDict] = None,
      rescale: bool = False,
      with_nms: bool = True,
  ) -> InstanceList:
      """Transform a batch of output features extracted from the head into
      bbox results.
  
      Note: When score_factors is not None, the cls_scores are
      usually multiplied by it then obtain the real score used in NMS,
      such as CenterNess in FCOS, IoU branch in ATSS.
  
      Args:
          cls_scores (list[Tensor]): Classification scores for all
              scale levels, each is a 4D-tensor, has shape
              (batch_size, num_priors * num_classes, H, W).
          bbox_preds (list[Tensor]): Box energies / deltas for all
              scale levels, each is a 4D-tensor, has shape
              (batch_size, num_priors * 4, H, W).
          score_factors (list[Tensor], optional): Score factor for
              all scale level, each is a 4D-tensor, has shape
              (batch_size, num_priors * 1, H, W). Defaults to None.
          batch_img_metas (list[dict], Optional): Batch image meta info.
              Defaults to None.
          cfg (ConfigDict, optional): Test / postprocessing
              configuration, if None, test_cfg would be used.
              Defaults to None.
          rescale (bool): If True, return boxes in original image space.
              Defaults to False.
          with_nms (bool): If True, do nms before return boxes.
              Defaults to True.
  
      Returns:
          list[:obj:`InstanceData`]: Object detection results of each image
          after the post process. 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).
      """
      assert len(cls_scores) == len(bbox_preds)
  
      if score_factors is None:
          # e.g. Retina, FreeAnchor, Foveabox, etc.
          with_score_factors = False
      else:
          # e.g. FCOS, PAA, ATSS, AutoAssign, etc.
          with_score_factors = True
          assert len(cls_scores) == len(score_factors)
  
      num_levels = len(cls_scores)
  
      featmap_sizes = [
          cls_scores[i].shape[-2:] for i in range(num_levels)
      ]
      mlvl_priors = self.prior_generator.grid_priors(
          featmap_sizes,
          dtype=cls_scores[0].dtype,
          device=cls_scores[0].device,
      )
  
      result_list = []
  
      for img_id in range(len(batch_img_metas)):
          img_meta = batch_img_metas[img_id]
          cls_score_list = select_single_mlvl(
              cls_scores, img_id, detach=True
          )
          bbox_pred_list = select_single_mlvl(
              bbox_preds, img_id, detach=True
          )
          if with_score_factors:
              score_factor_list = select_single_mlvl(
                  score_factors, img_id, detach=True
              )
          else:
              score_factor_list = [None for _ in range(num_levels)]
  
          results = self._predict_by_feat_single(
              cls_score_list=cls_score_list,
              bbox_pred_list=bbox_pred_list,
              score_factor_list=score_factor_list,
              mlvl_priors=mlvl_priors,
              img_meta=img_meta,
              cfg=cfg,
              rescale=rescale,
              with_nms=with_nms,
          )
          result_list.append(results)
      return result_list
  
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 8 for calling the BaseDenseHead obj's underlying member method code with example usage: obj.predict_by_feat(cls_scores, bbox_preds, score_factors, batch_img_metas, cfg, rescale, with_nms) and returns: result_list