gluonts.nursery.sagemaker_sdk package

class gluonts.nursery.sagemaker_sdk.GluonTSFramework(sagemaker_session: sagemaker.session.Session, role: str, image_name: str, base_job_name: str, train_instance_type: str = 'ml.c5.xlarge', train_instance_count: int = 1, dependencies: Optional[List[str]] = None, output_path: str = None, code_location: str = None, framework_version: str = '0.4.1', hyperparameters: Dict = None, entry_point: str = '/var/lib/jenkins/workspace/workspace/gluon-ts-gpu-py3/src/gluonts/nursery/sagemaker_sdk/entry_point_scripts/train_entry_point.py', **kwargs)[source]

Bases: sagemaker.estimator.Framework

This Estimator can be used to easily train and evaluate any GluonTS model on any dataset (own or built-in) in AWS Sagemaker using the provided Docker container. It also allows for the execution of custom scripts on AWS Sagemaker. Training is started by calling GluonTSFramework.train() on this Estimator. After training is complete, calling deploy() creates a hosted SageMaker endpoint and returns an GluonTSPredictor instance that can be used to perform inference against the hosted model. Alternatively, one can call the GluonTSFramework.run() method to run a custom script defined by the “entry_point” argument of the GluonTSFramework.run() method. Technical documentation on preparing GluonTSFramework scripts for SageMaker training and using the GluonTsFramework Estimator is available on the project home-page: https://github.com/awslabs/gluon-ts. See how_to_notebooks for examples of how to use this SDK.

Parameters
  • sagemaker_session – Session object which manages interactions with Amazon SageMaker APIs and any other AWS services needed.

  • role – 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.

  • image_name

    The estimator will use this image for training and hosting. It must be an ECR url. If you use an image with MXNET with GPU support, you will have to use a GPU instance. Example:

    '123.dkr.ecr.us-west-2.amazonaws.com/my-custom-image:1.0'
    

  • base_job_name – Prefix for training job name when the GluonTSFramework.train() or GluonTSFramework.run() method is called.

  • train_instance_type

    Type of EC2 instance to use for training. Example:

    'ml.c5.xlarge' # CPU,
    'ml.p2.xlarge' # GPU
    

  • train_instance_count – Currently not more than one supported. Otherwise the number of Amazon EC2 instances to use for training.

  • dependencies

    A list of paths to files or directories (absolute or relative) with any additional libraries that will be exported to the container. The library folders will be copied to SageMaker in the same folder where the “train.py” is copied. Include a path to a “requirements.txt” to install further dependencies at runtime. The provided dependencies take precedence over the pre-installed ones. If ‘git_config’ is provided, ‘dependencies’ should be a list of relative locations to directories with any additional libraries needed in the Git repo. Example:

    GluonTSFramework(
        entry_point='train.py',
        dependencies=['my/libs/common', 'requirements.txt']
    )
    

    results in the following inside the container:

    opt/ml/code
         ├---> train.py
         ├---> common
         └---> requirements.txt
    

    To use a custom GluonTS version just import your custom GluonTS version and then call:

     GluonTSFramework(
        entry_point='train.py',
        dependencies=[gluonts.__path__[0]]
    )
    

    This may brake the GluonTSFramework.train() method though. If not specified, them dependencies from the Estimator will be used.

  • output_path – S3 location for saving the transform result. If not specified, results are stored to a default bucket.

  • code_location – The S3 prefix URI where custom code will be uploaded. The code file uploaded in S3 is ‘code_location/source/sourcedir.tar.gz’. If not specified, the default code location is s3://default_bucket/job-name/. And code file uploaded to S3 is s3://default_bucket/job-name/source/sourcedir.tar.gz

  • framework_version – GluonTS version. If not specified, this will default to 0.4.1. Currently has no effect.

  • hyperparameters – # TODO add support for HPO Not the Estimator hyperparameters, those are provided through the Estimator in the GluonTSFramework.train() method. If you use the GluonTSFramework.run() method its up to you what you do with this parameter and you could use it to define the hyperparameters of your models. There is no support for Hyper Parameter Optimization (HPO) so far. In general hyperparameters will be used for training. They 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.

  • entry_point – Should not be overwritten if you intend to use the GluonTSFramework.train() method, and only be specified through the GluonTSFramework.run() method.

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

