code: def load(
      prog: Program,
      weights_dir: str,
      resume_on_errors: Optional[bool] = False,
      specification_version: Optional[
          int
      ] = _SPECIFICATION_VERSION_IOS_15,
      **kwargs,
  ):
      if "main" not in prog.functions:
          raise ValueError("main function not found in program")
  
      # if user has specified "ClassifierConfig", then add the "classify" op to the prog
      classifier_config = kwargs.get("classifier_config", None)
      predicted_feature_name = None
      predicted_probabilities_name = None
      if classifier_config is not None:
          (
              predicted_feature_name,
              predicted_probabilities_name,
          ) = _add_classify_op(prog, classifier_config)
  
      # convert pymil program into mil proto
      proto = _pymil_to_milproto(
          prog, weights_dir, specification_version
      )
  
      input_types = prog.main_input_types
      output_types = prog.main_output_types
  
      desc = kwargs.get("model_description", None)
      if desc and not isinstance(desc, ml.ModelDescription):
          raise ValueError("Invalid model descriptor")
  
      if desc:
          if classifier_config is not None:
              raise AssertionError(
                  "Both model_description and classifier_config can't be provided"
              )
          model = ml.Model(
              description=desc,
              specificationVersion=specification_version,
          )
          model.mlProgram.CopyFrom(proto)
          return model
  
      input_features = []
      output_features = []
      symbolic_inputs = []
      image_input_names = (
          {}
      )  # these are the model inputs marked as image by the user
      input_shape_map = {}
  
      for input_type in input_types:
          if isinstance(input_type, ImageType):
              image_input_names[input_type.name] = input_type
              # error checking for input(s) marked as images
              if input_type.name not in list(
                  prog.functions["main"].inputs.keys()
              ):
                  raise ValueError(
                      f"Provided image input '{input_type.name}' is not one of the inputs of the MIL program"
                  )
          if input_type.name is None:
              raise ValueError(
                  'Fail to auto-determine the input name. Please specify the "name" '
                  'parameter when use "inputs" in ct.convert().'
              )
          input_shape_map[input_type.name] = input_type
  
      for name, var in prog.functions["main"].inputs.items():
          input_feature_type = ft.FeatureType()
  
          # error checking for input(s) marked as images
          # an image input must be of type tensor in program proto
          # (since an image type does not exist in MIL program)
          if name in image_input_names and not types.is_tensor(
              var.sym_type
          ):
              raise ValueError(
                  "For the image input, '{}', its type in the MIL program must be tensor. "
                  "Instead it is {}.".format(
                      name, var.sym_type.__type_info__()
                  )
              )
  
          if types.is_tensor(var.sym_type):
              shape = var.sym_type.get_shape()
              if any_variadic(shape):
                  raise ValueError(
                      "Variable rank model inputs are not supported!"
                  )
              if any_symbolic(shape):
                  symbolic_inputs.append(name)
                  # We extract the default input shape given by user first
                  if name in input_shape_map:
                      shape = input_shape_map[name].shape.default
                  else:
                      logger.warning(
                          "Input shape not fully specified by enumerated shapes or range dim! 1 will be used for dimension not specified instead."
                      )
                  # If no input shape is provided (ex. auto conversion of -1 in Tensorflow)
                  shape = [1 if is_symbolic(d) else d for d in shape]
  
              if name not in image_input_names:
                  # make a feature type of Type "multiArrayType"
                  array_type = ft.ArrayFeatureType(
                      shape=shape,
                      dataType=cast_to_framework_io_dtype(var, False),
                  )
                  input_feature_type.multiArrayType.CopyFrom(array_type)
              else:
                  # make a feature type of Type "imageType"
                  input_type = image_input_names[name]
                  _validate_image_input_output_shapes(
                      input_type.color_layout,
                      shape,
                      name,
                      is_input=True,
                  )
                  if not input_type.channel_first:
                      raise ValueError(
                          "Image input, '{}', must be in the channel_first format".format(
                              name
                          )
                      )
                  clr_space = _get_colorspace_enum(
                      input_type.color_layout
                  )
                  image_type = ft.ImageFeatureType(
                      width=shape[-1],
                      height=shape[-2],
                      colorSpace=clr_space,
                  )
                  input_feature_type.imageType.CopyFrom(image_type)
  
              input_features.append(
                  ml.FeatureDescription(
                      name=name, type=input_feature_type
                  )
              )
          elif types.is_scalar(var.sym_type):
              array_type = ft.ArrayFeatureType(
                  shape=[1],
                  dataType=cast_to_framework_io_dtype(var, False),
              )
              input_feature_type.multiArrayType.CopyFrom(array_type)
              input_features.append(
                  ml.FeatureDescription(
                      name=var.name, type=input_feature_type
                  )
              )
          else:
              raise NotImplementedError()
  
      if output_types is not None and classifier_config is None:
          assert len(output_types) == len(
              prog.functions["main"].outputs
          ), "number of mil program outputs do not match the number of outputs provided by the user"
  
      for i, var in enumerate(prog.functions["main"].outputs):
          output_feature_type = ft.FeatureType()
          if types.is_tensor(var.sym_type) or types.is_primitive(
              var.sym_type
          ):
              if output_types is not None and isinstance(
                  output_types[i], ImageType
              ):
                  if not types.is_tensor(var.sym_type):
                      raise ValueError(
                          "Image output, '{}', is a scalar, but it should be a tensor of rank 4".format(
                              var.name
                          )
                      )
                  shape = var.sym_type.get_shape()
                  if any_variadic(shape):
                      raise ValueError(
                          "Variable rank model outputs, that are ImageTypes, are not supported"
                      )
                  if any([is_symbolic(d) for d in shape]):
                      raise NotImplementedError(
                          "Image output '{}' has symbolic dimensions in its shape".format(
                              var.name
                          )
                      )
                  _validate_image_input_output_shapes(
                      output_types[i].color_layout,
                      shape,
                      var.name,
                      is_input=False,
                  )
                  clr_space = _get_colorspace_enum(
                      output_types[i].color_layout
                  )
                  image_type = ft.ImageFeatureType(
                      width=shape[-1],
                      height=shape[-2],
                      colorSpace=clr_space,
                  )
                  output_feature_type.imageType.CopyFrom(image_type)
                  output_features.append(
                      ml.FeatureDescription(
                          name=var.name, type=output_feature_type
                      )
                  )
              else:
                  dataType = None
                  if (
                      classifier_config is None
                      or var.name != predicted_feature_name
                  ):
                      # Not a classifier output, make sure model output type matches with ML Program type.
                      dataType = cast_to_framework_io_dtype(var, True)
                  else:
                      # Classifier outputs are set up separately, so default to fp32 for now.
                      dataType = (
                          ft.ArrayFeatureType.ArrayDataType.FLOAT32
                      )
  
                  output_shape = (
                      None
                      if any_symbolic(var.shape)
                      or types.is_primitive(var.sym_type)
                      else var.shape
                  )
                  array_type = ft.ArrayFeatureType(
                      shape=output_shape, dataType=dataType
                  )
                  output_feature_type.multiArrayType.CopyFrom(
                      array_type
                  )
                  output_features.append(
                      ml.FeatureDescription(
                          name=var.name, type=output_feature_type
                      )
                  )
          elif types.is_dict(var.sym_type):
              output_feature_type.dictionaryType.MergeFromString(b"")
              keytype, valtype = var.sym_type.T
              if types.is_str(keytype):
                  output_feature_type.dictionaryType.stringKeyType.MergeFromString(
                      b""
                  )
              elif keytype == types.int64:
                  output_feature_type.dictionaryType.int64KeyType.MergeFromString(
                      b""
                  )
              else:
                  raise ValueError("Dictionary key type not supported.")
              output_features.append(
                  ml.FeatureDescription(
                      name=var.name, type=output_feature_type
                  )
              )
          else:
              raise NotImplementedError()
  
      # Model description
      desc = ml.ModelDescription(
          input=input_features, output=output_features
      )
      if classifier_config is not None:
          desc.predictedFeatureName = predicted_feature_name
          desc.predictedProbabilitiesName = predicted_probabilities_name
  
          # Manually edit output type of predictedFeatureName.
          # It doesn't use MLMultiArray and really uses a "primitive" type.
          for output in desc.output:
              if output.name == predicted_feature_name:
                  if type(classifier_config.class_labels[0]) == int:
                      output.type.int64Type.MergeFromString(b"")
                  else:
                      output.type.stringType.MergeFromString(b"")
                  break
  
      # Create ML Model
      model = ml.Model(
          description=desc, specificationVersion=specification_version
      )
      model.mlProgram.CopyFrom(proto)
  
      # Set symbolic shapes
      default_lower_bound = 1
      default_upper_bound = (
          default_lower_bound + 1
          if kwargs.get("convert_to", None) == "mlprogram"
          else -1
      )
      default_bound_used = False
      for input_name in symbolic_inputs:
          input_type = input_shape_map.get(input_name, None)
  
          if isinstance(input_type, ImageType):
              if isinstance(input_type.shape, EnumeratedShapes):
                  enumerated_shapes = []
                  for s in input_type.shape.shapes:
                      enumerated_shapes.append(
                          NeuralNetworkImageSize(
                              height=s.shape[-2], width=s.shape[-1]
                          )
                      )
                  add_enumerated_image_sizes(
                      model, input_name, sizes=enumerated_shapes
                  )
              else:
                  img_range = NeuralNetworkImageSizeRange()
                  H = input_type.shape.shape[-2]
                  W = input_type.shape.shape[-1]
  
                  if isinstance(H, RangeDim):
                      img_range.add_height_range(
                          (H.lower_bound, H.upper_bound)
                      )
                  elif is_symbolic(H):
                      img_range.add_height_range(
                          (default_lower_bound, default_upper_bound)
                      )
                      default_bound_used = True
                  else:
                      img_range.add_height_range((H, H))
                  if isinstance(W, RangeDim):
                      img_range.add_width_range(
                          (W.lower_bound, W.upper_bound)
                      )
                  elif is_symbolic(W):
                      img_range.add_width_range(
                          (default_lower_bound, default_upper_bound)
                      )
                      default_bound_used = True
                  else:
                      img_range.add_width_range((W, W))
  
                  update_image_size_range(model, input_name, img_range)
          elif isinstance(input_type, TensorType):
              if isinstance(input_type.shape, EnumeratedShapes):
                  add_multiarray_ndshape_enumeration(
                      model,
                      input_name,
                      [tuple(s.shape) for s in input_type.shape.shapes],
                  )
              else:
                  lb = []
                  ub = []
                  for s in input_type.shape.shape:
                      if isinstance(s, RangeDim):
                          lb.append(s.lower_bound)
                          ub.append(s.upper_bound)
                      elif is_symbolic(s):
                          lb.append(default_lower_bound)
                          ub.append(default_upper_bound)
                          default_bound_used = True
                      else:
                          lb.append(s)
                          ub.append(s)
                  set_multiarray_ndshape_range(
                      model,
                      input_name,
                      lower_bounds=lb,
                      upper_bounds=ub,
                  )
          elif input_type is None:
              sym_type = (
                  prog.functions["main"].inputs[input_name].sym_type
              )
              lb = []
              ub = []
              for s in sym_type.get_shape():
                  if is_symbolic(s):
                      lb.append(default_lower_bound)
                      ub.append(default_upper_bound)
                      default_bound_used = True
                  else:
                      lb.append(s)
                      ub.append(s)
              set_multiarray_ndshape_range(
                  model, input_name, lower_bounds=lb, upper_bounds=ub
              )
  
      if (
          default_bound_used
          and kwargs.get("convert_to", None) == "mlprogram"
      ):
          warnings.warn(
              "Some dimensions in the input shape are unknown, hence they are set to flexible ranges "
              f"with lower bound and default value = {default_lower_bound}, and upper bound = "
              f"{default_upper_bound}. To set different values for the default shape and upper bound, "
              "please use the ct.RangeDim() method as described here: "
              "https://coremltools.readme.io/docs/flexible-inputs#set-the-range-for-each-dimension.",
              UserWarning,
          )
          convert_from = kwargs.get("convert_from", None)
          if convert_from is not None and convert_from.startswith(
              "tensorflow"
          ):
              warnings.warn(
                  'There is "None" dim in TF input placeholder. Please consider specifying '
                  'input shapes by using the "inputs" param in ct.convert().'
              )
  
      # Set optional inputs
      _set_optional_inputs(model, input_types)
  
      return model
  
