迅速なデプロイに向けたYOLO26モデルのTorchScriptエクスポート
PyTorchではTorchScriptが非推奨となり、その機能が段階的に削除されています。新たにモバイルやエッジにデプロイする場合は、サポート対象のExecuTorchインテグレーションを使用してください。Ultralyticsでは、従来のC++との互換性のため、通常のTorchScriptエクスポートを引き続き提供しています。
Pythonを使わずにC++環境でコンピュータービジョンモデルをデプロイするには、ポータブルなシリアル化形式が必要です。TorchScriptは、従来のLibTorchアプリケーションとの互換性を提供します。
TorchScriptにエクスポートして、Ultralytics YOLO26モデルをシリアライズし、クロスプラットフォーム互換性と効率的なデプロイを実現します。このガイドでは、YOLO26モデルをTorchScript形式にエクスポートする方法を紹介し、より幅広いアプリケーションで利用できるようにします。
TorchScriptにエクスポートする理由#

PyTorchの開発元が開発したTorchScriptは、さまざまなプラットフォームでPyTorchモデルを最適化してデプロイするためのツールです。YOLO26モデルをTorchScriptにエクスポートすると、研究から実用アプリケーションへの移行が容易になります。PyTorchフレームワークの一部であるTorchScriptは、Pythonに対応していない環境でもPyTorchモデルを利用できるようにし、この移行を円滑にします。
このプロセスでは、トレーシングとスクリプティングという2つの手法を使用します。トレーシングはモデルの実行中に演算を記録し、スクリプティングはPythonのサブセットを使用してモデルを定義できるようにします。これらの手法により、YOLO26などのモデルを通常のPython環境以外でも実行できます。

TorchScriptモデルは、演算子フュージョンやメモリ使用量の改善などの手法で最適化することもでき、効率的な実行が可能になります。TorchScriptにエクスポートするもう1つのメリットは、さまざまなハードウェアプラットフォームでモデルの実行を高速化できる可能性があることです。PyTorchモデルをスタンドアロンの本番環境対応形式に変換でき、C++環境に統合できます。
TorchScriptモデルの主な機能#
PyTorchエコシステムの重要な要素であるTorchScriptは、ディープラーニングモデルを最適化してデプロイするための機能を提供します。

