class_docstr: CenterNetUpdateHead is an improved version of CenterNet in CenterNet2.
  
  Paper link `<https://arxiv.org/abs/2103.07461>`_.
  Args:
      num_classes (int): Number of categories excluding the background
          category.
      in_channels (int): Number of channel in the input feature map.
      regress_ranges (Sequence[Tuple[int, int]]): Regress range of multiple
          level points.
      hm_min_radius (int): Heatmap target minimum radius of cls branch.
          Defaults to 4.
      hm_min_overlap (float): Heatmap target minimum overlap of cls branch.
          Defaults to 0.8.
      more_pos_thresh (float): The filtering threshold when the cls branch
          adds more positive samples. Defaults to 0.2.
      more_pos_topk (int): The maximum number of additional positive samples
          added to each gt. Defaults to 9.
      soft_weight_on_reg (bool): Whether to use the soft target of the
          cls branch as the soft weight of the bbox branch.
          Defaults to False.
      loss_cls (:obj:`ConfigDict` or dict): Config of cls loss. Defaults to
          dict(type='GaussianFocalLoss', loss_weight=1.0)
      loss_bbox (:obj:`ConfigDict` or dict): Config of bbox loss. Defaults to
           dict(type='GIoULoss', loss_weight=2.0).
      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)``.
      train_cfg (:obj:`ConfigDict` or dict, optional): Training config.
          Unused in CenterNet. Reserved for compatibility with
          SingleStageDetector.
      test_cfg (:obj:`ConfigDict` or dict, optional): Testing config
          of CenterNet.
