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 single image's features extracted from the head into
  bbox results.
  
  Args:
      cls_score_list (list[Tensor]): Box scores from all scale
          levels of a single image, each item has shape
          (num_priors * num_classes, H, W).
      bbox_pred_list (list[Tensor]): Box energies / deltas from
          all scale levels of a single image, each item has shape
          (num_priors * 4, H, W).
      score_factor_list (list[Tensor]): Score factor from all scale
          levels of a single image, each item has shape
          (num_priors * 1, H, W).
      mlvl_priors (list[Tensor]): Each element in the list is
          the priors of a single level in feature pyramid. In all
          anchor-based methods, it has shape (num_priors, 4). In
          all anchor-free methods, it has shape (num_priors, 2)
          when `with_stride=True`, otherwise it still has shape
          (num_priors, 4).
      img_meta (dict): Image meta info.
      cfg (mmengine.Config): Test / postprocessing configuration,
          if None, test_cfg would be used.
      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:
      :obj:`InstanceData`: 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","single","image","'s","features","extracted","from","the","head","into","bbox","results",".","Args",":","cls_score_list","(","list","[","Tensor","]",")",":","Box","scores","from","all","scale","levels","of","a","single","image",",","each","item","has","shape","(","num_priors","*","num_classes",",","H",",","W",")",".","bbox_pred_list","(","list","[","Tensor","]",")",":","Box","energies","\/","deltas","from","all","scale","levels","of","a","single","image",",","each","item","has","shape","(","num_priors","*","4",",","H",",","W",")",".","score_factor_list","(","list","[","Tensor","]",")",":","Score","factor","from","all","scale","levels","of","a","single","image",",","each","item","has","shape","(","num_priors","*","1",",","H",",","W",")",".","mlvl_priors","(","list","[","Tensor","]",")",":","Each","element","in","the","list","is","the","priors","of","a","single","level","in","feature","pyramid",".","In","all","anchor-based","methods",",","it","has","shape","(","num_priors",",","4",")",".","In","all","anchor-free","methods",",","it","has","shape","(","num_priors",",","2",")","when","`","with_stride=True","`",",","otherwise","it","still","has","shape","(","num_priors",",","4",")",".","img_meta","(","dict",")",":","Image","meta","info",".","cfg","(","mmengine.Config",")",":","Test","\/","postprocessing","configuration",",","if","None",",","test_cfg","would","be","used",".","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",":",":","obj",":","`","InstanceData","`",":","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_single(
      self,
      cls_score_list: List[Tensor],
      bbox_pred_list: List[Tensor],
      score_factor_list: List[Tensor],
      mlvl_priors: List[Tensor],
      img_meta: dict,
      cfg: ConfigDict,
      rescale: bool = False,
      with_nms: bool = True,
  ) -> InstanceData:
      """Transform a single image's features extracted from the head into
      bbox results.
  
      Args:
          cls_score_list (list[Tensor]): Box scores from all scale
              levels of a single image, each item has shape
              (num_priors * num_classes, H, W).
          bbox_pred_list (list[Tensor]): Box energies / deltas from
              all scale levels of a single image, each item has shape
              (num_priors * 4, H, W).
          score_factor_list (list[Tensor]): Score factor from all scale
              levels of a single image, each item has shape
              (num_priors * 1, H, W).
          mlvl_priors (list[Tensor]): Each element in the list is
              the priors of a single level in feature pyramid. In all
              anchor-based methods, it has shape (num_priors, 4). In
              all anchor-free methods, it has shape (num_priors, 2)
              when `with_stride=True`, otherwise it still has shape
              (num_priors, 4).
          img_meta (dict): Image meta info.
          cfg (mmengine.Config): Test / postprocessing configuration,
              if None, test_cfg would be used.
          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:
          :obj:`InstanceData`: 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).
      """
      if score_factor_list[0] is None:
          # e.g. Retina, FreeAnchor, etc.
          with_score_factors = False
      else:
          # e.g. FCOS, PAA, ATSS, etc.
          with_score_factors = True
  
      cfg = self.test_cfg if cfg is None else cfg
      cfg = copy.deepcopy(cfg)
      img_shape = img_meta["img_shape"]
      nms_pre = cfg.get("nms_pre", -1)
  
      mlvl_bbox_preds = []
      mlvl_valid_priors = []
      mlvl_scores = []
      mlvl_labels = []
      if with_score_factors:
          mlvl_score_factors = []
      else:
          mlvl_score_factors = None
      for level_idx, (
          cls_score,
          bbox_pred,
          score_factor,
          priors,
      ) in enumerate(
          zip(
              cls_score_list,
              bbox_pred_list,
              score_factor_list,
              mlvl_priors,
          )
      ):
          assert cls_score.size()[-2:] == bbox_pred.size()[-2:]
  
          dim = self.bbox_coder.encode_size
          bbox_pred = bbox_pred.permute(1, 2, 0).reshape(-1, dim)
          if with_score_factors:
              score_factor = (
                  score_factor.permute(1, 2, 0).reshape(-1).sigmoid()
              )
          cls_score = cls_score.permute(1, 2, 0).reshape(
              -1, self.cls_out_channels
          )
  
          # the `custom_cls_channels` parameter is derived from
          # CrossEntropyCustomLoss and FocalCustomLoss, and is currently used
          # in v3det.
          if getattr(self.loss_cls, "custom_cls_channels", False):
              scores = self.loss_cls.get_activation(cls_score)
          elif self.use_sigmoid_cls:
              scores = cls_score.sigmoid()
          else:
              # remind that we set FG labels to [0, num_class-1]
              # since mmdet v2.0
              # BG cat_id: num_class
              scores = cls_score.softmax(-1)[:, :-1]
  
          # After https://github.com/open-mmlab/mmdetection/pull/6268/,
          # this operation keeps fewer bboxes under the same `nms_pre`.
          # There is no difference in performance for most models. If you
          # find a slight drop in performance, you can set a larger
          # `nms_pre` than before.
          score_thr = cfg.get("score_thr", 0)
  
          results = filter_scores_and_topk(
              scores,
              score_thr,
              nms_pre,
              dict(bbox_pred=bbox_pred, priors=priors),
          )
          scores, labels, keep_idxs, filtered_results = results
  
          bbox_pred = filtered_results["bbox_pred"]
          priors = filtered_results["priors"]
  
          if with_score_factors:
              score_factor = score_factor[keep_idxs]
  
          mlvl_bbox_preds.append(bbox_pred)
          mlvl_valid_priors.append(priors)
          mlvl_scores.append(scores)
          mlvl_labels.append(labels)
  
          if with_score_factors:
              mlvl_score_factors.append(score_factor)
  
      bbox_pred = torch.cat(mlvl_bbox_preds)
      priors = cat_boxes(mlvl_valid_priors)
      bboxes = self.bbox_coder.decode(
          priors, bbox_pred, max_shape=img_shape
      )
  
      results = InstanceData()
      results.bboxes = bboxes
      results.scores = torch.cat(mlvl_scores)
      results.labels = torch.cat(mlvl_labels)
      if with_score_factors:
          results.score_factors = torch.cat(mlvl_score_factors)
  
      return self._bbox_post_process(
          results=results,
          cfg=cfg,
          rescale=rescale,
          with_nms=with_nms,
          img_meta=img_meta,
      )
  
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 9 for calling the BaseDenseHead obj's underlying member method code with example usage: obj._predict_by_feat_single(cls_score_list, bbox_pred_list, score_factor_list, mlvl_priors, img_meta, cfg, rescale, with_nms) and returns: self