PyTorch

PyTorch Estimator

class sagemaker.pytorch.estimator.PyTorch(entry_point, framework_version=None, py_version=None, source_dir=None, hyperparameters=None, image_uri=None, distribution=None, compiler_config=None, **kwargs)

Bases: Framework

Handle end-to-end training and deployment of custom PyTorch code.

This Estimator executes a PyTorch script in a managed PyTorch execution environment.

The managed PyTorch environment is an Amazon-built Docker container that executes functions defined in the supplied entry_point Python script within a SageMaker Training Job.

Training is started by calling fit() on this Estimator. After training is complete, calling deploy() creates a hosted SageMaker endpoint and returns an PyTorchPredictor instance that can be used to perform inference against the hosted model.

Technical documentation on preparing PyTorch scripts for SageMaker training and using the PyTorch Estimator is available on the project home-page: https://github.com/aws/sagemaker-python-sdk

Parameters
  • entry_point (str or PipelineVariable) – Path (absolute or relative) to the Python source file which should be executed as the entry point to training. If source_dir is specified, then entry_point must point to a file located at the root of source_dir.

  • framework_version (str) – PyTorch version you want to use for executing your model training code. Defaults to None. Required unless image_uri is provided. List of supported versions: https://github.com/aws/deep-learning-containers/blob/master/available_images.md.

  • py_version (str) – Python version you want to use for executing your model training code. One of ‘py2’ or ‘py3’. Defaults to None. Required unless image_uri is provided.

  • source_dir (str or PipelineVariable) – Path (absolute, relative or an S3 URI) to a directory with any other training source code dependencies aside from the entry point file (default: None). If source_dir is an S3 URI, it must point to a tar.gz file. Structure within this directory are preserved when training on Amazon SageMaker.

  • hyperparameters (dict[str, str] or dict[str, PipelineVariable]) – Hyperparameters that will be used for training (default: None). The hyperparameters are made accessible as a dict[str, str] to the training code on SageMaker. For convenience, this accepts other types for keys and values, but str() will be called to convert them before training.

  • image_uri (str or PipelineVariable) –

    If specified, the estimator will use this image for training and hosting, instead of selecting the appropriate SageMaker official image based on framework_version and py_version. It can be an ECR url or dockerhub image and tag. .. rubric:: Examples

    • 123412341234.dkr.ecr.us-west-2.amazonaws.com/my-custom-image:1.0

    • custom-image:latest

    If framework_version or py_version are None, then image_uri is required. If also None, then a ValueError will be raised.

  • distribution (dict) –

    A dictionary with information on how to configure and run distributed training (default: None). The following options are available.

    To enable the SageMaker distributed data parallelism (SMDDP) library:

    { "smdistributed": { "dataparallel": { "enabled": True } } }
    

    Beside activating the SMDDP library through this parameter, you also need to add few lines of code in your training script for initializing PyTorch Distributed with the SMDDP setups. To learn how to configure your training job with the SMDDP library v2, see Run distributed training with the SageMaker distributed data parallelism library in the Amazon SageMaker User Guide.

    To enable the SageMaker distributed model parallelism (SMP) library v2:

    {
        "torch_distributed": { "enabled": True },
        "smdistributed": {
            "modelparallel": {
                "enabled": True,
                "parameters": {
                    "tensor_parallel_degree": 8,
                    "hybrid_shard_degree": 1,
                    ...
                },
            }
        },
    }
    

    Beside activating the SMP library v2 through this parameter, you also need to add few lines of code in your training script for initializing PyTorch Distributed with the SMP setups. To learn how to configure your training job with the SMP library v2, see Run distributed training with the SageMaker model parallelism library v2 in the Amazon SageMaker User Guide.

    Note

    The SageMaker distributed model parallel library v2 requires with torch_distributed.

    Note

    The documentation for the SMP library v1.x is archived and available at Run distributed training with the SageMaker model parallelism library in the Amazon SageMaker User Guide, and the SMP v1 API reference is available in the SageMaker Python SDK v2.199.0 documentation.

    To enable PyTorch DDP:

    {
        "pytorchddp": {
            "enabled": True
        }
    }
    

    To learn more, see Distributed PyTorch Training.

    To enable Torch Distributed:

    This is available for general distributed training on GPU instances from PyTorch v1.13.1 and later.

    {
        "torch_distributed": {
            "enabled": True
        }
    }
    

    This option also supports distributed training on Trn1. To learn more, see Distributed PyTorch Training on Trainium.

    To enable MPI:

    {
        "mpi": {
            "enabled": True
        }
    }
    

    To learn more, see Training with Horovod.

    To enable parameter server:

    {
        "parameter_server": {
            "enabled": True
        }
    }
    

    To learn more, see Training with parameter servers.

    To enable distributed training with SageMaker Training Compiler:

    {
        "pytorchxla": {
            "enabled": True
        }
    }
    

    To learn more, see SageMaker Training Compiler in the Amazon SageMaker Developer Guide.

    Note

    When you use this PyTorch XLA option for distributed training strategy, you must add the compiler_config parameter and activate SageMaker Training Compiler.

    compiler_config (TrainingCompilerConfig): Configures SageMaker Training Compiler to accelerate training.

  • **kwargs – Additional kwargs passed to the Framework constructor.

  • compiler_config (Optional[TrainingCompilerConfig]) –

