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: Calculate the loss based on the features extracted by the detection
  head.
  
  Args:
      cls_scores (list[Tensor]): Box scores for each scale level
          has shape (N, num_anchors * num_classes, H, W).
      bbox_preds (list[Tensor]): Box energies / deltas for each scale
          level with shape (N, num_anchors * 4, H, W).
      batch_gt_instances (list[:obj:`InstanceData`]): Batch of
          gt_instance. It usually includes ``bboxes`` and ``labels``
          attributes.
      batch_img_metas (list[dict]): Meta information of each image, e.g.,
          image size, scaling factor, etc.
      batch_gt_instances_ignore (list[:obj:`InstanceData`], optional):
          Batch of gt_instances_ignore. It includes ``bboxes`` attribute
          data that is ignored during training and testing.
          Defaults to None.
  
  Returns:
      dict: A dictionary of loss components.
docstr_tok: ["Calculate","the","loss","based","on","the","features","extracted","by","the","detection","head",".","Args",":","cls_scores","(","list","[","Tensor","]",")",":","Box","scores","for","each","scale","level","has","shape","(","N",",","num_anchors","*","num_classes",",","H",",","W",")",".","bbox_preds","(","list","[","Tensor","]",")",":","Box","energies","\/","deltas","for","each","scale","level","with","shape","(","N",",","num_anchors","*","4",",","H",",","W",")",".","batch_gt_instances","(","list","[",":","obj",":","`","InstanceData","`","]",")",":","Batch","of","gt_instance",".","It","usually","includes","``","bboxes","``","and","``","labels","``","attributes",".","batch_img_metas","(","list","[","dict","]",")",":","Meta","information","of","each","image",",","e.g.",",","image","size",",","scaling","factor",",","etc",".","batch_gt_instances_ignore","(","list","[",":","obj",":","`","InstanceData","`","]",",","optional",")",":","Batch","of","gt_instances_ignore",".","It","includes","``","bboxes","``","attribute","data","that","is","ignored","during","training","and","testing",".","Defaults","to","None",".","Returns",":","dict",":","A","dictionary","of","loss","components","."]
code: def loss_by_feat(
      self,
      cls_scores: List[Tensor],
      bbox_preds: List[Tensor],
      batch_gt_instances: InstanceList,
      batch_img_metas: List[dict],
      batch_gt_instances_ignore: OptInstanceList = None,
  ) -> dict:
      """Calculate the loss based on the features extracted by the detection
      head.
  
      Args:
          cls_scores (list[Tensor]): Box scores for each scale level
              has shape (N, num_anchors * num_classes, H, W).
          bbox_preds (list[Tensor]): Box energies / deltas for each scale
              level with shape (N, num_anchors * 4, H, W).
          batch_gt_instances (list[:obj:`InstanceData`]): Batch of
              gt_instance. It usually includes ``bboxes`` and ``labels``
              attributes.
          batch_img_metas (list[dict]): Meta information of each image, e.g.,
              image size, scaling factor, etc.
          batch_gt_instances_ignore (list[:obj:`InstanceData`], optional):
              Batch of gt_instances_ignore. It includes ``bboxes`` attribute
              data that is ignored during training and testing.
              Defaults to None.
  
      Returns:
          dict: A dictionary of loss components.
      """
      featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]
      assert len(featmap_sizes) == self.prior_generator.num_levels
  
      device = cls_scores[0].device
  
      anchor_list, valid_flag_list = self.get_anchors(
          featmap_sizes, batch_img_metas, device=device
      )
      cls_reg_targets = self.get_targets(
          anchor_list,
          valid_flag_list,
          batch_gt_instances,
          batch_img_metas,
          batch_gt_instances_ignore=batch_gt_instances_ignore,
      )
      (
          labels_list,
          label_weights_list,
          bbox_targets_list,
          bbox_weights_list,
          avg_factor,
      ) = cls_reg_targets
  
      # anchor number of multi levels
      num_level_anchors = [
          anchors.size(0) for anchors in anchor_list[0]
      ]
      # concat all level anchors and flags to a single tensor
      concat_anchor_list = []
      for i in range(len(anchor_list)):
          concat_anchor_list.append(cat_boxes(anchor_list[i]))
      all_anchor_list = images_to_levels(
          concat_anchor_list, num_level_anchors
      )
  
      losses_cls, losses_bbox = multi_apply(
          self.loss_by_feat_single,
          cls_scores,
          bbox_preds,
          all_anchor_list,
          labels_list,
          label_weights_list,
          bbox_targets_list,
          bbox_weights_list,
          avg_factor=avg_factor,
      )
      return dict(loss_cls=losses_cls, loss_bbox=losses_bbox)
  
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 11 for calling the AnchorHead obj's underlying member method code with example usage: obj.loss_by_feat(cls_scores, bbox_preds, batch_gt_instances, batch_img_metas, batch_gt_instances_ignore) and returns: dict