TensorFlow BYOM: Train locally and deploy on SageMaker.


This notebook’s CI test result for us-west-2 is as follows. CI test results in other regions can be found at the end of the notebook.

This us-west-2 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable


  1. Introduction

  2. Prerequisites and Preprocessing

    1. Permissions and environment variables

    2. Model definitions

    3. Data Setup

  3. Training the network locally

  4. Set up hosting for the model

    1. Export from TensorFlow

    2. Import model into SageMaker

    3. Create endpoint

  5. Validate the endpoint for use

Note: Compare this with the tensorflow bring your own model example

Thie notebook was last tested on a ml.m5.xlarge instance running the Python 3 (TensorFlow 2.3 Python 3.7 CPU Optimized) kernel in SageMaker Studio.

Introduction

We will do a classification task, training locally in the box from where this notebook is being run. We then set up a real-time hosted endpoint in SageMaker.

Consider the following model definition for IRIS classification. This mode uses the tensorflow.estimator.DNNClassifier which is a pre-defined estimator module for its model definition.

Prequisites and Preprocessing

Permissions and environment variables

Here we set up the linkage and authentication to AWS services. In this notebook we only need the roles used to give learning and hosting access to your data. The Sagemaker SDK will use S3 defualt buckets when needed. If the get_execution_role does not return a role with the appropriate permissions, you’ll need to specify an IAM role arn that does.

[ ]:
!pip install --upgrade tensorflow sagemaker
[ ]:
import boto3
import numpy as np
import os
import pandas as pd
import re
import sagemaker
from sagemaker.tensorflow import TensorFlowModel
from sagemaker.utils import S3DataConfig

import shutil
import tarfile
import tensorflow as tf
from tensorflow.python.keras.utils.np_utils import to_categorical
from tensorflow.keras.layers import Input, Dense

role = sagemaker.get_execution_role()
sm_session = sagemaker.Session()
bucket_name = sm_session.default_bucket()

Model Definitions

For this example, we’ll use a very simple network architecture, with three densely-connected layers.

[ ]:
def iris_mlp(metrics):
    ### Setup loss and output node activation
    output_activation = "softmax"
    loss = "sparse_categorical_crossentropy"

    input = Input(shape=(4,), name="input")

    x = Dense(
        units=10,
        kernel_regularizer=tf.keras.regularizers.l2(0.001),
        activation="relu",
        name="dense_layer1",
    )(input)

    x = Dense(
        units=20,
        kernel_regularizer=tf.keras.regularizers.l2(0.001),
        activation="relu",
        name="dense_layer2",
    )(x)

    x = Dense(
        units=10,
        activation="relu",
        kernel_regularizer=tf.keras.regularizers.l2(0.001),
        name="dense_layer3",
    )(x)

    output = Dense(units=3, activation=output_activation)(x)

    ### Compile the model
    model = tf.keras.Model(input, output)

    model.compile(optimizer="adam", loss=loss, metrics=metrics)

    return model

Data Setup

We’ll use the pre-processed iris training and test data stored in a public S3 bucket for this example.

[ ]:
data_bucket = S3DataConfig(
    sm_session, "example-notebooks-data-config", "config/data_config.json"
).get_data_bucket()
print(f"Using data from {data_bucket}")
[ ]:
# Download iris test and train data sets from S3
SOURCE_DATA_BUCKET = data_bucket
SOURCE_DATA_PREFIX = "datasets/tabular/iris"
sm_session.download_data(".", bucket=SOURCE_DATA_BUCKET, key_prefix=SOURCE_DATA_PREFIX)

# Load the training and test data from .csv to a Pandas data frame.
train_df = pd.read_csv(
    "iris_train.csv",
    header=0,
    names=["sepal_length", "sepal_width", "petal_length", "petal_width", "class"],
)
test_df = pd.read_csv(
    "iris_test.csv",
    header=0,
    names=["sepal_length", "sepal_width", "petal_length", "petal_width", "class"],
)

# Pop the record labels into N x 1 Numpy arrays
train_labels = np.array(train_df.pop("class"))
test_labels = np.array(test_df.pop("class"))

