{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Building your own algorithm container\n", "\n", "With Amazon SageMaker, you can package your own algorithms that can than be trained and deployed in the SageMaker environment. This notebook will guide you through an example that shows you how to build a Docker container for SageMaker and use it for training and inference.\n", "\n", "By packaging an algorithm in a container, you can bring almost any code to the Amazon SageMaker environment, regardless of programming language, environment, framework, or dependencies. \n", "\n", "You can bring your own PyTorch algorithms to SageMaker by extending SageMaker's pre-built container image. (https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms.html). We recommend the pre-built container be considered first. This example aims to demonstrate on bringing in your own Mask RCNN model to SageMaker as your own container for training and serving. \n", "\n", "1. [Building your own algorithm container](#Building-your-own-algorithm-container)\n", " 1. [When should I build my own algorithm container?](#When-should-I-build-my-own-algorithm-container%3F)\n", " 1. [Permissions](#Permissions)\n", " 1. [The example](#The-example)\n", " 1. [The presentation](#The-presentation)\n", "1. [Part 1: Packaging and Uploading your Algorithm for use with Amazon SageMaker](#Part-1%3A-Packaging-and-Uploading-your-Algorithm-for-use-with-Amazon-SageMaker)\n", " 1. [An overview of Docker](#An-overview-of-Docker)\n", " 1. [How Amazon SageMaker runs your Docker container](#How-Amazon-SageMaker-runs-your-Docker-container)\n", " 1. [Running your container during training](#Running-your-container-during-training)\n", " 1. [The input](#The-input)\n", " 1. [The output](#The-output)\n", " 1. [Running your container during hosting](#Running-your-container-during-hosting)\n", " 1. [The parts of the sample container](#The-parts-of-the-sample-container)\n", " 1. [The Dockerfile](#The-Dockerfile)\n", " 1. [Building and registering the container](#Building-and-registering-the-container)\n", " 1. [Testing your algorithm on your local machine or on an Amazon SageMaker notebook instance](#Testing-your-algorithm-on-your-local-machine-or-on-an-Amazon-SageMaker-notebook-instance)\n", "1. [Part 2: Using your Algorithm in Amazon SageMaker](#Part-2%3A-Using-your-Algorithm-in-Amazon-SageMaker)\n", " 1. [Set up the environment](#Set-up-the-environment)\n", " 1. [Create the session](#Create-the-session)\n", " 1. [Upload the data for training](#Upload-the-data-for-training)\n", " 1. [Create an estimator and fit the model](#Create-an-estimator-and-fit-the-model)\n", " 1. [Hosting your model](#Hosting-your-model)\n", " 1. [Deploy the model](#Deploy-the-model)\n", " 2. [Choose some data and use it for a prediction](#Choose-some-data-and-use-it-for-a-prediction)\n", " 3. [Optional cleanup](#Optional-cleanup)\n", " 1. [Run Batch Transform Job](#Run-Batch-Transform-Job)\n", " 1. [Create a Transform Job](#Create-a-Transform-Job)\n", " 2. [View Output](#View-Output)\n", "\n", "_or_ I'm impatient, just [let me see the code](#The-Dockerfile)!\n", "\n", "## When should I build my own algorithm container?\n", "\n", "You may not need to create a container to bring your own code to Amazon SageMaker. When you are using a framework (such as Apache MXNet or TensorFlow) that has direct support in SageMaker, you can simply supply the Python code that implements your algorithm using the SDK entry points for that framework. This set of frameworks is continually expanding, so we recommend that you check the current list if your algorithm is written in a common machine learning environment.\n", "\n", "Even if there is direct SDK support for your environment or framework, you may find it more effective to build your own container. If the code that implements your algorithm is quite complex on its own or you need special additions to the framework, building your own container may be the right choice.\n", "\n", "If there isn't direct SDK support for your environment, don't worry. You'll see in this walk-through that building your own container is quite straightforward.\n", "\n", "## Permissions\n", "\n", "Running this notebook requires permissions in addition to the normal `SageMakerFullAccess` permissions. This is because we'll creating new repositories in Amazon ECR. The easiest way to add these permissions is simply to add the managed policy `AmazonEC2ContainerRegistryFullAccess` to the role that you used to start your notebook instance. There's no need to restart your notebook instance when you do this, the new permissions will be available immediately.\n", "\n", "## The example\n", "\n", "The Mask R-CNN part of the code is based on the TorchVision Object Detection Funetuning Tutorial (https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html). To learn more about Mask R-CNN, please refer to the original paper published in 2017 (https://arxiv.org/abs/1703.06870).\n", "\n", "## The presentation\n", "\n", "This presentation is divided into two parts: _building_ the container and _using_ the container." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Part 1: Packaging and Uploading your Algorithm for use with Amazon SageMaker\n", "\n", "### An overview of Docker\n", "\n", "If you're familiar with Docker already, you can skip ahead to the next section.\n", "\n", "For many data scientists, Docker containers are a new concept, but they are not difficult, as you'll see here. \n", "\n", "Docker provides a simple way to package arbitrary code into an _image_ that is totally self-contained. Once you have an image, you can use Docker to run a _container_ based on that image. Running a container is just like running a program on the machine except that the container creates a fully self-contained environment for the program to run. Containers are isolated from each other and from the host environment, so the way you set up your program is the way it runs, no matter where you run it.\n", "\n", "Docker is more powerful than environment managers like conda or virtualenv because (a) it is completely language independent and (b) it comprises your whole operating environment, including startup commands, environment variable, etc.\n", "\n", "In some ways, a Docker container is like a virtual machine, but it is much lighter weight. For example, a program running in a container can start in less than a second and many containers can run on the same physical machine or virtual machine instance.\n", "\n", "Docker uses a simple file called a `Dockerfile` to specify how the image is assembled. We'll see an example of that below. You can build your Docker images based on Docker images built by yourself or others, which can simplify things quite a bit.\n", "\n", "Docker has become very popular in the programming and devops communities for its flexibility and well-defined specification of the code to be run. It is the underpinning of many services built in the past few years, such as [Amazon ECS].\n", "\n", "Amazon SageMaker uses Docker to allow users to train and deploy arbitrary algorithms.\n", "\n", "In Amazon SageMaker, Docker containers are invoked in a certain way for training and a slightly different way for hosting. The following sections outline how to build containers for the SageMaker environment.\n", "\n", "Some helpful links:\n", "\n", "* [Docker home page](http://www.docker.com)\n", "* [Getting started with Docker](https://docs.docker.com/get-started/)\n", "* [Dockerfile reference](https://docs.docker.com/engine/reference/builder/)\n", "* [`docker run` reference](https://docs.docker.com/engine/reference/run/)\n", "\n", "[Amazon ECS]: https://aws.amazon.com/ecs/\n", "\n", "### How Amazon SageMaker runs your Docker container\n", "\n", "Because you can run the same image in training or hosting, Amazon SageMaker runs your container with the argument `train` or `serve`. How your container processes this argument depends on the container:\n", "\n", "* In the example here, we don't define an `ENTRYPOINT` in the Dockerfile so Docker will run the command `train` at training time and `serve` at serving time. In this example, we define these as executable Python scripts, but they could be any program that we want to start in that environment.\n", "* If you specify a program as an `ENTRYPOINT` in the Dockerfile, that program will be run at startup and its first argument will be `train` or `serve`. The program can then look at that argument and decide what to do.\n", "* If you are building separate containers for training and hosting (or building only for one or the other), you can define a program as an `ENTRYPOINT` in the Dockerfile and ignore (or verify) the first argument passed in. \n", "\n", "#### Running your container during training\n", "\n", "When Amazon SageMaker runs training, your `train` script is run just like a regular Python program. A number of files are laid out for your use, under the `/opt/ml` directory:\n", "\n", " /opt/ml\n", " ├── input\n", " │   ├── config\n", " │   │   ├── hyperparameters.json\n", " │   │   └── resourceConfig.json\n", " │   └── data\n", " │   └── \n", " │   └── \n", " ├── model\n", " │   └── \n", " └── output\n", " └── failure\n", "\n", "##### The input\n", "\n", "* `/opt/ml/input/config` contains information to control how your program runs. `hyperparameters.json` is a JSON-formatted dictionary of hyperparameter names to values. These values will always be strings, so you may need to convert them. `resourceConfig.json` is a JSON-formatted file that describes the network layout used for distributed training. Since scikit-learn doesn't support distributed training, we'll ignore it here.\n", "* `/opt/ml/input/data//` (for File mode) contains the input data for that channel. The channels are created based on the call to CreateTrainingJob but it's generally important that channels match what the algorithm expects. The files for each channel will be copied from S3 to this directory, preserving the tree structure indicated by the S3 key structure. \n", "* `/opt/ml/input/data/_` (for Pipe mode) is the pipe for a given epoch. Epochs start at zero and go up by one each time you read them. There is no limit to the number of epochs that you can run, but you must close each pipe before reading the next epoch.\n", "\n", "##### The output\n", "\n", "* `/opt/ml/model/` is the directory where you write the model that your algorithm generates. Your model can be in any format that you want. It can be a single file or a whole directory tree. SageMaker will package any files in this directory into a compressed tar archive file. This file will be available at the S3 location returned in the `DescribeTrainingJob` result.\n", "* `/opt/ml/output` is a directory where the algorithm can write a file `failure` that describes why the job failed. The contents of this file will be returned in the `FailureReason` field of the `DescribeTrainingJob` result. For jobs that succeed, there is no reason to write this file as it will be ignored.\n", "\n", "#### Running your container during hosting\n", "\n", "Hosting has a very different model than training because hosting is reponding to inference requests that come in via HTTP. In this example, we use our recommended Python serving stack to provide robust and scalable serving of inference requests:\n", "\n", "![Request serving stack](stack.png)\n", "\n", "This stack is implemented in the sample code here and you can mostly just leave it alone. \n", "\n", "Amazon SageMaker uses two URLs in the container:\n", "\n", "* `/ping` will receive `GET` requests from the infrastructure. Your program returns 200 if the container is up and accepting requests.\n", "* `/invocations` is the endpoint that receives client inference `POST` requests. The format of the request and the response is up to the algorithm. If the client supplied `ContentType` and `Accept` headers, these will be passed in as well. \n", "\n", "The container will have the model files in the same place they were written during training:\n", "\n", " /opt/ml\n", " └── model\n", "    └── \n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The parts of the sample container\n", "\n", "In the `container` directory are all the components you need to package the sample algorithm for Amazon SageMager:\n", "\n", " .\n", " ├── Dockerfile\n", " ├── build_and_push.sh\n", " └── mask_r_cnn\n", " ├── nginx.conf\n", " ├── predictor.py\n", " ├── serve\n", " ├── wsgi.py\n", " ├── transforms.py\n", " ├── utils.py\n", " ├── coco_eval.py\n", " ├── coco_utils.py\n", " ├── engine.py\n", " └── helper.py\n", " \n", " \n", "\n", "Let's discuss each of these in turn:\n", "\n", "* __`Dockerfile`__ describes how to build your Docker container image. More details below.\n", "* __`build_and_push.sh`__ is a script that uses the Dockerfile to build your container images and then pushes it to ECR. We'll invoke the commands directly later in this notebook, but you can just copy and run the script for your own algorithms.\n", "* __`mask_r_cnn`__ is the directory which contains the files that will be installed in the container.\n", "\n", "\n", "In this simple application, we only install five files in the container. You may only need that many or, if you have many supporting routines, you may wish to install more. These five show the standard structure of our Python containers, although you are free to choose a different toolset and therefore could have a different layout. If you're writing in a different programming language, you'll certainly have a different layout depending on the frameworks and tools you choose.\n", "\n", "The files that we'll put in the container are:\n", "\n", "* __`nginx.conf`__ is the configuration file for the nginx front-end. Generally, you should be able to take this file as-is.\n", "* __`predictor.py`__ is the program that actually implements the Flask web server and the decision tree predictions for this app. \n", "* __`serve`__ is the program started when the container is started for hosting. It simply launches the gunicorn server which runs multiple instances of the Flask app defined in `predictor.py`. You should be able to take this file as-is.\n", "* __`train`__ is the program that is invoked when the container is run for training. \n", "* __`wsgi.py`__ is a small wrapper used to invoke the Flask app. You should be able to take this file as-is.\n", "\n", "We have customized `train.py` and `predictor.py` for fine tuning Mask R-CNN during training, and for loading tuned model, deserializing request data, making prediction, and sending back the serialized results." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The Dockerfile\n", "\n", "The Dockerfile describes the image that we want to build. You can think of it as describing the complete operating system installation of the system that you want to run. A Docker container running is quite a bit lighter than a full operating system, however, because it takes advantage of Linux on the host machine for the basic operations. \n", "\n", "For the Python science stack, we will start from a standard Ubuntu installation and run the normal tools to install the things needed by scikit-learn. Finally, we add the code that implements our specific algorithm to the container and set up the right environment to run under.\n", "\n", "Along the way, we clean up extra space. This makes the container smaller and faster to start.\n", "\n", "Let's look at the Dockerfile for the example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!cat container/Dockerfile" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Building and registering the container\n", "\n", "The following shell code shows how to build the container image using `docker build` and push the container image to ECR using `docker push`. This code is also available as the shell script `container/build-and-push.sh`, which you can run as `build-and-push.sh decision_trees_sample` to build the image `decision_trees_sample`. \n", "\n", "This code looks for an ECR repository in the account you're using and the current default region (if you're using a SageMaker notebook instance, this will be the region where the notebook instance was created). If the repository doesn't exist, the script will create it." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "%%sh\n", "\n", "# The name of our algorithm\n", "algorithm_name=mask-r-cnn\n", "\n", "cd container\n", "\n", "chmod +x mask_r_cnn/train\n", "chmod +x mask_r_cnn/serve\n", "\n", "account=$(aws sts get-caller-identity --query Account --output text)\n", "\n", "# Get the region defined in the current configuration (default to us-west-2 if none defined)\n", "region=$(aws configure get region)\n", "region=${region:-us-east-1}\n", "\n", "fullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${algorithm_name}:latest\"\n", "\n", "# If the repository doesn't exist in ECR, create it.\n", "aws ecr describe-repositories --repository-names \"${algorithm_name}\" > /dev/null 2>&1\n", "\n", "if [ $? -ne 0 ]\n", "then\n", " aws ecr create-repository --repository-name \"${algorithm_name}\" > /dev/null\n", "fi\n", "\n", "# Get the login command from ECR and execute it directly\n", "$(aws ecr get-login --region ${region} --no-include-email)\n", "\n", "# Build the docker image locally with the image name and then push it to ECR\n", "# with the full name.\n", "\n", "docker build -t ${algorithm_name} .\n", "docker tag ${algorithm_name} ${fullname}\n", "\n", "docker push ${fullname}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Part 2: Using your Algorithm in Amazon SageMaker\n", "\n", "Once you have your container packaged, you can use it to train models and use the model for hosting or batch transforms. Let's do that with the algorithm we made above.\n", "\n", "## Set up the environment\n", "\n", "Here we specify a bucket to use and the role that will be used for working with SageMaker." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define IAM role\n", "import boto3\n", "import re\n", "\n", "import os\n", "import numpy as np\n", "import pandas as pd\n", "from sagemaker import get_execution_role\n", "\n", "role = get_execution_role()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create the session\n", "\n", "The session remembers our connection parameters to SageMaker. We'll use it to perform all of our SageMaker operations." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import sagemaker as sage\n", "from time import gmtime, strftime\n", "\n", "sess = sage.Session()\n", "\n", "bucket = sess.default_bucket()\n", "prefix = 'DEMO-Mask-R-CNN'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Upload the data for training\n", "\n", "When training large models with huge amounts of data, you'll typically use big data tools, like Amazon Athena, AWS Glue, or Amazon EMR, to create your data in S3. For the purposes of this example, we're using some the classic [Iris dataset](https://en.wikipedia.org/wiki/Iris_flower_data_set), which we have included. \n", "\n", "We can use use the tools provided by the SageMaker Python SDK to upload the data to a default bucket. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "First, we need to download data for this sample notebook and upload it to S3. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%bash\n", "curl -o ./PennFudanPed.zip https://www.cis.upenn.edu/~jshi/ped_html/PennFudanPed.zip\n", "unzip PennFudanPed.zip\n", "aws s3 cp PennFudanPed s3://$bucket/$prefix/PennFudanPed --recursive" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!aws s3 cp PennFudanPed s3://$bucket/$prefix/PennFudanPed --recursive" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data_location = \"s3://{}/{}\".format(bucket, prefix)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create an estimator and fit the model\n", "\n", "In order to use SageMaker to fit our algorithm, we'll create an `Estimator` that defines how to use the container to train. This includes the configuration we need to invoke SageMaker training:\n", "\n", "* The __container name__. This is constructed as in the shell commands above.\n", "* The __role__. As defined above.\n", "* The __instance count__ which is the number of machines to use for training.\n", "* The __instance type__ which is the type of machine to use for training.\n", "* The __output path__ determines where the model artifact will be written.\n", "* The __session__ is the SageMaker session object that we defined above.\n", "\n", "Then we use fit() on the estimator to train against the data that we uploaded above." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "account = sess.boto_session.client('sts').get_caller_identity()['Account']\n", "region = sess.boto_session.region_name\n", "image = '{}.dkr.ecr.{}.amazonaws.com/mask-r-cnn:latest'.format(account, region)\n", "\n", "maskrcnn = sage.estimator.Estimator(image,\n", " role, 1, 'ml.p2.xlarge',\n", " output_path=\"s3://{}/output\".format(sess.default_bucket()),\n", " sagemaker_session=sess)\n", "#please adjust hyperparameters as needed. \n", "maskrcnn.set_hyperparameters(num_epochs = 1,\n", " num_classes = 2)\n", "\n", "maskrcnn.fit(data_location)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Hosting your model\n", "You can use a trained model to get real time predictions using HTTP endpoint. Follow these steps to walk you through the process." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Deploy the model\n", "\n", "Deploying the model to SageMaker hosting just requires a `deploy` call on the fitted model. This call takes an instance count, instance type, and optionally serializer and deserializer functions. These are used when the resulting predictor is created on the endpoint." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "#from sagemaker.predictor import csv_serializer\n", "predictor = maskrcnn.deploy(1, \n", " 'ml.p2.xlarge', \n", " endpoint_name='mask-r-cnn-2019-10-12-06-23-29-658') #, update_endpoint=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Choose some data and use it for a prediction\n", "\n", "In order to do some predictions, we'll extract some of the data we used for training and do predictions against it. This is, of course, bad statistical practice, but a good way to see how the mechanism works." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from PIL import Image\n", "import numpy as np\n", "import pickle" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json\n", "import time\n", "import io\n", "\n", "def test_image_using_img_bytes(fn):\n", " print('Opening image: {}...'.format(fn))\n", " pil_img = Image.open(fn)\n", " print('Image size is: {}...'.format(pil_img.size))\n", " \n", " if pil_img.size[0] * pil_img.size[1] > 5000000:\n", " print('Too big to pass to an SM endpoint, exiting\\n')\n", " else:\n", " display(pil_img)\n", " \n", " print('Finding the walkers...')\n", "\n", " buf = io.BytesIO()\n", " pil_img.save(buf, format='JPEG')\n", " byte_im = buf.getvalue()\n", "\n", " start_time = time.time()\n", " result = predictor.predict(byte_im)\n", " print('...took {:.2f} seconds'.format(time.time() - start_time))\n", " \n", " prediction = json.loads(result)\n", " print('Found {} people walking in that image'.format(len(prediction)))\n", " for i in range(len(prediction)):\n", " x = Image.fromarray(np.uint8(np.asarray(prediction[i][0])*255))\n", " display(x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "test_images = ['FudanPed00001.png']" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in test_images:\n", " test_image_using_img_bytes(i)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "test_image_using_img_bytes(test_images[0])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Optional cleanup\n", "When you're done with the endpoint, you'll want to clean it up." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sess.delete_endpoint(predictor.endpoint)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "conda_pytorch_p36", "language": "python", "name": "conda_pytorch_p36" }, "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.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }