如何使用dockerfile在aws sagemaker中运行python文件

问题描述 投票:0回答:1

我有一个经过预训练的python代码和一个模型,并且在与代码i相同的目录中有一个model.pkl文件,现在我必须将其运行或部署到aws sagemaker,但没有任何解决方案为此,aws sagemaker仅支持两个命令训练或分别用于训练和部署。

当前,我正在使用命令“ python filename.py”运行该程序,并且它已成功运行,我希望在aws sagemaker上运行该程序。

任何解决方案?

我尝试过与将模型部署到s3相同,并在部署时调用,我不知道它是正确还是错误。

python amazon-web-services amazon-sagemaker
1个回答
0
投票

[如果您具有要在SageMaker端点上运行的预训练模型和文件filename.py,则只需将其打包为Docker映像即可创建模型,然后将其部署到端点并进行调用。

为此,我只是遵循using your own inference code上AWS文档上的本指南。

步骤将是:

  1. 创建模型代码
  2. 用代码创建一个Docker镜像
  3. 使用此图像创建端点

步骤1:创建模型代码

让我们以这个简单的模型作为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

现在,当SageMaker从ECR读取模型时,我们需要将其发布到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端点如何配置它:

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

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.