LATEST_VERSION = '0.4.1'
create_model(model_server_workers: Optional[str] = None, role: str = None, vpc_config_override: Optional[Dict[str, List[str]]] = 'VPC_CONFIG_DEFAULT', entry_point: str = None, source_dir: str = None, dependencies: List[str] = None, image_name: str = None, **kwargs) → gluonts.nursery.sagemaker_sdk.model.GluonTSModel[source]

Create a GluonTSModel object that can be deployed to an Endpoint.

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

  • role – 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. If not specified, the role from the Estimator will be used.

  • vpc_config_override – 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 – Should not be overwritten if you intend to use the GluonTSFramework.train() method, and only be specified through the GluonTSFramework.run() method.

  • source_dir

    If you set this, your training script will have to be located within the specified source_dir and you will have to set entry_point to the relative path within your source_dir.

    Path (absolute, relative, or an S3 URI) to a directory with all training source code including dependencies. Structure within this directory is preserved when training on Amazon SageMaker. If ‘git_config’ is provided, ‘source_dir’ should be a relative location to a directory in the Git repo. For example with the following GitHub repo directory structure:

    |---> README.md
    └---> src
      |---> train.py
      └---> test.py
    

    and you need ‘train.py’ as entry point and ‘test.py’ as training source code as well, you must set entry_point=’train.py’, source_dir=’src’. If not specified, the model source directory from training is used.

  • dependencies

    A list of paths to files or directories (absolute or relative) with any additional libraries that will be exported to the container. The library folders will be copied to SageMaker in the same folder where the “train.py” is copied. Include a path to a “requirements.txt” to install further dependencies at runtime. The provided dependencies take precedence over the pre-installed ones. If ‘git_config’ is provided, ‘dependencies’ should be a list of relative locations to directories with any additional libraries needed in the Git repo. Example:

    GluonTSFramework(
        entry_point='train.py',
        dependencies=['my/libs/common', 'requirements.txt']
    )
    

    results in the following inside the container:

    opt/ml/code
        ├---> train.py
        ├---> common
        └---> requirements.txt
    

    To use a custom GluonTS version just import your custom GluonTS version and then call:

     GluonTSFramework(
        entry_point='train.py',
        dependencies=[gluonts.__path__[0]]
    )
    

    This may brake the GluonTSFramework.train() method though. If not specified, them dependencies from the Estimator will be used.

  • image_name

    The estimator will use this image for training and hosting. It must be an ECR url. If you use an image with MXNET with GPU support, you will have to use a GPU instance. Example:

    '123.dkr.ecr.us-west-2.amazonaws.com/my-custom-image:1.0'
    'custom-image:latest'
    

    If not specified, them image from the Estimator will be used.

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

Returns

A GluonTSModel object. See GluonTSModel() for full details.

Return type

gluonts.sagemaker.GluonTSModel

classmethod run(entry_point: str, inputs, sagemaker_session: sagemaker.session.Session, role: str, image_name: str, base_job_name: str, train_instance_type: str, train_instance_count: int = 1, dependencies: Optional[List[str]] = [], output_path: str = None, code_location: str = None, framework_version: str = '0.4.1', hyperparameters=None, source_dir: str = None, monitored_metrics: List[str] = ('mean_wQuantileLoss', 'ND', 'RMSE'), wait: bool = True, logs: bool = True, job_name: str = None, **kwargs) → Tuple[sagemaker.estimator.Framework, str][source]

Use this function to run a custom script specified in ‘entry_point’ in GluonTSFramework. To access files on s3 specify them in inputs. If you want to access local files you should have specified them in ‘dependencies’ in GluonTSFramework.

