class_docstr: Anchor-based head (RPN, RetinaNet, SSD, etc.).
  
  Args:
      num_classes (int): Number of categories excluding the background
          category.
      in_channels (int): Number of channels in the input feature map.
      feat_channels (int): Number of hidden channels. Used in child classes.
      anchor_generator (dict): Config dict for anchor generator
      bbox_coder (dict): Config of bounding box coder.
      reg_decoded_bbox (bool): If true, the regression loss would be
          applied directly on decoded bounding boxes, converting both
          the predicted boxes and regression targets to absolute
          coordinates format. Default False. It should be `True` when
          using `IoULoss`, `GIoULoss`, or `DIoULoss` in the bbox head.
      loss_cls (dict): Config of classification loss.
      loss_bbox (dict): Config of localization loss.
      train_cfg (dict): Training config of anchor head.
      test_cfg (dict): Testing config of anchor head.
      init_cfg (dict or list[dict], optional): Initialization config dict.
class_docstr_tok: ["Anchor-based","head","(","RPN",",","RetinaNet",",","SSD",",","etc.",")",".","Args",":","num_classes","(","int",")",":","Number","of","categories","excluding","the","background","category",".","in_channels","(","int",")",":","Number","of","channels","in","the","input","feature","map",".","feat_channels","(","int",")",":","Number","of","hidden","channels",".","Used","in","child","classes",".","anchor_generator","(","dict",")",":","Config","dict","for","anchor","generator","bbox_coder","(","dict",")",":","Config","of","bounding","box","coder",".","reg_decoded_bbox","(","bool",")",":","If","true",",","the","regression","loss","would","be","applied","directly","on","decoded","bounding","boxes",",","converting","both","the","predicted","boxes","and","regression","targets","to","absolute","coordinates","format",".","Default","False",".","It","should","be","`","True","`","when","using","`","IoULoss","`",",","`","GIoULoss","`",",","or","`","DIoULoss","`","in","the","bbox","head",".","loss_cls","(","dict",")",":","Config","of","classification","loss",".","loss_bbox","(","dict",")",":","Config","of","localization","loss",".","train_cfg","(","dict",")",":","Training","config","of","anchor","head",".","test_cfg","(","dict",")",":","Testing","config","of","anchor","head",".","init_cfg","(","dict","or","list","[","dict","]",",","optional",")",":","Initialization","config","dict","."]
docstr: Compute regression and classification targets for anchors in a
  single image.
  
  Args:
      flat_anchors (Tensor or :obj:`BaseBoxes`): Multi-level anchors
          of the image, which are concatenated into a single tensor
          or box type of shape (num_anchors, 4)
      valid_flags (Tensor): Multi level valid flags of the image,
          which are concatenated into a single tensor of
              shape (num_anchors, ).
      gt_instances (:obj:`InstanceData`): Ground truth of instance
          annotations. It should includes ``bboxes`` and ``labels``
          attributes.
      img_meta (dict): Meta information for current image.
      gt_instances_ignore (:obj:`InstanceData`, optional): Instances
          to be ignored during training. It includes ``bboxes`` attribute
          data that is ignored during training and testing.
          Defaults to None.
      unmap_outputs (bool): Whether to map outputs back to the original
          set of anchors.  Defaults to True.
  
  Returns:
      tuple:
  
          - labels (Tensor): Labels of each level.
          - label_weights (Tensor): Label weights of each level.
          - bbox_targets (Tensor): BBox targets of each level.
          - bbox_weights (Tensor): BBox weights of each level.
          - pos_inds (Tensor): positive samples indexes.
          - neg_inds (Tensor): negative samples indexes.
          - sampling_result (:obj:`SamplingResult`): Sampling results.
