TorchServe を使用したモデルのデプロイ - Amazon SageMaker AI

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

TorchServe を使用したモデルのデプロイ

TorchServe は、 AWS PyTorch 深層学習コンテナ (DLC) にプリインストールされた PyTorch 用の推奨モデルサーバーです。この強力なツールは、モデルのサイズやディストリビューションに関係なく、CPU、GPU、Neuron、Graviton などのさまざまな AWS インスタンスに複数の PyTorch モデルをデプロイする際に高いパフォーマンスを提供し、一貫性のあるユーザーフレンドリーなエクスペリエンスをお客様に提供します。

TorchServe は、動的バッチ処理、マイクロバッチ処理、モデル A/B テスト、ストリーミング、トーチ XLA、TensorRT、ONNX、IPEX など、さまざまな高度な機能をサポートしています。さらに、PyTorch の大規模モデルソリューションである PiPPy をシームレスに統合できるため、大規模モデルを効率的に処理できます。また、TorchServe は、DeepSpeed、Accelerate、Fast Transformers などの一般的なオープンソースライブラリにもサポートを拡張し、その機能をさらに拡張しています。TorchServe を使用すると、 AWS ユーザーは PyTorch モデルを自信を持ってデプロイして提供し、さまざまなハードウェア設定やモデルタイプにわたって汎用性と最適化されたパフォーマンスを活用できます。詳細な情報については、「PyTorch のドキュメント」と「GitHub の TorchServe」を参照してください。

次の表に、 AWS TorchServe でサポートされている PyTorch TorchServe DLCs を示します。

インスタンスタイプ SageMaker AI PyTorch DLC リンク

CPU および GPU

SageMaker AI PyTorch コンテナ

Neuron

PyTorch Neuron コンテナ

Graviton

SageMaker AI PyTorch Graviton コンテナ

以下のセクションでは、Amazon SageMaker AI で PyTorch DLCs を構築およびテストするためのセットアップについて説明します。

入門

開始するには、次の前提条件が整っていることを確認してください。

  1. AWS アカウントにアクセスできることを確認します。が IAM ユーザーまたは IAM AWS ロールを介してアカウント AWS CLI にアクセスできるように環境を設定します。IAM ロールの使用をお勧めします。個人アカウントでテストする目的で、以下の管理アクセス許可ポリシーを IAM ロールにアタッチできます。

  2. 次の例のように、依存関係をローカルに設定します。

    from datetime import datetime import os import json import logging import time # External Dependencies: import boto3 from botocore.exceptions import ClientError import sagemaker sess = boto3.Session() sm = sess.client("sagemaker") region = sess.region_name account = boto3.client("sts").get_caller_identity().get("Account") smsess = sagemaker.Session(boto_session=sess) role = sagemaker.get_execution_role() # Configuration: bucket_name = smsess.default_bucket() prefix = "torchserve" output_path = f"s3://{bucket_name}/{prefix}/models" print(f"account={account}, region={region}, role={role}")
  3. 次の例に示すように、PyTorch の DLC イメージを取得します。

    SageMaker AI PyTorch DLC イメージは、すべての AWS リージョンで利用できます。詳細については、「DLC コンテナイメージのリスト」を参照してください。

    baseimage = sagemaker.image_uris.retrieve( framework="pytorch", region="<region>", py_version="py310", image_scope="inference", version="2.0.1", instance_type="ml.g4dn.16xlarge", )
  4. ローカルワークスペースの作成

    mkdir -p workspace/

パッケージの追加

以下のセクションでは、PyTorch DLC イメージにパッケージを追加および事前インストールする方法について説明します。

BYOC のユースケース

以下の手順は、PyTorch DLC イメージにパッケージを追加する方法を示しています。コンテナのカスタマイズの詳細については、「Building AWS Deep Learning Containers Custom Images」を参照してください。

  1. PyTorch DLC Docker イメージにパッケージを追加するとします。次の例に示すように、docker ディレクトリの下に Dockerfile を作成します。

    mkdir -p workspace/docker cat workspace/docker/Dockerfile ARG BASE_IMAGE FROM $BASE_IMAGE #Install any additional libraries RUN pip install transformers==4.28.1
  2. 次の build_and_push.sh スクリプトを使用して、カスタマイズした Docker イメージをビルドして公開します。

    # Download script build_and_push.sh to workspace/docker ls workspace/docker build_and_push.sh Dockerfile # Build and publish your docker image reponame = "torchserve" versiontag = "demo-0.1" ./build_and_push.sh {reponame} {versiontag} {baseimage} {region} {account}

SageMaker AI プレインストールのユースケース

次の例は、PyTorch DLC コンテナにパッケージをプリインストールする方法を示しています。requirements.txt ファイルはディレクトリ workspace/code の下にローカルに作成する必要があります。

mkdir -p workspace/code cat workspace/code/requirements.txt transformers==4.28.1

TorchServe モデルアーティファクトの作成

