class_docstr: This class implements a `Mask RCNN style object detector <https://arxiv.org/abs/1703.06870>`
  
  Args:
      opts: command-line arguments
      encoder (BaseImageEncoder): Encoder network (e.g., ResNet or MobileViT)
class_docstr_tok: ["This","class","implements","a","`","Mask","RCNN","style","object","detector","<","https",":","\/\/arxiv.org\/abs\/1703.06870",">","`","Args",":","opts",":","command-line","arguments","encoder","(","BaseImageEncoder",")",":","Encoder","network","(","e.g.",",","ResNet","or","MobileViT",")"]
code: def __init__(
      self, opts, encoder: BaseImageEncoder, *args, **kwargs
  ) -> None:
      super().__init__(opts, encoder, *args, **kwargs)
      default_norm = self.set_norm_layer_opts()
  
      output_strides = getattr(
          opts,
          "model.detection.mask_rcnn.output_strides",
          [4, 8, 16, 32, 64],
      )
      if len(output_strides) == 0:
          logger.error(
              "Please specify output strides for extracting backbone feature maps "
              "using --model.detection.mask-rcnn.output-strides"
          )
      output_strides = sorted(output_strides)
      projection_channels = getattr(
          opts,
          "model.detection.mask_rcnn.backbone_projection_channels",
          256,
      )
  
      # anchor sizes and aspect ratios
      anchor_sizes = getattr(
          opts,
          "model.detection.mask_rcnn.anchor_sizes",
          [32, 64, 128, 256, 512],
      )
      # convert to a tuples
      if anchor_sizes is None:
          logger.error("Anchor sizes can't be None")
      elif len(anchor_sizes) != len(output_strides):
          logger.error(
              "Number of anchor sizes should be the same as the output stride. Got: {} and {}".format(
                  anchor_sizes, output_strides
              )
          )
      elif isinstance(anchor_sizes, List) and isinstance(
          anchor_sizes[0], List
      ):
          # anchor sizes is a list of list. Convert to tuple
          anchor_sizes = tuple(
              [tuple(a_size) for a_size in anchor_sizes]
          )
      elif isinstance(anchor_sizes, List) and isinstance(
          anchor_sizes[0], int
      ):
          # anchor sizes is a list of integers. Convert to tuple
          anchor_sizes = tuple([(a_size,) for a_size in anchor_sizes])
      else:
          raise NotImplementedError
  
      aspect_ratios = getattr(
          opts,
          "model.detection.mask_rcnn.aspect_ratio",
          [0.5, 1.0, 2.0],
      )  # ((0.5, 1.0, 2.0),) * len(anchor_sizes)
      if aspect_ratios is None:
          logger.error("Aspect ratios can't be None")
      elif isinstance(aspect_ratios, (int, float)):
          aspect_ratios = ((aspect_ratios,),) * len(anchor_sizes)
      elif isinstance(aspect_ratios, List):
          aspect_ratios = (tuple(aspect_ratios),) * len(anchor_sizes)
      else:
          raise NotImplementedError
  
      # feature map size for the bbox head
      box_fm_size = getattr(
          opts, "model.detection.mask_rcnn.bbox_head_fm_size", 7
      )
      mask_fm_size = getattr(
          opts, "model.detection.mask_rcnn.mask_head_fm_size", 14
      )
  
      # set-up the backbone
      backbone_lr_multiplier = getattr(
          opts, "model.detection.mask_rcnn.backbone_lr_multiplier"
      )
      backbone = MaskRCNNEncoder(
          opts,
          encoder=encoder,
          output_strides=output_strides,
          projection_channels=projection_channels,
          encoder_lr_multiplier=backbone_lr_multiplier,
      )
  
      # create RPN anchor generator
      rpn_anchor_generator = AnchorGenerator(
          sizes=anchor_sizes, aspect_ratios=aspect_ratios
      )
  
      # create RPN Head
      rpn_head = RPNHead(
          opts=opts,
          in_channels=projection_channels,
          num_anchors=rpn_anchor_generator.num_anchors_per_location()[
              0
          ],
          conv_depth=2,
      )
  
      # box related parameters
      representation_size = getattr(
          opts, "model.detection.mask_rcnn.representation_size", 1024
      )
      output_strides_str = [str(os) for os in output_strides]
      box_roi_pool = MultiScaleRoIAlign(
          featmap_names=output_strides_str,
          output_size=box_fm_size,
          sampling_ratio=2,
      )
  
      box_fm_size_conv_layer = getattr(
          opts,
          "model.detection.mask_rcnn.box_fm_size_conv_layer",
          [256] * 4,
      )
      box_head = FastRCNNConvFCHead(
          opts=opts,
          input_size=(projection_channels, box_fm_size, box_fm_size),
          conv_layers=box_fm_size_conv_layer,
          fc_layers=[representation_size],
      )
  
      box_predictor = FastRCNNPredictor(
          in_channels=representation_size,
          num_classes=self.n_detection_classes,
      )
  
      # mask related parameters
      mask_fm_size_conv_layer = getattr(
          opts,
          "model.detection.mask_rcnn.mask_fm_size_conv_layer",
          [256] * 4,
      )
      mask_dilation = getattr(
          opts, "model.detection.mask_rcnn.mask_dilation", 1
      )
      mask_roi_pool = MultiScaleRoIAlign(
          featmap_names=output_strides_str,
          output_size=mask_fm_size,
          sampling_ratio=2,
      )
  
      mask_dilation = mask_dilation
      mask_head = MaskRCNNHeads(
          opts=opts,
          in_channels=projection_channels,
          layers=mask_fm_size_conv_layer,
          dilation=mask_dilation,
      )
  
      mask_predictor = MaskRCNNPredictor(
          opts=opts,
          in_channels=mask_fm_size_conv_layer[-1],
          dim_reduced=256,
          num_classes=self.n_detection_classes,
      )
  
      # RPN and box detection related hyper-parameters
      rpn_pre_nms_top_n_train = getattr(
          opts,
          "model.detection.mask_rcnn.rpn_pre_nms_top_n_train",
          2000,
      )
      rpn_pre_nms_top_n_test = getattr(
          opts, "model.detection.mask_rcnn.rpn_pre_nms_top_n_test", 1000
      )
      rpn_post_nms_top_n_train = getattr(
          opts,
          "model.detection.mask_rcnn.rpn_post_nms_top_n_train",
          2000,
      )
      rpn_post_nms_top_n_test = getattr(
          opts,
          "model.detection.mask_rcnn.rpn_post_nms_top_n_test",
          1000,
      )
      rpn_nms_thresh = getattr(
          opts, "model.detection.mask_rcnn.rpn_nms_thresh", 0.7
      )
      rpn_fg_iou_thresh = getattr(
          opts, "model.detection.mask_rcnn.rpn_fg_iou_thresh", 0.7
      )
      rpn_bg_iou_thresh = getattr(
          opts, "model.detection.mask_rcnn.rpn_bg_iou_thresh", 0.3
      )
      rpn_batch_size_per_image = getattr(
          opts,
          "model.detection.mask_rcnn.rpn_batch_size_per_image",
          256,
      )
      rpn_positive_fraction = getattr(
          opts, "model.detection.mask_rcnn.rpn_positive_fraction", 0.5
      )
      rpn_score_thresh = getattr(
          opts, "model.detection.mask_rcnn.rpn_score_thresh", 0.0
      )
  
      box_score_thresh = getattr(
          opts, "model.detection.mask_rcnn.box_score_thresh", 0.05
      )
      box_nms_thresh = getattr(
          opts, "model.detection.mask_rcnn.box_nms_thresh", 0.5
      )
      box_detections_per_img = getattr(
          opts, "model.detection.mask_rcnn.box_detections_per_img", 100
      )
      box_fg_iou_thresh = getattr(
          opts, "model.detection.mask_rcnn.box_fg_iou_thresh", 0.5
      )
      box_bg_iou_thresh = getattr(
          opts, "model.detection.mask_rcnn.box_bg_iou_thresh", 0.5
      )
      box_batch_size_per_image = getattr(
          opts,
          "model.detection.mask_rcnn.box_batch_size_per_image",
          512,
      )
      box_positive_fraction = getattr(
          opts, "model.detection.mask_rcnn.box_positive_fraction", 0.25
      )
  
      # kwargs = {"_skip_resize": True}
      self.model = MaskRCNN(
          backbone=backbone,
          # num_classes=None, #self.n_detection_classes,
          # In CVNets, we don't use mean-std normalization
          image_mean=[0.0] * 3,
          image_std=[1.0] * 3,
          # RPN parameters
          rpn_anchor_generator=rpn_anchor_generator,
          rpn_head=rpn_head,
          rpn_pre_nms_top_n_train=rpn_pre_nms_top_n_train,
          rpn_pre_nms_top_n_test=rpn_pre_nms_top_n_test,
          rpn_post_nms_top_n_train=rpn_post_nms_top_n_train,
          rpn_post_nms_top_n_test=rpn_post_nms_top_n_test,
          rpn_nms_thresh=rpn_nms_thresh,
          rpn_fg_iou_thresh=rpn_fg_iou_thresh,
          rpn_bg_iou_thresh=rpn_bg_iou_thresh,
          rpn_batch_size_per_image=rpn_batch_size_per_image,
          rpn_positive_fraction=rpn_positive_fraction,
          rpn_score_thresh=rpn_score_thresh,
          # Box parameters
          box_roi_pool=box_roi_pool,
          box_head=box_head,
          box_score_thresh=box_score_thresh,
          box_nms_thresh=box_nms_thresh,
          box_detections_per_img=box_detections_per_img,
          box_fg_iou_thresh=box_fg_iou_thresh,
          box_bg_iou_thresh=box_bg_iou_thresh,
          box_batch_size_per_image=box_batch_size_per_image,
          box_positive_fraction=box_positive_fraction,
          bbox_reg_weights=None,
          box_predictor=box_predictor,
          # Mask parameters
          mask_roi_pool=mask_roi_pool,
          mask_head=mask_head,
          mask_predictor=mask_predictor
          # **kwargs
      )
  
      del self.encoder
  
      self.reset_norm_layer_opts(default_norm=default_norm)
      self.update_layer_norm_eps()
  
imports: import argparse
  from typing import Any, Dict, List, Optional, Tuple, Union
  import torch
  from torch import Tensor, nn
  from torch.nn import functional
  from torchvision.models.detection.anchor_utils import AnchorGenerator
  from torchvision.models.detection.mask_rcnn import MaskRCNN
  from torchvision.ops import MultiScaleRoIAlign
  from cvnets import parameter_list
  from cvnets.layers import ConvLayer2d, Identity
  from cvnets.models import MODEL_REGISTRY
  from cvnets.models.classification.base_image_encoder import BaseImageEncoder
  from cvnets.models.detection import DetectionPredTuple
  from cvnets.models.detection.base_detection import BaseDetection
  from cvnets.models.detection.utils.rcnn_utils import FastRCNNConvFCHead, FastRCNNPredictor, MaskRCNNHeads, MaskRCNNPredictor, RPNHead
  from utils import logger
label_desc: Use image node_id 1 to create a new MaskRCNNDetector object from inherited base classes: BaseDetection with example: obj = MaskRCNNDetector(opts, encoder)