如果您有一个预训练模型和一个文件 filename.py,您想在 SageMaker Endpoints 上运行,您只需将其打包为 Docker 映像以创建一个模型,然后您可以将其部署到 Endpoint 并进行调用.
为此,我只是按照using your own inference code 上的 AWS 文档中的指南进行操作。
步骤如下:
- 创建模型代码
- 使用代码创建 Docker 映像
- 用这张图片创建我们的端点
第一步:创建模型代码
我们以 Python 中的这个简单模型为例:
from flask import Flask, request
app = Flask(__name__)
@app.route('/ping')
def ping():
return ''
@app.route('/invocations')
def invoke():
return 'should do inference with your model here'
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=8080)
这是 requirements.txt:
Flask==0.10.1
第 2 步:创建 Docker 映像
我们需要一个 Dockerfile 来构建我们的镜像。这是我用的那个:
Dockerfile:
FROM ubuntu:16.04
RUN apt-get update -y && apt-get install -y python-pip python-dev
COPY ./requirements.txt /app/requirements.txt
WORKDIR /app
RUN pip install -r requirements.txt
COPY . /app
EXPOSE 8080
ENTRYPOINT ["python"]
CMD ["model.py"]
我们可以通过运行来构建镜像:docker build -t simple-model:latest .
这将创建图像,现在我们可以通过运行它来测试它:
docker run -d -p 8080:8080 simple-model
如果它正在运行,您应该能够curl 任何端点:
curl localhost:8080/ping
> ok
现在我们需要将其发布到 ECR,因为 SageMaker 从 ECR 读取模型。我关注this guide from AWS
通过运行docker images获取图像ID
在这里使用它。为方便起见,我使用的是 us-west-2。将其替换为您选择的地区:
docker tag <image id> <aws accound id>.dkr.ecr.us-west-2.amazonaws.com/simple-model
现在我们应该将其推送到 ECR:
docker push <aws accound id>.dkr.ecr.us-west-2.amazonaws.com/simple-model
第 3 步:创建端点
现在我们可以使用此图像创建模型。首先,您需要一个 SageMaker 执行角色。这将用于访问您的图像和其他资源。您可以在此AWS doc page 上进行设置。
其次,您需要设置AWS CLI。
让我们开始吧。
让我们先创建模型。这将指向您在上一步中创建的 ECR 映像。在此命令中替换您在上面创建的角色名称:
aws sagemaker create-model --model-name "SimpleModel" --execution-role-arn "arn:aws:iam::<aws account id>:role/<role name>" --primary-container "{
\"ContainerHostname\": \"ModelHostname\",
\"Image\": \"<aws account id>.dkr.ecr.us-west-2.amazonaws.com/simple-model:latest\"
}"
这将创建您的模型。现在我们需要创建一个EndpointConfig,它将告诉您的 SageMaker Endpoint 需要如何配置:
aws sagemaker create-endpoint-config --endpoint-config-name "SimpleConfig" --production-variants "[
{
\"VariantName\" : \"SimpleVariant\",
\"ModelName\" : \"SimpleModel\",
\"InitialInstanceCount\" : 1,
\"InstanceType\" : \"ml.t2.medium\"
}
]"
现在终于,我们可以使用该配置创建我们的端点了:
aws sagemaker create-endpoint --endpoint-name "SimpleEndpoint" --endpoint-config-name "SimpleConfig"
如果一切正常,请等到aws sagemaker describe-endpoint --endpoint-name SimpleEndpoint 说它是InService。
一旦完成,我们现在可以针对它调用调用:
aws sagemaker-runtime invoke-endpoint --endpoint-name SimpleEndpoint --body "empty"
结论
如果一切正常,您将拥有自己的端点。接下来的步骤将是自定义该 Python 脚本以使用您自己的模型进行自己的推理。 SageMaker 还能够自动获取您的模型工件,您不必将它们包含在您的模型容器中。见the documentation here。
希望对您有所帮助!