簡體   English   中英

AWS SageMaker - 如何加載經過訓練的 sklearn model 以進行推理?

[英]AWS SageMaker - How to load trained sklearn model to serve for inference?

我正在嘗試將使用 sklearn 訓練的 model 部署到端點,並將其作為 API 進行預測。 我只想使用 sagemaker 來部署和服務器 model 我已經使用joblib序列化,僅此而已。 我讀過的每個博客和 sagemaker python 文檔都顯示 sklearn model 必須在 sagemaker 上進行培訓才能部署在 sagemaker 中。

當我瀏覽 SageMaker 文檔時,我了解到 sagemaker 確實允許用戶加載存儲在 S3 中的序列化 model ,如下所示:

def model_fn(model_dir):
    clf = joblib.load(os.path.join(model_dir, "model.joblib"))
    return clf

這就是文檔中關於參數model_dir的說明:

SageMaker 將注入您的 model 文件和子目錄(通過 save 保存)已安裝的目錄。 Your model function should return a model object that can be used for model serving.

這再次意味着必須在 sagemaker 上進行培訓。

那么,有沒有辦法我可以指定序列化 model 的 S3 位置,並讓 sagemaker 從 S3 反序列化(或加載)model 並將其用於推理?

編輯1:

我在應用程序的答案中使用了代碼,但在嘗試從 SageMaker Studio 的筆記本部署時出現以下錯誤。 我相信 SageMaker 正在尖叫說沒有在 SageMaker 上進行培訓。

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-6662bbae6010> in <module>
      1 predictor = model.deploy(
      2     initial_instance_count=1,
----> 3     instance_type='ml.m4.xlarge'
      4 )

/opt/conda/lib/python3.7/site-packages/sagemaker/estimator.py in deploy(self, initial_instance_count, instance_type, serializer, deserializer, accelerator_type, endpoint_name, use_compiled_model, wait, model_name, kms_key, data_capture_config, tags, **kwargs)
    770         """
    771         removed_kwargs("update_endpoint", kwargs)
--> 772         self._ensure_latest_training_job()
    773         self._ensure_base_job_name()
    774         default_name = name_from_base(self.base_job_name)

/opt/conda/lib/python3.7/site-packages/sagemaker/estimator.py in _ensure_latest_training_job(self, error_message)
   1128         """
   1129         if self.latest_training_job is None:
-> 1130             raise ValueError(error_message)
   1131 
   1132     delete_endpoint = removed_function("delete_endpoint")

ValueError: Estimator is not associated with a training job

我的代碼:

import sagemaker
from sagemaker import get_execution_role
# from sagemaker.pytorch import PyTorchModel
from sagemaker.sklearn import SKLearn
from sagemaker.predictor import RealTimePredictor, json_serializer, json_deserializer

sm_role = sagemaker.get_execution_role()  # IAM role to run SageMaker, access S3 and ECR

model_file = "s3://sagemaker-manual-bucket/sm_model_artifacts/model.tar.gz"   # Must be ".tar.gz" suffix

class AnalysisClass(RealTimePredictor):
    def __init__(self, endpoint_name, sagemaker_session):
        super().__init__(
            endpoint_name,
            sagemaker_session=sagemaker_session,
            serializer=json_serializer,
            deserializer=json_deserializer,   # To be able to use JSON serialization
            content_type='application/json'   # To be able to send JSON as HTTP body
        )

model = SKLearn(model_data=model_file,
                entry_point='inference.py',
                name='rf_try_1',
                role=sm_role,
                source_dir='code',
                framework_version='0.20.0',
                instance_count=1,
                instance_type='ml.m4.xlarge',
                predictor_cls=AnalysisClass)
predictor = model.deploy(initial_instance_count=1,
                         instance_type='ml.m4.xlarge')

是的你可以。 AWS 文檔側重於 SageMaker 中從培訓到部署的端到端,給人的印象是必須在 sagemaker 上進行培訓。 AWS 文檔和示例應明確區分 Estimator 中的訓練、保存和加載 model 以及將 model 部署到 SageMaker 端點。

SageMaker Model

您需要創建AWS::SageMaker::Model資源,它指的是您已訓練的“模型”等等 AWS::SageMaker::Model 在 CloudFormation 文檔中,但它只是說明您需要什么 AWS 資源。

CreateModel API 創建 SageMaker model 資源。 參數指定要使用的 docker 映像、S3 中的 model 位置、要使用的 IAM 角色等。請參閱SageMaker 如何加載您的 Model Artif

Docker 圖像

顯然,您需要用於訓練 model 的框架,例如 ScikitLearn、TensorFlow、PyTorch 等。 您需要具有框架的 docker 圖像和 HTTP 前端來響應預測調用。 請參閱SageMaker 推理工具包使用 SageMaker 訓練和推理工具包

建立形象並不容易。 因此,AWS 提供了稱為AWS 深度學習容器的預構建圖像,可用圖像位於Github中。

如果那里列出了您的框架和版本,則可以將其用作圖像。 否則,您需要自己構建。 請參閱構建 docker 容器以訓練/部署我們的分類器

