创建异步推理端点 - Amazon SageMaker
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

创建异步推理端点

创建异步端点的方法,与使用 SageMaker 托管服务创建端点的方法相同:

  • 使用 CreateModel 在 SageMaker 中创建模型。

  • 使用 CreateEndpointConfig 创建端点配置。

  • 使用 CreateEndpoint 创建 HTTPS 端点。

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

有关可用 SageMaker 映像的完整列表,请参阅可用的深度学习容器映像。有关如何创建 Docker 映像的信息,请参阅使用您自己的推理代码

创建模型

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

  • sagemaker_client:低级 SageMaker 客户端对象,用于轻松地对 Amazon 服务发送和接收请求。

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

  • aws_region:字符串变量,带有您的 Amazon 区域的名称。

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 Amazon 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')

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

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

  • ExecutionRoleArn:IAM 角色的 Amazon 资源名称 (ARN),Amazon SageMaker 可代入此角色以访问模型构件和 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, })

有关 API 参数的完整列表,请参阅《SageMaker 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)

'MMS_MAX_REQUEST_SIZE': '1000000000'

'MMS_MAX_RESPONSE_SIZE': '1000000000'

'MMS_DEFAULT_RESPONSE_TIMEOUT': '900'

HuggingFace 推理容器(基于 MMS)

'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

以下示例演示了如何使用 Amazon 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 创建端点。端点名称在 Amazon 账户的一个 Amazon 区域内必须是唯一的。

以下命令使用在请求中指定的端点配置创建端点。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" }