imports: import os
  import warnings
  from typing import Optional
  import numpy
  from coremltools import _OPSET, _SPECIFICATION_VERSION_IOS_15
  from coremltools import _logger
  from coremltools.converters.mil.backend.backend_helper import _get_probability_var_for_classifier
  from coremltools.converters.mil.backend.mil.helper import cast_to_framework_io_dtype, create_file_value, create_immediate_value, create_list_scalarvalue, create_scalar_value, types_to_proto
  from coremltools.converters.mil.backend.nn.load import _set_optional_inputs
  from coremltools.converters.mil.input_types import EnumeratedShapes, ImageType, RangeDim, TensorType
  from coremltools.converters.mil.mil import Builder
  from coremltools.converters.mil.mil import Function, Program, mil_list, types
  from coremltools.converters.mil.mil.ops.registry import SSAOpRegistry
  from coremltools.converters.mil.mil.types.symbolic import any_symbolic, any_variadic, is_symbolic
  from coremltools.models.neural_network.flexible_shape_utils import NeuralNetworkImageSize, NeuralNetworkImageSizeRange, add_enumerated_image_sizes, add_multiarray_ndshape_enumeration, set_multiarray_ndshape_range, update_image_size_range
  from coremltools.models.utils import _WEIGHTS_FILE_NAME
  from coremltools.proto import FeatureTypes_pb2
  from coremltools.proto import MIL_pb2
  from coremltools.proto import Model_pb2
  from ..backend_helper import _get_colorspace_enum, _validate_image_input_output_shapes
label_desc: Use image node_id 9 for calling a global function with example usage: load(prog, weights_dir, resume_on_errors, specification_version) and returns: model, model