class_docstr: SOLO mask head used in `SOLO: Segmenting Objects by Locations.
  
  <https://arxiv.org/abs/1912.04488>`_
  
  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. Used in child classes.
          Defaults to 256.
      stacked_convs (int): Number of stacking convs of the head.
          Defaults to 4.
      strides (tuple): Downsample factor of each feature map.
      scale_ranges (tuple[tuple[int, int]]): Area range of multiple
          level masks, in the format [(min1, max1), (min2, max2), ...].
          A range of (16, 64) means the area range between (16, 64).
      pos_scale (float): Constant scale factor to control the center region.
      num_grids (list[int]): Divided image into a uniform grids, each
          feature map has a different grid value. The number of output
          channels is grid ** 2. Defaults to [40, 36, 24, 16, 12].
      cls_down_index (int): The index of downsample operation in
          classification branch. Defaults to 0.
      loss_mask (dict): Config of mask loss.
      loss_cls (dict): Config of classification loss.
      norm_cfg (dict): Dictionary to construct and config norm layer.
          Defaults to norm_cfg=dict(type='GN', num_groups=32,
          requires_grad=True).
      train_cfg (dict): Training config of head.
      test_cfg (dict): Testing config of head.
      init_cfg (dict or list[dict], optional): Initialization config dict.
docstr: Calculate the loss based on the features extracted by the mask head.
  
  Args:
      mlvl_mask_preds (list[Tensor]): Multi-level mask prediction.
          Each element in the list has shape
          (batch_size, num_grids**2 ,h ,w).
      batch_gt_instances (list[:obj:`InstanceData`]): Batch of
          gt_instance. It usually includes ``bboxes``, ``masks``,
          and ``labels`` attributes.
      batch_img_metas (list[dict]): Meta information of multiple images.
  
  Returns:
      dict[str, Tensor]: A dictionary of loss components.
code: def loss_by_feat(
      self,
      mlvl_mask_preds: List[Tensor],
      mlvl_cls_preds: List[Tensor],
      batch_gt_instances: InstanceList,
      batch_img_metas: List[dict],
      **kwargs,
  ) -> dict:
      """Calculate the loss based on the features extracted by the mask head.
  
      Args:
          mlvl_mask_preds (list[Tensor]): Multi-level mask prediction.
              Each element in the list has shape
              (batch_size, num_grids**2 ,h ,w).
          batch_gt_instances (list[:obj:`InstanceData`]): Batch of
              gt_instance. It usually includes ``bboxes``, ``masks``,
              and ``labels`` attributes.
          batch_img_metas (list[dict]): Meta information of multiple images.
  
      Returns:
          dict[str, Tensor]: A dictionary of loss components.
      """
      num_levels = self.num_levels
      num_imgs = len(batch_img_metas)
  
      featmap_sizes = [
          featmap.size()[-2:] for featmap in mlvl_mask_preds
      ]
  
      # `BoolTensor` in `pos_masks` represent
      # whether the corresponding point is
      # positive
      pos_mask_targets, labels, pos_masks = multi_apply(
          self._get_targets_single,
          batch_gt_instances,
          featmap_sizes=featmap_sizes,
      )
  
      # change from the outside list meaning multi images
      # to the outside list meaning multi levels
      mlvl_pos_mask_targets = [[] for _ in range(num_levels)]
      mlvl_pos_mask_preds = [[] for _ in range(num_levels)]
      mlvl_pos_masks = [[] for _ in range(num_levels)]
      mlvl_labels = [[] for _ in range(num_levels)]
      for img_id in range(num_imgs):
          assert num_levels == len(pos_mask_targets[img_id])
          for lvl in range(num_levels):
              mlvl_pos_mask_targets[lvl].append(
                  pos_mask_targets[img_id][lvl]
              )
              mlvl_pos_mask_preds[lvl].append(
                  mlvl_mask_preds[lvl][
                      img_id, pos_masks[img_id][lvl], ...
                  ]
              )
              mlvl_pos_masks[lvl].append(
                  pos_masks[img_id][lvl].flatten()
              )
              mlvl_labels[lvl].append(labels[img_id][lvl].flatten())
  
      # cat multiple image
      temp_mlvl_cls_preds = []
      for lvl in range(num_levels):
          mlvl_pos_mask_targets[lvl] = torch.cat(
              mlvl_pos_mask_targets[lvl], dim=0
          )
          mlvl_pos_mask_preds[lvl] = torch.cat(
              mlvl_pos_mask_preds[lvl], dim=0
          )
          mlvl_pos_masks[lvl] = torch.cat(mlvl_pos_masks[lvl], dim=0)
          mlvl_labels[lvl] = torch.cat(mlvl_labels[lvl], dim=0)
          temp_mlvl_cls_preds.append(
              mlvl_cls_preds[lvl]
              .permute(0, 2, 3, 1)
              .reshape(-1, self.cls_out_channels)
          )
  
      num_pos = sum(item.sum() for item in mlvl_pos_masks)
      # dice loss
      loss_mask = []
      for pred, target in zip(
          mlvl_pos_mask_preds, mlvl_pos_mask_targets
      ):
          if pred.size()[0] == 0:
              loss_mask.append(pred.sum().unsqueeze(0))
              continue
          loss_mask.append(
              self.loss_mask(pred, target, reduction_override="none")
          )
      if num_pos > 0:
          loss_mask = torch.cat(loss_mask).sum() / num_pos
      else:
          loss_mask = torch.cat(loss_mask).mean()
  
      flatten_labels = torch.cat(mlvl_labels)
      flatten_cls_preds = torch.cat(temp_mlvl_cls_preds)
      loss_cls = self.loss_cls(
          flatten_cls_preds, flatten_labels, avg_factor=num_pos + 1
      )
      return dict(loss_mask=loss_mask, loss_cls=loss_cls)
  
imports: from typing import List, Optional, Tuple
  import mmcv
  import numpy
  import torch
  import torch.nn
  import torch.nn.functional
  from mmcv.cnn import ConvModule
  from mmengine.structures import InstanceData
  from torch import Tensor
  from mmdet.models.utils.misc import floordiv
  from mmdet.registry import MODELS
  from mmdet.utils import ConfigType, InstanceList, MultiConfig, OptConfigType
  from ..layers import mask_matrix_nms
  from ..utils import center_of_mass, generate_coordinate, multi_apply
  from .base_mask_head import BaseMaskHead
label_desc: Use image node_id 5 for calling the SOLOHead obj's underlying member method code with example usage: obj.loss_by_feat(mlvl_mask_preds, mlvl_cls_preds, batch_gt_instances, batch_img_metas) and returns: dict