<jupyter_start><jupyter_text>Deploying Serverless Endpoints From SageMaker Model Registry  SageMaker XGBoost Algorithm Regression Example 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.[SageMaker Model Registry](https://docs.aws.amazon.com/sagemaker/latest/dg/model-registry.html) can be used to catalog and manage different model versions. Model Registry now supports deploying registered models to serverless endpoints. For this notebook we will take the existing [XGBoost Serverless example](https://github.com/aws/amazon-sagemaker-examples/blob/main/serverless-inference/Serverless-Inference-Walkthrough.ipynb) and integrate with the Model Registry. From there we will take our trained model and deploy it to a serverless endpoint using the Boto3 Python SDK. Note that there is no support for Model Registry in the SageMaker SDK with serverless endpoints at the moment.Notebook Setting- SageMaker Studio: Python 3 (Data Science)- Regions Available: SageMaker Serverless Inference is currently available in the following regions in preview: US East (Northern Virginia), US East (Ohio), US West (Oregon), EU (Ireland), Asia Pacific (Tokyo) and Asia Pacific (Sydney). After general availability it should be available in all commercial regions. To verify availability stay up to date with the [documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/serverless-endpoints.html) which will reflect all supported regions.  Table of Contents- Setup- Model Training- Model Registry- Deployment    - Model Creation    - Endpoint Configuration Creation    - Serverless Endpoint Creation    - Endpoint Invocation- Cleanup  SetupFor testing you need to properly configure your Notebook Role to have SageMaker Full Access.<jupyter_code>! pip install sagemaker botocore boto3 awscli --upgrade
# Setup clients
import boto3

client = boto3.client(service_name="sagemaker")
runtime = boto3.client(service_name="sagemaker-runtime")
import sagemaker
from sagemaker.estimator import Estimator

boto_session = boto3.session.Session()
region = boto_session.region_name
print(region)

sagemaker_session = sagemaker.Session()
base_job_prefix = "xgboost-example"
role = sagemaker.get_execution_role()
print(role)

default_bucket = sagemaker_session.default_bucket()
s3_prefix = base_job_prefix

training_instance_type = "ml.m5.xlarge"
# retrieve data
! curl https://sagemaker-sample-files.s3.amazonaws.com/datasets/tabular/uci_abalone/train_csv/abalone_dataset1_train.csv > abalone_dataset1_train.csv
# upload data to S3
!aws s3 cp abalone_dataset1_train.csv s3://{default_bucket}/xgboost-regression/train.csv<jupyter_output><empty_output><jupyter_text>Model TrainingNow, we train an ML model using the [SageMaker XGBoost Algorithm](https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost.html). In this example, we use a SageMaker-provided XGBoost container image and configure an estimator to train our model.<jupyter_code>from sagemaker.inputs import TrainingInput

training_path = f"s3://{default_bucket}/xgboost-regression/train.csv"
train_input = TrainingInput(training_path, content_type="text/csv")
model_path = f"s3://{default_bucket}/{s3_prefix}/xgb_model"

# retrieve xgboost image
image_uri = sagemaker.image_uris.retrieve(
    framework="xgboost",
    region=region,
    version="1.0-1",
    py_version="py3",
    instance_type=training_instance_type,
)

# Configure Training Estimator
xgb_train = Estimator(
    image_uri=image_uri,
    instance_type=training_instance_type,
    instance_count=1,
    output_path=model_path,
    sagemaker_session=sagemaker_session,
    role=role,
)

# Set Hyperparameters
xgb_train.set_hyperparameters(
    objective="reg:linear",
    num_round=50,
    max_depth=5,
    eta=0.2,
    gamma=4,
    min_child_weight=6,
    subsample=0.7,
    silent=0,
)
# Fit model
xgb_train.fit({"train": train_input})
# Retrieve model data from training job
model_artifacts = xgb_train.model_data
model_artifacts<jupyter_output><empty_output><jupyter_text>Model Registry<jupyter_code># Create a Model Package Group: https://docs.aws.amazon.com/sagemaker/latest/dg/model-registry-model-group.html
import time
from time import gmtime, strftime

model_package_group_name = "xgboost-abalone" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
model_package_group_input_dict = {
    "ModelPackageGroupName": model_package_group_name,
    "ModelPackageGroupDescription": "Model package group for xgboost regression model with Abalone dataset",
}

create_model_pacakge_group_response = client.create_model_package_group(
    **model_package_group_input_dict
)
print(
    "ModelPackageGroup Arn : {}".format(create_model_pacakge_group_response["ModelPackageGroupArn"])
)
model_package_group_arn = create_model_pacakge_group_response["ModelPackageGroupArn"]
modelpackage_inference_specification = {
    "InferenceSpecification": {
        "Containers": [
            {
                "Image": image_uri,
            }
        ],
        "SupportedContentTypes": ["text/csv"],
        "SupportedResponseMIMETypes": ["text/csv"],
    }
}

# Specify the model source
model_url = model_artifacts

# Specify the model data
modelpackage_inference_specification["InferenceSpecification"]["Containers"][0][
    "ModelDataUrl"
] = model_url

create_model_package_input_dict = {
    "ModelPackageGroupName": model_package_group_arn,
    "ModelPackageDescription": "Model for regression with the Abalone dataset",
    "ModelApprovalStatus": "PendingManualApproval",
}
create_model_package_input_dict.update(modelpackage_inference_specification)

# Create cross-account model package
create_mode_package_response = client.create_model_package(**create_model_package_input_dict)
model_package_arn = create_mode_package_response["ModelPackageArn"]
print("ModelPackage Version ARN : {}".format(model_package_arn))
client.list_model_packages(ModelPackageGroupName=model_package_group_name)
model_package_arn = client.list_model_packages(ModelPackageGroupName=model_package_group_name)[
    "ModelPackageSummaryList"
][0]["ModelPackageArn"]
model_package_arn
client.describe_model_package(ModelPackageName=model_package_arn)
# Approve the model package
model_package_update_input_dict = {
    "ModelPackageArn": model_package_arn,
    "ModelApprovalStatus": "Approved",
}
model_package_update_response = client.update_model_package(**model_package_update_input_dict)
print(model_package_update_response)<jupyter_output><empty_output><jupyter_text>Deployment  Model Creation<jupyter_code>model_name = "xgboost-serverless-model" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
print("Model name : {}".format(model_name))
container_list = [{"ModelPackageName": model_package_arn}]

create_model_response = client.create_model(
    ModelName=model_name, ExecutionRoleArn=role, Containers=container_list
)
print("Model arn : {}".format(create_model_response["ModelArn"]))<jupyter_output><empty_output><jupyter_text>Endpoint Configuration CreationThis is where you can adjust the [Serverless Configuration](https://docs.aws.amazon.com/sagemaker/latest/dg/serverless-endpoints-create.html) 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.<jupyter_code>endpoint_config_name = "xgboost-serverless-epc" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
print(endpoint_config_name)
create_endpoint_config_response = client.create_endpoint_config(
    EndpointConfigName=endpoint_config_name,
    ProductionVariants=[
        {
            "ServerlessConfig": {"MemorySizeInMB": 1024, "MaxConcurrency": 10},
            "ModelName": model_name,
            "VariantName": "AllTraffic",
        }
    ],
)
print("Endpoint Configuration Arn: " + create_endpoint_config_response["EndpointConfigArn"])<jupyter_output><empty_output><jupyter_text>Endpoint CreationNow 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.<jupyter_code>endpoint_name = "xgboost-serverless-ep" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
print("EndpointName={}".format(endpoint_name))

create_endpoint_response = client.create_endpoint(
    EndpointName=endpoint_name, EndpointConfigName=endpoint_config_name
)
print(create_endpoint_response["EndpointArn"])<jupyter_output><empty_output><jupyter_text>Wait until the endpoint status is `InService` before invoking the endpoint.<jupyter_code>import time

describe_endpoint_response = client.describe_endpoint(EndpointName=endpoint_name)

while describe_endpoint_response["EndpointStatus"] == "Creating":
    describe_endpoint_response = client.describe_endpoint(EndpointName=endpoint_name)
    print(describe_endpoint_response["EndpointStatus"])
    time.sleep(15)

describe_endpoint_response<jupyter_output><empty_output><jupyter_text>InvocationInvoke 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.<jupyter_code>response = runtime.invoke_endpoint(
    EndpointName=endpoint_name,
    Body=b".345,0.224414,.131102,0.042329,.279923,-0.110329,-0.099358,0.0",
    ContentType="text/csv",
)

print(response["Body"].read())<jupyter_output><empty_output><jupyter_text>CleanupDelete any resources you created in this notebook that you no longer wish to use.<jupyter_code>client.delete_model(ModelName=model_name)
client.delete_endpoint_config(EndpointConfigName=endpoint_config_name)
client.delete_endpoint(EndpointName=endpoint_name)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.0907108159016556, 'fraction_numerical': 0.011599087934965797, 'mean_word_length': 6.37966349670812, 'pattern_counts': {'":': 20, '<': 37, '<?xml version=': 0, '>': 38, 'https://': 7, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '255524', 'license': 'Apache-2.0', 'n_tokens_mistral': 3103, 'n_tokens_neox': 2965, 'n_words': 711, 'path': 'serverless-inference/serverless-model-registry.ipynb', 'repo_name': 'qidewenwhen/amazon-sagemaker-examples', 'size': '10087'}