class_docstr_tok: ["CenterNetUpdateHead","is","an","improved","version","of","CenterNet","in","CenterNet2",".","Paper","link","`","<","https",":","\/\/arxiv.org\/abs\/2103.07461",">","`","_",".","Args",":","num_classes","(","int",")",":","Number","of","categories","excluding","the","background","category",".","in_channels","(","int",")",":","Number","of","channel","in","the","input","feature","map",".","regress_ranges","(","Sequence","[","Tuple","[","int",",","int","]","]",")",":","Regress","range","of","multiple","level","points",".","hm_min_radius","(","int",")",":","Heatmap","target","minimum","radius","of","cls","branch",".","Defaults","to","4.","hm_min_overlap","(","float",")",":","Heatmap","target","minimum","overlap","of","cls","branch",".","Defaults","to","0.8.","more_pos_thresh","(","float",")",":","The","filtering","threshold","when","the","cls","branch","adds","more","positive","samples",".","Defaults","to","0.2.","more_pos_topk","(","int",")",":","The","maximum","number","of","additional","positive","samples","added","to","each","gt",".","Defaults","to","9.","soft_weight_on_reg","(","bool",")",":","Whether","to","use","the","soft","target","of","the","cls","branch","as","the","soft","weight","of","the","bbox","branch",".","Defaults","to","False",".","loss_cls","(",":","obj",":","`","ConfigDict","`","or","dict",")",":","Config","of","cls","loss",".","Defaults","to","dict","(","type='GaussianFocalLoss","'",",","loss_weight=1.0",")","loss_bbox","(",":","obj",":","`","ConfigDict","`","or","dict",")",":","Config","of","bbox","loss",".","Defaults","to","dict","(","type='GIoULoss","'",",","loss_weight=2.0",")",".","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",")","``",".","train_cfg","(",":","obj",":","`","ConfigDict","`","or","dict",",","optional",")",":","Training","config",".","Unused","in","CenterNet",".","Reserved","for","compatibility","with","SingleStageDetector",".","test_cfg","(",":","obj",":","`","ConfigDict","`","or","dict",",","optional",")",":","Testing","config","of","CenterNet","."]
docstr: Calculate the loss based on the features extracted by the detection
  head.
  
  Args:
      cls_scores (list[Tensor]): Box scores for each scale level,
          each is a 4D-tensor, the channel number is num_classes.
      bbox_preds (list[Tensor]): Box energies / deltas for each scale
          level, each is a 4D-tensor, the channel number is 4.
      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",",","each","is","a","4D-tensor",",","the","channel","number","is","num_classes",".","bbox_preds","(","list","[","Tensor","]",")",":","Box","energies","\/","deltas","for","each","scale","level",",","each","is","a","4D-tensor",",","the","channel","number","is","4.","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[str, Tensor]:
      """Calculate the loss based on the features extracted by the detection
      head.
  
      Args:
          cls_scores (list[Tensor]): Box scores for each scale level,
              each is a 4D-tensor, the channel number is num_classes.
          bbox_preds (list[Tensor]): Box energies / deltas for each scale
              level, each is a 4D-tensor, the channel number is 4.
          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 = cls_scores[0].size(0)
      assert len(cls_scores) == len(bbox_preds)
      featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]
      all_level_points = self.prior_generator.grid_priors(
          featmap_sizes,
          dtype=bbox_preds[0].dtype,
          device=bbox_preds[0].device,
      )
  
      # 1 flatten outputs
      flatten_cls_scores = [
          cls_score.permute(0, 2, 3, 1).reshape(
              -1, self.cls_out_channels
          )
          for cls_score in cls_scores
      ]
      flatten_bbox_preds = [
          bbox_pred.permute(0, 2, 3, 1).reshape(-1, 4)
          for bbox_pred in bbox_preds
      ]
      flatten_cls_scores = torch.cat(flatten_cls_scores)
      flatten_bbox_preds = torch.cat(flatten_bbox_preds)
  
      # repeat points to align with bbox_preds
      flatten_points = torch.cat(
          [points.repeat(num_imgs, 1) for points in all_level_points]
      )
  
      assert torch.isfinite(flatten_bbox_preds).all().item()
  
      # 2 calc reg and cls branch targets
      cls_targets, bbox_targets = self.get_targets(
          all_level_points, batch_gt_instances
      )
  
      # 3 pos index for cls branch
      featmap_sizes = flatten_points.new_tensor(featmap_sizes)
  
      if self.more_pos:
          pos_inds, cls_labels = self.add_cls_pos_inds(
              flatten_points,
              flatten_bbox_preds,
              featmap_sizes,
              batch_gt_instances,
          )
      else:
          pos_inds = self._get_label_inds(
              batch_gt_instances, batch_img_metas, featmap_sizes
          )
  
      # 4 calc cls loss
      if pos_inds is None:
          # num_gts=0
          num_pos_cls = bbox_preds[0].new_tensor(0, dtype=torch.float)
      else:
          num_pos_cls = bbox_preds[0].new_tensor(
              len(pos_inds), dtype=torch.float
          )
      num_pos_cls = max(reduce_mean(num_pos_cls), 1.0)
  
      cat_agn_cls_targets = cls_targets.max(dim=1)[0]  # M
  
      cls_pos_loss, cls_neg_loss = self.loss_cls(
          flatten_cls_scores.squeeze(1),
          cat_agn_cls_targets,
          pos_inds,
          num_pos_cls,
      )
  
      # 5 calc reg loss
      pos_bbox_inds = torch.nonzero(
          bbox_targets.max(dim=1)[0] >= 0
      ).squeeze(1)
      pos_bbox_preds = flatten_bbox_preds[pos_bbox_inds]
      pos_bbox_targets = bbox_targets[pos_bbox_inds]
  
      bbox_weight_map = cls_targets.max(dim=1)[0]
      bbox_weight_map = bbox_weight_map[pos_bbox_inds]
      bbox_weight_map = (
          bbox_weight_map
          if self.soft_weight_on_reg
          else torch.ones_like(bbox_weight_map)
      )
  
      num_pos_bbox = max(reduce_mean(bbox_weight_map.sum()), 1.0)
  
      if len(pos_bbox_inds) > 0:
          bbox_loss = (
              self.loss_bbox(
                  pos_bbox_preds,
                  pos_bbox_targets,
                  bbox_weight_map,
                  reduction="sum",
              )
              / num_pos_bbox
          )
      else:
          bbox_loss = flatten_bbox_preds.sum() * 0
  
      return dict(
          loss_bbox=bbox_loss,
          loss_cls_pos=cls_pos_loss,
          loss_cls_neg=cls_neg_loss,
      )
  
imports: import copy
  from typing import Dict, List, Optional, Sequence, Tuple
  import torch
  import torch.nn
  from mmcv.cnn import Scale
  from mmengine import ConfigDict
  from mmengine.structures import InstanceData
  from torch import Tensor
  from mmdet.models.dense_heads import CenterNetUpdateHead
  from mmdet.models.utils import unpack_gt_instances
  from mmdet.registry import MODELS
  from mmdet.structures import SampleList
  from mmdet.structures.bbox import bbox2distance
  from mmdet.utils import ConfigType, InstanceList, OptConfigType, OptInstanceList, reduce_mean
  from .iou_loss import IOULoss
label_desc: Use image node_id 4 for calling the CenterNetRPNHead 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