创建异步推理端点 - Amazon SageMaker

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

创建异步推理端点

创建异步终端节点的方式与使用 SageMaker 托管服务创建终端节点的方式相同:

  • 使用创建模型CreateModel。 SageMaker

  • 使用 CreateEndpointConfig 创建端点配置。

  • 使用 CreateEndpoint 创建 HTTPS 端点。

要创建端点,首先要使用 CreateModel 创建模型,在其中指向模型构件和 Docker 注册表路径(映像)。然后,您可以使用配置来CreateEndpointConfig指定一个或多个使用要部署的 CreateModel API 创建的模型以及 SageMaker 要预置的资源。使用在请求中指定的端点配置,通过 CreateEndpoint 创建端点。您可以使用 UpdateEndpoint API 更新异步端点。使用 InvokeEndpointAsync 发送和接收来自托管在端点上的模型的推理请求。您可以使用 DeleteEndpoint API 删除端点。

有关可用 SageMaker 图像的完整列表,请参阅可用的 Deep Learning Containers 镜像。有关如何创建 Docker 映像的信息,请参阅使用您自己的推理代码

创建模型

以下示例说明如何使用 AWS SDK for Python (Boto3)创建模型。前几行定义:

  • sagemaker_client: 一个低级别的 SageMaker 客户端对象,便于向 AWS 服务发送和接收请求。

  • sagemaker_role:带有 SageMaker IAM 角色亚马逊资源名称 (ARN) 的字符串变量。

  • aws_region: 带有您所在 AWS 地区名称的字符串变量。

import boto3 # Specify your AWS Region aws_region='<aws_region>' # Create a low-level SageMaker service client. sagemaker_client = boto3.client('sagemaker', region_name=aws_region) # Role to give SageMaker permission to access AWS services. sagemaker_role= "arn:aws:iam::<account>:role/*"

接下来,指定存储在 Amazon S3 中的预先训练模型的位置。在此示例中,我们使用名为 demo-xgboost-model.tar.gz 的预先训练 XGBoost 模型。完整的 Amazon S3 URI 存储在字符串变量中 model_url

#Create a variable w/ the model S3 URI s3_bucket = '<your-bucket-name>' # Provide the name of your S3 bucket bucket_prefix='saved_models' model_s3_key = f"{bucket_prefix}/demo-xgboost-model.tar.gz" #Specify S3 bucket w/ model model_url = f"s3://{s3_bucket}/{model_s3_key}"

指定主容器。对于主容器,您可以指定包含推理代码的 Docker 映像、构件(来自先前的训练)以及自定义环境映射,供推理代码在您部署模型进行预测时使用。

在此示例中,我们指定了 XGBoost 内置算法容器映像:

from sagemaker import image_uris # Specify an AWS container image. container = image_uris.retrieve(region=aws_region, framework='xgboost', version='0.90-1')

使用在 Amazon SageMaker 中创建模型CreateModel。指定以下内容:

  • ModelName:模型的名称(在此示例中,存储在名为 model_name 的字符串变量中)。

  • ExecutionRoleArn:亚马逊 SageMaker可以代入的 IAM 角色的亚马逊资源名称 (ARN),用于访问模型工件和 Docker 镜像,以便在 ML 计算实例上部署或批量转换任务。

  • PrimaryContainer:主 Docker 映像的位置,其中包含推理代码、关联构件和自定义环境映射,供推理代码在部署模型进行预测时使用。

model_name = '<The_name_of_the_model>' #Create model create_model_response = sagemaker_client.create_model( ModelName = model_name, ExecutionRoleArn = sagemaker_role, PrimaryContainer = { 'Image': container, 'ModelDataUrl': model_url, })

有关 SageMaker API 参数的完整列表,请参阅 API 参考指南中的CreateModel描述。

如果您使用的是 SageMaker 提供的容器,则可以通过在此步骤中设置环境变量,将模型服务器超时和有效负载大小从默认值增加到框架支持的最大值。如果您没有明确设置这些变量,则可能无法利用异步推理支持的最大超时和负载大小。以下示例说明如何基于 TorchServe为 PyTorch 推理容器设置环境变量。

model_name = '<The_name_of_the_model>' #Create model create_model_response = sagemaker_client.create_model( ModelName = model_name, ExecutionRoleArn = sagemaker_role, PrimaryContainer = { 'Image': container, 'ModelDataUrl': model_url, 'Environment': { 'TS_MAX_REQUEST_SIZE': '100000000', 'TS_MAX_RESPONSE_SIZE': '100000000', 'TS_DEFAULT_RESPONSE_TIMEOUT': '1000' }, })

在创建了端点之后,您应从 inference.py 脚本中打印环境变量,以测试是否正确设置了环境变量。下表列出了多个框架的环境变量,您可以设置这些变量来更改默认值。