Tip

You can find additional parameters for initializing this class at Framework and EstimatorBase.

LAUNCH_PYTORCH_DDP_ENV_NAME = 'sagemaker_pytorch_ddp_enabled'
LAUNCH_TORCH_DISTRIBUTED_ENV_NAME = 'sagemaker_torch_distributed_enabled'
INSTANCE_TYPE_ENV_NAME = 'sagemaker_instance_type'
hyperparameters()

Return hyperparameters used by your custom PyTorch code during model training.

create_model(model_server_workers=None, role=None, vpc_config_override='VPC_CONFIG_DEFAULT', entry_point=None, source_dir=None, dependencies=None, **kwargs)

Create a SageMaker PyTorchModel object that can be deployed to an Endpoint.

Parameters
  • model_server_workers (int) – Optional. The number of worker processes used by the inference server. If None, server will use one worker per vCPU.

  • role (str) – The ExecutionRoleArn IAM Role ARN for the Model, which is also used during transform jobs. If not specified, the role from the Estimator will be used.

  • vpc_config_override (dict[str, list[str]]) – Optional override for VpcConfig set on the model. Default: use subnets and security groups from this Estimator. * ‘Subnets’ (list[str]): List of subnet ids. * ‘SecurityGroupIds’ (list[str]): List of security group ids.

  • entry_point (str) – Path (absolute or relative) to the local Python source file which should be executed as the entry point to training. If source_dir is specified, then entry_point must point to a file located at the root of source_dir. If not specified, the training entry point is used.

  • source_dir (str) – Path (absolute or relative) to a directory with any other serving source code dependencies aside from the entry point file. If not specified, the model source directory from training is used.

  • dependencies (list[str]) – A list of paths to directories (absolute or relative) with any additional libraries that will be exported to the container. If not specified, the dependencies from training are used. This is not supported with “local code” in Local Mode.

  • **kwargs – Additional kwargs passed to the PyTorchModel constructor.

Returns

A SageMaker PyTorchModel object. See PyTorchModel() for full details.

Return type

sagemaker.pytorch.model.PyTorchModel

uploaded_code: Optional[UploadedCode]

PyTorch Model

class sagemaker.pytorch.model.PyTorchModel(model_data, role=None, entry_point=None, framework_version='1.3', py_version=None, image_uri=None, predictor_cls=<class 'sagemaker.pytorch.model.PyTorchPredictor'>, model_server_workers=None, **kwargs)

Bases: FrameworkModel

An PyTorch SageMaker Model that can be deployed to a SageMaker Endpoint.

Initialize a PyTorchModel.

