{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Hosting ONNX models with Amazon Elastic Inference\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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.ipynb)\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "*(This notebook was tested with the \"Python 3 (MXNet CPU Optimized)\" kernel.)*\n",
    "\n",
    "Amazon Elastic Inference (EI) is a resource you can attach to your Amazon EC2 instances to accelerate your deep learning (DL) inference workloads. EI allows you to add inference acceleration to an Amazon SageMaker hosted endpoint or Jupyter notebook and reduce the cost of running deep learning inference by up to 75%, when compared to using GPU instances. For more information, please visit: https://docs.aws.amazon.com/sagemaker/latest/dg/ei.html\n",
    "\n",
    "Amazon EI provides support for a variety of frameworks, including Apache MXNet and ONNX models. The [Open Neural Network Exchange](https://onnx.ai/) (ONNX) is an open standard format for deep learning models that enables interoperability between deep learning frameworks such as Apache MXNet, Microsoft Cognitive Toolkit (CNTK), PyTorch and more. This means that we can use any of these frameworks to train the model, export these pretrained models in ONNX format and then import them in MXNet for inference.\n",
    "\n",
    "In this example, we use the ResNet-152v1 model from [Deep residual learning for image recognition](https://arxiv.org/abs/1512.03385). This model, alongside many others, can be found at the [ONNX Model Zoo](https://github.com/onnx/models).\n",
    "\n",
    "We use the SageMaker Python SDK to host this ONNX model in SageMaker and perform inference requests."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "First, we get the IAM execution role from our notebook environment, so that SageMaker can access resources in your AWS account later in the example."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "isConfigCell": true
   },
   "outputs": [],
   "source": [
    "from sagemaker import get_execution_role\n",
    "\n",
    "role = get_execution_role()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The inference script\n",
    "\n",
    "We need to provide an inference script that can run on the SageMaker platform. This script is invoked by SageMaker when we perform inference.\n",
    "\n",
    "The script we're using here implements two functions:\n",
    "\n",
    "* `model_fn()` - loads the model\n",
    "* `transform_fn()` - uses the model to take the input and produce the output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pygmentize resnet152.py"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Preparing the model\n",
    "\n",
    "To create a SageMaker Endpoint, we first need to prepare the model to be used in SageMaker."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Downloading the model\n",
    "\n",
    "For this example, we use a pre-trained ONNX model from the [ONNX Model Zoo](https://github.com/onnx/models), where you can find a collection of pre-trained models to work with. Here, we download the [ResNet-152v1 model](https://s3.amazonaws.com/onnx-model-zoo/resnet/resnet152v1/resnet152v1.onnx) trained on ImageNet dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import mxnet as mx\n",
    "\n",
    "mx.test_utils.download(\n",
    "    \"https://s3.amazonaws.com/onnx-model-zoo/resnet/resnet152v1/resnet152v1.onnx\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Compressing the model data\n",
    "\n",
    "Now that we have the model data locally, we need to compress it, and then upload it to S3."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tarfile\n",
    "\n",
    "from sagemaker import s3, session\n",
    "\n",
    "with tarfile.open(\"onnx_model.tar.gz\", mode=\"w:gz\") as archive:\n",
    "    archive.add(\"resnet152v1.onnx\")\n",
    "\n",
    "bucket = session.Session().default_bucket()\n",
    "model_data = s3.S3Uploader.upload(\n",
    "    \"onnx_model.tar.gz\", \"s3://{}/mxnet-onnx-resnet152-example/model\".format(bucket)\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Creating a SageMaker Python SDK Model instance\n",
    "\n",
    "With the model data uploaded to S3, we now have everything we need to instantiate a SageMaker Python SDK Model. We provide the constructor the following arguments:\n",
    "\n",
    "* `model_data`: the S3 location of the model data\n",
    "* `entry_point`: the script for model hosting that we looked at above\n",
    "* `role`: the IAM role used\n",
    "* `framework_version`: the MXNet version in use, in this case '1.4.1'\n",
    "\n",
    "For more about creating an `MXNetModel` object, see the [SageMaker Python SDK API docs](https://sagemaker.readthedocs.io/en/latest/sagemaker.mxnet.html#mxnet-model)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sagemaker.mxnet import MXNetModel\n",
    "\n",
    "mxnet_model = MXNetModel(\n",
    "    model_data=model_data,\n",
    "    entry_point=\"resnet152.py\",\n",
    "    role=role,\n",
    "    py_version=\"py3\",\n",
    "    framework_version=\"1.4.1\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Creating an inference endpoint and attaching an Elastic Inference(EI) accelerator\n",
    "\n",
    "Now we can use our `MXNetModel` object to build and deploy an `MXNetPredictor`. This creates a SageMaker Model and Endpoint, the latter of which we can use for performing inference. \n",
    "\n",
    "We pass the following arguments to the `deploy()` method:\n",
    "\n",
    "* `instance_count` - how many instances to back the endpoint.\n",
    "* `instance_type` - which EC2 instance type to use for the endpoint.\n",
    "* `accelerator_type` - which EI accelerator type to attach to each of our instances.\n",
    "\n",
    "For information on supported instance types and accelerator types, please see [the AWS documentation](https://aws.amazon.com/sagemaker/pricing/instance-types).\n",
    "\n",
    "### How our models are loaded\n",
    "By default, the predefined SageMaker MXNet containers have a default `model_fn`, which loads the model. The default `model_fn` loads an MXNet Module object with a context based on the instance type of the endpoint.\n",
    "\n",
    "This applies for EI as well. If an EI accelerator is attached to your endpoint and a custom `model_fn` isn't provided, then the default `model_fn` loads the MXNet Module object with an EI context, `mx.eia()`. This default `model_fn` works with the default save function provided by the pre-built SageMaker MXNet Docker image for training. If the model is saved in a different manner, then a custom `model_fn` implementation may be needed. For more information on `model_fn`, see [the SageMaker documentation](https://sagemaker.readthedocs.io/en/stable/using_mxnet.html#load-a-model).\n",
    "\n",
    "### Choosing instance types\n",
    "Here, we deploy our model with instance type `ml.m5.xlarge` and `ml.eia1.medium`. For this model, we found that it requires more CPU memory and thus chose an M5 instance, which has more memory than C5 instances, making it more cost effective. With other models, you may want to experiment with other instance types and accelerators based on your model requirements."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "\n",
    "predictor = mxnet_model.deploy(\n",
    "    initial_instance_count=1, instance_type=\"ml.m5.xlarge\", accelerator_type=\"ml.eia1.medium\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Performing inference\n",
    "\n",
    "With our Endpoint deployed, we can now send inference requests to it. We use one image as an example here."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Preparing the image\n",
    "\n",
    "First, we download the image (and view it)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "img_path = mx.test_utils.download(\"https://s3.amazonaws.com/onnx-mxnet/examples/mallard_duck.jpg\")\n",
    "img = mx.image.imread(img_path)\n",
    "plt.imshow(img.asnumpy())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we preprocess inference image. We resize it to 256x256, take center crop of 224x224, normalize image, and add a dimension to batchify the image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from mxnet.gluon.data.vision import transforms\n",
    "\n",
    "\n",
    "def preprocess(img):\n",
    "    transform_fn = transforms.Compose(\n",
    "        [\n",
    "            transforms.Resize(256),\n",
    "            transforms.CenterCrop(224),\n",
    "            transforms.ToTensor(),\n",
    "            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n",
    "        ]\n",
    "    )\n",
    "    img = transform_fn(img)\n",
    "    img = img.expand_dims(axis=0)\n",
    "    return img\n",
    "\n",
    "\n",
    "input_image = preprocess(img)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Sending the inference request\n",
    "\n",
    "Now we can use the predictor object to classify the input image:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "scores = predictor.predict(input_image.asnumpy())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To see the inference result, let's download and load `synset.txt` file containing class labels for ImageNet. The top 5 classes generated in order, along with the probabilities are:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "mx.test_utils.download(\"https://s3.amazonaws.com/onnx-model-zoo/synset.txt\")\n",
    "with open(\"synset.txt\", \"r\") as f:\n",
    "    labels = [l.rstrip() for l in f]\n",
    "\n",
    "a = np.argsort(scores)[::-1]\n",
    "\n",
    "for i in a[0:5]:\n",
    "    print(\"class=%s; probability=%f\" % (labels[i], scores[i]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Deleting the Endpoint\n",
    "\n",
    "Since we've reached the end, we delete the SageMaker Endpoint to release the instance associated with it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictor.delete_endpoint()"
   ]
  },
  {
   "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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.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/aws_sagemaker_studio|frameworks|mxnet_onnx_ei|mxnet_onnx_ei.ipynb)\n"
   ]
  }
 ],
 "metadata": {
  "instance_type": "ml.t3.medium",
  "kernelspec": {
   "display_name": "Python 3 (MXNet 1.9 Python 3.8 CPU Optimized)",
   "language": "python",
   "name": "python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-west-2:236514542706:image/mxnet-1.9-cpu-py38-ubuntu20.04-sagemaker-v1.0"
  },
  "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.8.10"
  },
  "notice": "Copyright 2019 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
}