{ "cells": [ { "attachments": {}, "cell_type": "markdown", "id": "2fcf8993", "metadata": {}, "source": [ "# SageMaker Serverless Inference\n" ] }, { "attachments": {}, "cell_type": "markdown", "id": "61d5a3fa", "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/serverless-inference|Serverless-Inference-Walkthrough.ipynb)\n", "\n", "---" ] }, { "attachments": {}, "cell_type": "markdown", "id": "4048856b", "metadata": {}, "source": [ "## XGBoost Regression Example\n", "\n", "Amazon SageMaker Serverless Inference is a purpose-built inference option that makes it easy for customers to deploy and scale ML models. Serverless Inference is ideal for workloads which have idle periods between traffic spurts and can tolerate cold starts. Serverless endpoints also automatically launch compute resources and scale them in and out depending on traffic, eliminating the need to choose instance types or manage scaling policies.\n", "\n", "For this notebook we'll be working with the SageMaker XGBoost Algorithm to train a model and then deploy a serverless endpoint. We will be using the public S3 Abalone regression dataset for this example.\n", "\n", "Notebook Setting\n", "- SageMaker Classic Notebook Instance: ml.m5.xlarge Notebook Instance & `conda_python3` Kernel\n", "- SageMaker Studio: Python 3 (Data Science)\n", "- Regions Available: SageMaker Serverless Inference is currently available in the following regions: US East (Northern Virginia), US East (Ohio), US West (Oregon), EU (Ireland), Asia Pacific (Tokyo) and Asia Pacific (Sydney)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "5d45aa9a", "metadata": {}, "source": [ "## Table of Contents\n", "- Setup\n", "- Model Training\n", "- Deployment\n", " - Model Creation\n", " - Endpoint Configuration (Adjust for Serverless)\n", " - Serverless Endpoint Creation\n", " - Endpoint Invocation\n", "- Cleanup" ] }, { "attachments": {}, "cell_type": "markdown", "id": "3ec297d3", "metadata": {}, "source": [ "## Setup\n", "\n", "For testing you need to properly configure your Notebook Role to have SageMaker Full Access." ] }, { "attachments": {}, "cell_type": "markdown", "id": "1affea20", "metadata": {}, "source": [ "Let's start by upgrading the Python SDK, `boto3` and AWS `CLI` (Command Line Interface) packages." ] }, { "cell_type": "code", "execution_count": null, "id": "c500058e", "metadata": {}, "outputs": [], "source": [ "! pip install sagemaker botocore boto3 awscli --upgrade" ] }, { "cell_type": "code", "execution_count": null, "id": "f1cd6f53", "metadata": {}, "outputs": [], "source": [ "# Setup clients\n", "import boto3\n", "\n", "client = boto3.client(service_name=\"sagemaker\")\n", "runtime = boto3.client(service_name=\"sagemaker-runtime\")" ] }, { "attachments": {}, "cell_type": "markdown", "id": "aed409fe", "metadata": {}, "source": [ "### SageMaker Setup\n", "To begin, we import the AWS SDK for Python (Boto3) and set up our environment, including an IAM role and an S3 bucket to store our data." ] }, { "cell_type": "code", "execution_count": null, "id": "2c5e13f5", "metadata": {}, "outputs": [], "source": [ "import boto3\n", "import sagemaker\n", "from sagemaker.estimator import Estimator\n", "\n", "boto_session = boto3.session.Session()\n", "region = boto_session.region_name\n", "print(region)\n", "\n", "sagemaker_session = sagemaker.Session()\n", "base_job_prefix = \"xgboost-example\"\n", "role = sagemaker.get_execution_role()\n", "print(role)\n", "\n", "default_bucket = sagemaker_session.default_bucket()\n", "s3_prefix = base_job_prefix\n", "\n", "training_instance_type = \"ml.m5.xlarge\"" ] }, { "attachments": {}, "cell_type": "markdown", "id": "0f634875", "metadata": {}, "source": [ "Retrieve the Abalone dataset from a publicly hosted S3 bucket." ] }, { "cell_type": "code", "execution_count": null, "id": "dd1160f4", "metadata": {}, "outputs": [], "source": [ "# retrieve data\n", "s3 = boto3.client(\"s3\")\n", "s3.download_file(\n", " f\"sagemaker-example-files-prod-{region}\",\n", " \"datasets/tabular/uci_abalone/train_csv/abalone_dataset1_train.csv\",\n", " \"abalone_dataset1_train.csv\",\n", ")" ] }, { "attachments": {}, "cell_type": "markdown", "id": "70baa8b0", "metadata": {}, "source": [ "Upload the Abalone dataset to the default S3 bucket." ] }, { "cell_type": "code", "execution_count": null, "id": "81d7425b", "metadata": {}, "outputs": [], "source": [ "# upload data to S3\n", "!aws s3 cp abalone_dataset1_train.csv s3://{default_bucket}/xgboost-regression/train.csv" ] }, { "attachments": {}, "cell_type": "markdown", "id": "010a6765", "metadata": {}, "source": [ "## Model Training" ] }, { "attachments": {}, "cell_type": "markdown", "id": "6ccffd64", "metadata": {}, "source": [ "Now, we train an ML model using the XGBoost Algorithm. In this example, we use a SageMaker-provided [XGBoost](https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost.html) container image and configure an estimator to train our model." ] }, { "cell_type": "code", "execution_count": null, "id": "7e47bcc0", "metadata": {}, "outputs": [], "source": [ "from sagemaker.inputs import TrainingInput\n", "\n", "training_path = f\"s3://{default_bucket}/xgboost-regression/train.csv\"\n", "train_input = TrainingInput(training_path, content_type=\"text/csv\")" ] }, { "cell_type": "code", "execution_count": null, "id": "6eb21f5e", "metadata": {}, "outputs": [], "source": [ "model_path = f\"s3://{default_bucket}/{s3_prefix}/xgb_model\"\n", "\n", "# retrieve xgboost image\n", "image_uri = sagemaker.image_uris.retrieve(\n", " framework=\"xgboost\",\n", " region=region,\n", " version=\"1.0-1\",\n", " py_version=\"py3\",\n", " instance_type=training_instance_type,\n", ")\n", "\n", "# Configure Training Estimator\n", "xgb_train = Estimator(\n", " image_uri=image_uri,\n", " instance_type=training_instance_type,\n", " instance_count=1,\n", " output_path=model_path,\n", " sagemaker_session=sagemaker_session,\n", " role=role,\n", ")\n", "\n", "# Set Hyperparameters\n", "xgb_train.set_hyperparameters(\n", " objective=\"reg:linear\",\n", " num_round=50,\n", " max_depth=5,\n", " eta=0.2,\n", " gamma=4,\n", " min_child_weight=6,\n", " subsample=0.7,\n", " silent=0,\n", ")" ] }, { "attachments": {}, "cell_type": "markdown", "id": "8638fad2", "metadata": {}, "source": [ "Train the model on the Abalone dataset." ] }, { "cell_type": "code", "execution_count": null, "id": "ad24755a", "metadata": {}, "outputs": [], "source": [ "# Fit model\n", "xgb_train.fit({\"train\": train_input})" ] }, { "attachments": {}, "cell_type": "markdown", "id": "fb2f4628", "metadata": {}, "source": [ "## Deployment" ] }, { "attachments": {}, "cell_type": "markdown", "id": "efabadc5", "metadata": {}, "source": [ "After training the model, retrieve the model artifacts so that we can deploy the model to an endpoint." ] }, { "cell_type": "code", "execution_count": null, "id": "086573fb", "metadata": {}, "outputs": [], "source": [ "# Retrieve model data from training job\n", "model_artifacts = xgb_train.model_data\n", "model_artifacts" ] }, { "attachments": {}, "cell_type": "markdown", "id": "93b5dd29", "metadata": {}, "source": [ "### Model Creation\n", "Create a model by providing your model artifacts, the container image URI, environment variables for the container (if applicable), a model name, and the SageMaker IAM role." ] }, { "cell_type": "code", "execution_count": null, "id": "466b481a", "metadata": {}, "outputs": [], "source": [ "from time import gmtime, strftime\n", "\n", "model_name = \"xgboost-serverless\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n", "print(\"Model name: \" + model_name)\n", "\n", "# dummy environment variables\n", "byo_container_env_vars = {\"SAGEMAKER_CONTAINER_LOG_LEVEL\": \"20\", \"SOME_ENV_VAR\": \"myEnvVar\"}\n", "\n", "create_model_response = client.create_model(\n", " ModelName=model_name,\n", " Containers=[\n", " {\n", " \"Image\": image_uri,\n", " \"Mode\": \"SingleModel\",\n", " \"ModelDataUrl\": model_artifacts,\n", " \"Environment\": byo_container_env_vars,\n", " }\n", " ],\n", " ExecutionRoleArn=role,\n", ")\n", "\n", "print(\"Model Arn: \" + create_model_response[\"ModelArn\"])" ] }, { "attachments": {}, "cell_type": "markdown", "id": "a5a7ac35", "metadata": {}, "source": [ "### Endpoint Configuration Creation\n", "\n", "This is where you can adjust the Serverless Configuration for your endpoint. The current max concurrent invocations for a single endpoint, known as `MaxConcurrency`, can be any value from 1 to 200, and `MemorySize` can be any of the following: 1024 MB, 2048 MB, 3072 MB, 4096 MB, 5120 MB, or 6144 MB." ] }, { "cell_type": "code", "execution_count": null, "id": "cb84726e", "metadata": {}, "outputs": [], "source": [ "xgboost_epc_name = \"xgboost-serverless-epc\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n", "\n", "endpoint_config_response = client.create_endpoint_config(\n", " EndpointConfigName=xgboost_epc_name,\n", " ProductionVariants=[\n", " {\n", " \"VariantName\": \"byoVariant\",\n", " \"ModelName\": model_name,\n", " \"ServerlessConfig\": {\n", " \"MemorySizeInMB\": 4096,\n", " \"MaxConcurrency\": 1,\n", " },\n", " },\n", " ],\n", ")\n", "\n", "print(\"Endpoint Configuration Arn: \" + endpoint_config_response[\"EndpointConfigArn\"])" ] }, { "attachments": {}, "cell_type": "markdown", "id": "ea3321da", "metadata": {}, "source": [ "### Serverless Endpoint Creation\n", "Now that we have an endpoint configuration, we can create a serverless endpoint and deploy our model to it. When creating the endpoint, provide the name of your endpoint configuration and a name for the new endpoint." ] }, { "cell_type": "code", "execution_count": null, "id": "7f9f93e8", "metadata": {}, "outputs": [], "source": [ "endpoint_name = \"xgboost-serverless-ep\" + strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n", "\n", "create_endpoint_response = client.create_endpoint(\n", " EndpointName=endpoint_name,\n", " EndpointConfigName=xgboost_epc_name,\n", ")\n", "\n", "print(\"Endpoint Arn: \" + create_endpoint_response[\"EndpointArn\"])" ] }, { "attachments": {}, "cell_type": "markdown", "id": "831d2181", "metadata": {}, "source": [ "Wait until the endpoint status is `InService` before invoking the endpoint." ] }, { "cell_type": "code", "execution_count": null, "id": "335e2ecd", "metadata": {}, "outputs": [], "source": [ "# wait for endpoint to reach a terminal state (InService) using describe endpoint\n", "import time\n", "\n", "describe_endpoint_response = client.describe_endpoint(EndpointName=endpoint_name)\n", "\n", "while describe_endpoint_response[\"EndpointStatus\"] == \"Creating\":\n", " describe_endpoint_response = client.describe_endpoint(EndpointName=endpoint_name)\n", " print(describe_endpoint_response[\"EndpointStatus\"])\n", " time.sleep(15)\n", "\n", "describe_endpoint_response" ] }, { "attachments": {}, "cell_type": "markdown", "id": "bdd1d0a4", "metadata": {}, "source": [ "### Endpoint Invocation\n", "Invoke the endpoint by sending a request to it. The following is a sample data point grabbed from the CSV file downloaded from the public Abalone dataset." ] }, { "cell_type": "code", "execution_count": null, "id": "f2c93e8a", "metadata": {}, "outputs": [], "source": [ "response = runtime.invoke_endpoint(\n", " EndpointName=endpoint_name,\n", " Body=b\".345,0.224414,.131102,0.042329,.279923,-0.110329,-0.099358,0.0\",\n", " ContentType=\"text/csv\",\n", ")\n", "\n", "print(response[\"Body\"].read())" ] }, { "attachments": {}, "cell_type": "markdown", "id": "de35dc1e", "metadata": {}, "source": [ "## Clean Up\n", "Delete any resources you created in this notebook that you no longer wish to use." ] }, { "cell_type": "code", "execution_count": null, "id": "e895a46e", "metadata": {}, "outputs": [], "source": [ "client.delete_model(ModelName=model_name)\n", "client.delete_endpoint_config(EndpointConfigName=xgboost_epc_name)\n", "client.delete_endpoint(EndpointName=endpoint_name)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "b98fea79", "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/serverless-inference|Serverless-Inference-Walkthrough.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/serverless-inference|Serverless-Inference-Walkthrough.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/serverless-inference|Serverless-Inference-Walkthrough.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/serverless-inference|Serverless-Inference-Walkthrough.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/serverless-inference|Serverless-Inference-Walkthrough.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/serverless-inference|Serverless-Inference-Walkthrough.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/serverless-inference|Serverless-Inference-Walkthrough.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/serverless-inference|Serverless-Inference-Walkthrough.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/serverless-inference|Serverless-Inference-Walkthrough.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/serverless-inference|Serverless-Inference-Walkthrough.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/serverless-inference|Serverless-Inference-Walkthrough.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/serverless-inference|Serverless-Inference-Walkthrough.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/serverless-inference|Serverless-Inference-Walkthrough.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/serverless-inference|Serverless-Inference-Walkthrough.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/serverless-inference|Serverless-Inference-Walkthrough.ipynb)\n" ] } ], "metadata": { "instance_type": "ml.t3.medium", "kernelspec": { "display_name": "Python 3 (Data Science 3.0)", "language": "python", "name": "python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-east-1:081325390199:image/sagemaker-data-science-310-v1" }, "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.10.6" } }, "nbformat": 4, "nbformat_minor": 5 }