Parameters
  • model_data (str or PipelineVariable) – The S3 location of a SageMaker model data .tar.gz file.

  • role (str) – An AWS IAM role (either name or full ARN). The Amazon SageMaker training jobs and APIs that create Amazon SageMaker endpoints use this role to access training data and model artifacts. After the endpoint is created, the inference code might use the IAM role, if it needs to access an AWS resource.

  • entry_point (str) – Path (absolute or relative) to the Python source file which should be executed as the entry point to model hosting. If source_dir is specified, then entry_point must point to a file located at the root of source_dir.

  • framework_version (str) – PyTorch version you want to use for executing your model training code. Defaults to 1.3. Required unless image_uri is provided.

  • py_version (str) – Python version you want to use for executing your model training code. Defaults to None. Required unless image_uri is provided.

  • image_uri (str or PipelineVariable) – A Docker image URI (default: None). If not specified, a default image for PyTorch will be used. If framework_version or py_version are None, then image_uri is required. If image_uri is also None, then a ValueError will be raised.

  • predictor_cls (callable[str, sagemaker.session.Session]) – A function to call to create a predictor with an endpoint name and SageMaker Session. If specified, deploy() returns the result of invoking this function on the created endpoint name.

  • model_server_workers (int or PipelineVariable) – Optional. The number of worker processes used by the TorchServe model server. If None, available GPUs in system or number of logical processors available to the JVM.

  • **kwargs – Keyword arguments passed to the superclass FrameworkModel and, subsequently, its superclass Model.

Tip

You can find additional parameters for initializing this class at FrameworkModel and Model.

register(content_types=None, response_types=None, inference_instances=None, transform_instances=None, model_package_name=None, model_package_group_name=None, image_uri=None, model_metrics=None, metadata_properties=None, marketplace_cert=False, approval_status=None, description=None, drift_check_baselines=None, customer_metadata_properties=None, domain=None, sample_payload_url=None, task=None, framework=None, framework_version=None, nearest_model_name=None, data_input_configuration=None, skip_model_validation=None, source_uri=None, model_card=None)

Creates a model package for creating SageMaker models or listing on Marketplace.

Parameters
  • content_types (list[str] or list[PipelineVariable]) – The supported MIME types for the input data.

  • response_types (list[str] or list[PipelineVariable]) – The supported MIME types for the output data.

  • inference_instances (list[str] or list[PipelineVariable]) – A list of the instance types that are used to generate inferences in real-time (default: None).

  • transform_instances (list[str] or list[PipelineVariable]) – A list of the instance types on which a transformation job can be run or on which an endpoint can be deployed (default: None).

  • model_package_name (str or PipelineVariable) – Model Package name, exclusive to model_package_group_name, using model_package_name makes the Model Package un-versioned (default: None).

  • model_package_group_name (str or PipelineVariable) – Model Package Group name, exclusive to model_package_name, using model_package_group_name makes the Model Package versioned (default: None).

  • image_uri (str or PipelineVariable) – Inference image uri for the container. Model class’ self.image will be used if it is None (default: None).

  • model_metrics (ModelMetrics) – ModelMetrics object (default: None).

  • metadata_properties (MetadataProperties) – MetadataProperties object (default: None).

  • marketplace_cert (bool) – A boolean value indicating if the Model Package is certified for AWS Marketplace (default: False).

  • approval_status (str or PipelineVariable) – Model Approval Status, values can be “Approved”, “Rejected”, or “PendingManualApproval” (default: “PendingManualApproval”).

  • description (str) – Model Package description (default: None).

  • drift_check_baselines (DriftCheckBaselines) – DriftCheckBaselines object (default: None).

  • customer_metadata_properties (dict[str, str] or dict[str, PipelineVariable]) – A dictionary of key-value paired metadata properties (default: None).

  • domain (str or PipelineVariable) – Domain values can be “COMPUTER_VISION”, “NATURAL_LANGUAGE_PROCESSING”, “MACHINE_LEARNING” (default: None).

  • sample_payload_url (str or PipelineVariable) – The S3 path where the sample payload is stored (default: None).

  • task (str or PipelineVariable) – Task values which are supported by Inference Recommender are “FILL_MASK”, “IMAGE_CLASSIFICATION”, “OBJECT_DETECTION”, “TEXT_GENERATION”, “IMAGE_SEGMENTATION”, “CLASSIFICATION”, “REGRESSION”, “OTHER” (default: None).

  • framework (str or PipelineVariable) – Machine learning framework of the model package container image (default: None).

  • framework_version (str or PipelineVariable) – Framework version of the Model Package Container Image (default: None).

  • nearest_model_name (str or PipelineVariable) – Name of a pre-trained machine learning benchmarked by Amazon SageMaker Inference Recommender (default: None).

  • data_input_configuration (str or PipelineVariable) – Input object for the model (default: None).

  • skip_model_validation (str or PipelineVariable) – Indicates if you want to skip model validation. Values can be “All” or “None” (default: None).

  • source_uri (str or PipelineVariable) – The URI of the source for the model package (default: None).

  • model_card (ModeCard or ModelPackageModelCard) – document contains qualitative and quantitative information about a model (default: None).

