AWS SageMaker PyTorch:没有名为“sagemaker”的模块

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

我已使用 SageMaker 在 AWS 上部署了 PyTorch 模型,并尝试发送请求来测试该服务。但是,我收到一条非常模糊的错误消息:“没有名为‘sagemaker’的模块”。我尝试在网上搜索,但找不到类似消息的帖子。

我的客户代码:

import numpy as np
from sagemaker.pytorch.model import PyTorchPredictor

ENDPOINT = '<endpoint name>'

predictor = PyTorchPredictor(ENDPOINT)
predictor.predict(np.random.random_sample([1, 3, 224, 224]).tobytes())

详细错误信息:

Traceback (most recent call last):
  File "client.py", line 7, in <module>
    predictor.predict(np.random.random_sample([1, 3, 224, 224]).tobytes())
  File "/Users/jiashenc/Env/py3/lib/python3.7/site-packages/sagemaker/predictor.py", line 110, in predict
    response = self.sagemaker_session.sagemaker_runtime_client.invoke_endpoint(**request_args)
  File "/Users/jiashenc/Env/py3/lib/python3.7/site-packages/botocore/client.py", line 276, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/Users/jiashenc/Env/py3/lib/python3.7/site-packages/botocore/client.py", line 586, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.errorfactory.ModelError: An error occurred (ModelError) when calling the InvokeEndpoint operation: Received server error (500) from model with message "No module named 'sagemaker'". See https://us-east-2.console.aws.amazon.com/cloudwatch/home?region=us-east-2#logEventViewer:group=/aws/sagemaker/Endpoints/<endpoint name> in account xxxxxxxxxxxxxx for more information.

这个错误是因为我将服务脚本和部署脚本合并在一起,见下文

import os
import torch
import numpy as np
from sagemaker.pytorch.model import PyTorchModel
from torch import cuda
from torchvision.models import resnet50


def model_fn(model_dir):
    device = torch.device('cuda' if cuda.is_available() else 'cpu')
    model = resnet50()
    with open(os.path.join(model_dir, 'model.pth'), 'rb') as f:
        model.load_state_dict(torch.load(f, map_location=device))
    return model.to(device)

def predict_fn(input_data, model):
    device = torch.device('cuda' if cuda.is_available() else 'cpu')
    model.eval()
    with torch.no_grad():
        return model(input_data.to(device))


if __name__ == '__main__':
    pytorch_model = PyTorchModel(model_data='s3://<bucket name>/resnet50/model.tar.gz',
                                    entry_point='serve.py', role='jiashenC-sagemaker',
                                    py_version='py3', framework_version='1.3.1')
    predictor = pytorch_model.deploy(instance_type='ml.t2.medium', initial_instance_count=1)
    print(predictor.predict(np.random.random_sample([1, 3, 224, 224]).astype(np.float32)))

根本原因是我代码中的第四行。它尝试导入 sagemaker,这是一个不可用的库。

python amazon-web-services amazon-sagemaker
2个回答
4
投票

(2020 年 2 月 9 日编辑,添加额外代码片段)

您的服务代码尝试在内部使用

sagemaker
模块。
sagemaker
模块(也称为 SageMaker Python SDK,SageMaker 的众多编排 SDK 之一)并非设计用于模型容器,而是在模型之外编排其活动(训练、部署、贝叶斯调整) , ETC)。在您的具体示例中,您不应将部署和模型调用代码包含到服务器代码中,因为这些实际上是从服务器外部执行的操作,以编排其生命周期并与其交互。对于使用 Sagemaker Pytorch 容器进行模型部署,您的入口点脚本只需要包含模型反序列化所需的
model_fn
函数,以及可选的
input_fn
predict_fn
output_fn
,分别用于预处理、推理和后处理(此处的文档中有详细说明)。这个逻辑很漂亮:):您不需要任何其他东西来部署生产就绪的深度学习服务器! (Pytorch 和 MXNet 为 MMS,sklearn 为 Flask+Gunicorn)。

总而言之,这就是您的代码应该如何拆分:

一个入口点脚本

serve.py
,包含模型服务代码,如下所示:

import os

import numpy as np
import torch
from torch import cuda
from torchvision.models import resnet50

def model_fn(model_dir):
    # TODO instantiate a model from its artifact stored in model_dir
    return model

def predict_fn(input_data, model):
    # TODO apply model to the input_data, return result of interest
    return result

以及一些编排代码来实例化 SageMaker 模型对象,将其部署到服务器并查询它。它是从您选择的编排运行时运行的,可以是 SageMaker Notebook、您的笔记本电脑、AWS Lambda 函数、Apache Airflow 运算符等 - 以及您选择的 SDK;不需要为此使用 python。

import numpy as np
from sagemaker.pytorch.model import PyTorchModel

pytorch_model = PyTorchModel(
    model_data='s3://<bucket name>/resnet50/model.tar.gz',
    entry_point='serve.py',
    role='jiashenC-sagemaker',
    py_version='py3',
    framework_version='1.3.1')

predictor = pytorch_model.deploy(instance_type='ml.t2.medium', initial_instance_count=1)

print(predictor.predict(np.random.random_sample([1, 3, 224, 224]).astype(np.float32)))

0
投票

执行环境不包含安装的“sagemaker”,因此可以将其显式添加为.zip文件。

您的 AWS Lambda 函数的代码包含一个 .py 文件,其中包含函数的处理程序代码以及您的代码所依赖的任何其他包和模块。要将此函数代码部署到 Lambda,您可以使用部署包。该包可以是 .zip 文件存档或容器映像。

您也可以按照此操作:文档

  1. 要将部署包创建为 .zip 文件存档,您可以使用命令行工具。

  2. 将 zip 文件复制到 s3 存储桶

  3. 添加图层:图层是一个单独的 .zip 文件,可以包含附加代码和其他内容。 Lambda Python 运行时包括适用于 Python 的 AWS 开发工具包 (Boto3) 及其依赖项。 Lambda 在运行时提供了 SDK,适用于您无法添加自己的依赖项的部署场景。

  1. 将 zip 文件上传到 s3 存储桶并添加存储桶 URI 并创建图层。 请记住,您也可以从本地计算机上传 zip 文件。

  1. 将图层添加到 lambda 函数 向下滚动可以看到这个👇

单击保存并添加图层

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