class_docstr: YOLOXHead head used in `YOLOX <https://arxiv.org/abs/2107.08430>`_.
  
  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 in stacking convs.
          Defaults to 256
      stacked_convs (int): Number of stacking convs of the head.
          Defaults to (8, 16, 32).
      strides (Sequence[int]): Downsample factor of each feature map.
           Defaults to None.
      use_depthwise (bool): Whether to depthwise separable convolution in
          blocks. Defaults to False.
      dcn_on_last_conv (bool): If true, use dcn in the last layer of
          towers. Defaults to False.
      conv_bias (bool or str): If specified as `auto`, it will be decided by
          the norm_cfg. Bias of conv will be set as True if `norm_cfg` is
          None, otherwise False. Defaults to "auto".
      conv_cfg (:obj:`ConfigDict` or dict, optional): Config dict for
          convolution layer. Defaults to None.
      norm_cfg (:obj:`ConfigDict` or dict): Config dict for normalization
          layer. Defaults to dict(type='BN', momentum=0.03, eps=0.001).
      act_cfg (:obj:`ConfigDict` or dict): Config dict for activation layer.
          Defaults to None.
      loss_cls (:obj:`ConfigDict` or dict): Config of classification loss.
      loss_bbox (:obj:`ConfigDict` or dict): Config of localization loss.
      loss_obj (:obj:`ConfigDict` or dict): Config of objectness loss.
      loss_l1 (:obj:`ConfigDict` or dict): Config of L1 loss.
      train_cfg (:obj:`ConfigDict` or dict, optional): Training config of
          anchor head. Defaults to None.
      test_cfg (:obj:`ConfigDict` or dict, optional): Testing config of
          anchor head. Defaults to None.
      init_cfg (:obj:`ConfigDict` or list[:obj:`ConfigDict`] or dict or
          list[dict], optional): Initialization config dict.
          Defaults to None.
