

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

# 为 SageMaker AI 多模型端点构建自己的容器
<a name="build-multi-model-build-container"></a>

请参阅以下部分，了解如何将自己的容器和依赖项引入多模型端点。

**Topics**
+ [在 CPU 支持的实例上为多模型端点引入您自己的依赖项](#build-multi-model-container-cpu)
+ [在 GPU 支持的实例上为多模型端点引入您自己的依赖项](#build-multi-model-container-gpu)
+ [使用 A SageMaker I 推理工具包](#multi-model-inference-toolkit)
+ [多模型端点的自定义容器合同](mms-container-apis.md)

## 在 CPU 支持的实例上为多模型端点引入您自己的依赖项
<a name="build-multi-model-container-cpu"></a>

如果预先构建的容器映像都无法满足您的需求，可以构建您自己的容器以便与 CPU 支持的多模型端点一起使用。

部署在亚马逊 AI 中的自定义 Amazon Elastic Container Registry (A SageMaker mazon ECR) 镜像应遵守[自定义托管服务的推理代码](your-algorithms-inference-code.md)中描述的基本协议，该合同规定了人工智能与运行你自己的推理代码的 Docker 容器的交互 SageMaker 方式。为了使容器能够同时加载和提供多个模型，还必须遵循其他行为 APIs 和行为。此附加合同包括新增 APIs 的加载、列出、获取和卸载模型，以及用于调用模型的不同API。对于错误场景，也有不同的行为 APIs 需要遵守。为了表明您的容器符合额外要求，您可以在 Docker 文件中添加以下命令：

```
LABEL com.amazonaws.sagemaker.capabilities.multi-models=true
```

SageMaker AI 还会在容器中注入一个环境变量

```
SAGEMAKER_MULTI_MODEL=true
```

如果要为串行推理管道创建多模型端点，Docker 文件必须同时具有多模型和串行推理管道所需的标签。有关串行信息管道的更多信息，请参阅[使用推理管道运行实时预测](inference-pipeline-real-time.md)。

为了帮助您实施自定义容器的这些要求，我们提供了两个库：
+ [Multi Model Server](https://github.com/awslabs/multi-model-server) 是一个开源框架，用于提供机器学习模型，可以将其安装在容器中，以提供满足新多模型端点容器要求的前端。 APIs它提供了多模型端点所需的 HTTP 前端和模型管理功能，可以在单个容器中托管多个模型，在容器中动态加载和卸载模型，以及对指定加载模型执行推理。它还提供了一个支持可插入自定义后端处理程序的可插入后端，您可以在该后端实施自己的算法。
+ [SageMaker AI Inference Toolkit](https://github.com/aws/sagemaker-inference-toolkit) 是一个启动多模型服务器的库，其配置和设置使其与 SageMaker AI 多模型端点兼容。它还允许您根据场景需求调整重要的性能参数，例如，每个模型的工作人员数。

## 在 GPU 支持的实例上为多模型端点引入您自己的依赖项
<a name="build-multi-model-container-gpu"></a>

多模型服务器和 SageMaker AI 推理工具包库目前不支持在具有 GPU 支持的实例的多模型终端节点上使用自带容器 (BYOC) 功能。

要使用支持 GPU 的实例创建多模型终端节点，你可以使用 SageMaker AI 支持的 [NVIDIA Triton 推理服务器。和 NV [IDIA Tr](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#nvidia-triton-inference-containers-sm-support-only) iton 推理容器](https://docs.amazonaws.cn/sagemaker/latest/dg/triton.html)。要引入自己的依赖关系，你可以使用 SageMaker AI 支持的 [NVIDIA Triton 推理服务器](https://docs.amazonaws.cn/sagemaker/latest/dg/triton.html)作为 Docker 文件的基础映像来构建自己的容器：

```
FROM 301217895009.dkr.ecr.us-west-2.amazonaws.com/sagemaker-tritonserver:22.07-py3
```

**重要**  
带有 Triton 推理服务器的容器是唯一支持用于 GPU 支持的多模型端点的容器。

## 使用 A SageMaker I 推理工具包
<a name="multi-model-inference-toolkit"></a>

**注意**  
A SageMaker I 推理工具包仅支持 CPU 支持的多模型端点。GPU 支持的多模型端点目前不支持 SageMaker AI 推理工具包。

[支持多模型终端节点的算法、框架和实例](multi-model-support.md)中列出了支持多模型端点的预构建容器。如果要使用任何其他框架或算法，您需要构建一个容器。最简单的方法是使用 [SageMaker AI 推理工具包](https://github.com/aws/sagemaker-inference-toolkit)来扩展现有的预构建容器。 SageMaker AI 推理工具包是多模型服务器 (MMS) 的实现，用于创建可在 AI 中部署的端点。 SageMaker 有关演示如何设置和部署支持 SageMaker AI 中多模型端点的自定义容器的示例笔记本，请参阅多模型端点 [BYOC](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/advanced_functionality/multi_model_bring_your_own) 示例笔记本。

**注意**  
 SageMaker AI 推理工具包仅支持 Python 模型处理程序。如果要用任何其他语言实现处理程序，则必须构建自己的容器来实现额外的多模型端点 APIs。有关信息，请参阅[多模型端点的自定义容器合同](mms-container-apis.md)。

**使用 SageMaker AI 推理工具包扩展容器**

1. 创建一个模型处理程序。MMS 需要使用一个模型处理程序，这是一个 Python 文件，它实施一些函数以进行预处理，从模型中获得结果以及在模型处理程序中处理输出。有关模型处理程序的示例，请参阅示例笔记本中的 [model\$1handler.py](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/advanced_functionality/multi_model_bring_your_own/container/model_handler.py)。

1. 导入推理工具包并使用其 `model_server.start_model_server` 函数以启动 MMS。以下示例来自于示例笔记本中的 `dockerd-entrypoint.py` 文件。请注意，`model_server.start_model_server` 调用传递上一步中描述的模型处理程序：

   ```
   import subprocess
   import sys
   import shlex
   import os
   from retrying import retry
   from subprocess import CalledProcessError
   from sagemaker_inference import model_server
   
   def _retry_if_error(exception):
       return isinstance(exception, CalledProcessError or OSError)
   
   @retry(stop_max_delay=1000 * 50,
          retry_on_exception=_retry_if_error)
   def _start_mms():
       # by default the number of workers per model is 1, but we can configure it through the
       # environment variable below if desired.
       # os.environ['SAGEMAKER_MODEL_SERVER_WORKERS'] = '2'
       model_server.start_model_server(handler_service='/home/model-server/model_handler.py:handle')
   
   def main():
       if sys.argv[1] == 'serve':
           _start_mms()
       else:
           subprocess.check_call(shlex.split(' '.join(sys.argv[1:])))
   
       # prevent docker exit
       subprocess.call(['tail', '-f', '/dev/null'])
       
   main()
   ```

1. 在 `Dockerfile` 中，从第一步中复制模型处理程序，并在 `Dockerfile` 中将上一步中的 Python 文件指定为入口点。以下几行来自于示例笔记本中使用的 [Dockerfile](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/advanced_functionality/multi_model_bring_your_own/container/Dockerfile)：

   ```
   # Copy the default custom service file to handle incoming data and inference requests
   COPY model_handler.py /home/model-server/model_handler.py
   
   # Define an entrypoint script for the docker image
   ENTRYPOINT ["python", "/usr/local/bin/dockerd-entrypoint.py"]
   ```

1. 构建并注册您的容器。示例笔记本中的以下 Shell 脚本构建容器，并将其上传到您的 Amazon 账户中的 Amazon Elastic Container Registry 存储库：

   ```
   %%sh
   
   # The name of our algorithm
   algorithm_name=demo-sagemaker-multimodel
   
   cd container
   
   account=$(aws sts get-caller-identity --query Account --output text)
   
   # Get the region defined in the current configuration (default to us-west-2 if none defined)
   region=$(aws configure get region)
   region=${region:-us-west-2}
   
   fullname="${account}.dkr.ecr.${region}.amazonaws.com/${algorithm_name}:latest"
   
   # If the repository doesn't exist in ECR, create it.
   aws ecr describe-repositories --repository-names "${algorithm_name}" > /dev/null 2>&1
   
   if [ $? -ne 0 ]
   then
       aws ecr create-repository --repository-name "${algorithm_name}" > /dev/null
   fi
   
   # Get the login command from ECR and execute it directly
   $(aws ecr get-login --region ${region} --no-include-email)
   
   # Build the docker image locally with the image name and then push it to ECR
   # with the full name.
   
   docker build -q -t ${algorithm_name} .
   docker tag ${algorithm_name} ${fullname}
   
   docker push ${fullname}
   ```

现在，您可以使用此容器在 SageMaker AI 中部署多模型终端节点。

**Topics**
+ [在 CPU 支持的实例上为多模型端点引入您自己的依赖项](#build-multi-model-container-cpu)
+ [在 GPU 支持的实例上为多模型端点引入您自己的依赖项](#build-multi-model-container-gpu)
+ [使用 A SageMaker I 推理工具包](#multi-model-inference-toolkit)
+ [多模型端点的自定义容器合同](mms-container-apis.md)