TensorFlow

TensorFlow Estimator

class sagemaker.tensorflow.estimator.TensorFlow(training_steps=None, evaluation_steps=None, checkpoint_path=None, py_version='py2', framework_version=None, model_dir=None, requirements_file='', image_name=None, script_mode=False, distributions=None, **kwargs)

Bases: sagemaker.estimator.Framework

Handle end-to-end training and deployment of user-provided TensorFlow code.

Initialize a TensorFlow estimator.

Parameters:
  • training_steps (int) – Perform this many steps of training. None, the default means train forever.
  • evaluation_steps (int) – Perform this many steps of evaluation. None, the default means that evaluation runs until input from eval_input_fn is exhausted (or another exception is raised).
  • checkpoint_path (str) – Identifies S3 location where checkpoint data during model training can be saved (default: None). For distributed model training, this parameter is required.
  • py_version (str) – Python version you want to use for executing your model training code (default: ‘py2’).
  • framework_version (str) – TensorFlow version you want to use for executing your model training code. List of supported versions https://github.com/aws/sagemaker-python-sdk#tensorflow-sagemaker-estimators
  • model_dir (str) – S3 location where the checkpoint data and models can be exported to during training (default: None). If not specified a default S3 URI will be generated. It will be passed in the training script as one of the command line arguments.
  • requirements_file (str) – Path to a requirements.txt file (default: ‘’). The path should be within and relative to source_dir. Details on the format can be found in the Pip User Guide.
  • image_name (str) –

    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.

    Examples

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

  • script_mode (bool) – If set to True will the estimator will use the Script Mode containers (default: False). This will be ignored if py_version is set to ‘py3’.
  • distributions (dict) –

    A dictionary with information on how to run distributed training (default: None). Currently we support distributed training with parameter servers and MPI. To enable parameter server use the following setup:

    {
        ‘parameter_server’:
        {
            ‘enabled’: True
        }
    }
    

    To enable MPI:

    {
        ‘mpi’:
        {
            ‘enabled’: True
        }
    }
    
  • **kwargs – Additional kwargs passed to the Framework constructor.
LATEST_VERSION = '1.12'
fit(inputs=None, wait=True, logs=True, job_name=None, run_tensorboard_locally=False)

Train a model using the input training dataset.

See fit() for more details.

Parameters:
  • inputs (str or dict or sagemaker.session.s3_input) –

    Information about the training data. This can be one of three types:

    • (str) - the S3 location where training data is saved.
    • (dict[str, str] or dict[str, sagemaker.session.s3_input]) - If using multiple channels for
      training data, you can specify a dict mapping channel names to strings or s3_input() objects.
    • (sagemaker.session.s3_input) - channel configuration for S3 data sources that can provide
      additional information as well as the path to the training dataset. See sagemaker.session.s3_input() for full details.
  • wait (bool) – Whether the call should wait until the job completes (default: True).
  • logs (bool) – Whether to show the logs produced by the job. Only meaningful when wait is True (default: True).
  • job_name (str) – Training job name. If not specified, the estimator generates a default job name, based on the training image name and current timestamp.
  • run_tensorboard_locally (bool) – Whether to execute TensorBoard in a different process with downloaded checkpoint information (default: False). This is an experimental feature, and requires TensorBoard and AWS CLI to be installed. It terminates TensorBoard when execution ends.
create_model(model_server_workers=None, role=None, vpc_config_override='VPC_CONFIG_DEFAULT', endpoint_type=None)

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

Parameters:
  • 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.
  • model_server_workers (int) – Optional. The number of worker processes used by the inference server. If None, server will use one worker per vCPU.
  • 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.
  • endpoint_type – Optional. Selects the software stack used by the inference server. If not specified, the model will be configured to use the default SageMaker model server. If ‘tensorflow-serving’, the model will be configured to use the SageMaker Tensorflow Serving container.
Returns:

A SageMaker TensorFlowModel object.

See TensorFlowModel() for full details.

Return type:

sagemaker.tensorflow.model.TensorFlowModel

hyperparameters()

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

train_image()

Return the Docker image to use for training.

The fit() method, which does the model training, calls this method to find the image to use for model training.

Returns:The URI of the Docker image.
Return type:str

TensorFlow Model

class sagemaker.tensorflow.model.TensorFlowModel(model_data, role, entry_point, image=None, py_version='py2', framework_version='1.11', predictor_cls=<class 'sagemaker.tensorflow.model.TensorFlowPredictor'>, model_server_workers=None, **kwargs)

