class_docstr: Implements the Mask2Former head.
  
  See `Masked-attention Mask Transformer for Universal Image
  Segmentation <https://arxiv.org/pdf/2112.01527>`_ for details.
  
  Args:
      in_channels (list[int]): Number of channels in the input feature map.
      feat_channels (int): Number of channels for features.
      out_channels (int): Number of channels for output.
      num_things_classes (int): Number of things.
      num_stuff_classes (int): Number of stuff.
      num_queries (int): Number of query in Transformer decoder.
      pixel_decoder (:obj:`mmcv.ConfigDict` | dict): Config for pixel
          decoder. Defaults to None.
      enforce_decoder_input_project (bool, optional): Whether to add
          a layer to change the embed_dim of tranformer encoder in
          pixel decoder to the embed_dim of transformer decoder.
          Defaults to False.
      transformer_decoder (:obj:`mmcv.ConfigDict` | dict): Config for
          transformer decoder. Defaults to None.
      positional_encoding (:obj:`mmcv.ConfigDict` | dict): Config for
          transformer decoder position encoding. Defaults to None.
      loss_cls (:obj:`mmcv.ConfigDict` | dict): Config of the classification
          loss. Defaults to None.
      loss_mask (:obj:`mmcv.ConfigDict` | dict): Config of the mask loss.
          Defaults to None.
      loss_dice (:obj:`mmcv.ConfigDict` | dict): Config of the dice loss.
          Defaults to None.
      train_cfg (:obj:`mmcv.ConfigDict` | dict): Training config of
          Mask2Former head.
      test_cfg (:obj:`mmcv.ConfigDict` | dict): Testing config of
          Mask2Former head.
      init_cfg (dict or list[dict], optional): Initialization config dict.
          Defaults to None.
class_docstr_tok: ["Implements","the","Mask2Former","head",".","See","`","Masked-attention","Mask","Transformer","for","Universal","Image","Segmentation","<","https",":","\/\/arxiv.org\/pdf\/2112.01527",">","`","_","for","details",".","Args",":","in_channels","(","list","[","int","]",")",":","Number","of","channels","in","the","input","feature","map",".","feat_channels","(","int",")",":","Number","of","channels","for","features",".","out_channels","(","int",")",":","Number","of","channels","for","output",".","num_things_classes","(","int",")",":","Number","of","things",".","num_stuff_classes","(","int",")",":","Number","of","stuff",".","num_queries","(","int",")",":","Number","of","query","in","Transformer","decoder",".","pixel_decoder","(",":","obj",":","`","mmcv.ConfigDict","`","|","dict",")",":","Config","for","pixel","decoder",".","Defaults","to","None",".","enforce_decoder_input_project","(","bool",",","optional",")",":","Whether","to","add","a","layer","to","change","the","embed_dim","of","tranformer","encoder","in","pixel","decoder","to","the","embed_dim","of","transformer","decoder",".","Defaults","to","False",".","transformer_decoder","(",":","obj",":","`","mmcv.ConfigDict","`","|","dict",")",":","Config","for","transformer","decoder",".","Defaults","to","None",".","positional_encoding","(",":","obj",":","`","mmcv.ConfigDict","`","|","dict",")",":","Config","for","transformer","decoder","position","encoding",".","Defaults","to","None",".","loss_cls","(",":","obj",":","`","mmcv.ConfigDict","`","|","dict",")",":","Config","of","the","classification","loss",".","Defaults","to","None",".","loss_mask","(",":","obj",":","`","mmcv.ConfigDict","`","|","dict",")",":","Config","of","the","mask","loss",".","Defaults","to","None",".","loss_dice","(",":","obj",":","`","mmcv.ConfigDict","`","|","dict",")",":","Config","of","the","dice","loss",".","Defaults","to","None",".","train_cfg","(",":","obj",":","`","mmcv.ConfigDict","`","|","dict",")",":","Training","config","of","Mask2Former","head",".","test_cfg","(",":","obj",":","`","mmcv.ConfigDict","`","|","dict",")",":","Testing","config","of","Mask2Former","head",".","init_cfg","(","dict","or","list","[","dict","]",",","optional",")",":","Initialization","config","dict",".","Defaults","to","None","."]
docstr: Loss function for outputs from a single decoder layer.
  
  Args:
      cls_scores (Tensor): Mask score logits from a single decoder layer
          for all images. Shape (batch_size, num_queries,
          cls_out_channels). Note `cls_out_channels` should includes
          background.
      mask_preds (Tensor): Mask logits for a pixel decoder for all
          images. Shape (batch_size, num_queries, h, w).
      gt_labels_list (list[Tensor]): Ground truth class indices for each
          image, each with shape (num_gts, ).
      gt_masks_list (list[Tensor]): Ground truth mask for each image,
          each with shape (num_gts, h, w).
      img_metas (list[dict]): List of image meta information.
  
  Returns:
      tuple[Tensor]: Loss components for outputs from a single                 decoder layer.
