class_docstr: TOODHead used in `TOOD: Task-aligned One-stage Object Detection.
  
  <https://arxiv.org/abs/2108.07755>`_.
  
  TOOD uses Task-aligned head (T-head) and is optimized by Task Alignment
  Learning (TAL).
  
  Args:
      num_classes (int): Number of categories excluding the background
          category.
      in_channels (int): Number of channels in the input feature map.
      num_dcn (int): Number of deformable convolution in the head.
          Defaults to 0.
      anchor_type (str): If set to ``anchor_free``, the head will use centers
          to regress bboxes. If set to ``anchor_based``, the head will
          regress bboxes based on anchors. Defaults to ``anchor_free``.
      initial_loss_cls (:obj:`ConfigDict` or dict): Config of initial loss.
  
  Example:
      >>> self = TOODHead(11, 7)
      >>> feats = [torch.rand(1, 7, s, s) for s in [4, 8, 16, 32, 64]]
      >>> cls_score, bbox_pred = self.forward(feats)
      >>> assert len(cls_score) == len(self.scales)
class_docstr_tok: ["TOODHead","used","in","`","TOOD",":","Task-aligned","One-stage","Object","Detection",".","<","https",":","\/\/arxiv.org\/abs\/2108.07755",">","`","_",".","TOOD","uses","Task-aligned","head","(","T-head",")","and","is","optimized","by","Task","Alignment","Learning","(","TAL",")",".","Args",":","num_classes","(","int",")",":","Number","of","categories","excluding","the","background","category",".","in_channels","(","int",")",":","Number","of","channels","in","the","input","feature","map",".","num_dcn","(","int",")",":","Number","of","deformable","convolution","in","the","head",".","Defaults","to","0.","anchor_type","(","str",")",":","If","set","to","``","anchor_free","``",",","the","head","will","use","centers","to","regress","bboxes",".","If","set","to","``","anchor_based","``",",","the","head","will","regress","bboxes","based","on","anchors",".","Defaults","to","``","anchor_free","``",".","initial_loss_cls","(",":","obj",":","`","ConfigDict","`","or","dict",")",":","Config","of","initial","loss",".","Example",":",">",">",">","self","=","TOODHead","(","11",",","7",")",">",">",">","feats","=","[","torch.rand","(","1",",","7",",","s",",","s",")","for","s","in","[","4",",","8",",","16",",","32",",","64","]","]",">",">",">","cls_score",",","bbox_pred","=","self.forward","(","feats",")",">",">",">","assert","len","(","cls_score",")","==","len","(","self.scales",")"]
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]): Decoded box for each scale
          level with shape (N, num_anchors * 4, H, W) in
          [tl_x, tl_y, br_x, br_y] format.
      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 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","]",")",":","Decoded","box","for","each","scale","level","with","shape","(","N",",","num_anchors","*","4",",","H",",","W",")","in","[","tl_x",",","tl_y",",","br_x",",","br_y","]","format",".","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","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]): Decoded box for each scale
              level with shape (N, num_anchors * 4, H, W) in
              [tl_x, tl_y, br_x, br_y] format.
          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 loss components.
      """
      num_imgs = len(batch_img_metas)
      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
      )
  
      flatten_cls_scores = torch.cat(
          [
              cls_score.permute(0, 2, 3, 1).reshape(
                  num_imgs, -1, self.cls_out_channels
              )
              for cls_score in cls_scores
          ],
          1,
      )
      flatten_bbox_preds = torch.cat(
          [
              bbox_pred.permute(0, 2, 3, 1).reshape(num_imgs, -1, 4)
              * stride[0]
              for bbox_pred, stride in zip(
                  bbox_preds, self.prior_generator.strides
              )
          ],
          1,
      )
  
      cls_reg_targets = self.get_targets(
          flatten_cls_scores,
          flatten_bbox_preds,
          anchor_list,
          valid_flag_list,
          batch_gt_instances,
          batch_img_metas,
          batch_gt_instances_ignore=batch_gt_instances_ignore,
      )
      (
          anchor_list,
          labels_list,
          label_weights_list,
          bbox_targets_list,
          alignment_metrics_list,
      ) = cls_reg_targets
  
      (
          losses_cls,
          losses_bbox,
          cls_avg_factors,
          bbox_avg_factors,
      ) = multi_apply(
          self.loss_by_feat_single,
          anchor_list,
          cls_scores,
          bbox_preds,
          labels_list,
          label_weights_list,
          bbox_targets_list,
          alignment_metrics_list,
          self.prior_generator.strides,
      )
  
      cls_avg_factor = (
          reduce_mean(sum(cls_avg_factors)).clamp_(min=1).item()
      )
      losses_cls = list(map(lambda x: x / cls_avg_factor, losses_cls))
  
      bbox_avg_factor = (
          reduce_mean(sum(bbox_avg_factors)).clamp_(min=1).item()
      )
      losses_bbox = list(
          map(lambda x: x / bbox_avg_factor, losses_bbox)
      )
      return dict(loss_cls=losses_cls, loss_bbox=losses_bbox)
  
imports: from typing import List, Optional, Tuple
  import torch
  import torch.nn
  import torch.nn.functional
  from mmcv.cnn import ConvModule, Scale
  from mmcv.ops import deform_conv2d
  from mmengine import MessageHub
  from mmengine.config import ConfigDict
  from mmengine.model import bias_init_with_prob, normal_init
  from mmengine.structures import InstanceData
  from torch import Tensor
  from mmdet.registry import MODELS, TASK_UTILS
  from mmdet.structures.bbox import distance2bbox
  from mmdet.utils import ConfigType, InstanceList, OptConfigType, OptInstanceList, reduce_mean
  from ..task_modules.prior_generators import anchor_inside_flags
  from ..utils import filter_scores_and_topk, images_to_levels, multi_apply, sigmoid_geometric_mean, unmap
  from .atss_head import ATSSHead
label_desc: Use image node_id 8 for calling the TOODHead 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