{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# SageMaker Inference Recommender - XGBoost"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Introduction\n",
"\n",
"SageMaker Inference Recommender is a new capability of SageMaker that reduces the time required to get machine learning (ML) models in production by automating load tests and optimizing model performance across instance types. You can use Inference Recommender to select a real-time inference endpoint that delivers the best performance at the lowest cost. \n",
"\n",
"Get started with Inference Recommender on SageMaker in minutes while selecting an instance and get an optimized endpoint configuration in hours, eliminating weeks of manual testing and tuning time."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Setup \n",
"\n",
"Note that we are using the `conda_python3` kernel in SageMaker Notebook Instances. This is running Python 3.6. If you'd like to use the same setup, in the AWS Management Console, go to the Amazon SageMaker console. Choose Notebook Instances, and click create a new notebook instance. Upload the current notebook and set the kernel. You can also run this in SageMaker Studio Notebooks with the `Python 3 (Data Science)` kernel.\n",
"\n",
"In the next steps, you'll import standard methods and libraries as well as set variables that will be used in this notebook. The `get_execution_role` function retrieves the AWS Identity and Access Management (IAM) role you created at the time of creating your notebook instance."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sagemaker import get_execution_role, Session, image_uris\n",
"import boto3\n",
"import time"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"region = boto3.Session().region_name\n",
"role = get_execution_role()\n",
"sm_client = boto3.client(\"sagemaker\", region_name=region)\n",
"sagemaker_session = Session()\n",
"print(region)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Machine learning model details\n",
"\n",
"Inference Recommender uses metadata about your ML model to recommend the best instance types and endpoint configurations for deployment. You can provide as much or as little information as you'd like but the more information you provide, the better your recommendations will be.\n",
"\n",
"ML Frameworks: `TENSORFLOW, PYTORCH, XGBOOST, SAGEMAKER-SCIKIT-LEARN`\n",
"\n",
"ML Domains: `COMPUTER_VISION, NATURAL_LANGUAGE_PROCESSING, MACHINE_LEARNING`\n",
"\n",
"Example ML Tasks: `CLASSIFICATION, REGRESSION, IMAGE_CLASSIFICATION, OBJECT_DETECTION, SEGMENTATION, MASK_FILL, TEXT_CLASSIFICATION, TEXT_GENERATION, OTHER`\n",
"\n",
"Note: Select the task that is the closest match to your model. Chose `OTHER` if none apply."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# ML framework details\n",
"framework = \"XGBOOST\"\n",
"framework_version = \"1.2.0\"\n",
"\n",
"# model name as standardized by model zoos or a similar open source model\n",
"model_name = \"xgboost\"\n",
"\n",
"# ML model details\n",
"ml_domain = \"MACHINE_LEARNING\"\n",
"ml_task = \"CLASSIFICATION\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. Create a model archive\n",
"\n",
"SageMaker models need to be packaged in `.tar.gz` files. When your SageMaker Endpoint is provisioned, the files in the archive will be extracted and put in `/opt/ml/model/` on the Endpoint. \n",
"\n",
"In this step, there are two optional tasks to:\n",
"\n",
" (1) Download a pretrained model from Keras applications\n",
" \n",
" (2) Download a sample inference script (inference.py) from S3\n",
" \n",
"These tasks are provided as a sample reference but can and should be modified when using your own trained models with Inference Recommender. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Optional: Train an XGBoost model\n",
"\n",
"Let's quickly train an XGBoost model. If you already have a model, you can skip this step and proceed to the next section.\n",
"\n",
"For the purposes of this notebook, we are training an XGBoost model on random data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Install sklearn and XGBoost\n",
"!pip3 install -U scikit-learn xgboost==1.2.0 --quiet"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Import required libraries\n",
"import numpy as np\n",
"from numpy import loadtxt\n",
"from xgboost import XGBClassifier\n",
"from sklearn.model_selection import train_test_split"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Generate dummy data to perform binary classification\n",
"seed = 7\n",
"features = 50 # number of features\n",
"samples = 10000 # number of samples\n",
"X = np.random.rand(samples, features).astype(\"float32\")\n",
"Y = np.random.randint(2, size=samples)\n",
"\n",
"test_size = 0.1\n",
"X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=test_size, random_state=seed)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model = XGBClassifier()\n",
"model.fit(X_train, y_train)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model_fname = \"xgboost.model\"\n",
"model.save_model(model_fname)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create a tarball\n",
"\n",
"To bring your own XGBoost model, SageMaker expects a single archive file in .tar.gz format, containing a model file and optionally inference code."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model_archive_name = \"xgbmodel.tar.gz\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!tar -cvpzf {model_archive_name} 'xgboost.model'"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "z9kutpTP-uxd"
},
"source": [
"### Upload to S3\n",
"\n",
"We now have a model archive ready. We need to upload it to S3 before we can use with Inference Recommender. Furthermore, we will use the SageMaker Python SDK to handle the upload."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "TocwZSw4-uxd"
},
"outputs": [],
"source": [
"# model package tarball (model artifact + inference code)\n",
"model_url = sagemaker_session.upload_data(path=model_archive_name, key_prefix=\"xgbmodel\")\n",
"print(\"model uploaded to: {}\".format(model_url))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5. Create a sample payload archive\n",
"\n",
"We need to create an archive that contains individual files that Inference Recommender can send to your SageMaker Endpoints. Inference Recommender will randomly sample files from this archive so make sure it contains a similar distribution of payloads you'd expect in production. Note that your inference code must be able to read in the file formats from the sample payload.\n",
"\n",
"*Here we are only adding a single CSV file for the example. In your own use case(s), it's recommended to add a variety of samples that is representative of your payloads.* "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"payload_archive_name = \"xgb_payload.tar.gz\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(X_test.shape)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"batch_size = 100\n",
"np.savetxt(\"sample.csv\", X_test[0:batch_size, :], delimiter=\",\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!wc -l sample.csv"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create a tarball"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!tar -cvzf {payload_archive_name} sample.csv"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Upload to S3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, we'll upload the packaged payload examples (payload.tar.gz) that was created above to S3. The S3 location will be used as input to our Inference Recommender job later in this notebook. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sample_payload_url = sagemaker_session.upload_data(path=payload_archive_name, key_prefix=\"xgb_payload\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 6. Register model in Model Registry\n",
"\n",
"In order to use Inference Recommender, you must have a versioned model in SageMaker Model Registry. To register a model in the Model Registry, you must have a model artifact packaged in a tarball and an inference container image. Registering a model includes the following steps:\n",
"\n",
"\n",
"1) **Create Model Group:** This is a one-time task per machine learning use case. A Model Group contains one or more versions of your packaged model. \n",
"\n",
"2) **Register Model Version/Package:** This task is performed for each new packaged model version. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Container image URL\n",
"\n",
"If you don’t have an inference container image, you can use one of the open source AWS [Deep Learning Containers (DLCs)](https://github.com/aws/deep-learning-containers) provided by AWS to serve your ML model. The code below retrieves a DLC based on your ML framework, framework version, python version, and instance type."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"dlc_uri = image_uris.retrieve(\"xgboost\", region, \"1.2-1\")\n",
"dlc_uri"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create Model Group"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model_package_group_name = \"{}-cpu-models-\".format(framework) + str(round(time.time()))\n",
"model_package_group_description = \"{} models\".format(ml_task.lower())\n",
"\n",
"model_package_group_input_dict = {\n",
" \"ModelPackageGroupName\": model_package_group_name,\n",
" \"ModelPackageGroupDescription\": model_package_group_description,\n",
"}\n",
"\n",
"create_model_package_group_response = sm_client.create_model_package_group(\n",
" **model_package_group_input_dict\n",
")\n",
"print(\n",
" \"ModelPackageGroup Arn : {}\".format(create_model_package_group_response[\"ModelPackageGroupArn\"])\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Register Model Version/Package\n",
"\n",
"In this step, you'll register your pretrained model that was packaged in the prior steps as a new version in SageMaker Model Registry. First, you'll configure the model package/version identifying which model package group this new model should be registered within as well as identify the initial approval status. You'll also identify the domain and task for your model. These values were set earlier in the notebook \n",
"where `ml_domain = 'MACHINE_LEARNING'` and `ml_task = 'CLASSIFICATION'`\n",
"\n",
"*Note: ModelApprovalStatus is a configuration parameter that can be used in conjunction with SageMaker Projects to trigger automated deployment pipeline.* "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model_package_description = \"{} {} inference recommender\".format(framework, model_name)\n",
"\n",
"model_approval_status = \"PendingManualApproval\"\n",
"\n",
"create_model_package_input_dict = {\n",
" \"ModelPackageGroupName\": model_package_group_name,\n",
" \"Domain\": ml_domain.upper(),\n",
" \"Task\": ml_task.upper(),\n",
" \"SamplePayloadUrl\": sample_payload_url,\n",
" \"ModelPackageDescription\": model_package_description,\n",
" \"ModelApprovalStatus\": model_approval_status,\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Set up inference specification\n",
"\n",
"You'll now set up the inference specification configuration for your model version. This contains information on how the model should be hosted."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Inference Recommender expects a single input MIME type for sending requests. Learn more about [common inference data formats on SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-inference.html). This MIME type will be sent in the Content-Type header when invoking your endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"input_mime_types = [\"text/csv\"]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you specify a set of instance types below (i.e. non-empty list), then Inference Recommender will only support recommendations within the set of instances below. For this example, we provide a list of common CPU instance types used with XGBoost. Note that, if you want to try to compile your XGboost model with Amazon SageMaker Neo, it supports images list here: [Inference Container Images](https://docs.aws.amazon.com/sagemaker/latest/dg/neo-deployment-hosting-services-container-images.html) or SageMaker XGboost containers. And you need to make sure the xgboost version is 1.0 to 1.3."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"supported_realtime_inference_types = [\n",
" \"ml.m4.2xlarge\",\n",
" \"ml.c5.2xlarge\",\n",
" \"ml.c5.xlarge\",\n",
" \"ml.c5.9xlarge\",\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"modelpackage_inference_specification = {\n",
" \"InferenceSpecification\": {\n",
" \"Containers\": [\n",
" {\n",
" \"Image\": dlc_uri,\n",
" \"Framework\": framework.upper(),\n",
" \"FrameworkVersion\": framework_version,\n",
" \"NearestModelName\": model_name\n",
" }\n",
" ],\n",
" \"SupportedContentTypes\": input_mime_types, # required, must be non-null\n",
" \"SupportedResponseMIMETypes\": [],\n",
" \"SupportedRealtimeInferenceInstanceTypes\": supported_realtime_inference_types, # optional\n",
" }\n",
"}\n",
"\n",
"# Specify the model data\n",
"modelpackage_inference_specification[\"InferenceSpecification\"][\"Containers\"][0][\n",
" \"ModelDataUrl\"\n",
"] = model_url"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that you've configured the model package, the next step is to create the model package/version in SageMaker Model Registry"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"create_model_package_input_dict.update(modelpackage_inference_specification)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"create_mode_package_response = sm_client.create_model_package(**create_model_package_input_dict)\n",
"model_package_arn = create_mode_package_response[\"ModelPackageArn\"]\n",
"print(\"ModelPackage Version ARN : {}\".format(model_package_arn))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 7. Create an Inference Recommender Default Job\n",
"\n",
"Now with your model in Model Registry, you can kick off a 'Default' job to get instance recommendations. This only requires your `ModelPackageVersionArn` and comes back with recommendations within 45 minutes.\n",
"\n",
"The output is a list of instance type recommendations with associated environment variables, cost, throughput and latency metrics."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"job_name = model_name + \"-instance-\" + str(round(time.time()))\n",
"job_description = \"{} {}\".format(framework, model_name)\n",
"job_type = \"Default\"\n",
"print(job_name)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"rv = sm_client.create_inference_recommendations_job(\n",
" JobName=job_name,\n",
" JobDescription=job_description, # optional\n",
" JobType=job_type,\n",
" RoleArn=role,\n",
" InputConfig={\"ModelPackageVersionArn\": model_package_arn},\n",
")\n",
"\n",
"print(rv)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 8. Instance Recommendation Results\n",
"\n",
"Each inference recommendation includes `InstanceType`, `InitialInstanceCount`, `EnvironmentParameters` which are tuned environment variable parameters for better performance. We also include performance and cost metrics such as `MaxInvocations`, `ModelLatency`, `CostPerHour` and `CostPerInference`. We believe these metrics will help you narrow down to a specific endpoint configuration that suits your use case. \n",
"\n",
"Example: \n",
"\n",
"If your motivation is overall price-performance with an emphasis on throughput, then you should focus on `CostPerInference` metrics \n",
"If your motivation is a balance between latency and throughput, then you should focus on `ModelLatency` / `MaxInvocations` metrics\n",
"\n",
"| Metric | Description |\n",
"| --- | --- |\n",
"| ModelLatency | The interval of time taken by a model to respond as viewed from SageMaker. This interval includes the local communication times taken to send the request and to fetch the response from the container of a model and the time taken to complete the inference in the container.
Units: Microseconds |\n",
"| MaximumInvocations | The maximum number of InvokeEndpoint requests sent to a model endpoint.
Units: None |\n",
"| CostPerHour | The estimated cost per hour for your real-time endpoint.
Units: US Dollars |\n",
"| CostPerInference | The estimated cost per inference for your real-time endpoint.
Units: US Dollars |"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pprint\n",
"import pandas as pd\n",
"\n",
"finished = False\n",
"while not finished:\n",
" inference_recommender_job = sm_client.describe_inference_recommendations_job(JobName=job_name)\n",
" if inference_recommender_job[\"Status\"] in [\"COMPLETED\", \"STOPPED\", \"FAILED\"]:\n",
" finished = True\n",
" else:\n",
" print(\"In progress\")\n",
" time.sleep(300)\n",
"\n",
"if inference_recommender_job[\"Status\"] == \"FAILED\":\n",
" print(\"Inference recommender job failed \")\n",
" print(\"Failed Reason: {}\".inference_recommender_job[\"FailedReason\"])\n",
"else:\n",
" print(\"Inference recommender job completed\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data = [\n",
" {**x[\"EndpointConfiguration\"], **x[\"ModelConfiguration\"], **x[\"Metrics\"]}\n",
" for x in inference_recommender_job[\"InferenceRecommendations\"]\n",
"]\n",
"df = pd.DataFrame(data)\n",
"df.drop(\"VariantName\", inplace=True, axis=1)\n",
"pd.set_option(\"max_colwidth\", 400)\n",
"df.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 9. Conclusion\n",
"\n",
"This notebook discussed how to use SageMaker Inference Recommender with an XGBoost model to help determine the right CPU instance to reduce costs and maximize performance. The notebook walked you through training a quick XGBoost model, registering your model in Model Registry, and creating an Inference Recommender Default job to get recommendations. You can modify the batch size, features and instance types to match your own ML workload as well as bring your own XGBoost model for testing."
]
}
],
"metadata": {
"instance_type": "ml.m5.large",
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"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.9"
}
},
"nbformat": 4,
"nbformat_minor": 4
}