Amazon SageMakerエンドポイントへのYOLO26デプロイガイド
Amazon SageMaker Endpointsは、コンピュータービジョンモデル(Ultralytics YOLO26など)を本番環境の機械学習アプリケーションでホストする、マネージド型のスケーラブルな環境を提供します。モデルのデプロイを成功させるには、モデル側とAWS側の両方で、セットアップ、構成、デプロイの手順を理解する必要があります。
このガイドでは、YOLO26のPyTorchモデルをAmazon SageMakerエンドポイントにデプロイする手順を順を追って説明します。AWS環境の準備、モデルの適切な設定、AWS CloudFormationやAWS Cloud Development Kit(CDK)などのツールを使ったデプロイについて学びます。
Amazon SageMaker#
Amazon SageMakerはAmazon Web Services(AWS)が提供する機械学習サービスで、機械学習モデルの構築、トレーニング、デプロイのプロセスを簡素化します。機械学習ワークフローのさまざまな側面に対応する幅広いツールを提供しています。これには、モデルのチューニングを自動化する機能、大規模なモデルのトレーニングオプション、モデルを本番環境に簡単にデプロイする方法が含まれます。SageMakerは主要な機械学習フレームワークをサポートし、多様なプロジェクトに必要な柔軟性を提供します。また、データラベリング、ワークフロー管理、パフォーマンス分析の機能も備えています。
Amazon SageMakerエンドポイントへのYOLO26のデプロイ#
YOLO26をAmazon SageMakerにデプロイすると、マネージド環境でリアルタイム推論を実行し、オートスケーリングなどの機能を活用できます。以下のAWSアーキテクチャをご覧ください。
ステップ1:AWS環境をセットアップする#
まず、次の前提条件が整っていることを確認してください。
-
AWSアカウント: まだお持ちでない場合は、AWSアカウントを登録してください。
-
設定済みのIAMロール: Amazon SageMaker、AWS CloudFormation、Amazon S3に必要な権限を持つIAMロールが必要です。このロールには、これらのサービスへのアクセスを許可するポリシーを設定してください。
-
AWS CLI: まだインストールしていない場合は、AWS Command Line Interface(CLI)をダウンロードしてインストールし、アカウント情報を設定してください。インストール方法については、AWS CLIの手順をご覧ください。
-
AWS CDK: まだインストールしていない場合は、デプロイのスクリプト作成に使用するAWS Cloud Development Kit(CDK)をインストールしてください。インストール方法については、AWS CDKの手順をご覧ください。
-
十分なサービスクォータ: Amazon SageMakerで2つの別個のリソースに十分なクォータがあることを確認してください。1つはエンドポイントの使用に必要な
ml.m5.4xlarge、もう1つはノートブックインスタンスの使用に必要なml.m5.4xlargeです。どちらもクォータ値が最低1必要です。現在のクォータがこの要件を満たしていない場合は、それぞれの増加をリクエストしてください。クォータの増加は、AWS Service Quotasのドキュメントに記載された詳しい手順に従ってリクエストできます。
ステップ2: YOLO26 SageMakerリポジトリをクローンする#
次に、SageMakerへのYOLO26のデプロイに必要なリソースを含む、専用のAWSリポジトリをクローンします。GitHubでホストされているこのリポジトリには、必要なCDKスクリプトと設定ファイルが含まれています。
-
GitHubリポジトリをクローンする: ターミナルで次のコマンドを実行し、host-yolov8-on-sagemaker-endpointリポジトリをクローンします。
git clone https://github.com/aws-samples/host-yolov8-on-sagemaker-endpoint.git -
クローンしたディレクトリに移動する: 作業ディレクトリをクローンしたリポジトリに変更します。
cd host-yolov8-on-sagemaker-endpoint/yolov8-pytorch-cdk
ステップ3: CDK環境をセットアップする#
必要なコードが揃ったら、AWS CDKを使ったデプロイに向けて環境をセットアップします。
-
Python仮想環境を作成する: Python環境と依存関係を分離します。次を実行します。
python3 -m venv .venv -
仮想環境を有効化する:
source .venv/bin/activate -
依存関係をインストールする: プロジェクトに必要なPython依存関係をインストールします。
pip3 install -r requirements.txt -
AWS CDKライブラリをアップグレードする: AWS CDKライブラリが最新バージョンであることを確認します。
pip install --upgrade aws-cdk-lib
ステップ4: AWS CloudFormationスタックを作成する#
-
CDKアプリケーションを合成する: CDKコードからAWS CloudFormationテンプレートを生成します。
cdk synth -
CDKアプリケーションをブートストラップする: CDKデプロイに向けてAWS環境を準備します。
cdk bootstrap -
スタックをデプロイする: 必要なAWSリソースが作成され、モデルがデプロイされます。
cdk deploy
ステップ5: YOLOモデルをデプロイする#
AWS CloudFormationスタックの作成後、次のステップではYOLO26をデプロイします。
-
ノートブックインスタンスを開く: AWSコンソールでAmazon SageMakerサービスに移動します。ダッシュボードから「Notebook Instances」を選択し、CDKデプロイスクリプトで作成されたノートブックインスタンスを探します。ノートブックインスタンスを開いてJupyter環境にアクセスします。
-
inference.pyにアクセスして編集する: JupyterでSageMakerノートブックインスタンスを開いた後、inference.pyファイルを探します。以下に示すようにinference.pyのoutput_fn関数を編集し、構文エラーがないことを確認してスクリプトを保存します。
import json def output_fn(prediction_output, content_type): """Formats model outputs as JSON string, extracting attributes like boxes, masks, keypoints.""" print("Executing output_fn from inference.py ...") infer = {} for result in prediction_output: if result.boxes is not None: infer["boxes"] = result.boxes.numpy().data.tolist() if result.masks is not None: infer["masks"] = result.masks.numpy().data.tolist() if result.keypoints is not None: infer["keypoints"] = result.keypoints.numpy().data.tolist() if result.obb is not None: infer["obb"] = result.obb.numpy().data.tolist() if result.probs is not None: infer["probs"] = result.probs.numpy().data.tolist() return json.dumps(infer) -
1_DeployEndpoint.ipynbを使用してエンドポイントをデプロイします。Jupyter環境で、sm-notebookディレクトリにある1_DeployEndpoint.ipynbノートブックを開きます。ノートブック内の
model_nameに、yolo26n.ptなどのYOLO26チェックポイントを設定します(デフォルトはYOLOv8モデルです)。次にセルを実行すると、モデルのダウンロード、更新済み推論コードとのパッケージ化、Amazon S3バケットへのアップロードが行われます。このノートブックの手順に従って、YOLO26モデル用のSageMakerエンドポイントを作成してデプロイします。
ステップ6: デプロイをテストする#
YOLO26モデルをデプロイしたら、パフォーマンスと機能をテストすることが重要です。
-
テスト用ノートブックを開く: 同じJupyter環境で、sm-notebookディレクトリにある2_TestEndpoint.ipynbノートブックを探して開きます。
-
テスト用ノートブックを実行する: ノートブックの手順に従って、デプロイ済みのSageMakerエンドポイントをテストします。これには、エンドポイントへの画像送信と推論の実行が含まれます。次に、以下に示すように出力をプロットして、モデルのパフォーマンスと精度を可視化します。
- リソースをクリーンアップする: テスト用ノートブックでは、エンドポイントとホストされたモデルをクリーンアップする手順も確認できます。デプロイしたモデルをすぐに使用する予定がない場合は特に、コストとリソースを効率的に管理するうえで重要な手順です。
ステップ7: 監視と管理#
テスト後は、デプロイしたモデルを継続的に監視し、管理することが重要です。
-
Amazon CloudWatchで監視する: Amazon CloudWatchを使って、SageMakerエンドポイントのパフォーマンスと健全性を定期的に確認します。
-
エンドポイントを管理する: SageMakerコンソールを使用して、エンドポイントを継続的に管理します。これには、必要に応じたモデルのスケーリング、更新、再デプロイが含まれます。
これらの手順を完了すると、Amazon SageMaker EndpointsにYOLO26モデルをデプロイしてテストできます。同じワークフローを他のモデルのAWSへのデプロイにも適用できます。
概要#
このガイドでは、AWS CloudFormationとAWS Cloud Development Kit(CDK)を使用して、Amazon SageMaker EndpointsにYOLO26をデプロイする手順を順に説明しました。AWS Machine Learning Blogの投稿「Amazon SageMaker EndpointsでYOLOv8 PyTorchモデルをホストする」にあるAWSサンプルリポジトリのクローン作成、CDK環境のセットアップ、AWSサービスを使用したモデルのデプロイ、SageMakerでの性能テストを行います。
よくある質問#
Ultralytics YOLO26 モデルを Amazon SageMaker Endpoints にデプロイするには、次の手順に従ってください。
- AWS 環境のセットアップ: AWS アカウント、必要な権限を持つ IAM ロール、設定済みの AWS CLI があることを確認してください。まだインストールしていない場合は AWS CDK をインストールしてください(AWS CDK の手順を参照)。
- YOLO26 SageMaker リポジトリのクローン:
git clone https://github.com/aws-samples/host-yolov8-on-sagemaker-endpoint.git cd host-yolov8-on-sagemaker-endpoint/yolov8-pytorch-cdk - CDK 環境のセットアップ: Python 仮想環境を作成して有効化し、依存関係をインストールして、AWS CDK ライブラリをアップグレードします。
python3 -m venv .venv source .venv/bin/activate pip3 install -r requirements.txt pip install --upgrade aws-cdk-lib - AWS CDK を使用したデプロイ: CloudFormation スタックを合成してデプロイし、環境をブートストラップします。
cdk synth cdk bootstrap cdk deploy
YOLO26をAmazon SageMakerにデプロイするには、次の前提条件を満たしていることを確認してください。
- AWSアカウント:有効なAWSアカウント(AWSに登録)。
- IAM ロール: SageMaker、CloudFormation、Amazon S3 の権限を持つ IAM ロールが設定されていること。
- AWS CLI: AWS コマンドラインインターフェイスがインストールされ、設定されていること(AWS CLI のインストールガイド)。
- AWS CDK: AWS クラウド開発キットがインストールされていること(CDK のセットアップガイド)。
- サービスクォータ: エンドポイントとノートブックの両方で
ml.m5.4xlargeインスタンスを使用するために十分なクォータがあること(クォータの引き上げをリクエスト)。
Amazon SageMaker で Ultralytics YOLO26 を使用すると、いくつかのメリットがあります。
- スケーラビリティと管理: SageMaker は自動スケーリングなどの機能を備えたマネージド環境を提供し、リアルタイム推論のニーズに対応できます。
- AWSサービスとの統合:データストレージ用のS3、Infrastructure as Code用のCloudFormation、監視用のCloudWatchなど、他のAWSサービスと統合します。
- デプロイの容易さ: AWS CDK スクリプトを使用することでセットアップが簡素化され、デプロイプロセスも効率化されます。
- 性能:Amazon SageMakerのマネージドインフラストラクチャを使用して、大規模な推論ワークロードを実行します。
はい、Amazon SageMaker で YOLO26 の推論ロジックをカスタマイズできます。
-
inference.pyを変更:inference.pyファイル内のoutput_fn関数を見つけ、出力形式に合わせてカスタマイズします。import json def output_fn(prediction_output, content_type): """Formats model outputs as JSON string, extracting attributes like boxes, masks, keypoints.""" infer = {} for result in prediction_output: if result.boxes is not None: infer["boxes"] = result.boxes.numpy().data.tolist() # 必要に応じて、さらに処理ロジックを追加します return json.dumps(infer) -
更新したモデルをデプロイ: 変更を反映するため、用意されている Jupyter ノートブック(
1_DeployEndpoint.ipynb)を使用してモデルを再デプロイしてください。
変更したモデルのデプロイについては、詳しい手順を参照してください。
-
Amazon SageMaker にデプロイした YOLO26 モデルをテストするには、次の手順に従ってください。
- テスト用ノートブックを開く: SageMaker Jupyter 環境で
2_TestEndpoint.ipynbノートブックを見つけます。 - ノートブックを実行する: ノートブックの手順に従ってエンドポイントに画像を送信し、推論を実行して、結果を表示します。
- 結果の可視化:ノートブックのプロット用コードを使用して、テスト画像に予測されたバウンディングボックスを描画します。
包括的なテスト手順については、テストのセクションをご覧ください。
- テスト用ノートブックを開く: SageMaker Jupyter 環境で
コメント10
質問したり、結果を共有したり、ほかの人をサポートしたりできます。
UserI want to upload the YOLOv8 model I trained on my own dataset to Jupyter, and then compress it into a
model.tar.gzfile following the officialdeployendpointsteps. However, when I usetestendpoint, I encounter an error. If I rename my trained model toyolov8, the test succeeds, but it uses the original model from the official website instead of my custom one. How should I modifyinference.pyto ensure it loads my trained model?1
Glenn JocherUltralytics@lijoe123 to ensure your custom YOLOv8 model is used, modify the
inference.pyto load your model by specifying its path directly. Ensure the model name in your deployment matches your custom model's name. For detailed steps, refer to the Ultralytics documentation on Amazon SageMaker.
UserThank you for your answer. I had followed the
1_DeployEndpoint.ipynbto delpoy my own model. In the 1.4 Create the SageMaker PyTorchModel, I had set theenv={'TS_MAX_RESPONSE_SIZE':'20000000', 'MY_MODEL': 'my_own_model'}. And in theinference.py:def model_fn(model_dir): print("Executing model_fn from inference.py ...") env = os.environ model = YOLO(os.path.join(model_dir, env['MY_MODEL'])) return modelI think it will be use my own model directly. But it failed, and it occur this problem:
ModelError: An error occurred (ModelError) when calling the InvokeEndpoint operation: Received server error (0)from primary with message "Your invocation timed out while waiting for a response from container primary. Reviewthe latency metrics for each container in Amazon Cloudatch, resolve the issue, and try again.". See https://useast-1. console. aws. aazon. com/cloudwatch/home?region=us-east-1#logEventViewer: group=/aws/sagemaker Endpoints/yolov8-pytorch-2024-09-06-11-33-49-418696 in account 211125332801 for more information.Could you tell me how to modify the
inference.pyto load my own model. Thank you so much.
Glenn JocherUltralyticsTo ensure your custom YOLOv8 model is used, verify that the
model_fnininference.pycorrectly points to your model's path. Ensure theMY_MODELenvironment variable matches your model's filename. If issues persist, check CloudWatch logs for detailed error messages. For further guidance, refer to the Ultralytics documentation on Amazon SageMaker.
SJTUPanda
Thanks for your sharing, it's very clear and useful. My own deployment workflow on AWS has already built but the test result is not so satisfying. The performance of detection result of yolo11-xl on AWS is worse than on my own laptop. I not sure if there is some default quantization when it's deployed to the AWS(I did not modified much to host-yolov8-on-sagemaker-endpoint), or do you have some other ideas about which would bring this significant performance differences?
Glenn JocherUltralytics@SJTUPanda thank you for your feedback! The performance difference could stem from several factors like hardware disparities (AWS instance vs laptop GPU), inference settings, or environment configurations. First, verify that your SageMaker instance type matches your local hardware capabilities, and ensure identical inference parameters (e.g.,
imgsz,batch). Check our Amazon SageMaker deployment guide for optimization tips and consider profiling both environments withyolo valto isolate bottlenecks. Let us know if specific metrics differ! 🚀SJTUPanda
Thanks for your quick reply. The issue is fixed after I comment out resize related code. Although the model is trained with (640,640) and the input image size is (720,440), using the raw images directly as input is better than resized it. I am curious the input images would be auto-resized by the model just as in the training/testing part? And why resized by myself has so much impact on the results? If these part code should be update because yolo version updating?
image_height, image_width, _ = orig_image.shape model_height, model_width = 640, 640 x_ratio = image_width/model_width y_ratio = image_height/model_height # Resize the image as numpy array resized_image = cv2.resize(orig_image, (model_height, model_width)) # Conver the array into jpeg resized_jpeg = cv2.imencode('.jpg', resized_image)[1] # Serialize the jpg using base 64 payload = base64.b64encode(resized_jpeg).decode('utf-8')
Glenn JocherUltralyticsThank you for sharing your findings! YOLO models do automatically resize inputs to match their training dimensions while preserving aspect ratio with letterboxing. Manual resizing can distort aspect ratios or introduce artifacts, potentially degrading performance. We recommend using the model's native preprocessing by feeding full-size images directly, as this maintains proper scaling and aspect ratio handling. For implementation details, refer to our model deployment best practices regarding input consistency.
NikoXanthidis
Gostaria de saber se esses recursos são pagos.
Glenn JocherUltralyticsOlá! 👋 Os recursos mencionados para implementar o YOLOv8 no Amazon SageMaker não são pagos por si só. No entanto, o uso do Amazon SageMaker e outros serviços da AWS associados à implementação e execução do modelo podem incorrer em custos conforme o uso. A AWS oferece uma camada gratuita que você pode aproveitar para experimentar alguns serviços sem custo, mas é sempre bom verificar a página de preços do SageMaker para detalhes específicos. Se precisar de ajuda para estimar os custos ou tiver outras dúvidas, estou aqui para ajudar! 🚀