class_docstr: YOLACT box head used in https://arxiv.org/abs/1904.02689.
  
  Note that YOLACT head is a light version of RetinaNet head.
  Four differences are described as follows:
  
  1. YOLACT box head has three-times fewer anchors.
  2. YOLACT box head shares the convs for box and cls branches.
  3. YOLACT box head uses OHEM instead of Focal loss.
  4. YOLACT box head predicts a set of mask coefficients for each box.
  
  Args:
      num_classes (int): Number of categories excluding the background
          category.
      in_channels (int): Number of channels in the input feature map.
      anchor_generator (:obj:`ConfigDict` or dict): Config dict for
          anchor generator
      loss_cls (:obj:`ConfigDict` or dict): Config of classification loss.
      loss_bbox (:obj:`ConfigDict` or dict): Config of localization loss.
      num_head_convs (int): Number of the conv layers shared by
          box and cls branches.
      num_protos (int): Number of the mask coefficients.
      use_ohem (bool): If true, ``loss_single_OHEM`` will be used for
          cls loss calculation. If false, ``loss_single`` will be used.
      conv_cfg (:obj:`ConfigDict` or dict, optional): Dictionary to
          construct and config conv layer.
      norm_cfg (:obj:`ConfigDict` or dict, optional): Dictionary to
          construct and config norm layer.
      init_cfg (:obj:`ConfigDict` or list[:obj:`ConfigDict`] or dict or
          list[dict], optional): Initialization config dict.
class_docstr_tok: ["YOLACT","box","head","used","in","https",":","\/\/arxiv.org\/abs\/1904.02689",".","Note","that","YOLACT","head","is","a","light","version","of","RetinaNet","head",".","Four","differences","are","described","as","follows",":","1",".","YOLACT","box","head","has","three-times","fewer","anchors",".","2",".","YOLACT","box","head","shares","the","convs","for","box","and","cls","branches",".","3",".","YOLACT","box","head","uses","OHEM","instead","of","Focal","loss",".","4",".","YOLACT","box","head","predicts","a","set","of","mask","coefficients","for","each","box",".","Args",":","num_classes","(","int",")",":","Number","of","categories","excluding","the","background","category",".","in_channels","(","int",")",":","Number","of","channels","in","the","input","feature","map",".","anchor_generator","(",":","obj",":","`","ConfigDict","`","or","dict",")",":","Config","dict","for","anchor","generator","loss_cls","(",":","obj",":","`","ConfigDict","`","or","dict",")",":","Config","of","classification","loss",".","loss_bbox","(",":","obj",":","`","ConfigDict","`","or","dict",")",":","Config","of","localization","loss",".","num_head_convs","(","int",")",":","Number","of","the","conv","layers","shared","by","box","and","cls","branches",".","num_protos","(","int",")",":","Number","of","the","mask","coefficients",".","use_ohem","(","bool",")",":","If","true",",","``","loss_single_OHEM","``","will","be","used","for","cls","loss","calculation",".","If","false",",","``","loss_single","``","will","be","used",".","conv_cfg","(",":","obj",":","`","ConfigDict","`","or","dict",",","optional",")",":","Dictionary","to","construct","and","config","conv","layer",".","norm_cfg","(",":","obj",":","`","ConfigDict","`","or","dict",",","optional",")",":","Dictionary","to","construct","and","config","norm","layer",".","init_cfg","(",":","obj",":","`","ConfigDict","`","or","list","[",":","obj",":","`","ConfigDict","`","]","or","dict","or","list","[","dict","]",",","optional",")",":","Initialization","config","dict","."]
docstr: Calculate the loss based on the features extracted by the bbox head.
  
  When ``self.use_ohem == True``, it functions like ``SSDHead.loss``,
  otherwise, it follows ``AnchorHead.loss``.
  
  Args:
      cls_scores (list[Tensor]): Box scores for each scale level
          has shape (N, num_anchors * num_classes, H, W).
      bbox_preds (list[Tensor]): Box energies / deltas for each scale
          level with shape (N, num_anchors * 4, H, W).
      coeff_preds (list[Tensor]): Mask coefficients for each scale
          level with shape (N, num_anchors * num_protos, H, W)
      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: A dictionary of loss components.