用於框架的 SageMaker Python SDK

使用 API 自己創建 SageMaker Model 很難。 因此,AWS SageMaker Python SDK 提供了用於為多個框架創建 SageMaker 模型的實用程序。 有關可用框架,請參閱框架 如果它不存在,您仍然可以使用sagemaker.model.FrameworkModelModel來加載經過訓練的 model。 對於您的情況,請參閱將 Scikit-learn 與 SageMaker Python SDK 一起使用

model.tar.gz

例如,如果您使用 PyTorch 並將 model 保存為 model.pth。 要加載 model 和推理代碼以從 model 獲取預測,您需要創建 model.tar.gz 文件。 model.tar.gz 內部的結構在Model 目錄結構中進行了說明。 如果您使用 Windows,請注意 CRLF 到 LF。 AWS SageMaker 在 *NIX 環境中運行。 請參閱為 model 文件創建目錄結構

|- model.pth        # model file is inside / directory.
|- code/            # Code artefacts must be inside /code
  |- inference.py   # Your inference code for the framework
  |- requirements.txt  # only for versions 1.3.1 and higher. Name must be "requirements.txt"

將 tar.gz 文件保存在 S3 中。 確保 IAM 角色可以訪問 S3 存儲桶和對象。

加載 model 並得到推斷

請參閱創建 PyTorchModel object 在實例化 PyTorchModel class 時,SageMaker 會自動為framework_version中指定的版本選擇 PyTorch 的 AWS 深度學習容器映像。 如果該版本的圖像不存在,則它會失敗。 這尚未在 AWS 中記錄,但需要注意。 然后,SageMaker 使用 S3 model 文件位置和 AWS 深度學習容器映像 URL 在內部調用 CreateModel API。

import sagemaker
from sagemaker import get_execution_role
from sagemaker.pytorch import PyTorchModel
from sagemaker.predictor import RealTimePredictor, json_serializer, json_deserializer

role = sagemaker.get_execution_role()  # IAM role to run SageMaker, access S3 and ECR
model_file = "s3://YOUR_BUCKET/YOUR_FOLDER/model.tar.gz"   # Must be ".tar.gz" suffix


class AnalysisClass(RealTimePredictor):
    def __init__(self, endpoint_name, sagemaker_session):
        super().__init__(
            endpoint_name,
            sagemaker_session=sagemaker_session,
            serializer=json_serializer,
            deserializer=json_deserializer,   # To be able to use JSON serialization
            content_type='application/json'   # To be able to send JSON as HTTP body
        )

model = PyTorchModel(
    model_data=model_file,
    name='YOUR_MODEL_NAME_WHATEVER',
    role=role,
    entry_point='inference.py',
    source_dir='code',              # Location of the inference code
    framework_version='1.5.0',      # Availble AWS Deep Learning PyTorch container version must be specified
    predictor_cls=AnalysisClass     # To specify the HTTP request body format (application/json)
)

predictor = model.deploy(
    initial_instance_count=1,
    instance_type='ml.m5.xlarge'
)

test_data = {"body": "YOUR PREDICTION REQUEST"}
prediction = predictor.predict(test_data)

默認情況下,SageMaker 使用 NumPy 作為序列化格式。 為了能夠使用 JSON,需要指定序列化器和 content_type。 您可以將它們指定為預測器,而不是使用 RealTimePredictor class。

predictor.serializer=json_serializer
predictor.predict(test_data)

或者

predictor.serializer=None # As the serializer is None, predictor won't serialize the data
serialized_test_data=json.dumps(test_data) 
predictor.predict(serialized_test_data)

推理代碼示例

See Process Model Input , Get Predictions from a PyTorch Model and Process Model Output . 在本例中,預測請求在 HTTP 請求正文中作為 JSON 發送。

import os
import sys
import datetime
import json
import torch
import numpy as np

CONTENT_TYPE_JSON = 'application/json'

def model_fn(model_dir):
    # SageMaker automatically load the model.tar.gz from the S3 and 
    # mount the folders inside the docker container. The  'model_dir'
    # points to the root of the extracted tar.gz file.

    model_path = f'{model_dir}/'
    
    # Load the model
    # You can load whatever from the Internet, S3, wherever <--- Answer to your Question
    # NO Need to use the model in tar.gz. You can place a dummy model file.
    ...

    return model


def predict_fn(input_data, model):
    # Do your inference
    ...

def input_fn(serialized_input_data, content_type=CONTENT_TYPE_JSON):
    input_data = json.loads(serialized_input_data)
    return input_data


def output_fn(prediction_output, accept=CONTENT_TYPE_JSON):
    if accept == CONTENT_TYPE_JSON:
        return json.dumps(prediction_output), accept
    raise Exception('Unsupported content type') 

筆記

SageMaker 團隊不斷更改實施,文檔經常過時。 當您確定您確實遵循了文檔並且它不起作用時,很可能是過時的文檔。 在這種情況下,需要通過 AWS 支持進行澄清,或在 Github 中提出問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM