Простой шаблон… прямо к делу

Существует множество способов развертывания модели с помощью AWS Sagemaker, и иногда бывает сложно решить, какой из них выбрать. Преимущество метода, описанного в этом руководстве (Принесите свою собственную модель), заключается в том, что он универсален, но при этом относительно прост в реализации. То есть он будет работать со всеми платформами, в отличие от некоторых других более строгих подходов (Принесите свою собственную модель). Например, на момент написания Catboost не был платформой, поддерживаемой подходом BYOM.

Модель, которую мы собираемся развернуть на конечной точке Sagemaker, представляет собой простой классификатор CatBoost.

В этом руководстве я запускаю весь код в блокноте Sagemaker, и предполагается, что ваши артефакты модели хранятся на Amazon S3.

Шаг 1: Создание контейнера

Вот все файлы, которые нам нужны:

src/
├─ prediction_script.py
Dockerfile
requirements.txt

требования.txt

catboost
numpy
pandas
flask
gunicorn
boto3

Файл Docker

# Use an official Python 3.8 runtime as a base image
FROM python:3.8

# Set environment variables
# ensures that Python outputs everything that's printed directly to the terminal (so logs can be seen in real-time)
ENV PYTHONUNBUFFERED=TRUE
# ensures Python doesn't try to write .pyc files to disk (useful for improving performance in some scenarios)
ENV PYTHONDONTWRITEBYTECODE=TRUE
# Update PATH environment variable to include /opt/program directory
ENV PATH="/opt/program:${PATH}"

# Set the working directory in the Docker image to /opt/program
WORKDIR /opt/program

# Upgrade pip package manager to the latest version
RUN pip install --upgrade pip

# Get requirements.txt file and install packages
COPY ./requirements.txt /opt/program/requirements.txt
RUN pip install --no-cache-dir --upgrade -r requirements.txt

# Copy the source code of the application
COPY ./src /opt/program

ENTRYPOINT ["gunicorn", "-b", ":8080", "prediction_script:app"]

src/prediction_script.py

# Import the necessary libraries
import boto3
import json
from catboost import CatBoostClassifier
from flask import Flask, request, jsonify
import pandas as pd

# Instantiate Flask app
app = Flask(__name__)

# Define the model path
# When you configure the model, you will need to specify the S3 location of your model artifacts.
# Sagemaker will automatically download, decompress and store the model's weights in the /opt/ml/model folder.
MODEL_PATH = "/opt/ml/model/<model_artifacts>"

# Load the CatBoost model from the specified path
model = CatBoostClassifier().load_model(MODEL_PATH)

# Define an endpoint for health check
@app.route('/ping', methods=['GET'])
def ping():
  return '', 200

# Define an endpoint for making predictions
@app.route('/invocations', methods=['POST'])
def predict():
  # Get data from the POST request
  data = request.get_data().decode('utf-8')

  # Convert the data into a Pandas DataFrame
  df = pd.read_json(data, orient='split')
  
  # Make predictions using the loaded model
  prediction = model.predict(df)

  # Return the prediction results as JSON
  return json.dumps(prediction.tolist())

Шаг 2. Создание репозитория ECR и добавление в него контейнера.

import boto3

# Set the repository name and region
REPOSITORY_NAME = "<your_repository_name>"
REGION = "<your_region>"

# Create a new repository in the Amazon Elastic Container Registry (ECR) using the AWS CLI
# The 'sleep 8' command is used to wait for 8 seconds to ensure the repository is created before the next commands are executed
!aws ecr create-repository --repository-name {REPOSITORY_NAME} ; sleep 8

# Use Boto3 to describe the repository and select the newly created one
ecr = boto3.client('ecr')
response = ecr.describe_repositories()
selected_repository = [repo for repo in response['repositories'] if repo['repositoryName'] == REPOSITORY_NAME][0]

# Log into the ECR repository with Docker using the AWS CLI to retrieve a login password
!aws ecr get-login-password --region {REGION} | docker login --username AWS --password-stdin {selected_repository['repositoryUri']}

# Tag the Docker image with the ECR repository URI
!docker tag {REPOSITORY_NAME}:latest {selected_repository['repositoryUri']}:latest

# Push the Docker image to the ECR repository
!docker push {selected_repository['repositoryUri']}:latest

Шаг 3: Создайте модель и ее конечную точку

  • пойти к создателю мудрецов

Создание модели:

  • слева: Inference-›Models -› Create model

Вам необходимо предоставить ECR URI вашего изображения, а также S3 location артефактов вашей модели. Sagemaker автоматически загрузит, распакует и сохранит вес модели в папке /opt/ml/model.

Создание конечной точки:

  • слева: Inference-›Endpoints -› Create endpoint

Шаг 4. Проверьте конечную точку.

import boto3

sample_data = '{}' # json string generated with DataFrame.to_json(orient="split")

runtime = boto3.client('runtime.sagemaker')
response = runtime.invoke_endpoint(EndpointName='<your_sagemaker_endpoint_name>',
                                   ContentType='application/json',
                                   Body=sample_data)
print(response['Body'].read())

Вот и все! Теперь вы можете делать прогнозы, запрашивая свою конечную точку!