1. 程式人生 > 實用技巧 >在AWS上部署、監控和擴充套件機器學習模型

在AWS上部署、監控和擴充套件機器學習模型

作者|Aparna Dhinakaran
編譯|Flin
來源|towardsdatascience

部署健壯的、可擴充套件的機器學習解決方案仍然是一個非常複雜的過程,需要大量的人力參與,並做出很多努力。因此,新產品和服務需要很長時間才能上市,或者在原型狀態下就被放棄,從而降低了行業內的對它的興趣。那麼,我們如何才能促進將機器學習模型投入生產的過程呢?

Cortex是一個將機器學習模型部署為生產網路服務的開源平臺。它利用強大的AWS生態系統,根據需要部署、監視和擴充套件與框架無關的模型。其主要特點概括如下:

  • 框架無關:Cortex支援任何python程式碼;與其他python指令碼一樣,TensorFlow、PyTorch、scikit-learn、XGBoost都是由該庫支援的。

  • 自動縮放:Cortex自動縮放你的api,以處理生產負載。

  • CPU / GPU支援:使用AWS IaaS作為底層基礎架構,Cortex可以在CPU或GPU環境下執行。

  • Spot例項:Cortex支援EC2 Spot例項來降低成本。

  • 滾動更新:Cortex對模型應用任何更新,沒有任何停機時間。

  • 日誌流:Cortex使用類似docker的語法將部署模型中的日誌儲存下來,並將其流式傳輸到CLI。

  • 預測監測:Cortex監測網路指標並跟蹤預測。

  • 最小配置:Cortex部署配置被定義為一個簡單的YAML檔案。

在本文中,我們使用Cortex將一個影象分類模型作為web服務部署到AWS上。那麼,言歸正傳,讓我們來介紹一下Cortex。

將模型部署為Web服務

