class_docstr: Detection Head of `YOLOF <https://arxiv.org/abs/2103.09460>`_
  
  Args:
      num_classes (int): The number of object classes (w/o background)
      in_channels (list[int]): The number of input channels per scale.
      cls_num_convs (int): The number of convolutions of cls branch.
         Defaults to 2.
      reg_num_convs (int): The number of convolutions of reg branch.
         Defaults to 4.
      norm_cfg (:obj:`ConfigDict` or dict): Config dict for normalization
          layer. Defaults to ``dict(type='BN', requires_grad=True)``.
class_docstr_tok: ["Detection","Head","of","`","YOLOF","<","https",":","\/\/arxiv.org\/abs\/2103.09460",">","`","_","Args",":","num_classes","(","int",")",":","The","number","of","object","classes","(","w\/o","background",")","in_channels","(","list","[","int","]",")",":","The","number","of","input","channels","per","scale",".","cls_num_convs","(","int",")",":","The","number","of","convolutions","of","cls","branch",".","Defaults","to","2.","reg_num_convs","(","int",")",":","The","number","of","convolutions","of","reg","branch",".","Defaults","to","4.","norm_cfg","(",":","obj",":","`","ConfigDict","`","or","dict",")",":","Config","dict","for","normalization","layer",".","Defaults","to","``","dict","(","type='BN","'",",","requires_grad=True",")","``","."]
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.
      """
      assert len(cls_scores) == 1
      assert self.prior_generator.num_levels == 1
  
      device = cls_scores[0].device
      featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]
      anchor_list, valid_flag_list = self.get_anchors(
          featmap_sizes, batch_img_metas, device=device
      )
  
      # The output level is always 1
      anchor_list = [anchors[0] for anchors in anchor_list]
      valid_flag_list = [
          valid_flags[0] for valid_flags in valid_flag_list
      ]
  
      cls_scores_list = levels_to_images(cls_scores)
      bbox_preds_list = levels_to_images(bbox_preds)
  
      cls_reg_targets = self.get_targets(
          cls_scores_list,
          bbox_preds_list,
          anchor_list,
          valid_flag_list,
          batch_gt_instances,
          batch_img_metas,
          batch_gt_instances_ignore=batch_gt_instances_ignore,
      )
      if cls_reg_targets is None:
          return None
      (
          batch_labels,
          batch_label_weights,
          avg_factor,
          batch_bbox_weights,
          batch_pos_predicted_boxes,
          batch_target_boxes,
      ) = cls_reg_targets
  
      flatten_labels = batch_labels.reshape(-1)
      batch_label_weights = batch_label_weights.reshape(-1)
      cls_score = (
          cls_scores[0]
          .permute(0, 2, 3, 1)
          .reshape(-1, self.cls_out_channels)
      )
  
      avg_factor = reduce_mean(
          torch.tensor(avg_factor, dtype=torch.float, device=device)
      ).item()
  
      # classification loss
      loss_cls = self.loss_cls(
          cls_score,
          flatten_labels,
          batch_label_weights,
          avg_factor=avg_factor,
      )
  
      # regression loss
      if batch_pos_predicted_boxes.shape[0] == 0:
          # no pos sample
          loss_bbox = batch_pos_predicted_boxes.sum() * 0
      else:
          loss_bbox = self.loss_bbox(
              batch_pos_predicted_boxes,
              batch_target_boxes,
              batch_bbox_weights.float(),
              avg_factor=avg_factor,
          )
  
      return dict(loss_cls=loss_cls, loss_bbox=loss_bbox)
  
imports: from typing import List, Optional, Tuple
  import torch
  import torch.nn
  from mmcv.cnn import ConvModule, is_norm
  from mmengine.model import bias_init_with_prob, constant_init, normal_init
  from mmengine.structures import InstanceData
  from torch import Tensor
  from mmdet.registry import MODELS
  from mmdet.utils import ConfigType, InstanceList, OptInstanceList, reduce_mean
  from ..task_modules.prior_generators import anchor_inside_flags
  from ..utils import levels_to_images, multi_apply, unmap
  from .anchor_head import AnchorHead
label_desc: Use image node_id 5 for calling the YOLOFHead 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, None