Parameters
  • entry_point

    Path (absolute or relative) to the local Python source file which should be executed as the entry point to training. This should be compatible with Python 3.6. If ‘git_config’ is provided, ‘entry_point’ should be a relative location to the Python source file in the Git repo. For example with the following GitHub repo directory structure:

    |---> README.md
    └---> src
        |---> train.py
        └---> test.py
    

    You can assign entry_point=’src/train.py’.

  • inputs

    Type is str or dict or sagemaker.s3_input, however, cannot be empty! Information about the training data. This can be one of three types;

    • If (str) the S3 location where training data is saved.

    • If (dict[str, str] or dict[str, sagemaker.s3_input]) If using multiple

      channels for training data, you can specify a dict mapping channel names to strings or s3_input() objects.

    • If (sagemaker.s3_input) - channel configuration for S3 data sources that can

      provide additional information as well as the path to the training dataset. See sagemaker.s3_input() for full details.

    • If (sagemaker.session.FileSystemInput) - channel configuration for

      a file system data source that can provide additional information as well as the path to the training dataset.

    Example:

    inputs = {'my_dataset': sagemaker.s3_input(my_dataset_file, content_type='application/json')} # or
    inputs = {'my_dataset': my_dataset_dir}
    

    where ‘my_dataset_file’ and ‘my_dataset_dir’ are the relative or absolute paths as strings.

  • sagemaker_session – Session object which manages interactions with Amazon SageMaker APIs and any other AWS services needed.

  • role – 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.

  • image_name

    The estimator will use this image for training and hosting. It must be an ECR url. If you use an image with MXNET with GPU support, you will have to use a GPU instance. Example:

    '123.dkr.ecr.us-west-2.amazonaws.com/my-custom-image:1.0'
    

  • base_job_name – Prefix for training job name when the GluonTSFramework.train() or GluonTSFramework.run() method is called.

  • train_instance_type

    Type of EC2 instance to use for training. Example:

    'ml.c5.xlarge' # CPU,
    'ml.p2.xlarge' # GPU
    

  • train_instance_count – Currently not more than one supported. Otherwise the number of Amazon EC2 instances to use for training.

  • dependencies

    A list of paths to files or directories (absolute or relative) with any additional libraries that will be exported to the container. The library folders will be copied to SageMaker in the same folder where the “train.py” is copied. Include a path to a “requirements.txt” to install further dependencies at runtime. The provided dependencies take precedence over the pre-installed ones. If ‘git_config’ is provided, ‘dependencies’ should be a list of relative locations to directories with any additional libraries needed in the Git repo. Example:

    GluonTSFramework.run(entry_point='train.py', dependencies=['my/libs/common', 'requirements.txt'])
    

    results in the following inside the container:

    opt/ml/code
         ├---> train.py
         ├---> common
         └---> requirements.txt
    

    To use a custom GluonTS version just import your custom GluonTS version and then call:

    GluonTSFramework.run(entry_point='train.py', dependencies=[gluonts.__path__[0]])
    

    This may brake the GluonTSFramework.train() method though. If not specified, them dependencies from the Estimator will be used.

  • output_path – S3 location for saving the transform result. If not specified, results are stored to a default bucket.

  • code_location – The S3 prefix URI where custom code will be uploaded. The code file uploaded in S3 is ‘code_location/source/sourcedir.tar.gz’. If not specified, the default code location is s3://default_bucket/job-name/. And code file uploaded to S3 is s3://default_bucket/job-name/source/sourcedir.tar.gz

  • framework_version – GluonTS version. If not specified, this will default to 0.4.1. Currently has no effect.

  • hyperparameters – Its up to you what you do with this parameter and you could use it to define the hyperparameters of your models. In general hyperparameters will be used for training. They 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.

  • source_dir

    If you set this, your training script will have to be located within the specified source_dir and you will have to set entry_point to the relative path within your source_dir. Path (absolute, relative, or an S3 URI) to a directory with all training source code including dependencies. Structure within this directory is preserved when training on Amazon SageMaker. If ‘git_config’ is provided, ‘source_dir’ should be a relative location to a directory in the Git repo. For example with the following GitHub repo directory structure:

    |---> README.md
    └---> src
      |---> train.py
      └---> test.py
    

    and you need ‘train.py’ as entry point and ‘test.py’ as training source code as well, you must set entry_point=’train.py’, source_dir=’src’.

  • monitored_metrics – Names of the metrics that will be parsed from logs in a one minute interval in order to monitor them in Sagemaker.

  • wait – Whether the call should wait until the job completes (default: True).

  • logs – Whether to show the logs produced by the job. Only meaningful when wait is True (default: True).

  • job_name – Training job name. If not specified, a default job name will be generated, based on the base_job_name and the current timestamp.

