{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# Train an MNIST model with PyTorch\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", "![This us-west-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-west-2/frameworks|pytorch|get_started_mnist_train.ipynb)\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 shows how to train and test an MNIST model on SageMaker using PyTorch. \n", "\n", "## Runtime\n", "\n", "This notebook takes approximately 5 minutes to run.\n", "\n", "## Contents\n", "\n", "1. [PyTorch Estimator](#PyTorch-Estimator)\n", "1. [Implement the entry point for training](#Implement-the-entry-point-for-training)\n", "1. [Set hyperparameters](#Set-hyperparameters)\n", "1. [Set up channels for the training and testing data](#Set-up-channels-for-the-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 executing the training container](#Test-and-debug-the-entry-point-before-executing-the-training-container)\n", "1. [Conclusion](#Conclusion)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import json\n", "\n", "import sagemaker\n", "from sagemaker.pytorch import PyTorch\n", "from sagemaker import get_execution_role\n", "\n", "\n", "sess = sagemaker.Session()\n", "region = sess.boto_region_name\n", "\n", "role = get_execution_role()\n", "\n", "output_path = \"s3://\" + sess.default_bucket() + \"/DEMO-mnist\"" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## PyTorch Estimator\n", "\n", "The `PyTorch` 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 *training container*. \n", "\n", "You need to configure\n", "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 \n", "instructions for training. We 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. \n", "Set it to `local` if you want to run the training job on \n", "the SageMaker instance you are using to run this notebook\n", "\n", "- `instance_count`: The number of instances to run your training job on. \n", "Multiple instances are needed for distributed training.\n", "\n", "- `output_path`: \n", "S3 bucket URI to save training output (model artifacts and output files)\n", "\n", "- `framework_version`: The version of PyTorch 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 entry point for training\n", "\n", "The entry point for training is a Python script that provides all \n", "the code for training a PyTorch model. It is used by the SageMaker \n", "PyTorch Estimator (`PyTorch` class above) as the entry point for running the training job.\n", "\n", "Under the hood, SageMaker PyTorch Estimator creates a docker image\n", "with runtime environemnts \n", "specified by the parameters you provide 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 PyTorch 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 PyTorch Estimator.\n" ] }, { "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 PyTorch 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 True 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 = PyTorch(\n", " entry_point=\"train.py\",\n", " source_dir=\"code\", # directory of your training script\n", " role=role,\n", " framework_version=\"1.5.0\",\n", " py_version=\"py3\",\n", " instance_type=instance_type,\n", " instance_count=1,\n", " volume_size=250,\n", " output_path=output_path,\n", " hyperparameters={\"batch-size\": 128, \"epochs\": 1, \"learning-rate\": 1e-3, \"log-interval\": 100},\n", ")" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "The training container executes your training script like:\n", "\n", "```\n", "python train.py --batch-size 100 --epochs 1 --learning-rate 1e-3 --log-interval 100\n", "```" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Set up channels for the training and testing data\n", "\n", "Tell the `PyTorch` 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-{region}\"\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`.\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Run the training script on SageMaker\n", "Now, the training container has everything to execute 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": [ "pt_mnist_model_data = est.model_data\n", "print(\"Model artifact saved at:\\n\", pt_mnist_model_data)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "We store the variable `pt_mnist_model_data` in the current notebook kernel." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%store pt_mnist_model_data" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Test and debug the entry point before executing the training container\n", "\n", "The entry point `code/train.py` can be executed 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 PyTorch 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 PyTorch Model](https://sagemaker-examples.readthedocs.io/en/latest/frameworks/pytorch/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", "![This us-east-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-east-1/frameworks|pytorch|get_started_mnist_train.ipynb)\n", "\n", "![This us-east-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-east-2/frameworks|pytorch|get_started_mnist_train.ipynb)\n", "\n", "![This us-west-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/us-west-1/frameworks|pytorch|get_started_mnist_train.ipynb)\n", "\n", "![This ca-central-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ca-central-1/frameworks|pytorch|get_started_mnist_train.ipynb)\n", "\n", "![This sa-east-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/sa-east-1/frameworks|pytorch|get_started_mnist_train.ipynb)\n", "\n", "![This eu-west-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-west-1/frameworks|pytorch|get_started_mnist_train.ipynb)\n", "\n", "![This eu-west-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-west-2/frameworks|pytorch|get_started_mnist_train.ipynb)\n", "\n", "![This eu-west-3 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-west-3/frameworks|pytorch|get_started_mnist_train.ipynb)\n", "\n", "![This eu-central-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-central-1/frameworks|pytorch|get_started_mnist_train.ipynb)\n", "\n", "![This eu-north-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/eu-north-1/frameworks|pytorch|get_started_mnist_train.ipynb)\n", "\n", "![This ap-southeast-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-southeast-1/frameworks|pytorch|get_started_mnist_train.ipynb)\n", "\n", "![This ap-southeast-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-southeast-2/frameworks|pytorch|get_started_mnist_train.ipynb)\n", "\n", "![This ap-northeast-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-northeast-1/frameworks|pytorch|get_started_mnist_train.ipynb)\n", "\n", "![This ap-northeast-2 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-northeast-2/frameworks|pytorch|get_started_mnist_train.ipynb)\n", "\n", "![This ap-south-1 badge failed to load. Check your device's internet connectivity, otherwise the service is currently unavailable](https://h75twx4l60.execute-api.us-west-2.amazonaws.com/sagemaker-nb/ap-south-1/frameworks|pytorch|get_started_mnist_train.ipynb)\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (PyTorch 1.13 Python 3.9 CPU Optimized)", "language": "python", "name": "python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-west-2:236514542706:image/pytorch-1.13-cpu-py39" }, "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 }