[英]Sagemaker timing out for flask model deployment
下面是 ECR Container 中的 predict.py。 Sagemaker 端點在重試 10-12 分鍾后給出“狀態:失敗”輸出。 /ping 和 /invocations 方法都可用
/opt/ml/code/predict.py
----------
logger = logging.getLogger()
logger.setLevel(logging.INFO)
classpath = <.pkl file>
model = pickle.load(open(classpath, "rb"))
app = flask.Flask(__name__)
print(app)
@app.route("/ping", methods=["GET"]
def ping():
"""Determine if the container is working and healthy."""
return flask.Response(response="Flask running", status=200, mimetype="application/json")
@app.route("/invocations", methods=["POST"])
""InferenceCode""
return flask.Response(response="Invocation Completed", status=200,
mimetype="application/json")
Below snippet was both added and removed , however I still have the endpoint in failed status
if __name__ == '__main__':
app.run(host='0.0.0.0',port=5000)
Error :
"The primary container for production variant <modelname> did not pass the ping health check. Please check CloudWatch logs for this endpoint."
Sagemaker endpoint Cloudwatch logs.
[INFO] Starting gunicorn 20.1.0
[INFO] Listening at: http://0.0.0.0:8000 (1)
[INFO] Using worker: sync
[INFO] Booting worker with pid: 11```
您的預測器文件旨在測試模型是否已加載到 /ping 中,以及您是否可以在 /invocations 中執行推理。 如果您已在 SageMaker 上訓練您的模型,您需要按如下方式從 /opt/ml 目錄加載它。
prefix = "/opt/ml/"
model_path = os.path.join(prefix, "model")
class ScoringService(object):
model = None # Where we keep the model when it's loaded
@classmethod
def get_model(rgrs):
"""Get the model object for this instance, loading it if it's not already loaded."""
if rgrs.model == None:
with open(os.path.join(model_path, "rf-model.pkl"), "rb") as inp:
rgrs.model = pickle.load(inp)
return rgrs.model
@classmethod
def predict(rgrs, input):
"""For the input, do the predictions and return them.
Args:
input (a pandas dataframe): The data on which to do the predictions. There will be
one prediction per row in the dataframe"""
rf = rgrs.get_model()
return rf.predict(input)
該類有助於加載您的模型,然后我們可以在 /ping 中進行驗證。
# The flask app for serving predictions
app = flask.Flask(__name__)
@app.route("/ping", methods=["GET"])
def ping():
"""Determine if the container is working and healthy. In this sample container, we declare
it healthy if we can load the model successfully."""
health = ScoringService.get_model() is not None # You can insert a health check here
status = 200 if health else 404
return flask.Response(response="\n", status=status, mimetype="application/json")
在這里 SageMaker 將測試您是否正確加載了模型。 對於 /invocations 包括您傳遞到模型預測功能的任何數據格式的推理邏輯。
@app.route("/invocations", methods=["POST"])
def transformation():
data = None
# Convert from CSV to pandas
if flask.request.content_type == "text/csv":
data = flask.request.data.decode("utf-8")
s = io.StringIO(data)
data = pd.read_csv(s, header=None)
else:
return flask.Response(
response="This predictor only supports CSV data", status=415, mimetype="text/plain"
)
print("Invoked with {} records".format(data.shape[0]))
# Do the prediction
predictions = ScoringService.predict(data)
# Convert from numpy back to CSV
out = io.StringIO()
pd.DataFrame({"results": predictions}).to_csv(out, header=False, index=False)
result = out.getvalue()
return flask.Response(response=result, status=200, mimetype="text/csv")
確保如上所示設置或配置您的 predictor.py,以便 SageMaker 能夠正確理解/檢索您的模型。
我為 AWS 工作,我的意見是我自己的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.