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

创建端点并部署模型

使用 SageMaker 托管服务部署模型有多种选择。您可以使用 Amazon SDK(如 SDK for Python (Boto3))、SageMaker Python SDK、Amazon CLI 以编程方式部署模型,或者也可以使用 SageMaker 控制台以交互方式部署模型。Amazon SDK 是一个低级 API,支持 Java、C++、Go、JavaScript、Node.js、PHP、Ruby 和 Python,而 SageMaker Python SDK 是高级 Python API。以下文档演示了如何使用 Amazon SDK for Python (Boto3) 和 SageMaker Python SDK 部署模型。

如果您使用 Amazon SDK for Python (Boto3)、Amazon CLI 或 SageMaker 控制台,那么使用 SageMaker 托管服务部署模型的过程分为三个步骤:

  1. 在 SageMaker 中创建 SageMaker 模型。

  2. 为 HTTPS 端点创建端点配置。

  3. 创建 HTTPS 端点。

使用 SageMaker Python SDK 部署模型不需要您创建端点配置。因此,此过程包括两个步骤:

  1. Model 类创建可部署到 HTTPS 端点的模型对象。

  2. 使用模型对象的预构建 deploy() 方法创建 HTTPS 端点。

要使用接下来的代码片段,请将示例代码中的斜体占位符文本替换为您自己的信息。

注意
  • SageMaker 支持运行 (a) 多个模型,(b) 一个模型的多个变体,或 (c) 同一端点上的模型和变体的组合。模型变体可以引用同一模型推理容器(即运行相同的算法),但使用不同的模型构件(例如,基于其他超参数配置的不同模型权重值)。与之相对的是,两个不同的模型可能使用相同的算法,但侧重于不同的业务问题或基本目标,并可能在不同的数据集上运行。

  • 在创建端点时,SageMaker 将 Amazon EBS 存储卷附加到托管该端点的每个 ML 计算实例。存储卷的大小取决于实例类型。有关 SageMaker 托管服务支持的实例类型列表,请参阅 Amazon 服务限制。有关 SageMaker 附加到每个实例的存储卷的大小列表,请参阅托管实例存储卷

  • 端点的作用域限于单个 Amazon 账户,并且端点不是公有的。URL 不包含账户 ID,但 SageMaker 从调用方提供的身份验证令牌中确定账户 ID。

    有关如何使用 Amazon API Gateway 和 Amazon Lambda 来设置和部署可从账户范围之外的客户端应用程序调用的 Web 服务的示例,请参阅 Amazon 机器学习博客中的使用 Amazon API Gateway 和 Amazon Lambda 调用 SageMaker 模型端点

开始前的准备工作

在创建并部署 SageMaker 模型之前,请找到并记下以下信息:

  • Amazon S3 存储桶所在的 Amazon 区域

  • 存储模型构件的 Amazon S3 URI 路径

  • SageMaker 的 IAM 角色

  • 包含推理代码的自定义映像的 Docker Amazon ECR URI 注册表路径,或者 Amazon 支持的内置 Docker 映像的框架和版本。

有关每个 Amazon 区域中可用 Amazon 服务的列表,请参阅区域地图和边缘网络。有关如何创建 IAM 角色的信息,请参阅创建 IAM 角色

重要

存储模型构件的 Amazon S3 存储桶必须与所创建的模型位于相同区域中。

下面演示了如何以编程方式定义上述参数。

Amazon SDK for Python (Boto3)

