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: Compute targets for predictions of single image.
  
  Args:
      gt_instances (:obj:`InstanceData`): Ground truth of instance
          annotations. It should includes ``bboxes``, ``labels``,
          and ``masks`` attributes.
      featmap_sizes (list[:obj:`torch.size`]): Size of each
          feature map from feature pyramid, each element
          means (feat_h, feat_w). Defaults to None.
  
  Returns:
      Tuple: Usually returns a tuple containing targets for predictions.
  
          - mlvl_pos_mask_targets (list[Tensor]): Each element represent
            the binary mask targets for positive points in this
            level, has shape (num_pos, out_h, out_w).
          - mlvl_labels (list[Tensor]): Each element is
            classification labels for all
            points in this level, has shape
            (num_grid, num_grid).
          - mlvl_pos_masks  (list[Tensor]): Each element is
            a `BoolTensor` to represent whether the
            corresponding point in single level
            is positive, has shape (num_grid **2).
          - mlvl_pos_indexes  (list[list]): Each element
            in the list contains the positive index in
            corresponding level, has shape (num_pos).
docstr_tok: ["Compute","targets","for","predictions","of","single","image",".","Args",":","gt_instances","(",":","obj",":","`","InstanceData","`",")",":","Ground","truth","of","instance","annotations",".","It","should","includes","``","bboxes","``",",","``","labels","``",",","and","``","masks","``","attributes",".","featmap_sizes","(","list","[",":","obj",":","`","torch.size","`","]",")",":","Size","of","each","feature","map","from","feature","pyramid",",","each","element","means","(","feat_h",",","feat_w",")",".","Defaults","to","None",".","Returns",":","Tuple",":","Usually","returns","a","tuple","containing","targets","for","predictions",".","-","mlvl_pos_mask_targets","(","list","[","Tensor","]",")",":","Each","element","represent","the","binary","mask","targets","for","positive","points","in","this","level",",","has","shape","(","num_pos",",","out_h",",","out_w",")",".","-","mlvl_labels","(","list","[","Tensor","]",")",":","Each","element","is","classification","labels","for","all","points","in","this","level",",","has","shape","(","num_grid",",","num_grid",")",".","-","mlvl_pos_masks","(","list","[","Tensor","]",")",":","Each","element","is","a","`","BoolTensor","`","to","represent","whether","the","corresponding","point","in","single","level","is","positive",",","has","shape","(","num_grid","*","*","2",")",".","-","mlvl_pos_indexes","(","list","[","list","]",")",":","Each","element","in","the","list","contains","the","positive","index","in","corresponding","level",",","has","shape","(","num_pos",")","."]
code: def _get_targets_single(
      self,
      gt_instances: InstanceData,
      featmap_sizes: Optional[list] = None,
  ) -> tuple:
      """Compute targets for predictions of single image.
  
      Args:
          gt_instances (:obj:`InstanceData`): Ground truth of instance
              annotations. It should includes ``bboxes``, ``labels``,
              and ``masks`` attributes.
          featmap_sizes (list[:obj:`torch.size`]): Size of each
              feature map from feature pyramid, each element
              means (feat_h, feat_w). Defaults to None.
  
      Returns:
          Tuple: Usually returns a tuple containing targets for predictions.
  
              - mlvl_pos_mask_targets (list[Tensor]): Each element represent
                the binary mask targets for positive points in this
                level, has shape (num_pos, out_h, out_w).
              - mlvl_labels (list[Tensor]): Each element is
                classification labels for all
                points in this level, has shape
                (num_grid, num_grid).
              - mlvl_pos_masks  (list[Tensor]): Each element is
                a `BoolTensor` to represent whether the
                corresponding point in single level
                is positive, has shape (num_grid **2).
              - mlvl_pos_indexes  (list[list]): Each element
                in the list contains the positive index in
                corresponding level, has shape (num_pos).
      """
      gt_labels = gt_instances.labels
      device = gt_labels.device
  
      gt_bboxes = gt_instances.bboxes
      gt_areas = torch.sqrt(
          (gt_bboxes[:, 2] - gt_bboxes[:, 0])
          * (gt_bboxes[:, 3] - gt_bboxes[:, 1])
      )
      gt_masks = gt_instances.masks.to_tensor(
          dtype=torch.bool, device=device
      )
  
      mlvl_pos_mask_targets = []
      mlvl_pos_indexes = []
      mlvl_labels = []
      mlvl_pos_masks = []
      for (lower_bound, upper_bound), num_grid in zip(
          self.scale_ranges, self.num_grids
      ):
          mask_target = []
          # FG cat_id: [0, num_classes -1], BG cat_id: num_classes
          pos_index = []
          labels = (
              torch.zeros(
                  [num_grid, num_grid], dtype=torch.int64, device=device
              )
              + self.num_classes
          )
          pos_mask = torch.zeros(
              [num_grid**2], dtype=torch.bool, device=device
          )
  
          gt_inds = (
              ((gt_areas >= lower_bound) & (gt_areas <= upper_bound))
              .nonzero()
              .flatten()
          )
          if len(gt_inds) == 0:
              mlvl_pos_mask_targets.append(
                  torch.zeros(
                      [0, featmap_sizes[0], featmap_sizes[1]],
                      dtype=torch.uint8,
                      device=device,
                  )
              )
              mlvl_labels.append(labels)
              mlvl_pos_masks.append(pos_mask)
              mlvl_pos_indexes.append([])
              continue
          hit_gt_bboxes = gt_bboxes[gt_inds]
          hit_gt_labels = gt_labels[gt_inds]
          hit_gt_masks = gt_masks[gt_inds, ...]
  
          pos_w_ranges = (
              0.5
              * (hit_gt_bboxes[:, 2] - hit_gt_bboxes[:, 0])
              * self.pos_scale
          )
          pos_h_ranges = (
              0.5
              * (hit_gt_bboxes[:, 3] - hit_gt_bboxes[:, 1])
              * self.pos_scale
          )
  
          # Make sure hit_gt_masks has a value
          valid_mask_flags = hit_gt_masks.sum(dim=-1).sum(dim=-1) > 0
  
          for (
              gt_mask,
              gt_label,
              pos_h_range,
              pos_w_range,
              valid_mask_flag,
          ) in zip(
              hit_gt_masks,
              hit_gt_labels,
              pos_h_ranges,
              pos_w_ranges,
              valid_mask_flags,
          ):
              if not valid_mask_flag:
                  continue
              upsampled_size = (
                  featmap_sizes[0] * self.mask_stride,
                  featmap_sizes[1] * self.mask_stride,
              )
              center_h, center_w = center_of_mass(gt_mask)
  
              coord_w = int(
                  floordiv(
                      (center_w / upsampled_size[1]),
                      (1.0 / num_grid),
                      rounding_mode="trunc",
                  )
              )
              coord_h = int(
                  floordiv(
                      (center_h / upsampled_size[0]),
                      (1.0 / num_grid),
                      rounding_mode="trunc",
                  )
              )
  
              # left, top, right, down
              top_box = max(
                  0,
                  int(
                      floordiv(
                          (center_h - pos_h_range) / upsampled_size[0],
                          (1.0 / num_grid),
                          rounding_mode="trunc",
                      )
                  ),
              )
              down_box = min(
                  num_grid - 1,
                  int(
                      floordiv(
                          (center_h + pos_h_range) / upsampled_size[0],
                          (1.0 / num_grid),
                          rounding_mode="trunc",
                      )
                  ),
              )
              left_box = max(
                  0,
                  int(
                      floordiv(
                          (center_w - pos_w_range) / upsampled_size[1],
                          (1.0 / num_grid),
                          rounding_mode="trunc",
                      )
                  ),
              )
              right_box = min(
                  num_grid - 1,
                  int(
                      floordiv(
                          (center_w + pos_w_range) / upsampled_size[1],
                          (1.0 / num_grid),
                          rounding_mode="trunc",
                      )
                  ),
              )
  
              top = max(top_box, coord_h - 1)
              down = min(down_box, coord_h + 1)
              left = max(coord_w - 1, left_box)
              right = min(right_box, coord_w + 1)
  
              labels[top : (down + 1), left : (right + 1)] = gt_label
              # ins
              gt_mask = np.uint8(gt_mask.cpu().numpy())
              # Follow the original implementation, F.interpolate is
              # different from cv2 and opencv
              gt_mask = mmcv.imrescale(
                  gt_mask, scale=1.0 / self.mask_stride
              )
              gt_mask = torch.from_numpy(gt_mask).to(device=device)
  
              for i in range(top, down + 1):
                  for j in range(left, right + 1):
                      index = int(i * num_grid + j)
                      this_mask_target = torch.zeros(
                          [featmap_sizes[0], featmap_sizes[1]],
                          dtype=torch.uint8,
                          device=device,
                      )
                      this_mask_target[
                          : gt_mask.shape[0], : gt_mask.shape[1]
                      ] = gt_mask
                      mask_target.append(this_mask_target)
                      pos_mask[index] = True
                      pos_index.append(index)
          if len(mask_target) == 0:
              mask_target = torch.zeros(
                  [0, featmap_sizes[0], featmap_sizes[1]],
                  dtype=torch.uint8,
                  device=device,
              )
          else:
              mask_target = torch.stack(mask_target, 0)
          mlvl_pos_mask_targets.append(mask_target)
          mlvl_labels.append(labels)
          mlvl_pos_masks.append(pos_mask)
          mlvl_pos_indexes.append(pos_index)
      return (
          mlvl_pos_mask_targets,
          mlvl_labels,
          mlvl_pos_masks,
          mlvl_pos_indexes,
      )
  
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 4 for calling the SOLOV2Head obj's underlying member method code with example usage: obj._get_targets_single(gt_instances, featmap_sizes) and returns: mlvl_pos_mask_targets,  mlvl_labels,  mlvl_pos_masks,  mlvl_pos_indexes