Returns

The GluonTSFramework and the job name of the training job.

Return type

Tuple[Framework, str]

train(dataset: str, estimator: gluonts.model.estimator.Estimator, num_samples: int = 100, quantiles: List[float] = (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9), monitored_metrics: List[str] = ('mean_wQuantileLoss', 'ND', 'RMSE'), wait: bool = True, logs: bool = True, job_name: str = None) → Union[gluonts.nursery.sagemaker_sdk.estimator.TrainResult, str][source]

Use this function to train and evaluate any GluonTS model on Sagemaker. You need to call this method before you can call ‘deploy’.

Parameters
  • dataset

    An s3 path-stype URL to a dataset in GluonTs format, or the name of a provided dataset (see gluonts.dataset.repository.datasets.dataset_recipes.keys()). Required dataset structure:

    dataset
        ├---> train
        |   └--> data.json
        ├---> test
        |   └--> data.json
        └--> metadata.json
    

  • estimator – The GluonTS estimator that should be trained. If you want to train a custom estimator you must have specified the code location in the dependencies argument of the GLuonTSFramework.

  • num_samples – The num_samples parameter for the gluonts.evaluation.backtest.make_evaluation_predictions method used for evaluation. (default: (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9))

  • quantiles – The quantiles parameter for the gluonts.evaluation.Evaluator used for evaluation. (default: 0.1)

  • monitored_metrics – Names of the metrics that will be parsed from logs in a one minute interval in order to monitor them in Sagemaker.

  • wait – Whether the call should wait until the job completes (default: True).

  • logs – Whether to show the logs produced by the job. Only meaningful when wait is True (default: True).

  • job_name – Training job name. If not specified, a default job name will be generated, based on the base_job_name and the current timestamp.

Returns

The job name used during training.

Return type

job_name

class gluonts.nursery.sagemaker_sdk.GluonTSPredictor(endpoint_name: str, sagemaker_session: sagemaker.session.Session = None)[source]

Bases: sagemaker.predictor.RealTimePredictor

A RealTimePredictor for inference against GluonTS Endpoints. This is able to serialize and deserialize datasets in the gluonts data format.

class gluonts.nursery.sagemaker_sdk.GluonTSModel(model_data, role, entry_point, image: str = None, framework_version: str = '0.4.1', predictor_cls=<class 'gluonts.nursery.sagemaker_sdk.model.GluonTSPredictor'>, model_server_workers: int = None, **kwargs)[source]

Bases: sagemaker.model.FrameworkModel

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

prepare_container_def(instance_type, accelerator_type=None) → Dict[str, str][source]

Return a container definition with framework configuration set in model environment variables.

Parameters
  • instance_type

    The EC2 instance type to deploy this Model to. Example:

    'ml.c5.xlarge' # CPU,
    'ml.p2.xlarge' # GPU.
    

  • accelerator_type

    The Elastic Inference accelerator type to deploy to the instance for loading and making inferences to the model. Example:

    "ml.eia1.medium"
    

Returns

A container definition object usable with the CreateModel API.

Return type

Dict[str, str]