# Save the remaining features as Numpy arrays
train_np = np.array(train_df)
test_np = np.array(test_df)

Training the Network Locally

Here, we train the network using the Tensorflow .fit method, just like if we were using our local computers. This should only take a few seconds because the model is so simple.

[ ]:
EPOCHS = 50
BATCH_SIZE = 32

EARLY_STOPPING = tf.keras.callbacks.EarlyStopping(
    monitor="val_loss", mode="auto", restore_best_weights=True
)

# Instantiate classifier
classifier = iris_mlp(metrics=["accuracy", "binary_accuracy"])

# Fit classifier
history = classifier.fit(
    x=train_np,
    y=train_labels,
    validation_data=(test_np, test_labels),
    callbacks=[EARLY_STOPPING],
    batch_size=BATCH_SIZE,
    epochs=EPOCHS,
)

Set up hosting for the model

Export the model from tensorflow

In order to set up hosting, we have to import the model from training to hosting. We will begin by exporting the model from TensorFlow and saving it to our file system. We also need to convert the model into a form that is readable by sagemaker.tensorflow.model.TensorFlowModel. There is a small difference between a SageMaker model and a TensorFlow model. The conversion is easy and fairly trivial. Simply move the tensorflow exported model into a directory export\Servo\ and tar the entire directory. SageMaker will recognize this as a loadable TensorFlow model.

[ ]:
classifier.save("export/Servo/1")
with tarfile.open("model.tar.gz", "w:gz") as tar:
    tar.add("export")

Open a new sagemaker session and upload the model on to the default S3 bucket. We can use the sagemaker.Session.upload_data method to do this. We need the location of where we exported the model from TensorFlow and where in our default bucket we want to store the model(/model). The default S3 bucket can be found using the sagemaker.Session.default_bucket method.

Here, we upload the model to S3

[ ]:
s3_response = sm_session.upload_data("model.tar.gz", bucket=bucket_name, key_prefix="model")

Import model into SageMaker

Use the sagemaker.tensorflow.model.TensorFlowModel to import the model into SageMaker that can be deployed. We need the location of the S3 bucket where we have the model and the role for authentication.

[ ]:
sagemaker_model = TensorFlowModel(
    model_data=f"s3://{bucket_name}/model/model.tar.gz",
    role=role,
    framework_version="2.3",
)

Create endpoint

Now the model is ready to be deployed at a SageMaker endpoint. We can use the sagemaker.tensorflow.model.TensorFlowModel.deploy method to do this. Unless you have created or prefer other instances, we recommend using a single 'ml.m5.2xlarge' instance for this example. These are supplied as arguments.

[ ]:
%%time
predictor = sagemaker_model.deploy(initial_instance_count=1, instance_type="ml.m5.2xlarge")

Validate the endpoint for use

We can now use this endpoint to classify an example to ensure that it works. The output from predict will be an array of probabilities for each of the 3 classes.

[ ]:
sample = [6.4, 3.2, 4.5, 1.5]
predictor.predict(sample)

Delete all temporary directories so that we are not affecting the next run. Also, optionally delete the end points.

[ ]:
os.remove("model.tar.gz")
os.remove("iris_test.csv")
os.remove("iris_train.csv")
os.remove("iris.data")
shutil.rmtree("export")

If you do not want to continue using the endpoint, you can remove it. Remember, open endpoints are charged. If this is a simple test or practice, it is recommended to delete them.

[ ]:
predictor.delete_endpoint()

Notebook CI Test Results

This notebook was tested in multiple regions. The test results are as follows, except for us-west-2 which is shown at the top of the notebook.

This us-east-1 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable

This us-east-2 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable

This us-west-1 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable

This ca-central-1 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable

This sa-east-1 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable

This eu-west-1 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable

This eu-west-2 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable

This eu-west-3 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable

This eu-central-1 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable

This eu-north-1 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable

This ap-southeast-1 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable

This ap-southeast-2 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable

This ap-northeast-1 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable

This ap-northeast-2 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable

This ap-south-1 badge failed to load. Check your device’s internet connectivity, otherwise the service is currently unavailable