docstr_tok: ["Loss","function","for","outputs","from","a","single","decoder","layer",".","Args",":","cls_scores","(","Tensor",")",":","Mask","score","logits","from","a","single","decoder","layer","for","all","images",".","Shape","(","batch_size",",","num_queries",",","cls_out_channels",")",".","Note","`","cls_out_channels","`","should","includes","background",".","mask_preds","(","Tensor",")",":","Mask","logits","for","a","pixel","decoder","for","all","images",".","Shape","(","batch_size",",","num_queries",",","h",",","w",")",".","gt_labels_list","(","list","[","Tensor","]",")",":","Ground","truth","class","indices","for","each","image",",","each","with","shape","(","num_gts",",",")",".","gt_masks_list","(","list","[","Tensor","]",")",":","Ground","truth","mask","for","each","image",",","each","with","shape","(","num_gts",",","h",",","w",")",".","img_metas","(","list","[","dict","]",")",":","List","of","image","meta","information",".","Returns",":","tuple","[","Tensor","]",":","Loss","components","for","outputs","from","a","single","decoder","layer","."]
code: def loss_single(
      self,
      cls_scores,
      mask_preds,
      gt_labels_list,
      gt_masks_list,
      img_metas,
  ):
      """Loss function for outputs from a single decoder layer.
  
          Args:
              cls_scores (Tensor): Mask score logits from a single decoder layer
                  for all images. Shape (batch_size, num_queries,
                  cls_out_channels). Note `cls_out_channels` should includes
                  background.
              mask_preds (Tensor): Mask logits for a pixel decoder for all
                  images. Shape (batch_size, num_queries, h, w).
              gt_labels_list (list[Tensor]): Ground truth class indices for each
                  image, each with shape (num_gts, ).
              gt_masks_list (list[Tensor]): Ground truth mask for each image,
                  each with shape (num_gts, h, w).
              img_metas (list[dict]): List of image meta information.
  
          Returns:
              tuple[Tensor]: Loss components for outputs from a single \
                  decoder layer.
          """
      num_imgs = cls_scores.size(0)
      cls_scores_list = [cls_scores[i] for i in range(num_imgs)]
      mask_preds_list = [mask_preds[i] for i in range(num_imgs)]
      (
          labels_list,
          label_weights_list,
          mask_targets_list,
          mask_weights_list,
          num_total_pos,
          num_total_neg,
      ) = self.get_targets(
          cls_scores_list,
          mask_preds_list,
          gt_labels_list,
          gt_masks_list,
          img_metas,
      )
      # shape (batch_size, num_queries)
      labels = torch.stack(labels_list, dim=0)
      # shape (batch_size, num_queries)
      label_weights = torch.stack(label_weights_list, dim=0)
      # shape (num_total_gts, h, w)
      mask_targets = torch.cat(mask_targets_list, dim=0)
      # shape (batch_size, num_queries)
      mask_weights = torch.stack(mask_weights_list, dim=0)
  
      # classfication loss
      # shape (batch_size * num_queries, )
      cls_scores = cls_scores.flatten(0, 1)
      labels = labels.flatten(0, 1)
      label_weights = label_weights.flatten(0, 1)
  
      class_weight = cls_scores.new_tensor(self.class_weight)
      loss_cls = self.loss_cls(
          cls_scores,
          labels,
          label_weights,
          avg_factor=class_weight[labels].sum(),
      )
  
      num_total_masks = reduce_mean(
          cls_scores.new_tensor([num_total_pos])
      )
      num_total_masks = max(num_total_masks, 1)
  
      # extract positive ones
      # shape (batch_size, num_queries, h, w) -> (num_total_gts, h, w)
      mask_preds = mask_preds[mask_weights > 0]
  
      if mask_targets.shape[0] == 0:
          # zero match
          loss_dice = mask_preds.sum()
          loss_mask = mask_preds.sum()
          return loss_cls, loss_mask, loss_dice
  
      with torch.no_grad():
          points_coords = get_uncertain_point_coords_with_randomness(
              mask_preds.unsqueeze(1),
              None,
              self.num_points,
              self.oversample_ratio,
              self.importance_sample_ratio,
          )
          # shape (num_total_gts, h, w) -> (num_total_gts, num_points)
          mask_point_targets = point_sample(
              mask_targets.unsqueeze(1).float(), points_coords
          ).squeeze(1)
      # shape (num_queries, h, w) -> (num_queries, num_points)
      mask_point_preds = point_sample(
          mask_preds.unsqueeze(1), points_coords
      ).squeeze(1)
  
      # dice loss
      loss_dice = self.loss_dice(
          mask_point_preds,
          mask_point_targets,
          avg_factor=num_total_masks,
      )
  
      # mask loss
      # shape (num_queries, num_points) -> (num_queries * num_points, )
      mask_point_preds = mask_point_preds.reshape(-1, 1)
      # shape (num_total_gts, num_points) -> (num_total_gts * num_points, )
      mask_point_targets = mask_point_targets.reshape(-1)
      loss_mask = self.loss_mask(
          mask_point_preds,
          mask_point_targets,
          avg_factor=num_total_masks * self.num_points,
      )
  
      return loss_cls, loss_mask, loss_dice
  
imports: import copy
  import torch
  import torch.nn
  import torch.nn.functional
  from mmcv.cnn import Conv2d, build_plugin_layer, caffe2_xavier_init
  from mmcv.cnn.bricks.transformer import build_positional_encoding, build_transformer_layer_sequence
  from mmcv.ops import point_sample
  from mmcv.runner import ModuleList, force_fp32
  from mmseg.models.builder import HEADS, build_loss
  from mmseg.models.decode_heads.decode_head import BaseDecodeHead
  from ...core import build_sampler, multi_apply, reduce_mean
  from ..builder import build_assigner
  from ..utils import get_uncertain_point_coords_with_randomness
label_desc: Use image node_id 5 for calling the Mask2FormerHead obj's underlying member method code with example usage: obj.loss_single(cls_scores, mask_preds, gt_labels_list, gt_masks_list, img_metas) and returns: loss_cls,  loss_mask,  loss_dice, loss_cls,  loss_mask,  loss_dice