class_docstr: FreeAnchor RetinaHead used in https://arxiv.org/abs/1909.02466.
  
  Args:
      num_classes (int): Number of categories excluding the background
          category.
      in_channels (int): Number of channels in the input feature map.
      stacked_convs (int): Number of conv layers in cls and reg tower.
          Defaults to 4.
      conv_cfg (:obj:`ConfigDict` or dict, optional): dictionary to
          construct and config conv layer. Defaults to None.
      norm_cfg (:obj:`ConfigDict` or dict, optional): dictionary to
          construct and config norm layer. Defaults to
          norm_cfg=dict(type='GN', num_groups=32, requires_grad=True).
      pre_anchor_topk (int): Number of boxes that be token in each bag.
          Defaults to 50
      bbox_thr (float): The threshold of the saturated linear function.
          It is usually the same with the IoU threshold used in NMS.
          Defaults to 0.6.
      gamma (float): Gamma parameter in focal loss. Defaults to 2.0.
      alpha (float): Alpha parameter in focal loss. Defaults to 0.5.
class_docstr_tok: ["FreeAnchor","RetinaHead","used","in","https",":","\/\/arxiv.org\/abs\/1909.02466",".","Args",":","num_classes","(","int",")",":","Number","of","categories","excluding","the","background","category",".","in_channels","(","int",")",":","Number","of","channels","in","the","input","feature","map",".","stacked_convs","(","int",")",":","Number","of","conv","layers","in","cls","and","reg","tower",".","Defaults","to","4.","conv_cfg","(",":","obj",":","`","ConfigDict","`","or","dict",",","optional",")",":","dictionary","to","construct","and","config","conv","layer",".","Defaults","to","None",".","norm_cfg","(",":","obj",":","`","ConfigDict","`","or","dict",",","optional",")",":","dictionary","to","construct","and","config","norm","layer",".","Defaults","to","norm_cfg=dict","(","type='GN","'",",","num_groups=32",",","requires_grad=True",")",".","pre_anchor_topk","(","int",")",":","Number","of","boxes","that","be","token","in","each","bag",".","Defaults","to","50","bbox_thr","(","float",")",":","The","threshold","of","the","saturated","linear","function",".","It","is","usually","the","same","with","the","IoU","threshold","used","in","NMS",".","Defaults","to","0.6.","gamma","(","float",")",":","Gamma","parameter","in","focal","loss",".","Defaults","to","2.0.","alpha","(","float",")",":","Alpha","parameter","in","focal","loss",".","Defaults","to","0.5","."]
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, _ = self.get_anchors(
          featmap_sizes=featmap_sizes,
          batch_img_metas=batch_img_metas,
          device=device,
      )
      concat_anchor_list = [torch.cat(anchor) for anchor in anchor_list]
  
      # concatenate each level
      cls_scores = [
          cls.permute(0, 2, 3, 1).reshape(
              cls.size(0), -1, self.cls_out_channels
          )
          for cls in cls_scores
      ]
      bbox_preds = [
          bbox_pred.permute(0, 2, 3, 1).reshape(
              bbox_pred.size(0), -1, 4
          )
          for bbox_pred in bbox_preds
      ]
      cls_scores = torch.cat(cls_scores, dim=1)
      cls_probs = torch.sigmoid(cls_scores)
      bbox_preds = torch.cat(bbox_preds, dim=1)
  
      box_probs, positive_losses, num_pos_list = multi_apply(
          self.positive_loss_single,
          cls_probs,
          bbox_preds,
          concat_anchor_list,
          batch_gt_instances,
      )
  
      num_pos = sum(num_pos_list)
      positive_loss = torch.cat(positive_losses).sum() / max(1, num_pos)
  
      # box_prob: P{a_{j} \in A_{+}}
      box_probs = torch.stack(box_probs, dim=0)
  
      # negative_loss:
      # \sum_{j}{ FL((1 - P{a_{j} \in A_{+}}) * (1 - P_{j}^{bg})) } / n||B||
      negative_loss = self.negative_bag_loss(
          cls_probs, box_probs
      ).sum() / max(1, num_pos * self.pre_anchor_topk)
  
      # avoid the absence of gradients in regression subnet
      # when no ground-truth in a batch
      if num_pos == 0:
          positive_loss = bbox_preds.sum() * 0
  
      losses = {
          "positive_bag_loss": positive_loss,
          "negative_bag_loss": negative_loss,
      }
      return losses
  
file_path: mmdetection/mmdet/models/dense_heads/free_anchor_retina_head.py
imports: from typing import List
  import torch
  import torch.nn.functional
  from mmengine.structures import InstanceData
  from torch import Tensor
  from mmdet.registry import MODELS
  from mmdet.structures.bbox import bbox_overlaps
  from mmdet.utils import InstanceList, OptConfigType, OptInstanceList
  from ..utils import multi_apply
  from .retina_head import RetinaHead
label_desc: Use image node_id 2 for calling the FreeAnchorRetinaHead 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: losses