簡體   English   中英

如何在 AWS sagemaker 上部署預訓練的 sklearn model? (端點停留在創建)

[英]How do I deploy a pre trained sklearn model on AWS sagemaker? (Endpoint stuck on creating)

首先,我知道這個問題已被多次詢問,但我還沒有找到解決問題的方法。

因此,首先我使用 joblib.dump 來保存本地訓練的 sklearn RandomForest。 然后我將其上傳到 s3,創建了一個名為 code 的文件夾,並在其中放入了一個名為 inference.py 的推理腳本。

import joblib
import json
import numpy
import scipy
import sklearn
import os

"""
Deserialize fitted model
"""
def model_fn(model_dir):
    model_path = os.path.join(model_dir, 'test_custom_model')
    model = joblib.load(model_path)
    return model

"""
input_fn
    request_body: The body of the request sent to the model.
    request_content_type: (string) specifies the format/variable type of the request
"""
def input_fn(request_body, request_content_type):
    if request_content_type == 'application/json':
        request_body = json.loads(request_body)
        inpVar = request_body['Input']
        return inpVar
    else:
        raise ValueError("This model only supports application/json input")

"""
predict_fn
    input_data: returned array from input_fn above
    model (sklearn model) returned model loaded from model_fn above
"""
def predict_fn(input_data, model):
    return model.predict(input_data)

"""
output_fn
    prediction: the returned value from predict_fn above
    content_type: the content type the endpoint expects to be returned. Ex: JSON, string
"""

def output_fn(prediction, content_type):
    res = int(prediction[0])
    respJSON = {'Output': res}
    return respJSON

到目前為止非常簡單。

我也將其放入本地 jupyter sagemaker session

all_files(文件夾)code(文件夾)inference.py(python 文件)test_custom_model(模型的作業庫轉儲)

該腳本將此文件夾 all_files 轉換為 tar.gz 文件

然后是我在 sagemaker 上運行的主腳本:

import boto3
import json
import os
import joblib
import pickle
import tarfile
import sagemaker
import time
from time import gmtime, strftime
import subprocess
from sagemaker import get_execution_role

#Setup
client = boto3.client(service_name="sagemaker")
runtime = boto3.client(service_name="sagemaker-runtime")
boto_session = boto3.session.Session()
s3 = boto_session.resource('s3')
region = boto_session.region_name
print(region)
sagemaker_session = sagemaker.Session()
role = get_execution_role()

#Bucket for model artifacts
default_bucket = 'pretrained-model-deploy'
model_artifacts = f"s3://{default_bucket}/test_custom_model.tar.gz"

#Build tar file with model data + inference code
bashCommand = "tar -cvpzf test_custom_model.tar.gz all_files"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()

#Upload tar.gz to bucket
response = s3.meta.client.upload_file('test_custom_model.tar.gz', default_bucket, 'test_custom_model.tar.gz')

# retrieve sklearn image
image_uri = sagemaker.image_uris.retrieve(
    framework="sklearn",
    region=region,
    version="0.23-1",
    py_version="py3",
    instance_type="ml.m5.xlarge",
)

#Step 1: Model Creation
model_name = "sklearn-test" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
print("Model name: " + model_name)
create_model_response = client.create_model(
    ModelName=model_name,
    Containers=[
        {
            "Image": image_uri,
            "ModelDataUrl": model_artifacts,
        }
    ],
    ExecutionRoleArn=role,
)
print("Model Arn: " + create_model_response["ModelArn"])

#Step 2: EPC Creation - Serverless
sklearn_epc_name = "sklearn-epc" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
response = client.create_endpoint_config(
   EndpointConfigName=sklearn_epc_name,
   ProductionVariants=[
        {
            "ModelName": model_name,
            "VariantName": "sklearnvariant",
            "ServerlessConfig": {
                "MemorySizeInMB": 2048,
                "MaxConcurrency": 20
            }
        } 
    ]
)

# #Step 2: EPC Creation - Synchronous
# sklearn_epc_name = "sklearn-epc" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
# endpoint_config_response = client.create_endpoint_config(
#     EndpointConfigName=sklearn_epc_name,
#     ProductionVariants=[
#         {
#             "VariantName": "sklearnvariant",
#             "ModelName": model_name,
#             "InstanceType": "ml.m5.xlarge",
#             "InitialInstanceCount": 1
#         },
#     ],
# )
# print("Endpoint Configuration Arn: " + endpoint_config_response["EndpointConfigArn"])

#Step 3: EP Creation
endpoint_name = "sklearn-local-ep" + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
create_endpoint_response = client.create_endpoint(
    EndpointName=endpoint_name,
    EndpointConfigName=sklearn_epc_name,
)
print("Endpoint Arn: " + create_endpoint_response["EndpointArn"])


#Monitor creation
describe_endpoint_response = client.describe_endpoint(EndpointName=endpoint_name)
while describe_endpoint_response["EndpointStatus"] == "Creating":
    describe_endpoint_response = client.describe_endpoint(EndpointName=endpoint_name)
    print(describe_endpoint_response)
    time.sleep(15)
print(describe_endpoint_response)

現在,我主要只想要無服務器部署,但一段時間后失敗並顯示以下錯誤消息:

{'EndpointName': 'sklearn-local-ep2022-04-29-12-16-10', 'EndpointArn': 'arn:aws:sagemaker:us-east-1:963400650255:endpoint/sklearn-local-ep2022-04-29-12-16-10', 'EndpointConfigName': 'sklearn-epc2022-04-29-12-16-03', 'EndpointStatus': 'Creating', 'CreationTime': datetime.datetime(2022, 4, 29, 12, 16, 10, 290000, tzinfo=tzlocal()), 'LastModifiedTime': datetime.datetime(2022, 4, 29, 12, 16, 11, 52000, tzinfo=tzlocal()), 'ResponseMetadata': {'RequestId': '1d25120e-ddb1-474d-9c5f-025c6be24383', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '1d25120e-ddb1-474d-9c5f-025c6be24383', 'content-type': 'application/x-amz-json-1.1', 'content-length': '305', 'date': 'Fri, 29 Apr 2022 12:21:59 GMT'}, 'RetryAttempts': 0}}
{'EndpointName': 'sklearn-local-ep2022-04-29-12-16-10', 'EndpointArn': 'arn:aws:sagemaker:us-east-1:963400650255:endpoint/sklearn-local-ep2022-04-29-12-16-10', 'EndpointConfigName': 'sklearn-epc2022-04-29-12-16-03', 'EndpointStatus': 'Failed', 'FailureReason': 'Unable to successfully stand up your model within the allotted 180 second timeout. Please ensure that downloading your model artifacts, starting your model container and passing the ping health checks can be completed within 180 seconds.', 'CreationTime': datetime.datetime(2022, 4, 29, 12, 16, 10, 290000, tzinfo=tzlocal()), 'LastModifiedTime': datetime.datetime(2022, 4, 29, 12, 22, 2, 68000, tzinfo=tzlocal()), 'ResponseMetadata': {'RequestId': '59fb8ddd-9d45-41f5-9383-236a2baffb73', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '59fb8ddd-9d45-41f5-9383-236a2baffb73', 'content-type': 'application/x-amz-json-1.1', 'content-length': '559', 'date': 'Fri, 29 Apr 2022 12:22:15 GMT'}, 'RetryAttempts': 0}}

實時部署只是永久停留在創建過程中。

Cloudwatch 出現以下錯誤: Error handling request /ping

AttributeError: 'NoneType' object 沒有屬性 'startswith'

追溯:

Traceback (most recent call last):
  File "/miniconda3/lib/python3.7/site-packages/gunicorn/workers/base_async.py", line 55, in handle
    self.handle_request(listener_name, req, client, addr)

復制粘貼已停止工作,所以我附上了它的圖像。

在此處輸入圖像描述

這是我收到的錯誤消息:Endpoint Arn: arn:aws:sagemaker:us-east-1:963400650255:endpoint/sklearn-local-ep2022-04-29-13-18-09 {'EndpointName': 'sklearn- local-ep2022-04-29-13-18-09', 'EndpointArn': 'arn:aws:sagemaker:us-east-1:963400650255:endpoint/sklearn-local-ep2022-04-29-13-18- 09', 'EndpointConfigName': 'sklearn-epc2022-04-29-13-18-07', 'EndpointStatus': 'Creating', 'CreationTime': datetime.datetime(2022, 4, 29, 13, 18, 9 , 548000, tzinfo=tzlocal()), 'LastModifiedTime': datetime.datetime(2022, 4, 29, 13, 18, 13, 119000, tzinfo=tzlocal()), 'ResponseMetadata': {'RequestId': 'ef0e49ee -618e-45de-9c49-d796206404a4', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'ef0e49ee-618e-45de-9c49-d796206404a4', 'content-type': 'application/ x-amz-json-1.1', 'content-length': '306', 'date': 'Fri, 29 Apr 2022 13:18:24 GMT'}, 'RetryAttempts': 0}}

這些是我與該角色關聯的權限:

AmazonSageMaker-ExecutionPolicy
SecretsManagerReadWrite
AmazonS3FullAccess
AmazonSageMakerFullAccess
EC2InstanceProfileForImageBuilderECRContainerBuilds
AWSAppRunnerServicePolicyForECRAccess

我究竟做錯了什么? 我為 zip 文件嘗試了不同的文件夾結構,不同的帳戶,都無濟於事。 我真的不想使用 model.deploy() 方法,因為我不知道如何使用無服務器,而且它在不同的 model 類型之間也不一致(我試圖在不同的地方制作靈活的部署管道( xgb / sklearn) 模型可以通過最小的更改進行部署。

請提供幫助,我差點弄壞頭發,撕掉筆記本電腦,整整 4 天都在為此苦苦掙扎。

請遵循本指南: https://github.com/RamVegiraju/Pre-Trained-Sklearn-SageMaker 在 model 創建期間,我認為您的推理腳本未在環境變量中指定。

我認為問題出在壓縮文件上。 從這個問題我了解到您正在嘗試 zip 包括 model 轉儲和腳本在內的所有文件。

我建議從 model 工件中刪除推理腳本。

model.tar.gz 文件應僅包含 model。

並按照@ram-vegiraju 的建議添加推理腳本的環境變量。

該腳本應該在本地可用。

我已經解決了這個問題 - 我使用 sagemaker.model.model 加載了我已經擁有的 model 數據,我調用了上述 model object 上的部署方法來部署它。 此外,我將推理腳本和 model 文件放在與筆記本相同的位置並直接調用它們,因為這也給了我一個錯誤。

暫無
暫無

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

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