class_docstr: SOLOv2 mask head used in `SOLOv2: Dynamic and Fast Instance
  Segmentation. <https://arxiv.org/pdf/2003.10152>`_
  
  Args:
      mask_feature_head (dict): Config of SOLOv2MaskFeatHead.
      dynamic_conv_size (int): Dynamic Conv kernel size. Defaults to 1.
      dcn_cfg (dict): Dcn conv configurations in kernel_convs and cls_conv.
          Defaults to None.
      dcn_apply_to_all_conv (bool): Whether to use dcn in every layer of
          kernel_convs and cls_convs, or only the last layer. It shall be set
          `True` for the normal version of SOLOv2 and `False` for the
          light-weight version. Defaults to True.
      init_cfg (dict or list[dict], optional): Initialization config dict.
class_docstr_tok: ["SOLOv2","mask","head","used","in","`","SOLOv2",":","Dynamic","and","Fast","Instance","Segmentation",".","<","https",":","\/\/arxiv.org\/pdf\/2003.10152",">","`","_","Args",":","mask_feature_head","(","dict",")",":","Config","of","SOLOv2MaskFeatHead",".","dynamic_conv_size","(","int",")",":","Dynamic","Conv","kernel","size",".","Defaults","to","1.","dcn_cfg","(","dict",")",":","Dcn","conv","configurations","in","kernel_convs","and","cls_conv",".","Defaults","to","None",".","dcn_apply_to_all_conv","(","bool",")",":","Whether","to","use","dcn","in","every","layer","of","kernel_convs","and","cls_convs",",","or","only","the","last","layer",".","It","shall","be","set","`","True","`","for","the","normal","version","of","SOLOv2","and","`","False","`","for","the","light-weight","version",".","Defaults","to","True",".","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_kernel_preds (list[Tensor]): Multi-level dynamic kernel
          prediction. The kernel is used to generate instance
          segmentation masks by dynamic convolution. Each element in the
          list has shape
          (batch_size, kernel_out_channels, num_grids, num_grids).
      mlvl_cls_preds (list[Tensor]): Multi-level scores. Each element
          in the list has shape
          (batch_size, num_classes, num_grids, num_grids).
      mask_feats (Tensor): Unified mask feature map used to generate
          instance segmentation masks by dynamic convolution. Has shape
          (batch_size, mask_out_channels, 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.
docstr_tok: ["Calculate","the","loss","based","on","the","features","extracted","by","the","mask","head",".","Args",":","mlvl_kernel_preds","(","list","[","Tensor","]",")",":","Multi-level","dynamic","kernel","prediction",".","The","kernel","is","used","to","generate","instance","segmentation","masks","by","dynamic","convolution",".","Each","element","in","the","list","has","shape","(","batch_size",",","kernel_out_channels",",","num_grids",",","num_grids",")",".","mlvl_cls_preds","(","list","[","Tensor","]",")",":","Multi-level","scores",".","Each","element","in","the","list","has","shape","(","batch_size",",","num_classes",",","num_grids",",","num_grids",")",".","mask_feats","(","Tensor",")",":","Unified","mask","feature","map","used","to","generate","instance","segmentation","masks","by","dynamic","convolution",".","Has","shape","(","batch_size",",","mask_out_channels",",","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_kernel_preds: List[Tensor],
      mlvl_cls_preds: List[Tensor],
      mask_feats: 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_kernel_preds (list[Tensor]): Multi-level dynamic kernel
              prediction. The kernel is used to generate instance
              segmentation masks by dynamic convolution. Each element in the
              list has shape
              (batch_size, kernel_out_channels, num_grids, num_grids).
          mlvl_cls_preds (list[Tensor]): Multi-level scores. Each element
              in the list has shape
              (batch_size, num_classes, num_grids, num_grids).
          mask_feats (Tensor): Unified mask feature map used to generate
              instance segmentation masks by dynamic convolution. Has shape
              (batch_size, mask_out_channels, 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.
      """
      featmap_sizes = mask_feats.size()[-2:]
  
      pos_mask_targets, labels, pos_masks, pos_indexes = multi_apply(
          self._get_targets_single,
          batch_gt_instances,
          featmap_sizes=featmap_sizes,
      )
  
      mlvl_mask_targets = [
          torch.cat(lvl_mask_targets, 0)
          for lvl_mask_targets in zip(*pos_mask_targets)
      ]
  
      mlvl_pos_kernel_preds = []
      for lvl_kernel_preds, lvl_pos_indexes in zip(
          mlvl_kernel_preds, zip(*pos_indexes)
      ):
          lvl_pos_kernel_preds = []
          for img_lvl_kernel_preds, img_lvl_pos_indexes in zip(
              lvl_kernel_preds, lvl_pos_indexes
          ):
              img_lvl_pos_kernel_preds = img_lvl_kernel_preds.view(
                  img_lvl_kernel_preds.shape[0], -1
              )[:, img_lvl_pos_indexes]
              lvl_pos_kernel_preds.append(img_lvl_pos_kernel_preds)
          mlvl_pos_kernel_preds.append(lvl_pos_kernel_preds)
  
      # make multilevel mlvl_mask_pred
      mlvl_mask_preds = []
      for lvl_pos_kernel_preds in mlvl_pos_kernel_preds:
          lvl_mask_preds = []
          for img_id, img_lvl_pos_kernel_pred in enumerate(
              lvl_pos_kernel_preds
          ):
              if img_lvl_pos_kernel_pred.size()[-1] == 0:
                  continue
              img_mask_feats = mask_feats[[img_id]]
              h, w = img_mask_feats.shape[-2:]
              num_kernel = img_lvl_pos_kernel_pred.shape[1]
              img_lvl_mask_pred = F.conv2d(
                  img_mask_feats,
                  img_lvl_pos_kernel_pred.permute(1, 0).view(
                      num_kernel,
                      -1,
                      self.dynamic_conv_size,
                      self.dynamic_conv_size,
                  ),
                  stride=1,
              ).view(-1, h, w)
              lvl_mask_preds.append(img_lvl_mask_pred)
          if len(lvl_mask_preds) == 0:
              lvl_mask_preds = None
          else:
              lvl_mask_preds = torch.cat(lvl_mask_preds, 0)
          mlvl_mask_preds.append(lvl_mask_preds)
      # dice loss
      num_pos = 0
      for img_pos_masks in pos_masks:
          for lvl_img_pos_masks in img_pos_masks:
              # Fix `Tensor` object has no attribute `count_nonzero()`
              # in PyTorch 1.6, the type of `lvl_img_pos_masks`
              # should be `torch.bool`.
              num_pos += lvl_img_pos_masks.nonzero().numel()
      loss_mask = []
      for lvl_mask_preds, lvl_mask_targets in zip(
          mlvl_mask_preds, mlvl_mask_targets
      ):
          if lvl_mask_preds is None:
              continue
          loss_mask.append(
              self.loss_mask(
                  lvl_mask_preds,
                  lvl_mask_targets,
                  reduction_override="none",
              )
          )
      if num_pos > 0:
          loss_mask = torch.cat(loss_mask).sum() / num_pos
      else:
          loss_mask = mask_feats.sum() * 0
  
      # cate
      flatten_labels = [
          torch.cat(
              [
                  img_lvl_labels.flatten()
                  for img_lvl_labels in lvl_labels
              ]
          )
          for lvl_labels in zip(*labels)
      ]
      flatten_labels = torch.cat(flatten_labels)
  
      flatten_cls_preds = [
          lvl_cls_preds.permute(0, 2, 3, 1).reshape(
              -1, self.num_classes
          )
          for lvl_cls_preds in mlvl_cls_preds
      ]
      flatten_cls_preds = torch.cat(flatten_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: import warnings
  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.model import BaseModule
  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 .solo_head import SOLOHead
label_desc: Use image node_id 5 for calling the SOLOV2Head obj's underlying member method code with example usage: obj.loss_by_feat(mlvl_kernel_preds, mlvl_cls_preds, mask_feats, batch_gt_instances, batch_img_metas) and returns: dict