Bases: sagemaker.model.FrameworkModel

Initialize an TensorFlowModel.

Parameters:
  • model_data (str) – 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. This should be compatible with either Python 2.7 or Python 3.5.
  • image (str) – A Docker image URI (default: None). If not specified, a default image for TensorFlow will be used.
  • py_version (str) – Python version you want to use for executing your model training code (default: ‘py2’).
  • framework_version (str) – TensorFlow version you want to use for executing your model training code.
  • 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) – Optional. The number of worker processes used by the inference server. If None, server will use one worker per vCPU.
  • **kwargs – Keyword arguments passed to the FrameworkModel initializer.
prepare_container_def(instance_type, accelerator_type=None)

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

This also uploads user-supplied code to S3.

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. For example, ‘ml.eia1.medium’.
Returns:

A container definition object usable with the CreateModel API.

Return type:

dict[str, str]

TensorFlow Predictor

class sagemaker.tensorflow.model.TensorFlowPredictor(endpoint_name, sagemaker_session=None)

Bases: sagemaker.predictor.RealTimePredictor

A RealTimePredictor for inference against TensorFlow endpoint.

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

Initialize an TensorFlowPredictor.

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.

TensorFlow Serving Model

class sagemaker.tensorflow.serving.Model(model_data, role, image=None, framework_version='1.11', container_log_level=None, predictor_cls=<class 'sagemaker.tensorflow.serving.Predictor'>, **kwargs)

Bases: sagemaker.model.Model

Initialize a Model.

Parameters:
  • model_data (str) – 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 APIs that create Amazon SageMaker endpoints use this role to access model artifacts.
  • image (str) – A Docker image URI (default: None). If not specified, a default image for TensorFlow Serving will be used.
  • framework_version (str) – Optional. TensorFlow Serving version you want to use.
  • container_log_level (int) – Log level to use within the container (default: logging.ERROR). Valid values are defined in the Python logging module.
  • 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.
  • **kwargs – Keyword arguments passed to the Model initializer.
FRAMEWORK_NAME = 'tensorflow-serving'
LOG_LEVEL_PARAM_NAME = 'SAGEMAKER_TFS_NGINX_LOGLEVEL'
LOG_LEVEL_MAP = {10: 'debug', 20: 'info', 30: 'warn', 40: 'error', 50: 'crit'}
prepare_container_def(instance_type, accelerator_type=None)

Return a dict created by sagemaker.container_def() for deploying this model to a specified instance type.

Subclasses can override this to provide custom container definitions for deployment to a specific instance type. Called by deploy().

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. For example, ‘ml.eia1.medium’.
Returns:

A container definition object usable with the CreateModel API.

Return type:

dict

TensorFlow Serving Predictor

class sagemaker.tensorflow.serving.Predictor(endpoint_name, sagemaker_session=None, serializer=<sagemaker.predictor._JsonSerializer object>, deserializer=<sagemaker.predictor._JsonDeserializer object>, content_type=None, model_name=None, model_version=None)

Bases: sagemaker.predictor.RealTimePredictor

A RealTimePredictor implementation for inference against TensorFlow Serving endpoints.

Initialize a TFSPredictor. See sagemaker.RealTimePredictor for more info about parameters.

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 (callable) – Optional. Default serializes input data to json. Handles dicts, lists, and numpy arrays.
  • deserializer (callable) – Optional. Default parses the response using json.load(...).
  • content_type (str) – Optional. The “ContentType” for invocation requests. If specified, overrides the content_type from the serializer (default: None).
  • model_name (str) – Optional. The name of the SavedModel model that should handle the request. If not specified, the endpoint’s default model will handle the request.
  • model_version (str) – Optional. The version of the SavedModel model that should handle the request. If not specified, the latest version of the model will be used.
classify(data)
regress(data)
predict(data, initial_args=None)

Return the inference from the specified endpoint.

Parameters:
  • data (object) – Input data for which you want the model to provide inference. If a serializer was specified when creating the RealTimePredictor, the result of the serializer is sent as input data. Otherwise the data must be sequence of bytes, and the predict method then sends the bytes in the request body as is.
  • initial_args (dict[str,str]) – Optional. Default arguments for boto3 invoke_endpoint call. Default is None (no default arguments).
Returns:

Inference for the given input. If a deserializer was specified when creating

the RealTimePredictor, the result of the deserializer is returned. Otherwise the response returns the sequence of bytes as is.

Return type:

object