Вызов конечной точки sagemaker с помощью настраиваемого сценария вывода

Я развернул конечную точку sagemaker, используя следующий код:

from sagemaker.pytorch import PyTorchModel
from sagemaker import get_execution_role, Session

sess = Session()
role = get_execution_role()

model = PyTorchModel(model_data=my_trained_model_location,
                     role=role,
                     sagemaker_session=sess,
                     framework_version='1.5.0',
                     entry_point='inference.py',
                     source_dir='.')

predictor = model.deploy(initial_instance_count=1, 
                         instance_type='ml.m4.xlarge',
                         endpoint_name='my_endpoint')

Если я бегу:

import numpy as np

pseudo_data = [np.random.randn(1, 300), np.random.randn(6, 300), np.random.randn(3, 300), np.random.randn(7, 300), np.random.randn(5, 300)] # input data is a list of 2D numpy arrays with variable first dimension and fixed second dimension
result = predictor.predict(pseudo_data)

Я могу сгенерировать результат без ошибок. Однако, если я хочу вызвать конечную точку и сделать прогноз, запустив:

from sagemaker.predictor import RealTimePredictor

predictor = RealTimePredictor(endpoint='my_endpoint')
result = predictor.predict(pseudo_data)

Я бы получил ошибку:

Traceback (most recent call last):
  File "default_local.py", line 77, in <module>
    score = predictor.predict(input_data)
  File "/home/biggytruck/.local/lib/python3.6/site-packages/sagemaker/predictor.py", line 113, in predict
    response = self.sagemaker_session.sagemaker_runtime_client.invoke_endpoint(**request_args)
  File "/home/biggytruck/.local/lib/python3.6/site-packages/botocore/client.py", line 316, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/home/biggytruck/.local/lib/python3.6/site-packages/botocore/client.py", line 608, in _make_api_call
    api_params, operation_model, context=request_context)
  File "/home/biggytruck/.local/lib/python3.6/site-packages/botocore/client.py", line 656, in _convert_to_request_dict
    api_params, operation_model)
  File "/home/biggytruck/.local/lib/python3.6/site-packages/botocore/validate.py", line 297, in serialize_to_request
    raise ParamValidationError(report=report.generate_report())
botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter Body

Насколько я понимаю, ошибка возникает из-за того, что я не передал inference.py в качестве файла точки входа, который требуется для обработки ввода, поскольку он не в стандартном формате, поддерживаемом Sagemaker. Однако sagemaker.predictor.RealTimePredictor не позволяет мне определять файл точки входа. Как я могу это решить?


person Steven Chan    schedule 05.07.2020    source источник


Ответы (1)


Ошибка, которую вы видите, возникает из-за библиотеки SDK SageMaker Python на стороне клиента, а не из удаленной конечной точки, которую вы опубликовали.

Вот документация для аргумента data (в вашем случае это pseudo_data)

data (object) – Input data for which you want the model to provide inference. If a serializer was specified when creating the RealTimePredictor, the result of the serializer is sent as input data. Otherwise the data must be sequence of bytes, and the predict method then sends the bytes in the request body as is.

Источник: https://sagemaker.readthedocs.io/en/stable/api/inference/predictors.html#sagemaker.predictor.RealTimePredictor.predict

Я предполагаю, что pseudo_data - это не тот тип, который ожидает SageMaker Python SDK, а это последовательность bytes.

person Yoav Zimmerman    schedule 07.07.2020
comment
Как показано в моем коде, pseudo_data - это в основном список массивов numpy. Я знаю, что это не тот тип данных, который ожидает SDK Sagemaker Python, поэтому мне нужен inference.py, в котором определена настраиваемая функция input_fn, чтобы правильно обрабатывать случай. - person Steven Chan; 08.07.2020
comment
Понятно. Возможно, вы можете попробовать сбросить список массивов numpy в строковое представление JSON перед отправкой его в конечную точку? - person Yoav Zimmerman; 09.07.2020