code: def save_model(
      name: Tag | str,
      checkpointables: Engine.DefaultPredictor | nn.Module,
      config: Config.CfgNode | None = None,
      *,
      signatures: ModelSignaturesType | None = None,
      labels: dict[str, str] | None = None,
      custom_objects: dict[str, t.Any] | None = None,
      external_modules: t.List[ModuleType] | None = None,
      metadata: dict[str, t.Any] | None = None,
  ) -> bentoml.Model:
      """
      Save a model instance to BentoML modelstore.
  
      Args:
          name: Name for given model instance. This should pass Python identifier check.
          checkpointables: The model instance to be saved. Could be a ``detectron2.engine.DefaultPredictor`` or a ``torch.nn.Module``.
          config: Optional ``CfgNode`` for the model. Required when checkpointables is a ``torch.nn.Module``.
          signatures: Methods to expose for running inference on the target model. Signatures are used for creating :obj:`~bentoml.Runner` instances when serving model with :obj:`~bentoml.Service`
          labels: User-defined labels for managing models, e.g. ``team=nlp``, ``stage=dev``.
          custom_objects: Custom objects to be saved with the model. An example is ``{"my-normalizer": normalizer}``.
                          Custom objects are currently serialized with cloudpickle, but this implementation is subject to change.
          external_modules: user-defined additional python modules to be saved alongside the model or custom objects,
                            e.g. a tokenizer module, preprocessor module, model configuration module
          metadata: Custom metadata for given model.
  
      Returns:
          :obj:`~bentoml.Tag`: A :obj:`tag` with a format ``name:version`` where ``name`` is the user-defined model's name, and a generated ``version``.
  
      Examples:
  
      .. tab-set::
  
         .. tab-item:: ModelZoo and CfgNode
  
            .. code-block:: python
  
                import bentoml
                import detectron2
                from detectron2 import model_zoo
                from detectron2.config import get_cfg
                from detectron2.modeling import build_model
  
                model_url = "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"
                cfg = get_cfg()
                cfg.merge_from_file(model_zoo.get_config_file(model_url))
                # set threshold for this model
                cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
                cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(model_url)
                cloned = cfg.clone()
                cloned.MODEL.DEVICE = "cpu"
  
                bento_model = bentoml.detectron2.save_model('mask_rcnn', build_model(cloned), config=cloned)
  
         .. tab-item:: Predictor
  
            .. code-block:: python
  
                import bentoml
                import detectron2
                from detectron2.engine import DefaultPredictor
                from detectron2 import model_zoo
                from detectron2.config import get_cfg
                from detectron2.modeling import build_model
  
                model_url = "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"
                cfg = get_cfg()
                cfg.merge_from_file(model_zoo.get_config_file(model_url))
                # set threshold for this model
                cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
                cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(model_url)
                cloned = cfg.clone()
                cloned.MODEL.DEVICE = "cpu"
  
                predictor = DefaultPredictor(cloned)
                bento_model = bentoml.detectron2.save_model('mask_rcnn', predictor)
      """  # noqa
      context = ModelContext(
          framework_name="detectron2",
          framework_versions={
              "detectron2": get_pkg_version("detectron2")
          },
      )
  
      if signatures is None:
          signatures = {"__call__": {"batchable": False}}
          logger.info(
              'Using the default model signature for Detectron (%s) for model "%s".',
              signatures,
              name,
          )
      if metadata is None:
          metadata = {}
  
      metadata["_is_predictor"] = isinstance(
          checkpointables, Engine.DefaultPredictor
      )
  
      if custom_objects is None:
          custom_objects = {}
  
      if isinstance(checkpointables, nn.Module):
          if config is None:
              raise ValueError(
                  "config is required when 'checkpointables' is a derived 'torch.nn.Module'."
              )
          model = checkpointables
          model.eval()
      else:
          model = checkpointables.model
          if config is not None:
              logger.warning(
                  "config is ignored when 'checkpointables' is a 'DefaultPredictor'."
              )
          config = t.cast(Config.CfgNode, checkpointables.cfg)
  
      custom_objects["config"] = config
  
      with bentoml.models.create(
          name,
          module=MODULE_NAME,
          api_version=API_VERSION,
          labels=labels,
          context=context,
          options=ModelOptions(),
          signatures=signatures,
          custom_objects=custom_objects,
          external_modules=external_modules,
          metadata=metadata,
      ) as bento_model:
          checkpointer = Checkpoint.Checkpointer(
              model, save_dir=bento_model.path
          )
          checkpointer.save(MODEL_FILENAME)
          return bento_model
  
imports: from __future__ import annotations
  import logging
  import typing
  from types import ModuleType
  import bentoml
  from ...exceptions import MissingDependencyException
  from ...exceptions import NotFound
  from ..models.model import Model
  from ..models.model import ModelContext
  from ..models.model import ModelSignature
  from ..models.model import PartialKwargsModelOptions
  from ..runner.utils import Params
  from ..tag import Tag
  from ..types import LazyType
  from ..utils import LazyLoader
  from ..utils.pkg import get_pkg_version
  from .common.pytorch import PyTorchTensorContainer
  from .common.pytorch import inference_mode_ctx
  from .common.pytorch import torch
label_desc: Use image node_id 3 for calling a global function with example usage: save_model(name, checkpointables, config) and returns: bento_model