在這個例子中,我們使用fast.ai庫(https://pypi.org/project/fastai/) ,並從相關MOOC的第一個課程中(https://course.fast.ai/) 借用pets分類模型。以下各節介紹了Cortex的安裝和pets分類模型作為web服務的部署。

安裝

如果還沒有安裝,首先應該在AWS上建立一個具有程式設計訪問許可權的新使用者帳戶。為此,請選擇IAM服務,然後從右側面板中選擇Users,最後按Add User按鈕。為使用者指定一個名稱並選擇Programmatic access

接下來,在Permissions 螢幕中,選擇Attach existing policies directly

選項卡,然後選擇AdministratorAccess

你可以將標記頁留空,檢視並建立使用者。最後,注意訪問金鑰ID和金鑰訪問金鑰。

在AWS控制檯上,你還可以建立一個S3 bucket來儲存經過訓練的模型和程式碼可能生成的任何其他人工製品。你可以隨意命名這個bucket,只要它是一個唯一的名字。在這裡,我們建立了一個名為cortex-pets-model的bucket。

下一步,我們必須在系統上安裝Cortex CLI並啟動Kubernetes叢集。要安裝Cortex CLI,請執行以下命令:

bash -c “$(curl -sS https://raw.githubusercontent.com/cortexlabs/cortex/0.14/get-cli.sh)"

通過訪問相應的文件部分(https://www.cortex.dev/) ,檢查你是否正在安裝最新版本的Cortex CLI。

我們現在準備建立叢集。使用Cortex建立Kubernetes叢集是很簡單的。只需執行以下命令:

cortex cluster up

Cortex會要求你提供一些資訊,比如你的AWS金鑰、你想使用的區域、你想啟動的計算例項以及它們的數量。Cortex也會讓你知道你會花多少錢來使用你選擇的服務。整個過程可能需要20分鐘。

訓練你的模型

Cortex並不關心你如何建立或訓練你的模型。在本例中,我們使用fast.ai庫和Oxford IIIT Pet資料集。這個資料集包含37種不同的狗和貓。因此,我們的模型應該將每個影象分為這37類。

建立一個類似下面的trainer.py檔案

import boto3
import pickle

from fastai.vision import *


# initialize boto session
session = boto3.Session(
    aws_access_key_id=<your_accress_key_id>,
    aws_secret_access_key='<your_secret_access_key>',
)

# get the data
path = untar_data(URLs.PETS, dest='sample_data')
path_img = path/'images'
fnames = get_image_files(path_img)

# process the data
bs = 64
pat = r'/([^/]+)_\d+.jpg$'
data = ImageDataBunch.from_name_re(path_img, fnames, pat, 
                                   ds_tfms=get_transforms(), size=224, bs=bs) \
                     .normalize(imagenet_stats)

# create, fit and save the model
learn = cnn_learner(data, models.resnet18, metrics=accuracy)
learn.fit_one_cycle(4)

with open('model.pkl', 'wb') as handle:
    pickle.dump(learn.model, handle)

# upload the model to s3
s3 = session.client('s3')
s3.upload_file('model.pkl', 'cortex-pets-model', 'model.pkl')

與其他python指令碼一樣,在本地執行該指令碼:python trainer.py

但是,請確保提供你的AWS憑據和S3 bucket名稱。這個指令碼獲取資料,處理它們,適合一個預先訓練好的ResNet模型並將其上傳到S3。當然,你可以使用幾種技術(更復雜的體系結構、有區別的學習率、面向更多時代的訓練)來擴充套件此指令碼以使模型更精確,但是這與我們的目標無關。如果你想進一步瞭解ResNet體系結構,請參閱下面的文章。

https://towardsdatascience.com/xresnet-from-scratch-in-pytorch-e64e309af722

部署模型

現在我們已經訓練了模型並將其儲存在S3中,下一步是將其作為web服務部署到生產環境中。為此,我們建立了一個名為predictor.py的python指令碼,像下圖:

import torch
import boto3
import pickle
import requests

from PIL import Image
from io import BytesIO
from torchvision import transforms


# initialize boto session
session = boto3.Session(
    aws_access_key_id='<your_access_key_id>',
    aws_secret_access_key='<your_secret_access_key>',
)


# define the predictor
class PythonPredictor:
    def __init__(self, config):
        s3 = session.client('s3')
        s3.download_file(config['bucket'], config['key'], 'model.pkl')
        self.model = pickle.load(open('model.pkl', 'rb'))
        self.model.eval()

        normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
        self.preprocess = transforms.Compose(
            [transforms.Resize(224), transforms.ToTensor(), normalize]
        )

        self.labels = ['Abyssinian', 'Bengal', 'Birman', 'Bombay', 'British_Shorthair',
                       'Egyptian_Mau', 'Maine_Coon', 'Persian', 'Ragdoll', 'Russian_Blue',
                       'Siamese', 'Sphynx', 'american_bulldog', 'american_pit_bull_terrier',
                       'basset_hound', 'beagle', 'boxer', 'chihuahua', 'english_cocker_spaniel',
                       'english_setter', 'german_shorthaired', 'great_pyrenees', 'havanese',
                       'japanese_chin', 'keeshond', 'leonberger', 'miniature_pinscher', 'newfoundland',
                       'pomeranian', 'pug', 'saint_bernard', 'samoyed', 'scottish_terrier', 'shiba_inu',
                       'staffordshire_bull_terrier', 'wheaten_terrier',  'yorkshire_terrier']

        self.device = config['device']

    def predict(self, payload):
        image = requests.get(payload["url"]).content
        img_pil = Image.open(BytesIO(image))
        img_tensor = self.preprocess(img_pil)
        img_tensor.unsqueeze_(0)
        img_tensor = img_tensor.to(self.device)
        with torch.no_grad():
            prediction = self.model(img_tensor)
        _, index = prediction[0].max(0)
        return self.labels[index]

這個檔案定義了一個預測器類。在例項化它時,它從S3中檢索模型,將其載入到記憶體中,並定義一些必要的轉換和引數。在推理期間,它從給定的URL中讀取影象並返回預測的類的名稱。一個用於初始化的方法__init__和一個用於接收有效負載並返回結果的預測方法predict

預測器指令碼有兩個附帶的檔案。一個記錄庫依賴項的requirements.txt檔案(如pytorch、fastai、boto3等)和一個YAML配置檔案。最小配置如下:

- name: pets-classifier
  predictor:
    type: python
    path: predictor.py
    config:
      bucket: cortex-pets-model
      key: model.pkl
      device: cpu 

在這個YAML檔案中,我們定義了執行哪個指令碼進行推理,在哪個裝置(例如CPU)上執行,以及在哪裡找到訓練好的模型。文件中提供了更多的選項。

最後,專案的結構應該遵循下面的層次結構。請注意,這是最低限度的要求,但是如果你有一個可以部署的模型,那麼你可以提交train .py

- Project name
    |----trainer.py
    |----predictor.py
    |----requirements.txt
    |----cortex.yaml

有了所有這些,你只需執行cortex deploy,幾秒鐘之內,你的新端點就可以接受請求了。執行corted get pets-classifier來監視端點並檢視其他詳細資訊。

status   up-to-date   requested   last update   avg request   2XX   
live     1            1           13m           -             -
endpoint: http://a984d095c6d3a11ea83cc0acfc96419b-1937254434.us-west-2.elb.amazonaws.com/pets-classifier
curl: curl http://a984d095c6d3a11ea83cc0acfc96419b-1937254434.us-west-2.elb.amazonaws.com/pets-classifier?debug=true -X POST -H "Content-Type: application/json" -d @sample.json
configuration
name: pets-classifier
endpoint: /pets-classifier
predictor:
  type: python
  path: predictor.py
  config:
    bucket: cortex-pets-model
    device: cpu
    key: model.pkl
compute:
  cpu: 200m
autoscaling:
  min_replicas: 1
  max_replicas: 100
  init_replicas: 1
  workers_per_replica: 1
  threads_per_worker: 1
  target_replica_concurrency: 1.0
  max_replica_concurrency: 1024
  window: 1m0s
  downscale_stabilization_period: 5m0s
  upscale_stabilization_period: 0s
  max_downscale_factor: 0.5
  max_upscale_factor: 10.0
  downscale_tolerance: 0.1
  upscale_tolerance: 0.1
update_strategy:
  max_surge: 25%
  max_unavailable: 25%

剩下的就是用curl和pomeranian的影象來測試它:

curl http://a984d095c6d3a11ea83cc0acfc96419b-1937254434.us-west-2.elb.amazonaws.com/pets-classifier -X POST -H "Content-Type: application/json" -d '{"url": "https://i.imgur.com/HPRQ28l.jpeg"}'

釋放資源

當我們完成服務和叢集時,我們應該釋放資源以避免額外的成本。Cortex很容易做到:

cortex delete pets-classifier
cortex cluster down

結論

在這篇文章中,我們看到了如何使用Cortex,一個開源平臺,來將機器學習模型部署為生產web服務。我們訓練了一個影象分類器,將其部署到AWS上,監控其效能並進行測試。

有關更高階的概念,如預測監視、滾動更新、叢集配置、自動縮放等,請訪問官方文件站點(https://www.cortex.dev/) 和專案的GitHub頁面(https://github.com/cortexlabs/cortex)。

原文連結:https://towardsdatascience.com/deploy-monitor-and-scale-machine-learning-models-on-aws-408dfd397422

歡迎關注磐創AI部落格站:
http://panchuang.net/

sklearn機器學習中文官方文件:
http://sklearn123.com/

歡迎關注磐創部落格資源彙總站:
http://docs.panchuang.net/