Returns

A sagemaker.model.ModelPackage instance.

prepare_container_def(instance_type=None, accelerator_type=None, serverless_inference_config=None, accept_eula=None, model_reference_arn=None)

A container definition with framework configuration set in model environment variables.

Parameters
  • instance_type (str) – The EC2 instance type to deploy this Model to. For example, ‘ml.p2.xlarge’.

  • accelerator_type (str) – The Elastic Inference accelerator type to deploy to the instance for loading and making inferences to the model.

  • serverless_inference_config (sagemaker.serverless.ServerlessInferenceConfig) – Specifies configuration related to serverless endpoint. Instance type is not provided in serverless inference. So this is used to find image URIs.

  • accept_eula (bool) – For models that require a Model Access Config, specify True or False to indicate whether model terms of use have been accepted. The accept_eula value must be explicitly defined as True in order to accept the end-user license agreement (EULA) that some models require. (Default: None).

Returns

A container definition object usable with the CreateModel API.

Return type

dict[str, str]

serving_image_uri(region_name, instance_type, accelerator_type=None, serverless_inference_config=None)

Create a URI for the serving image.

Parameters
  • region_name (str) – AWS region where the image is uploaded.

  • instance_type (str) – SageMaker instance type. Used to determine device type (cpu/gpu/family-specific optimized).

  • accelerator_type (str) – The Elastic Inference accelerator type to deploy to the instance for loading and making inferences to the model.

  • serverless_inference_config (sagemaker.serverless.ServerlessInferenceConfig) – Specifies configuration related to serverless endpoint. Instance type is not provided in serverless inference. So this is used to determine device type.

Returns

The appropriate image URI based on the given parameters.

Return type

str

PyTorch Predictor

class sagemaker.pytorch.model.PyTorchPredictor(endpoint_name, sagemaker_session=None, serializer=<sagemaker.base_serializers.NumpySerializer object>, deserializer=<sagemaker.base_deserializers.NumpyDeserializer object>, component_name=None)

Bases: Predictor

A Predictor for inference against PyTorch Endpoints.

This is able to serialize Python lists, dictionaries, and numpy arrays to multidimensional tensors for PyTorch inference.

Initialize an PyTorchPredictor.

Parameters
  • endpoint_name (str) – The name of the endpoint to perform inference on.

  • sagemaker_session (sagemaker.session.Session) – Session object which manages interactions with Amazon SageMaker APIs and any other AWS services needed. If not specified, the estimator creates one using the default AWS configuration chain.

  • serializer (sagemaker.serializers.BaseSerializer) – Optional. Default serializes input data to .npy format. Handles lists and numpy arrays.

  • deserializer (sagemaker.deserializers.BaseDeserializer) – Optional. Default parses the response from .npy format to numpy array.

  • component_name (str) – Optional. Name of the Amazon SageMaker inference component corresponding to the predictor.

PyTorch Processor

class sagemaker.pytorch.processing.PyTorchProcessor(framework_version, role=None, instance_count=None, instance_type=None, py_version='py3', image_uri=None, command=None, volume_size_in_gb=30, volume_kms_key=None, output_kms_key=None, code_location=None, max_runtime_in_seconds=None, base_job_name=None, sagemaker_session=None, env=None, tags=None, network_config=None)

Bases: FrameworkProcessor

Handles Amazon SageMaker processing tasks for jobs using PyTorch containers.

This processor executes a Python script in a PyTorch execution environment.

Unless image_uri is specified, the PyTorch environment is an Amazon-built Docker container that executes functions defined in the supplied code Python script.

The arguments have the exact same meaning as in FrameworkProcessor.

Tip

You can find additional parameters for initializing this class at FrameworkProcessor.

Parameters
estimator_cls

alias of PyTorch