빠른 배포를 위한 YOLO26 모델의 TorchScript 내보내기
PyTorch는 TorchScript를 더 이상 사용하지 않도록 지정했으며 관련 기능을 점차 제거하고 있습니다. 새로운 모바일 및 엣지 배포에는 지원되는 ExecuTorch 통합을 사용하세요. Ultralytics는 레거시 C++ 호환성을 위해 일반 TorchScript 내보내기를 유지합니다.
Python 없이 C++ 환경에 컴퓨터 비전 모델을 배포하려면 이식 가능한 직렬화 표현이 필요합니다. TorchScript는 레거시 LibTorch 애플리케이션에 이러한 호환성을 제공합니다.
Ultralytics YOLO26 모델을 TorchScript로 내보내 직렬화하면 플랫폼 간 호환성을 확보하고 배포를 간소화할 수 있습니다. 이 가이드에서는 YOLO26 모델을 TorchScript 형식으로 내보내 더 다양한 애플리케이션에서 사용하는 방법을 설명합니다.
TorchScript로 내보내야 하는 이유는 무엇인가요?#

PyTorch 제작자가 개발한 TorchScript는 다양한 플랫폼에서 PyTorch 모델을 최적화하고 배포하기 위한 도구입니다. YOLO26 모델을 TorchScript로 내보내면 연구 단계의 모델을 실제 애플리케이션에 적용하는 데 도움이 됩니다. PyTorch 프레임워크의 일부인 TorchScript는 Python을 지원하지 않는 환경에서도 PyTorch 모델을 사용할 수 있게 해 이러한 전환을 원활하게 합니다.
이 과정에는 트레이싱과 스크립팅이라는 두 가지 기법이 사용됩니다. 트레이싱은 모델 실행 중 연산을 기록하고, 스크립팅은 Python의 일부 기능을 사용해 모델을 정의할 수 있게 합니다. 이러한 기법을 통해 YOLO26과 같은 모델을 일반적인 Python 환경 외부에서도 실행할 수 있습니다.

TorchScript 모델은 연산자 융합이나 메모리 사용 개선과 같은 기법으로 최적화하여 효율적으로 실행할 수도 있습니다. TorchScript로 내보내면 다양한 하드웨어 플랫폼에서 모델 실행을 가속화할 수 있다는 점도 장점입니다. 이 과정에서는 PyTorch 모델을 독립형 프로덕션용 표현으로 변환하여 C++ 환경에 통합할 수 있습니다.
TorchScript 모델의 주요 기능#
PyTorch 생태계의 핵심 요소인 TorchScript는 딥러닝 모델을 최적화하고 배포하는 기능을 제공합니다.

TorchScript를 개발자에게 유용한 도구로 만들어 주는 주요 기능은 다음과 같습니다.
-
정적 그래프 실행: TorchScript는 PyTorch의 동적 그래프 실행과 달리 모델 연산을 정적 그래프로 표현합니다. 정적 그래프 실행에서는 실제 실행 전에 연산 그래프를 정의하고 한 번 컴파일하므로 추론 성능이 향상됩니다.
-
모델 직렬화: TorchScript를 사용하면 PyTorch 모델을 플랫폼에 종속되지 않는 형식으로 직렬화할 수 있습니다. 직렬화된 모델은 원본 Python 코드 없이도 로드할 수 있어 다양한 런타임 환경에 배포할 수 있습니다.
-
JIT 컴파일: TorchScript는 적시(JIT) 컴파일을 사용하여 PyTorch 모델을 최적화된 중간 표현으로 변환합니다. JIT는 모델의 연산 그래프를 컴파일하여 대상 디바이스에서 효율적으로 실행할 수 있게 합니다.
-
점진적 변환: TorchScript는 PyTorch 모델의 일부를 점진적으로 TorchScript로 변환할 수 있는 방식을 제공합니다. 복잡한 모델을 다루거나 코드의 특정 부분만 최적화하려는 경우 특히 유용합니다.
TorchScript의 배포 옵션#
YOLO26 모델을 TorchScript 형식으로 내보내는 코드를 살펴보기 전에, TorchScript 모델이 일반적으로 어디에 사용되는지 알아보겠습니다.
TorchScript는 머신러닝 모델에 다음과 같은 다양한 배포 옵션을 제공합니다.
-
C++ API: TorchScript의 가장 일반적인 사용 사례는 LibTorch C++ API입니다. 이 API를 사용하면 최적화된 TorchScript 모델을 C++ 애플리케이션에서 직접 로드하고 실행할 수 있습니다. Python이 적합하지 않거나 사용할 수 없는 프로덕션 환경에 이상적입니다. C++ API는 TorchScript 모델을 낮은 오버헤드로 효율적으로 실행하여 성능을 극대화합니다.
-
모바일 배포: 모바일 디바이스에서 낮은 지연 시간으로 오프라인 추론을 수행하고 데이터 개인정보 보호를 유지하려면 PyTorch의 TorchScript Mobile 대체 솔루션인 ExecuTorch를 사용하세요.
-
클라우드 배포: TorchScript 모델은 NVIDIA Triton Inference Server와 같은 솔루션을 사용해 클라우드 서버에 배포할 수 있습니다. 이 솔루션은 프로덕션 환경에서 확장 가능한 배포를 위해 모델 버전 관리, 배칭, 메트릭 모니터링 등의 기능을 제공합니다. TorchScript를 클라우드에 배포하면 API 또는 기타 웹 서비스를 통해 모델에 액세스할 수 있습니다.
지원 작업#
TorchScript 내보내기는 Ultralytics의 7개 작업을 모두 지원합니다. 의미론적 분할과 깊이 추정은 해당 헤드를 제공하는 유일한 제품군인 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 | 원시 출력(None, 기본값), 내장 NMS(True) 또는 NMS가 없는 head(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는 정적 그래프 실행과 적시(JIT) 컴파일을 지원하여 모델 성능을 최적화할 수 있습니다.
- 언어 간 통합: TorchScript 모델을 다른 프로그래밍 언어에 통합하여 유연성과 확장성을 높일 수 있습니다.
- 직렬화: 모델을 직렬화하면 플랫폼에 관계없이 모델을 로드하고 추론을 실행할 수 있습니다.
배포에 관한 자세한 내용은 C++ 배포 가이드를 참조하세요. 기기 내 모바일 배포의 경우, PyTorch는 이제 TorchScript가 아닌 자체적인 별도
torch.export()→.pte파이프라인을 사용하는 ExecuTorch를 권장합니다.YOLO26 모델을 내보내는 데 필요한 패키지를 설치하려면 다음 명령어를 사용하세요:
설치# Install the required package for YOLO26 pip install ultralytics자세한 안내는 Ultralytics Installation guide를 참조하세요. 설치 중 문제가 발생하면 Common Issues guide를 확인하세요.
YOLO26 모델을 TorchScript 형식으로 내보낸 후에는 다양한 플랫폼에 배포할 수 있습니다:
- C++ API: 오버헤드가 적고 효율성이 높은 프로덕션 환경에는 LibTorch를 사용하세요.
- 모바일 배포: 별도의
.pte내보내기 파이프라인을 사용하는 PyTorch 지원 대체 솔루션 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!