导入 Boto3。定义 Amazon 区域。接下来,使用 Client 类初始化低级 SageMaker 服务客户端对象。这实现了轻松地向 Amazon 服务发送和接收请求。此外,定义 Amazon 角色,授权 SageMaker 代表您访问 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::<region>:<account>:role/*"

前几行定义了:

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

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

  • aws_region:字符串变量,包含 Amazon 区域的名称。

从 SageMaker Python SDK 导入 image_uris 模块。使用 retrieve() 函数检索与给定参数匹配的 Docker 映像的 Amazon ECR URI。提供框架或算法的名称(framework 字段),以及框架或算法的版本(version 字段)。有关 Amazon 提供的内置 Docker 映像的列表,请参阅可用的深度学习容器映像。有关如何自带映像的更多信息,请参阅使用您自己的推理代码

from sagemaker import image_uris # Name of the framework or algorithm framework='<framework>' #framework='xgboost' # Example # Version of the framework or algorithm version = '<version-number>' #version = '0.90-1' # Example # Specify an AWS container image. container = image_uris.retrieve(region=aws_region, framework=framework, version=version)

接下来,提供预训练模型的 Amazon S3 URI。在下一步中,将使用此模型创建 SageMaker Python SDK Model.model 对象。在此示例中,完整的 Amazon S3 URI 存储在字符串变量 model_url 中:

# Create a variable w/ the model S3 URI # First, provide the name of your S3 bucket s3_bucket = '<your-bucket-name>' # Specify what directory within your S3 bucket your model is stored in bucket_prefix = '<directory-name>' # Replace with the name of your model artifact model_filename = '<model-name>.tar.gz' # Relative S3 path model_s3_key = f'{bucket_prefix}/'+model_filename # Combine bucket name, model file name, and relate S3 path to create S3 model URI model_url = f's3://{s3_bucket}/{model_s3_key}'
SageMaker Python SDK

定义 Amazon 区域。此外,定义 Amazon 角色,授权 SageMaker 代表您访问 Amazon 服务:

# Specify your AWS Region aws_region='<aws_region>' # Role to give SageMaker permission to access Amazon services. sagemaker_role= "arn:aws:iam::<region>:<account>:role/*"

前几行定义:

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

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

从 SageMaker Python SDK 导入 image_uris 模块。使用 retrieve() 函数检索与给定参数匹配的 Docker 映像的 Amazon ECR URI。提供框架或算法的名称(framework 字段),以及框架或算法的版本(version 字段)。有关 Amazon 提供的内置 Docker 映像的列表,请参阅可用的深度学习容器映像。有关如何自带映像的更多信息,请参阅使用您自己的推理代码

from sagemaker import image_uris # Name of the framework or algorithm framework='<framework>' #framework='xgboost' # Example # Version of the framework or algorithm version = '<version-number>' #version = '0.90-1' # Example # Specify an AWS container image. container = image_uris.retrieve(region=aws_region, framework=framework, version=version)

接下来,提供预训练模型的 Amazon S3 URI。在下一步中,将使用此模型创建 SageMaker Python SDK Model.model 对象。在此示例中,完整的 Amazon S3 URI 存储在字符串变量 model_url 中:

# Create a variable w/ the model S3 URI # First, provide the name of your S3 bucket s3_bucket = '<your-bucket-name>' # Specify what directory within your S3 bucket your model is stored in bucket_prefix = '<directory-name>' # Replace with the name of your model artifact model_filename = '<model-name>.tar.gz' # Relative S3 path model_s3_key = f'{bucket_prefix}/'+model_filename # Combine bucket name, model file name, and relate S3 path to create S3 model URI model_url = f's3://{s3_bucket}/{model_s3_key}'

创建模型

通过创建模型,您可以告知 SageMaker 在何处查找模型组件。

Amazon SDK for Python (Boto3)

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

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

  • ExecutionRoleArn:IAM 角色的 Amazon 资源名称 (ARN),Amazon SageMaker 可代入此角色以访问模型构件和 Docker 映像,从而在 ML 计算实例上进行部署或用于批量转换作业。

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

对于主容器,指定 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 Python SDK

从 SageMaker Python SDK Model 类创建模型对象。在后面的步骤中,您将使用此对象将模型部署到端点。

from sagemaker.model import Model model = Model(image_uri=container, model_data=model_url, role=sagemaker_role)

创建端点配置

为 HTTPS 端点创建端点配置。指定生产(变体)中一个或多个模型的名称,以及您希望 SageMaker 启动以托管各个生产变体的 ML 计算实例。

注意

如果您只使用 SageMaker Python SDK,可跳过本部分。

在生产环境中托管模型时,您可以配置端点以弹性扩展部署的 ML 计算实例。对于每个生产变体,指定您希望部署的 ML 计算实例数量。如果指定两个或更多实例,SageMaker 会在多个可用区中启动实例。这可确保连续可用性。SageMaker 管理实例的部署。

Amazon SDK for Python (Boto3)

使用 CreateEndpointConfig 创建端点配置。Amazon SageMaker 托管服务使用此配置部署模型。在此配置中,您可以标识使用 CreateModel 创建的一个或多个模型,以部署您希望 Amazon SageMaker 预置的资源。

以下示例演示了如何使用 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 = '<endpoint-config-name>' # 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>' instance_type = '<instance-type>' # instance_type='ml.m5.xlarge' # Example 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": instance_type, # Specify the compute instance type. "InitialInstanceCount": 1 # Number of instances to launch initially. } ] ) print(f"Created EndpointConfig: {endpoint_config_response['EndpointConfigArn']}")

在上述示例中,您为 ProductionVariants 字段指定了以下键:

SageMaker Python SDK

如果您使用 SageMaker Python SDK Model 类,则无需为实时端点定义端点配置。

部署模型

部署模型并创建 HTTPS 端点。

Amazon SDK for Python (Boto3)

向 SageMaker 提供端点配置。该服务会启动 ML 计算实例,并按照配置的指定部署一个或多个模型。

完成模型和端点配置后,可使用 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。

SageMaker Python SDK

为端点定义名称。此为可选步骤。如果未提供名称,SageMaker 将为您创建一个唯一名称:

from datetime import datetime endpoint_name = f"DEMO-{datetime.utcnow():%Y-%m-%d-%H%M}" print("EndpointName =", endpoint_name)

使用模型对象的内置 deploy() 方法,将模型部署到实时 HTTPS 端点。在 instance_type 字段中提供要将此模型部署到的 Amazon EC2 实例类型名称,并在 initial_instance_count 字段中提供要在其上运行端点的初始实例数:

initial_instance_count=<integer> # initial_instance_count=1 # Example instance_type='<instance-type>' # instance_type='ml.m4.xlarge' # Example model.deploy( initial_instance_count=initial_instance_count, instance_type=instance_type, endpoint_name=endpoint_name )