TorchScriptが開発者にとって有用なツールとなる主な機能は、次のとおりです。
-
静的グラフ実行: TorchScriptは、PyTorchの動的グラフ実行とは異なり、モデルの計算を静的グラフで表現します。静的グラフ実行では、実際の実行前に計算グラフを定義して一度コンパイルするため、推論時のパフォーマンスが向上します。
-
モデルのシリアル化: TorchScriptを使うと、PyTorchモデルをプラットフォームに依存しない形式にシリアル化できます。シリアル化されたモデルは、元のPythonコードを必要とせずに読み込めるため、さまざまなランタイム環境にデプロイできます。
-
JITコンパイル: TorchScriptは、Just-In-Time (JIT)コンパイルを使用して、PyTorchモデルを最適化された中間表現に変換します。JITはモデルの計算グラフをコンパイルし、ターゲットデバイス上で効率的に実行できるようにします。
-
段階的な変換: TorchScriptでは、PyTorchモデルの一部を段階的にTorchScriptに変換できます。この柔軟な方法は、複雑なモデルを扱う場合や、コードの特定部分を最適化したい場合に特に有用です。
TorchScriptのデプロイオプション#
YOLO26モデルをTorchScript形式にエクスポートするコードを見る前に、TorchScriptモデルの一般的な使用場面を紹介します。
TorchScriptは、機械学習モデル向けに次のようなさまざまなデプロイオプションを提供します。
-
C++ API: TorchScriptの最も一般的なユースケースはLibTorch C++ APIです。これを使うと、最適化済みのTorchScriptモデルをC++アプリケーション内で直接読み込んで実行できます。Pythonが適さない、または利用できない本番環境に最適です。C++ APIはTorchScriptモデルを低オーバーヘッドかつ効率的に実行し、パフォーマンスを最大限に引き出します。
-
モバイルへのデプロイ: モバイルデバイスで低レイテンシのオフライン推論とデータプライバシーを実現するには、PyTorch Mobileに代わるTorchScriptの後継であるExecuTorchを使用してください。
-
クラウドデプロイ: TorchScriptモデルは、NVIDIA Triton Inference Serverなどのソリューションを使用して、クラウドベースのサーバーにデプロイできます。このソリューションは、モデルのバージョン管理、バッチ処理、メトリクスのモニタリングなどの機能を提供し、本番環境でのスケーラブルなデプロイを実現します。TorchScriptを使用したクラウドデプロイにより、APIやその他のWebサービス経由でモデルにアクセスできるようになります。
対応タスク#
TorchScriptエクスポートは、Ultralyticsの7つすべてのタスクをサポートします。セマンティックセグメンテーションと深度推定を利用できるのはYOLO26のみです。これらのヘッドを搭載しているのはYOLO26ファミリーだけです。
TorchScriptへのエクスポート: YOLO26モデルの変換#
YOLO26モデルをTorchScriptにエクスポートすると、Python以外の環境でも簡単に実行できます。たとえば、LibTorchを利用するC++アプリケーションで実行できます。
インストール#
必要なパッケージをインストールするには、次を実行します。
# Install the required package for YOLO26
pip install ultralyticsインストール手順の詳細とベストプラクティスについては、Ultralyticsのインストールガイドをご覧ください。YOLO26に必要なパッケージのインストールで問題が発生した場合は、解決策とヒントが記載されたよくある問題のガイドをご確認ください。
使用方法#
すべてのUltralytics YOLO26モデルは、追加設定なしでエクスポートできるように設計されているため、希望するデプロイワークフローに簡単に統合できます。アプリケーションに最適な設定を選ぶには、対応するエクスポート形式と設定オプションの一覧をご覧ください。
TorchScript形式は、エクスポート、予測、検証の各モードをサポートします。モデルをエクスポートした後、エクスポート済みモデルを読み込んで推論を実行するか、精度を検証してください。
from ultralytics import YOLO
# YOLO26モデルを読み込みます
model = YOLO("yolo26n.pt")
# モデルをTorchScript形式にエクスポート
model.export(format="torchscript") # 'yolo26n.torchscript'を作成from ultralytics import YOLO
# エクスポート済みのTorchScriptモデルを読み込む
model = YOLO("yolo26n.torchscript")
# 推論を実行
results = model("https://ultralytics.com/images/bus.jpg")from ultralytics import YOLO
# エクスポート済みのTorchScriptモデルを読み込む
model = YOLO("yolo26n.torchscript")
# COCO8データセットで精度を検証します
metrics = model.val(data="coco8.yaml")エクスポート引数#
| 引数 | 種類 | デフォルト | 説明 |
|---|---|---|---|
format | str | 'torchscript' | エクスポートしたモデルのターゲットフォーマットです。さまざまなデプロイ環境との互換性を定義します。 |
imgsz | intまたはtuple | 640 | モデル入力の画像サイズです。正方形画像の場合は整数、特定のサイズの場合はタプル(height, width)を指定できます。 |
dynamic | bool | False | 動的な入力サイズを使用できるようにし、さまざまな画像サイズを柔軟に扱えるようにします。 |
quantize | intまたはstr | None | 量子化の精度: 16 (FP16)には、device=0を指定したGPUエクスポートが必要です。32/未設定の場合はFP32です。非推奨のhalfフラグを置き換えます。 |
nms | bool、省略可 | None | raw出力(None、デフォルト)、組み込みNMS(True)、NMSなしのヘッド(False)から選択します。 |
batch | int | 1 | エクスポートモデルのバッチ推論サイズ、またはpredictモードでエクスポートモデルが同時に処理する画像の最大数を指定します。 |
device | str | None | エクスポートに使用するデバイスを指定します。GPU(device=0)、CPU(device=cpu)、Appleシリコン向けMPS(device=mps)から選択します。 |
エクスポートプロセスの詳細については、Ultralyticsのエクスポートに関するドキュメントページをご覧ください。
エクスポート済みYOLO26 TorchScriptモデルのデプロイ#
Ultralytics YOLO26モデルをTorchScript形式に正常にエクスポートできたら、モデルをデプロイできます。TorchScriptモデルを実行する際の最初の手順として推奨される方法は、前述の使用例のコードスニペットに示すYOLO("model.torchscript")メソッドを使用することです。TorchScriptモデルを他の環境にデプロイする詳しい手順については、次のリソースをご覧ください。
-
モバイルへのデプロイ方法を見る: 現在のPyTorchモバイルデプロイでは、ExecuTorch独自の
torch.export()→.pteパイプラインを使用してください。 -
サーバーサイドデプロイをマスターする: NVIDIA Triton Inference ServerのPyTorchバックエンドを使用してTorchScriptモデルを提供し、スケーラブルで効率的なモデルサービングを実現する方法をご紹介します。
-
C++へのデプロイを実装する: 「C++でTorchScriptモデルを読み込むチュートリアル」を確認し、TorchScriptモデルをC++アプリケーションに統合して、パフォーマンスと汎用性を高める方法をご覧ください。
概要#
このガイドでは、Ultralytics YOLO26モデルをTorchScript形式にエクスポートする方法を説明しました。手順に従うことで、YOLO26モデルのパフォーマンスを最適化し、さまざまなプラットフォームや環境に柔軟にデプロイできます。
使用方法の詳細については、TorchScriptの公式ドキュメントをご覧ください。
よくある質問#
Ultralytics YOLO26モデルをTorchScriptにエクスポートすると、柔軟なクロスプラットフォームデプロイが可能になります。PyTorchエコシステムの一部であるTorchScriptを使うと、モデルをシリアル化して、Pythonをサポートしない環境で実行できます。このため、C++環境でのモデルのデプロイに役立ちます。
YOLO26モデルをTorchScriptにエクスポートするには、次のコード例を使用できます。
使用方法from ultralytics import YOLO # YOLO26モデルを読み込みます model = YOLO("yolo26n.pt") # モデルをTorchScript形式にエクスポート model.export(format="torchscript") # 'yolo26n.torchscript'を作成 # エクスポート済みのTorchScriptモデルを読み込む torchscript_model = YOLO("yolo26n.torchscript") # 推論を実行 results = torchscript_model("https://ultralytics.com/images/bus.jpg")エクスポート手順の詳細については、エクスポートに関するUltralyticsドキュメントをご覧ください。
YOLO26モデルのデプロイにTorchScriptを使用すると、次のようなメリットがあります。
- ポータビリティ: エクスポート済みモデルは、Pythonを使わずにC++アプリケーションで実行できます。
- 最適化: TorchScriptは静的グラフ実行とJust-In-Time (JIT)コンパイルをサポートし、モデルのパフォーマンスを最適化できます。
- 言語間の統合: TorchScriptモデルは他のプログラミング言語に統合できるため、柔軟性と拡張性が高まります。
- シリアル化: モデルをシリアル化することで、プラットフォームに依存せずに読み込み、推論を実行できます。
デプロイの詳細については、C++デプロイガイドをご覧ください。モバイルデバイスへのデプロイについて、PyTorchは現在ExecuTorchを推奨しています。ExecuTorchはTorchScriptではなく、独自の
torch.export()→.pteパイプラインを使用します。YOLO26モデルのエクスポートに必要なパッケージをインストールするには、次のコマンドを使用します。
インストール# Install the required package for YOLO26 pip install ultralytics詳しい手順については、Ultralytics Installation guideをご覧ください。インストール中に問題が発生した場合は、Common Issues guideを参照してください。
YOLO26モデルをTorchScript形式にエクスポートした後、さまざまなプラットフォームにデプロイできます。
- C++ API: オーバーヘッドが少なく、高効率が求められる本番環境では、LibTorchを使用します。
- モバイルデプロイ: PyTorchがサポートする代替手段であり、独自の
.pteエクスポートパイプラインを備えたExecuTorchを使用します。 - クラウドデプロイ: スケーラブルなサーバーサイドデプロイには、NVIDIA Triton Inference Serverなどのサービスを使用してください。
コメント9
質問したり、結果を共有したり、ほかの人をサポートしたりできます。
amarnathreddy0201
Load the YOLOv8 model
model = YOLO("yolov8n.pt")
Export the model to TorchScript format
model.export(format="torchscript") # creates 'yolov8n.torchscript'
Load the exported TorchScript model
torchscript_model = YOLO("yolov8n.torchscript")
For loading "yolov8n.torchscript" here yolo is used. is it possible to load the model using pytorch and prediction/Segmentation.
Paula DerrengerUltralytics@amarnathreddy0201 yes, you can load and use the exported TorchScript model directly with PyTorch. After exporting your YOLOv8 model to TorchScript format, you can load it using
torch.jit.load('yolov8n.torchscript')and then perform inference as usual with PyTorch. For detailed instructions, you can refer to the TorchScript documentation.amarnathreddy0201
Model = torch.jit.load('yolov8n.torchscript') results = Model(image)
It will predict the boxes, classes
amarnathreddy0201(編集済み)
@pderrenger I written small application for person detection but it's not detecting properly nd bounding boxes is some where else.
import torch import cv2 import numpy as np
classes = [ "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush" ]
model = torch.jit.load("yolov8n.torchscript") image_ori = cv2.imread(r"C:\Users\amarn\OneDrive\Pictures\father mother.jpg") image = cv2.resize(image_ori, (640, 640)) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image_tensor = torch.from_numpy(image).float() image_tensor = image_tensor.permute(2, 0, 1) # Change from HWC to CHW format image_tensor = image_tensor / 255.0 # Normalize to [0, 1] image_tensor = image_tensor.unsqueeze(0)
with torch.no_grad(): results = model(image_tensor)
results = results[0] # Remove the batch dimension if there's only one image
boxes = results[:, :4]
print(len(boxes)) object_confidences = results[:, 4] # Objectness score class_confidences = results[:, 5:] # Class scoresconf_threshold = 0.5 # Example threshold; adjust as necessary predictions = [] for i in range(len(object_confidences)): if object_confidences[i] > conf_threshold: class_id = torch.argmax(class_confidences[i]).item() class_conf = class_confidences[i][class_id].item()
if class_conf > conf_threshold: box_np = boxes[i].cpu().numpy() if boxes[i].is_cuda else boxes[i].numpy() x, y, w, h = box_np x1 = int((x - w / 2) ) y1 = int((y - h / 2) ) x2 = int((x + w / 2) ) y2 = int((y + h / 2)) cv2.rectangle(image_ori, (int(x1),int( y1)), (int(x1+ w), int(y1 + h)), (0, 255, 0), 2)cv2.imshow('image', image_ori) cv2.waitKey(0)
classes is from yolo only
1
Paula DerrengerUltralyticsIt looks like there might be an issue with the bounding box coordinates. Ensure that the coordinates are correctly transformed from the model's output format to the image's coordinate system. Also, verify that the model is correctly loaded and that the input image is preprocessed as expected. If the issue persists, please try updating to the latest version of the Ultralytics package and check if the problem is reproducible. For more details on exporting and using TorchScript models, you can refer to the Ultralytics documentation.
clausMeko(編集済み)
@amarnathreddy0201 I could make the boxes work for my One-Item only use case. I guess the tensor structure was not really clear to you as it seemed to me you have profound knowledge. ty for heavy lifting :partying_face:
@glenn-jocher and @pderrenger if you care what use case I had and could not simply
from ultralytics import YOLO: I chain YOLO with other models and have conflicts with imports, especially numpy v1 vs v2. So i figured export all as torchscript and chain them.import torch import cv2 # Knwoledge: https://github.com/ultralytics/ultralytics/issues/5863 # Knwoledge: https://github.com/orgs/ultralytics/discussions/9002 def preprocess_image(image_ori) -> torch.Tensor: image = cv2.resize(image_ori, (640, 640)) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image_tensor = torch.from_numpy(image).float() image_tensor = image_tensor.permute(2, 0, 1) # Change from HWC to CHW format image_tensor = image_tensor / 255.0 # Normalize to [0, 1] image_tensor = image_tensor.unsqueeze(0) return image_tensor def main(): # Load the TorchScript model map_location = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') model = torch.jit.load('./best.torchscript', map_location=map_location) cv2_img = cv2.imread("../obj-det/datasets/test/images/00018_png.rf.d602082fdf686063a7d430aba6dfedde.jpg") image = preprocess_image(cv2_img) with torch.no_grad(): results: torch.Tensor = model(image.to(map_location)) results = results[0] # Remove the batch dimension if there's only one image boxes = results[:4, :] object_confidences = results[4, :] conf_threshold = 0.5 # Example threshold; adjust as necessary dominant_item = torch.argmax(object_confidences) if object_confidences[dominant_item] < conf_threshold: cv2.imshow('nothing found', cv2_img) cv2.waitKey(0) return box_np = boxes[:,dominant_item].cpu().numpy() if boxes[:,dominant_item].is_cuda else boxes[:,dominant_item].numpy() x, y, w, h = box_np x1 = int((x - w / 2)) y1 = int((y - h / 2)) x2 = int(x1 + w) y2 = int(y1 + h) cv2.rectangle(cv2_img, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.imshow('image', cv2_img) cv2.waitKey(0) if __name__ == '__main__': main()1
Glenn JocherUltralyticsThank you for sharing your use case and detailed implementation! Exporting models as TorchScript for chaining is indeed a smart approach, especially when managing dependency conflicts. If adjustments are needed for bounding boxes or results, ensure the coordinate transformations align with the input image dimensions. For additional guidance on TorchScript usage, feel free to reference Ultralytics TorchScript Docs. Let us know if you encounter further issues!
tryprncp
hi, I'm implementing yolov8 model in android gallery's search mechanism. the purpose of yolov8 model is to scan media files and return images that has a bounding box label that matches the search query. i can make it work with yolov5s.torchscript.ptl using org.pytorch:pytorch_android_lite:1.10.0 and org.pytorch:pytorch_android_torchvision_lite:1.10.0 but it wont work with yolov8s.torchscript. i really need help with this.
Glenn JocherUltralyticsHey there! 😊 It sounds like you've made great progress integrating YOLOv8 into your Android app's search mechanism! If you've successfully used YOLOv5 models but are facing issues with YOLOv8's TorchScript model, let's try to sort this out.
First, ensure you've exported the YOLOv8 model to TorchScript correctly using the latest YOLOv8 and PyTorch versions. Here's a quick snippet for exporting:
from ultralytics import YOLO # Load YOLOv8 model model = YOLO('yolov8s.pt') # Use the appropriate YOLOv8 variant # Export to TorchScript model.export(format='torchscript')This creates a file named
yolov8s.torchscript. Ensure that this file is what you're trying to load in your Android app.If you're still having trouble after confirming the export process, consider checking the PyTorch Android version compatibility. YOLOv8 may require a newer version of PyTorch Android than YOLOv5, so updating
org.pytorch:pytorch_android_liteandorg.pytorch:pytorch_android_torchvision_liteto the latest versions might help.Lastly, since YOLOv8 is more recent, make sure you're using the latest release of the Ultralytics YOLO library for any compatibility fixes or improvements.
If these steps don't resolve the issue, feel free to share any error messages or more specifics about the problem you're encountering. I'm here to help!