docstr_tok: ["Calculate","the","loss","based","on","the","features","extracted","by","the","bbox","head",".","When","``","self.use_ohem","==","True","``",",","it","functions","like","``","SSDHead.loss","``",",","otherwise",",","it","follows","``","AnchorHead.loss","``",".","Args",":","cls_scores","(","list","[","Tensor","]",")",":","Box","scores","for","each","scale","level","has","shape","(","N",",","num_anchors","*","num_classes",",","H",",","W",")",".","bbox_preds","(","list","[","Tensor","]",")",":","Box","energies","\/","deltas","for","each","scale","level","with","shape","(","N",",","num_anchors","*","4",",","H",",","W",")",".","coeff_preds","(","list","[","Tensor","]",")",":","Mask","coefficients","for","each","scale","level","with","shape","(","N",",","num_anchors","*","num_protos",",","H",",","W",")","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",":","A","dictionary","of","loss","components","."]
code: def loss_by_feat(
      self,
      cls_scores: List[Tensor],
      bbox_preds: List[Tensor],
      coeff_preds: List[Tensor],
      batch_gt_instances: InstanceList,
      batch_img_metas: List[dict],
      batch_gt_instances_ignore: OptInstanceList = None,
  ) -> dict:
      """Calculate the loss based on the features extracted by the bbox head.
  
      When ``self.use_ohem == True``, it functions like ``SSDHead.loss``,
      otherwise, it follows ``AnchorHead.loss``.
  
      Args:
          cls_scores (list[Tensor]): Box scores for each scale level
              has shape (N, num_anchors * num_classes, H, W).
          bbox_preds (list[Tensor]): Box energies / deltas for each scale
              level with shape (N, num_anchors * 4, H, W).
          coeff_preds (list[Tensor]): Mask coefficients for each scale
              level with shape (N, num_anchors * num_protos, H, W)
          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: A dictionary of loss components.
      """
      featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]
      assert len(featmap_sizes) == self.prior_generator.num_levels
  
      device = cls_scores[0].device
  
      anchor_list, valid_flag_list = self.get_anchors(
          featmap_sizes, batch_img_metas, device=device
      )
      cls_reg_targets = self.get_targets(
          anchor_list,
          valid_flag_list,
          batch_gt_instances,
          batch_img_metas,
          batch_gt_instances_ignore=batch_gt_instances_ignore,
          unmap_outputs=not self.use_ohem,
          return_sampling_results=True,
      )
      (
          labels_list,
          label_weights_list,
          bbox_targets_list,
          bbox_weights_list,
          avg_factor,
          sampling_results,
      ) = cls_reg_targets
  
      if self.use_ohem:
          num_images = len(batch_img_metas)
          all_cls_scores = torch.cat(
              [
                  s.permute(0, 2, 3, 1).reshape(
                      num_images, -1, self.cls_out_channels
                  )
                  for s in cls_scores
              ],
              1,
          )
          all_labels = torch.cat(labels_list, -1).view(num_images, -1)
          all_label_weights = torch.cat(label_weights_list, -1).view(
              num_images, -1
          )
          all_bbox_preds = torch.cat(
              [
                  b.permute(0, 2, 3, 1).reshape(num_images, -1, 4)
                  for b in bbox_preds
              ],
              -2,
          )
          all_bbox_targets = torch.cat(bbox_targets_list, -2).view(
              num_images, -1, 4
          )
          all_bbox_weights = torch.cat(bbox_weights_list, -2).view(
              num_images, -1, 4
          )
  
          # concat all level anchors to a single tensor
          all_anchors = []
          for i in range(num_images):
              all_anchors.append(torch.cat(anchor_list[i]))
  
          # check NaN and Inf
          assert (
              torch.isfinite(all_cls_scores).all().item()
          ), "classification scores become infinite or NaN!"
          assert (
              torch.isfinite(all_bbox_preds).all().item()
          ), "bbox predications become infinite or NaN!"
  
          losses_cls, losses_bbox = multi_apply(
              self.OHEMloss_by_feat_single,
              all_cls_scores,
              all_bbox_preds,
              all_anchors,
              all_labels,
              all_label_weights,
              all_bbox_targets,
              all_bbox_weights,
              avg_factor=avg_factor,
          )
      else:
          # anchor number of multi levels
          num_level_anchors = [
              anchors.size(0) for anchors in anchor_list[0]
          ]
          # concat all level anchors and flags to a single tensor
          concat_anchor_list = []
          for i in range(len(anchor_list)):
              concat_anchor_list.append(torch.cat(anchor_list[i]))
          all_anchor_list = images_to_levels(
              concat_anchor_list, num_level_anchors
          )
          losses_cls, losses_bbox = multi_apply(
              self.loss_by_feat_single,
              cls_scores,
              bbox_preds,
              all_anchor_list,
              labels_list,
              label_weights_list,
              bbox_targets_list,
              bbox_weights_list,
              avg_factor=avg_factor,
          )
      losses = dict(loss_cls=losses_cls, loss_bbox=losses_bbox)
      # update `_raw_positive_infos`, which will be used when calling
      # `get_positive_infos`.
      self._raw_positive_infos.update(coeff_preds=coeff_preds)
      return losses
  
imports: import copy
  from typing import List, Optional
  import numpy
  import torch
  import torch.nn
  import torch.nn.functional
  from mmcv.cnn import ConvModule
  from mmengine.model import BaseModule, ModuleList
  from mmengine.structures import InstanceData
  from torch import Tensor
  from mmdet.registry import MODELS
  from mmdet.utils import ConfigType, InstanceList, OptConfigType, OptInstanceList, OptMultiConfig
  from ..layers import fast_nms
  from ..utils import images_to_levels, multi_apply, select_single_mlvl
  from ..utils.misc import empty_instances
  from .anchor_head import AnchorHead
  from .base_mask_head import BaseMaskHead
label_desc: Use image node_id 4 for calling the YOLACTHead obj's underlying member method code with example usage: obj.loss_by_feat(cls_scores, bbox_preds, coeff_preds, batch_gt_instances, batch_img_metas, batch_gt_instances_ignore) and returns: losses