class_docstr_tok: ["YOLOXHead","head","used","in","`","YOLOX","<","https",":","\/\/arxiv.org\/abs\/2107.08430",">","`","_",".","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","in","stacking","convs",".","Defaults","to","256","stacked_convs","(","int",")",":","Number","of","stacking","convs","of","the","head",".","Defaults","to","(","8",",","16",",","32",")",".","strides","(","Sequence","[","int","]",")",":","Downsample","factor","of","each","feature","map",".","Defaults","to","None",".","use_depthwise","(","bool",")",":","Whether","to","depthwise","separable","convolution","in","blocks",".","Defaults","to","False",".","dcn_on_last_conv","(","bool",")",":","If","true",",","use","dcn","in","the","last","layer","of","towers",".","Defaults","to","False",".","conv_bias","(","bool","or","str",")",":","If","specified","as","`","auto","`",",","it","will","be","decided","by","the","norm_cfg",".","Bias","of","conv","will","be","set","as","True","if","`","norm_cfg","`","is","None",",","otherwise","False",".","Defaults","to","``","auto","''",".","conv_cfg","(",":","obj",":","`","ConfigDict","`","or","dict",",","optional",")",":","Config","dict","for","convolution","layer",".","Defaults","to","None",".","norm_cfg","(",":","obj",":","`","ConfigDict","`","or","dict",")",":","Config","dict","for","normalization","layer",".","Defaults","to","dict","(","type='BN","'",",","momentum=0.03",",","eps=0.001",")",".","act_cfg","(",":","obj",":","`","ConfigDict","`","or","dict",")",":","Config","dict","for","activation","layer",".","Defaults","to","None",".","loss_cls","(",":","obj",":","`","ConfigDict","`","or","dict",")",":","Config","of","classification","loss",".","loss_bbox","(",":","obj",":","`","ConfigDict","`","or","dict",")",":","Config","of","localization","loss",".","loss_obj","(",":","obj",":","`","ConfigDict","`","or","dict",")",":","Config","of","objectness","loss",".","loss_l1","(",":","obj",":","`","ConfigDict","`","or","dict",")",":","Config","of","L1","loss",".","train_cfg","(",":","obj",":","`","ConfigDict","`","or","dict",",","optional",")",":","Training","config","of","anchor","head",".","Defaults","to","None",".","test_cfg","(",":","obj",":","`","ConfigDict","`","or","dict",",","optional",")",":","Testing","config","of","anchor","head",".","Defaults","to","None",".","init_cfg","(",":","obj",":","`","ConfigDict","`","or","list","[",":","obj",":","`","ConfigDict","`","]","or","dict","or","list","[","dict","]",",","optional",")",":","Initialization","config","dict",".","Defaults","to","None","."]
docstr: Calculate the loss based on the features extracted by the detection
  head.
  
  Args:
      cls_scores (Sequence[Tensor]): Box scores for each scale level,
          each is a 4D-tensor, the channel number is
          num_priors * num_classes.
      bbox_preds (Sequence[Tensor]): Box energies / deltas for each scale
          level, each is a 4D-tensor, the channel number is
          num_priors * 4.
      objectnesses (Sequence[Tensor]): Score factor for
          all scale level, each is a 4D-tensor, has shape
          (batch_size, 1, 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[str, Tensor]: A dictionary of losses.
docstr_tok: ["Calculate","the","loss","based","on","the","features","extracted","by","the","detection","head",".","Args",":","cls_scores","(","Sequence","[","Tensor","]",")",":","Box","scores","for","each","scale","level",",","each","is","a","4D-tensor",",","the","channel","number","is","num_priors","*","num_classes",".","bbox_preds","(","Sequence","[","Tensor","]",")",":","Box","energies","\/","deltas","for","each","scale","level",",","each","is","a","4D-tensor",",","the","channel","number","is","num_priors","*","4.","objectnesses","(","Sequence","[","Tensor","]",")",":","Score","factor","for","all","scale","level",",","each","is","a","4D-tensor",",","has","shape","(","batch_size",",","1",",","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","[","str",",","Tensor","]",":","A","dictionary","of","losses","."]
code: def loss_by_feat(
      self,
      cls_scores: Sequence[Tensor],
      bbox_preds: Sequence[Tensor],
      objectnesses: Sequence[Tensor],
      batch_gt_instances: Sequence[InstanceData],
      batch_img_metas: Sequence[dict],
      batch_gt_instances_ignore: OptInstanceList = None,
  ) -> dict:
      """Calculate the loss based on the features extracted by the detection
      head.
  
      Args:
          cls_scores (Sequence[Tensor]): Box scores for each scale level,
              each is a 4D-tensor, the channel number is
              num_priors * num_classes.
          bbox_preds (Sequence[Tensor]): Box energies / deltas for each scale
              level, each is a 4D-tensor, the channel number is
              num_priors * 4.
          objectnesses (Sequence[Tensor]): Score factor for
              all scale level, each is a 4D-tensor, has shape
              (batch_size, 1, 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[str, Tensor]: A dictionary of losses.
      """
      num_imgs = len(batch_img_metas)
      if batch_gt_instances_ignore is None:
          batch_gt_instances_ignore = [None] * num_imgs
  
      featmap_sizes = [cls_score.shape[2:] for cls_score in cls_scores]
      mlvl_priors = self.prior_generator.grid_priors(
          featmap_sizes,
          dtype=cls_scores[0].dtype,
          device=cls_scores[0].device,
          with_stride=True,
      )
  
      flatten_cls_preds = [
          cls_pred.permute(0, 2, 3, 1).reshape(
              num_imgs, -1, self.cls_out_channels
          )
          for cls_pred in cls_scores
      ]
      flatten_bbox_preds = [
          bbox_pred.permute(0, 2, 3, 1).reshape(num_imgs, -1, 4)
          for bbox_pred in bbox_preds
      ]
      flatten_objectness = [
          objectness.permute(0, 2, 3, 1).reshape(num_imgs, -1)
          for objectness in objectnesses
      ]
  
      flatten_cls_preds = torch.cat(flatten_cls_preds, dim=1)
      flatten_bbox_preds = torch.cat(flatten_bbox_preds, dim=1)
      flatten_objectness = torch.cat(flatten_objectness, dim=1)
      flatten_priors = torch.cat(mlvl_priors)
      flatten_bboxes = self._bbox_decode(
          flatten_priors, flatten_bbox_preds
      )
  
      (
          pos_masks,
          cls_targets,
          obj_targets,
          bbox_targets,
          l1_targets,
          num_fg_imgs,
      ) = multi_apply(
          self._get_targets_single,
          flatten_priors.unsqueeze(0).repeat(num_imgs, 1, 1),
          flatten_cls_preds.detach(),
          flatten_bboxes.detach(),
          flatten_objectness.detach(),
          batch_gt_instances,
          batch_img_metas,
          batch_gt_instances_ignore,
      )
  
      # The experimental results show that 'reduce_mean' can improve
      # performance on the COCO dataset.
      num_pos = torch.tensor(
          sum(num_fg_imgs),
          dtype=torch.float,
          device=flatten_cls_preds.device,
      )
      num_total_samples = max(reduce_mean(num_pos), 1.0)
  
      pos_masks = torch.cat(pos_masks, 0)
      cls_targets = torch.cat(cls_targets, 0)
      obj_targets = torch.cat(obj_targets, 0)
      bbox_targets = torch.cat(bbox_targets, 0)
      if self.use_l1:
          l1_targets = torch.cat(l1_targets, 0)
  
      loss_obj = (
          self.loss_obj(flatten_objectness.view(-1, 1), obj_targets)
          / num_total_samples
      )
      if num_pos > 0:
          loss_cls = (
              self.loss_cls(
                  flatten_cls_preds.view(-1, self.num_classes)[
                      pos_masks
                  ],
                  cls_targets,
              )
              / num_total_samples
          )
          loss_bbox = (
              self.loss_bbox(
                  flatten_bboxes.view(-1, 4)[pos_masks], bbox_targets
              )
              / num_total_samples
          )
      else:
          # Avoid cls and reg branch not participating in the gradient
          # propagation when there is no ground-truth in the images.
          # For more details, please refer to
          # https://github.com/open-mmlab/mmdetection/issues/7298
          loss_cls = flatten_cls_preds.sum() * 0
          loss_bbox = flatten_bboxes.sum() * 0
  
      loss_dict = dict(
          loss_cls=loss_cls, loss_bbox=loss_bbox, loss_obj=loss_obj
      )
  
      if self.use_l1:
          if num_pos > 0:
              loss_l1 = (
                  self.loss_l1(
                      flatten_bbox_preds.view(-1, 4)[pos_masks],
                      l1_targets,
                  )
                  / num_total_samples
              )
          else:
              # Avoid cls and reg branch not participating in the gradient
              # propagation when there is no ground-truth in the images.
              # For more details, please refer to
              # https://github.com/open-mmlab/mmdetection/issues/7298
              loss_l1 = flatten_bbox_preds.sum() * 0
          loss_dict.update(loss_l1=loss_l1)
  
      return loss_dict
  
imports: import math
  from typing import List, Optional, Sequence, Tuple, Union
  import torch
  import torch.nn
  import torch.nn.functional
  from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule
  from mmcv.ops.nms import batched_nms
  from mmengine.config import ConfigDict
  from mmengine.model import bias_init_with_prob
  from mmengine.structures import InstanceData
  from torch import Tensor
  from mmdet.registry import MODELS, TASK_UTILS
  from mmdet.structures.bbox import bbox_xyxy_to_cxcywh
  from mmdet.utils import ConfigType, OptConfigType, OptInstanceList, OptMultiConfig, reduce_mean
  from ..task_modules.prior_generators import MlvlPointGenerator
  from ..task_modules.samplers import PseudoSampler
  from ..utils import multi_apply
  from .base_dense_head import BaseDenseHead
label_desc: Use image node_id 11 for calling the YOLOXHead obj's underlying member method code with example usage: obj.loss_by_feat(cls_scores, bbox_preds, objectnesses, batch_gt_instances, batch_img_metas, batch_gt_instances_ignore) and returns: loss_dict