框架 环境变量

PyTorch 1.8(基于 TorchServe)

'TS_MAX_REQUEST_SIZE': '100000000'

'TS_MAX_RESPONSE_SIZE': '100000000'

'TS_DEFAULT_RESPONSE_TIMEOUT': '1000'

PyTorch 1.4(基于彩信)

'MMS_MAX_REQUEST_SIZE': '1000000000'

'MMS_MAX_RESPONSE_SIZE': '1000000000'

'MMS_DEFAULT_RESPONSE_TIMEOUT': '900'

HuggingFace 推理容器(基于彩信)

'MMS_MAX_REQUEST_SIZE': '2000000000'

'MMS_MAX_RESPONSE_SIZE': '2000000000'

'MMS_DEFAULT_RESPONSE_TIMEOUT': '900'

创建端点配置

拥有模型后,请使用 CreateEndpointConfig 创建端点配置。Amazon SageMaker 托管服务使用此配置来部署模型。在配置中,您可以标识使用和创建的一个或多个模型 CreateModel,用于部署您希望 Amazon 预置 SageMaker 的资源。指定 AsyncInferenceConfig 对象并为 OutputConfig 提供输出 Amazon S3 位置。您可以选择指定 Amazon SNS 主题,在其上发送有关预测结果的通知。有关 Amazon SNS 主题的更多信息,请参阅配置 Amazon SNS

以下示例演示了如何使用 AWS SDK for Python (Boto3)创建端点配置:

import datetime from time import gmtime, strftime # Create an endpoint config name. Here we create one based on the date # so it we can search endpoints based on creation time. endpoint_config_name = f"XGBoostEndpointConfig-{strftime('%Y-%m-%d-%H-%M-%S', gmtime())}" # The name of the model that you want to host. This is the name that you specified when creating the model. model_name='<The_name_of_your_model>' create_endpoint_config_response = sagemaker_client.create_endpoint_config( EndpointConfigName=endpoint_config_name, # You will specify this name in a CreateEndpoint request. # List of ProductionVariant objects, one for each model that you want to host at this endpoint. ProductionVariants=[ { "VariantName": "variant1", # The name of the production variant. "ModelName": model_name, "InstanceType": "ml.m5.xlarge", # Specify the compute instance type. "InitialInstanceCount": 1 # Number of instances to launch initially. } ], AsyncInferenceConfig={ "OutputConfig": { # Location to upload response outputs when no location is provided in the request. "S3OutputPath": f"s3://{s3_bucket}/{bucket_prefix}/output" # (Optional) specify Amazon SNS topics "NotificationConfig": { "SuccessTopic": "arn:aws:sns:aws-region:account-id:topic-name", "ErrorTopic": "arn:aws:sns:aws-region:account-id:topic-name", } }, "ClientConfig": { # (Optional) Specify the max number of inflight invocations per instance # If no value is provided, Amazon SageMaker will choose an optimal value for you "MaxConcurrentInvocationsPerInstance": 4 } } ) print(f"Created EndpointConfig: {create_endpoint_config_response['EndpointConfigArn']}")

在上述示例中,您为 AsyncInferenceConfig 字段的 OutputConfig 指定以下键:

  • S3OutputPath:请求中没有提供位置时,将响应输出上传到的位置。

  • NotificationConfig:(可选)推理请求成功 (SuccessTopic) 或者失败 (ErrorTopic) 时向您发布通知的 SNS 主题。

您还可以在 AsyncInferenceConfig 字段中为 ClientConfig 指定以下可选参数:

  • MaxConcurrentInvocationsPerInstance:(可选) SageMaker 客户端向模型容器发送的最大并发请求数。

创建端点

完成模型和端点配置后,可使用 CreateEndpoint API 创建端点。终端节点名称在您 AWS 账户的某个 AWS 区域内必须是唯一的。

下文将使用在请求中指定的端点配置创建端点。Amazon SageMaker 使用终端节点来配置资源和部署模型。

# The name of the endpoint.The name must be unique within an AWS Region in your AWS account. endpoint_name = '<endpoint-name>' # The name of the endpoint configuration associated with this endpoint. endpoint_config_name='<endpoint-config-name>' create_endpoint_response = sagemaker_client.create_endpoint( EndpointName=endpoint_name, EndpointConfigName=endpoint_config_name)

当您调用 CreateEndpoint API 时,Amazon SageMaker 异步推理会发送测试通知,以检查您是否已配置了 Amazon SNS 主题。Amazon SageMaker 异步推理还会在调用UpdateEndpointUpdateEndpointWeightsAndCapacities后发送测试通知。这可以 SageMaker 检查您是否具有所需的权限。通知可以直接忽略。测试通知格式如下:

{ "eventVersion":"1.0", "eventSource":"aws:sagemaker", "eventName":"TestNotification" }