次の例では、事前トレーニング済みの MNIST モデルを使用します。ディレクトリ workspace/mnist を作成し、TorchServe カスタムサービスの手順に従って mnist_handler.py を実装し、model-config.yamlモデルパラメータを設定 (バッチサイズやワーカーなど) します。次に、TorchServe ツール torch-model-archiver を使用してモデルアーティファクトを構築し、Amazon S3 にアップロードします。

  1. model-config.yaml でモデルパラメータを設定します。

    ls -al workspace/mnist-dev mnist.py mnist_handler.py mnist_cnn.pt model-config.yaml # config the model cat workspace/mnist-dev/model-config.yaml minWorkers: 1 maxWorkers: 1 batchSize: 4 maxBatchDelay: 200 responseTimeout: 300
  2. torch-model-archiver を使用してモデルアーティファクトを構築します。

    torch-model-archiver --model-name mnist --version 1.0 --model-file workspace/mnist-dev/mnist.py --serialized-file workspace/mnist-dev/mnist_cnn.pt --handler workspace/mnist-dev/mnist_handler.py --config-file workspace/mnist-dev/model-config.yaml --archive-format tgz

    パッケージをプリインストールする場合は、code ディレクトリを tar.gz ファイルに含める必要があります。

    cd workspace torch-model-archiver --model-name mnist --version 1.0 --model-file mnist-dev/mnist.py --serialized-file mnist-dev/mnist_cnn.pt --handler mnist-dev/mnist_handler.py --config-file mnist-dev/model-config.yaml --archive-format no-archive cd mnist mv ../code . tar cvzf mnist.tar.gz .
  3. mnist.tar.gz を Amazon S3 にアップロードします。

    # upload mnist.tar.gz to S3 output_path = f"s3://{bucket_name}/{prefix}/models" aws s3 cp mnist.tar.gz {output_path}/mnist.tar.gz

単一モデルのエンドポイントを使用した TorchServe でのデプロイ

次の例は、Amazon SageMaker Python SDK を使用して、単一モデルのリアルタイム推論エンドポイントを作成し、そのモデルをエンドポイントにデプロイし、エンドポイントをテストする方法を示しています。

from sagemaker.model import Model from sagemaker.predictor import Predictor # create the single model endpoint and deploy it on SageMaker AI model = Model(model_data = f'{output_path}/mnist.tar.gz', image_uri = baseimage, role = role, predictor_cls = Predictor, name = "mnist", sagemaker_session = smsess) endpoint_name = 'torchserve-endpoint-' + time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime()) predictor = model.deploy(instance_type='ml.g4dn.xlarge', initial_instance_count=1, endpoint_name = endpoint_name, serializer=JSONSerializer(), deserializer=JSONDeserializer()) # test the endpoint import random import numpy as np dummy_data = {"inputs": np.random.rand(16, 1, 28, 28).tolist()} res = predictor.predict(dummy_data)

マルチモデルエンドポイントを使用した TorchServe でのデプロイ

マルチモデルエンドポイントは、1 つのエンドポイントの背後で多数のモデルをホスティングするためのスケーラブルで費用対効果の高いソリューションです。同じリソースのフリートとサービングコンテナを共有し、すべてのモデルをホストすることで、エンドポイントの使用率を向上させます。また、SageMaker AI はモデルのロードとアンロードを動的に管理し、トラフィックパターンに基づいてリソースをスケーリングするため、デプロイのオーバーヘッドも削減されます。マルチモデルエンドポイントは、処理能力の高速化を必要とする深層学習や生成系 AI モデルに特に役立ちます。

SageMaker AI マルチモデルエンドポイントで TorchServe を使用すると、SageMaker AI マルチモデルエンドポイントが提供するリソース共有と簡易モデル管理を活用しながら、使い慣れたサービングスタックを使用することで開発を高速化できます。

次の例は、Amazon SageMaker Python SDK を使用してマルチモデルエンドポイントを作成し、そのモデルをエンドポイントにデプロイし、エンドポイントをテストする方法を示しています。その他の詳細については、この「ノートブックサンプル」を参照してください。

from sagemaker.multidatamodel import MultiDataModel from sagemaker.model import Model from sagemaker.predictor import Predictor # create the single model endpoint and deploy it on SageMaker AI model = Model(model_data = f'{output_path}/mnist.tar.gz', image_uri = baseimage, role = role, sagemaker_session = smsess) endpoint_name = 'torchserve-endpoint-' + time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime()) mme = MultiDataModel( name = endpoint_name, model_data_prefix = output_path, model = model, sagemaker_session = smsess) mme.deploy( initial_instance_count = 1, instance_type = "ml.g4dn.xlarge", serializer=sagemaker.serializers.JSONSerializer(), deserializer=sagemaker.deserializers.JSONDeserializer()) # list models list(mme.list_models()) # create mnist v2 model artifacts cp mnist.tar.gz mnistv2.tar.gz # add mnistv2 mme.add_model(mnistv2.tar.gz) # list models list(mme.list_models()) predictor = Predictor(endpoint_name=mme.endpoint_name, sagemaker_session=smsess) # test the endpoint import random import numpy as np dummy_data = {"inputs": np.random.rand(16, 1, 28, 28).tolist()} res = predictor.predict(date=dummy_data, target_model="mnist.tar.gz")

メトリクス

TorchServe は、システムレベルとモデルレベルの両方のメトリクスをサポートします。環境変数 TS_METRICS_MODE を介して、ログ形式モードまたは Prometheus モードのいずれかでメトリクスを有効にできます。TorchServe セントラルメトリクス設定ファイル metrics.yaml を使用して、リクエスト数、レイテンシー、メモリ使用量、GPU 使用率など、追跡するメトリクスのタイプを指定できます。このファイルを参照することで、デプロイされたモデルのパフォーマンスと状態に関するインサイトが得られ、TorchServer サーバーの動作をリアルタイムで効果的にモニタリングできます。詳細については、「TorchServe メトリクスのドキュメント」を参照してください。

Amazon CloudWatch ログフィルターを介して StatsD 形式に似た TorchServe メトリクスログにアクセスできます。TorchServe メトリクスログの例を次に示します。

CPUUtilization.Percent:0.0|#Level:Host|#hostname:my_machine_name,timestamp:1682098185 DiskAvailable.Gigabytes:318.0416717529297|#Level:Host|#hostname:my_machine_name,timestamp:1682098185