{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Train an MNIST model with TensorFlow\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"\n",
"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. \n",
"\n",
"\n",
"\n",
"---"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"MNIST is a widely-used dataset for handwritten digit classification. It consists of 70,000 labeled 28x28 pixel grayscale images of hand-written digits. The dataset is split into 60,000 training images and 10,000 test images. There are 10 classes (one for each of the 10 digits). This tutorial will show how to train a TensorFlow V2 model on MNIST model on SageMaker.\n",
"\n",
"## Runtime\n",
"\n",
"This notebook takes approximately 5 minutes to run.\n",
"\n",
"## Contents\n",
"\n",
"1. [TensorFlow Estimator](#TensorFlow-Estimator)\n",
"1. [Implement the training entry point](#Implement-the-training-entry-point)\n",
"1. [Set hyperparameters](#Set-hyperparameters)\n",
"1. [Set up channels for training and testing data](#Set-up-channels-for-training-and-testing-data)\n",
"1. [Run the training script on SageMaker](#Run-the-training-script-on-SageMaker)\n",
"1. [Inspect and store model data](#Inspect-and-store-model-data)\n",
"1. [Test and debug the entry point before running the training container](#Test-and-debug-the-entry-point-before-running-the-training-container)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import json\n",
"\n",
"import sagemaker\n",
"from sagemaker.tensorflow import TensorFlow\n",
"from sagemaker import get_execution_role\n",
"\n",
"sess = sagemaker.Session()\n",
"\n",
"role = get_execution_role()\n",
"\n",
"output_path = \"s3://\" + sess.default_bucket() + \"/DEMO-tensorflow/mnist\""
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## TensorFlow Estimator\n",
"\n",
"The `TensorFlow` class allows you to run your training script on SageMaker\n",
"infrastracture in a containerized environment. In this notebook, we\n",
"refer to this container as the \"training container.\" \n",
"\n",
"Configure it with the following parameters to set up the environment:\n",
"\n",
"- `entry_point`: A user-defined Python file used by the training container as the instructions for training. We will further discuss this file in the next subsection.\n",
"\n",
"- `role`: An IAM role to make AWS service requests\n",
"\n",
"- `instance_type`: The type of SageMaker instance to run your training script. Set it to `local` if you want to run the training job on the SageMaker instance you are using to run this notebook.\n",
"\n",
"- `model_dir`: S3 bucket URI where the checkpoint data and models can be exported to during training (default: None). \n",
"To disable having model_dir passed to your training script, set `model_dir`=False\n",
"\n",
"- `instance_count`: The number of instances to run your training job on. Multiple instances are needed for distributed training.\n",
"\n",
"- `output_path`: the S3 bucket URI to save training output (model artifacts and output files).\n",
"\n",
"- `framework_version`: The TensorFlow version to use.\n",
"\n",
"- `py_version`: The Python version to use.\n",
"\n",
"For more information, see the [EstimatorBase API reference](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.EstimatorBase).\n",
"\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Implement the training entry point\n",
"\n",
"The entry point for training is a Python script that provides all \n",
"the code for training a TensorFlow model. It is used by the SageMaker \n",
"TensorFlow Estimator (`TensorFlow` class above) as the entry point for running the training job.\n",
"\n",
"Under the hood, SageMaker TensorFlow Estimator downloads a docker image\n",
"with runtime environments \n",
"specified by the parameters to initiate the\n",
"estimator class and it injects the training script into the \n",
"docker image as the entry point to run the container.\n",
"\n",
"In the rest of the notebook, we use *training image* to refer to the \n",
"docker image specified by the TensorFlow Estimator and *training container*\n",
"to refer to the container that runs the training image. \n",
"\n",
"This means your training script is very similar to a training script\n",
"you might run outside Amazon SageMaker, but it can access the useful environment \n",
"variables provided by the training image. See [the complete list of environment variables](https://github.com/aws/sagemaker-training-toolkit/blob/master/ENVIRONMENT_VARIABLES.md) for a complete \n",
"description of all environment variables your training script\n",
"can access. \n",
"\n",
"In this example, we use the training script `code/train.py`\n",
"as the entry point for our TensorFlow Estimator. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pygmentize 'code/train.py'"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Set hyperparameters\n",
"\n",
"In addition, the TensorFlow estimator allows you to parse command line arguments\n",
"to your training script via `hyperparameters`.\n",
"\n",
" Note: local mode is not supported in SageMaker Studio. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Set local_mode to be True if you want to run the training script on the machine that runs this notebook\n",
"\n",
"local_mode = False\n",
"\n",
"if local_mode:\n",
" instance_type = \"local\"\n",
"else:\n",
" instance_type = \"ml.c4.xlarge\"\n",
"\n",
"est = TensorFlow(\n",
" entry_point=\"train.py\",\n",
" source_dir=\"code\", # directory of your training script\n",
" role=role,\n",
" framework_version=\"2.3.1\",\n",
" model_dir=False, # don't pass --model_dir to your training script\n",
" py_version=\"py37\",\n",
" instance_type=instance_type,\n",
" instance_count=1,\n",
" volume_size=250,\n",
" output_path=output_path,\n",
" hyperparameters={\n",
" \"batch-size\": 512,\n",
" \"epochs\": 1,\n",
" \"learning-rate\": 1e-3,\n",
" \"beta_1\": 0.9,\n",
" \"beta_2\": 0.999,\n",
" },\n",
")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"The training container runs your training script like:\n",
"\n",
"```\n",
"python train.py --batch-size 32 --epochs 1 --learning-rate 0.001 --beta_1 0.9 --beta_2 0.999\n",
"```"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Set up channels for training and testing data\n",
"\n",
"Tell `TensorFlow` estimator where to find the training and \n",
"testing data. It can be a path to an S3 bucket, or a path\n",
"in your local file system if you use local mode. In this example,\n",
"we download the MNIST data from a public S3 bucket and upload it \n",
"to your default bucket. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import logging\n",
"import boto3\n",
"from botocore.exceptions import ClientError\n",
"\n",
"# Download training and testing data from a public S3 bucket\n",
"\n",
"\n",
"def download_from_s3(data_dir=\"./data\", train=True):\n",
" \"\"\"Download MNIST dataset and convert it to numpy array\n",
"\n",
" Args:\n",
" data_dir (str): directory to save the data\n",
" train (bool): download training set\n",
"\n",
" Returns:\n",
" None\n",
" \"\"\"\n",
"\n",
" if not os.path.exists(data_dir):\n",
" os.makedirs(data_dir)\n",
"\n",
" if train:\n",
" images_file = \"train-images-idx3-ubyte.gz\"\n",
" labels_file = \"train-labels-idx1-ubyte.gz\"\n",
" else:\n",
" images_file = \"t10k-images-idx3-ubyte.gz\"\n",
" labels_file = \"t10k-labels-idx1-ubyte.gz\"\n",
"\n",
" # download objects\n",
" s3 = boto3.client(\"s3\")\n",
" bucket = f\"sagemaker-example-files-prod-{boto3.session.Session().region_name}\"\n",
" for obj in [images_file, labels_file]:\n",
" key = os.path.join(\"datasets/image/MNIST\", obj)\n",
" dest = os.path.join(data_dir, obj)\n",
" if not os.path.exists(dest):\n",
" s3.download_file(bucket, key, dest)\n",
" return\n",
"\n",
"\n",
"download_from_s3(\"./data\", True)\n",
"download_from_s3(\"./data\", False)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Upload to the default bucket\n",
"\n",
"prefix = \"DEMO-mnist\"\n",
"bucket = sess.default_bucket()\n",
"loc = sess.upload_data(path=\"./data\", bucket=bucket, key_prefix=prefix)\n",
"\n",
"channels = {\"training\": loc, \"testing\": loc}"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"The keys of the `channels` dictionary are passed to the training image,\n",
"and it creates the environment variable `SM_CHANNEL_`. \n",
"\n",
"In this example, `SM_CHANNEL_TRAINING` and `SM_CHANNEL_TESTING` are created in the training image (see \n",
"how `code/train.py` accesses these variables). For more information,\n",
"see: [SM_CHANNEL_{channel_name}](https://github.com/aws/sagemaker-training-toolkit/blob/master/ENVIRONMENT_VARIABLES.md#sm_channel_channel_name).\n",
"\n",
"If you want, you can create a channel for validation:\n",
"```\n",
"channels = {\n",
" 'training': train_data_loc,\n",
" 'validation': val_data_loc,\n",
" 'test': test_data_loc\n",
"}\n",
"```\n",
"You can then access this channel within your training script via\n",
"`SM_CHANNEL_VALIDATION`."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Run the training script on SageMaker\n",
"Now, the training container has everything to run your training\n",
"script. Start the container by calling the `fit()` method."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"est.fit(inputs=channels)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Inspect and store model data\n",
"\n",
"Now, the training is finished, and the model artifact has been saved in \n",
"the `output_path`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tf_mnist_model_data = est.model_data\n",
"print(\"Model artifact saved at:\\n\", tf_mnist_model_data)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"We store the variable `tf_mnist_model_data` in the current notebook kernel. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%store tf_mnist_model_data"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Test and debug the entry point before running the training container\n",
"\n",
"The entry point `code/train.py` provided here has been tested and it can be runs in the training container. \n",
"When you develop your own training script, it is a good practice to simulate the container environment \n",
"in the local shell and test it before sending it to SageMaker, because debugging in a containerized environment\n",
"is rather cumbersome. The following script shows how you can test your training script:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pygmentize code/test_train.py"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Conclusion\n",
"\n",
"In this notebook, we trained a TensorFlow model on the MNIST dataset by fitting a SageMaker estimator. For next steps on how to deploy the trained model and perform inference, see [Deploy a Trained TensorFlow V2 Model](https://sagemaker-examples.readthedocs.io/en/latest/frameworks/tensorflow/get_started_mnist_deploy.html)."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Notebook CI Test Results\n",
"\n",
"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.\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n"
]
}
],
"metadata": {
"instance_type": "ml.t3.medium",
"kernelspec": {
"display_name": "Python 3 (TensorFlow 2.10.0 Python 3.9 CPU Optimized)",
"language": "python",
"name": "python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-west-2:236514542706:image/tensorflow-2.10.1-cpu-py39-ubuntu20.04-sagemaker-v1.2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
},
"notice": "Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License."
},
"nbformat": 4,
"nbformat_minor": 4
}