docstr_tok: ["Compute","regression","and","classification","targets","for","anchors","in","a","single","image",".","Args",":","flat_anchors","(","Tensor","or",":","obj",":","`","BaseBoxes","`",")",":","Multi-level","anchors","of","the","image",",","which","are","concatenated","into","a","single","tensor","or","box","type","of","shape","(","num_anchors",",","4",")","valid_flags","(","Tensor",")",":","Multi","level","valid","flags","of","the","image",",","which","are","concatenated","into","a","single","tensor","of","shape","(","num_anchors",",",")",".","gt_instances","(",":","obj",":","`","InstanceData","`",")",":","Ground","truth","of","instance","annotations",".","It","should","includes","``","bboxes","``","and","``","labels","``","attributes",".","img_meta","(","dict",")",":","Meta","information","for","current","image",".","gt_instances_ignore","(",":","obj",":","`","InstanceData","`",",","optional",")",":","Instances","to","be","ignored","during","training",".","It","includes","``","bboxes","``","attribute","data","that","is","ignored","during","training","and","testing",".","Defaults","to","None",".","unmap_outputs","(","bool",")",":","Whether","to","map","outputs","back","to","the","original","set","of","anchors",".","Defaults","to","True",".","Returns",":","tuple",":","-","labels","(","Tensor",")",":","Labels","of","each","level",".","-","label_weights","(","Tensor",")",":","Label","weights","of","each","level",".","-","bbox_targets","(","Tensor",")",":","BBox","targets","of","each","level",".","-","bbox_weights","(","Tensor",")",":","BBox","weights","of","each","level",".","-","pos_inds","(","Tensor",")",":","positive","samples","indexes",".","-","neg_inds","(","Tensor",")",":","negative","samples","indexes",".","-","sampling_result","(",":","obj",":","`","SamplingResult","`",")",":","Sampling","results","."]
code: def _get_targets_single(
      self,
      flat_anchors: Union[Tensor, BaseBoxes],
      valid_flags: Tensor,
      gt_instances: InstanceData,
      img_meta: dict,
      gt_instances_ignore: Optional[InstanceData] = None,
      unmap_outputs: bool = True,
  ) -> tuple:
      """Compute regression and classification targets for anchors in a
      single image.
  
      Args:
          flat_anchors (Tensor or :obj:`BaseBoxes`): Multi-level anchors
              of the image, which are concatenated into a single tensor
              or box type of shape (num_anchors, 4)
          valid_flags (Tensor): Multi level valid flags of the image,
              which are concatenated into a single tensor of
                  shape (num_anchors, ).
          gt_instances (:obj:`InstanceData`): Ground truth of instance
              annotations. It should includes ``bboxes`` and ``labels``
              attributes.
          img_meta (dict): Meta information for current image.
          gt_instances_ignore (:obj:`InstanceData`, optional): Instances
              to be ignored during training. It includes ``bboxes`` attribute
              data that is ignored during training and testing.
              Defaults to None.
          unmap_outputs (bool): Whether to map outputs back to the original
              set of anchors.  Defaults to True.
  
      Returns:
          tuple:
  
              - labels (Tensor): Labels of each level.
              - label_weights (Tensor): Label weights of each level.
              - bbox_targets (Tensor): BBox targets of each level.
              - bbox_weights (Tensor): BBox weights of each level.
              - pos_inds (Tensor): positive samples indexes.
              - neg_inds (Tensor): negative samples indexes.
              - sampling_result (:obj:`SamplingResult`): Sampling results.
      """
      inside_flags = anchor_inside_flags(
          flat_anchors,
          valid_flags,
          img_meta["img_shape"][:2],
          self.train_cfg["allowed_border"],
      )
      if not inside_flags.any():
          raise ValueError(
              "There is no valid anchor inside the image boundary. Please "
              "check the image size and anchor sizes, or set "
              "``allowed_border`` to -1 to skip the condition."
          )
      # assign gt and sample anchors
      anchors = flat_anchors[inside_flags]
  
      pred_instances = InstanceData(priors=anchors)
      assign_result = self.assigner.assign(
          pred_instances, gt_instances, gt_instances_ignore
      )
      # No sampling is required except for RPN and
      # Guided Anchoring algorithms
      sampling_result = self.sampler.sample(
          assign_result, pred_instances, gt_instances
      )
  
      num_valid_anchors = anchors.shape[0]
      target_dim = (
          gt_instances.bboxes.size(-1)
          if self.reg_decoded_bbox
          else self.bbox_coder.encode_size
      )
      bbox_targets = anchors.new_zeros(num_valid_anchors, target_dim)
      bbox_weights = anchors.new_zeros(num_valid_anchors, target_dim)
  
      # TODO: Considering saving memory, is it necessary to be long?
      labels = anchors.new_full(
          (num_valid_anchors,), self.num_classes, dtype=torch.long
      )
      label_weights = anchors.new_zeros(
          num_valid_anchors, dtype=torch.float
      )
  
      pos_inds = sampling_result.pos_inds
      neg_inds = sampling_result.neg_inds
      # `bbox_coder.encode` accepts tensor or box type inputs and generates
      # tensor targets. If regressing decoded boxes, the code will convert
      # box type `pos_bbox_targets` to tensor.
      if len(pos_inds) > 0:
          if not self.reg_decoded_bbox:
              pos_bbox_targets = self.bbox_coder.encode(
                  sampling_result.pos_priors,
                  sampling_result.pos_gt_bboxes,
              )
          else:
              pos_bbox_targets = sampling_result.pos_gt_bboxes
              pos_bbox_targets = get_box_tensor(pos_bbox_targets)
          bbox_targets[pos_inds, :] = pos_bbox_targets
          bbox_weights[pos_inds, :] = 1.0
  
          labels[pos_inds] = sampling_result.pos_gt_labels
          if self.train_cfg["pos_weight"] <= 0:
              label_weights[pos_inds] = 1.0
          else:
              label_weights[pos_inds] = self.train_cfg["pos_weight"]
      if len(neg_inds) > 0:
          label_weights[neg_inds] = 1.0
  
      # map up to original set of anchors
      if unmap_outputs:
          num_total_anchors = flat_anchors.size(0)
          labels = unmap(
              labels,
              num_total_anchors,
              inside_flags,
              fill=self.num_classes,
          )  # fill bg label
          label_weights = unmap(
              label_weights, num_total_anchors, inside_flags
          )
          bbox_targets = unmap(
              bbox_targets, num_total_anchors, inside_flags
          )
          bbox_weights = unmap(
              bbox_weights, num_total_anchors, inside_flags
          )
  
      return (
          labels,
          label_weights,
          bbox_targets,
          bbox_weights,
          pos_inds,
          neg_inds,
          sampling_result,
      )
  
imports: import warnings
  from typing import List, Optional, Tuple, Union
  import torch
  import torch.nn
  from mmengine.structures import InstanceData
  from torch import Tensor
  from mmdet.registry import MODELS, TASK_UTILS
  from mmdet.structures.bbox import BaseBoxes, cat_boxes, get_box_tensor
  from mmdet.utils import ConfigType, InstanceList, OptConfigType, OptInstanceList, OptMultiConfig
  from ..task_modules.prior_generators import AnchorGenerator, anchor_inside_flags
  from ..task_modules.samplers import PseudoSampler
  from ..utils import images_to_levels, multi_apply, unmap
  from .base_dense_head import BaseDenseHead
label_desc: Use image node_id 8 for calling the AnchorHead obj's underlying member method code with example usage: obj._get_targets_single(flat_anchors, valid_flags, gt_instances, img_meta, gt_instances_ignore, unmap_outputs) and returns: labels,  label_weights,  bbox_targets,  bbox_weights,  pos_inds,  neg_inds,  sampling_result