Ultralytics YOLO27: Join the waitlist.

YOLO26 Model Export to TorchScript for Quick Deployment

PyTorch is retiring TorchScript

PyTorch has deprecated TorchScript and is gradually removing its features. For new mobile and edge deployments, use the supported ExecuTorch integration. Ultralytics retains regular TorchScript export for legacy C++ compatibility.

Deploying computer vision models in C++ environments without Python requires a portable serialized representation. TorchScript provides that compatibility for legacy LibTorch applications.

Export to TorchScript to serialize your Ultralytics YOLO26 models for cross-platform compatibility and streamlined deployment. This guide shows how to export your YOLO26 models to the TorchScript format so you can use them across a wider range of applications.

Why should you export to TorchScript?#

TorchScript model serialization and deployment workflow overview

Developed by the creators of PyTorch, TorchScript is a tool for optimizing and deploying PyTorch models across a variety of platforms. Exporting YOLO26 models to TorchScript helps move them from research to real-world applications. TorchScript, part of the PyTorch framework, helps make this transition smoother by allowing PyTorch models to be used in environments that don't support Python.

The process involves two techniques: tracing and scripting. Tracing records operations during model execution, while scripting allows for the definition of models using a subset of Python. These techniques allow models like YOLO26 to run outside their usual Python environment.

TorchScript scripting vs tracing comparison

TorchScript models can also be optimized through techniques such as operator fusion and refinements in memory usage, ensuring efficient execution. Another advantage of exporting to TorchScript is its potential to accelerate model execution across various hardware platforms. It creates a standalone, production-ready representation of your PyTorch model that can be integrated into C++ environments.

Key Features of TorchScript Models#

TorchScript, a key part of the PyTorch ecosystem, provides features for optimizing and deploying deep learning models.

TorchScript key features overview

Here are the key features that make TorchScript a valuable tool for developers:

  • Static Graph Execution: TorchScript uses a static graph representation of the model's computation, which is different from PyTorch's dynamic graph execution. In static graph execution, the computational graph is defined and compiled once before the actual execution, resulting in improved performance during inference.

  • Model Serialization: TorchScript allows you to serialize PyTorch models into a platform-independent format. Serialized models can be loaded without requiring the original Python code, enabling deployment in different runtime environments.

  • JIT Compilation: TorchScript uses Just-In-Time (JIT) compilation to convert PyTorch models into an optimized intermediate representation. JIT compiles the model's computational graph, enabling efficient execution on target devices.

  • Gradual Conversion: TorchScript provides a gradual conversion approach, allowing you to incrementally convert parts of your PyTorch model into TorchScript. This flexibility is particularly useful when dealing with complex models or when you want to optimize specific portions of the code.

Deployment Options in TorchScript#

Before looking at the code for exporting YOLO26 models to the TorchScript format, here is where TorchScript models are typically used.

TorchScript offers various deployment options for machine learning models, such as:

  • C++ API: The most common use case for TorchScript is its LibTorch C++ API, which allows you to load and execute optimized TorchScript models directly within C++ applications. This is ideal for production environments where Python may not be suitable or available. The C++ API offers low-overhead and efficient execution of TorchScript models, maximizing performance potential.

  • Mobile Deployment: For low-latency, offline inference and data privacy on mobile devices, use ExecuTorch, PyTorch's replacement for TorchScript Mobile.

  • Cloud Deployment: TorchScript models can be deployed to cloud-based servers using solutions like NVIDIA Triton Inference Server. It provides features like model versioning, batching, and metrics monitoring for scalable deployment in production environments. Cloud deployment with TorchScript can make your models accessible via APIs or other web services.

Supported Tasks#

TorchScript export supports all seven Ultralytics tasks. Semantic segmentation and depth estimation are available only with YOLO26, the only family that ships those heads.

TaskYOLOv8YOLO11YOLO26
Detect✅✅✅
Segment✅✅✅
Semantic❌❌✅
Depth❌❌✅
Classify✅✅✅
Pose✅✅✅
OBB✅✅✅

Export to TorchScript: Converting Your YOLO26 Model#

Exporting YOLO26 models to TorchScript makes it easier to run them outside Python, for example in C++ applications built on LibTorch.

Installation#

To install the required package, run:

Installation
# Install the required package for YOLO26
pip install ultralytics

For detailed instructions and best practices related to the installation process, check our Ultralytics Installation guide. While installing the required packages for YOLO26, if you encounter any difficulties, consult our Common Issues guide for solutions and tips.

Usage#

All Ultralytics YOLO26 models are designed to support export out of the box, making it easy to integrate them into your preferred deployment workflow. You can view the full list of supported export formats and configuration options to choose the best setup for your application.

The TorchScript format supports the Export, Predict, and Validate modes. Export your model, then load the exported model to run inference or validate its accuracy.

Export
from ultralytics import YOLO

# Load a YOLO26 model
model = YOLO("yolo26n.pt")

# Export the model to TorchScript format
model.export(format="torchscript")  # creates 'yolo26n.torchscript'
Predict
from ultralytics import YOLO

# Load the exported TorchScript model
model = YOLO("yolo26n.torchscript")

# Run inference
results = model("https://ultralytics.com/images/bus.jpg")
Validate
from ultralytics import YOLO

# Load the exported TorchScript model
model = YOLO("yolo26n.torchscript")

# Validate accuracy on the COCO8 dataset
metrics = model.val(data="coco8.yaml")

Export Arguments#

ArgumentTypeDefaultDescription
formatstr'torchscript'Target format for the exported model, defining compatibility with various deployment environments.
imgszint or tuple640Desired image size for the model input. Can be an integer for square images or a tuple (height, width) for specific dimensions.
dynamicboolFalseAllows dynamic input sizes, enhancing flexibility in handling varying image dimensions.
quantizeint or strNoneQuantization precision: 16 (FP16) requires GPU export with device=0; 32/unset is FP32. Replaces the deprecated half flag.
nmsbool, optionalNoneSelect raw output (None, default), embedded NMS (True), or the NMS-free head (False).
batchint1Specifies export model batch inference size or the max number of images the exported model will process concurrently in predict mode.
devicestrNoneSpecifies the device for exporting: GPU (device=0), CPU (device=cpu), MPS for Apple silicon (device=mps).

For more details about the export process, visit the Ultralytics documentation page on exporting.

Deploying Exported YOLO26 TorchScript Models#

After successfully exporting your Ultralytics YOLO26 models to TorchScript format, you can now deploy them. The primary and recommended first step for running a TorchScript model is to use the YOLO("model.torchscript") method, as outlined in the previous usage code snippet. For in-depth instructions on deploying your TorchScript models in other settings, take a look at the following resources:

  • Explore Mobile Deployment: Use ExecuTorch's separate torch.export() → .pte pipeline for current PyTorch mobile deployment.

  • Master Server-Side Deployment: Learn how to serve TorchScript models with the PyTorch backend of NVIDIA Triton Inference Server for scalable, efficient model serving.

  • Implement C++ Deployment: Dive into the Tutorial on Loading a TorchScript Model in C++, facilitating the integration of your TorchScript models into C++ applications for enhanced performance and versatility.

Summary#

This guide covered exporting Ultralytics YOLO26 models to the TorchScript format. By following the provided instructions, you can optimize YOLO26 models for performance and gain the flexibility to deploy them across various platforms and environments.

For further details on usage, visit TorchScript's official documentation.

FAQ#

  • Exporting an Ultralytics YOLO26 model to TorchScript allows for flexible, cross-platform deployment. TorchScript, a part of the PyTorch ecosystem, facilitates the serialization of models, which can then be executed in environments that lack Python support. This makes it useful for deploying models in C++ environments.

  • To export a YOLO26 model to TorchScript, you can use the following example code:

    Usage
    from ultralytics import YOLO
    
    # Load a YOLO26 model
    model = YOLO("yolo26n.pt")
    
    # Export the model to TorchScript format
    model.export(format="torchscript")  # creates 'yolo26n.torchscript'
    
    # Load the exported TorchScript model
    torchscript_model = YOLO("yolo26n.torchscript")
    
    # Run inference
    results = torchscript_model("https://ultralytics.com/images/bus.jpg")

    For more details about the export process, refer to the Ultralytics documentation on exporting.

  • Using TorchScript for deploying YOLO26 models offers several advantages:

    • Portability: Exported models can run in C++ applications without Python.
    • Optimization: TorchScript supports static graph execution and Just-In-Time (JIT) compilation, which can optimize model performance.
    • Cross-Language Integration: TorchScript models can be integrated into other programming languages, enhancing flexibility and expandability.
    • Serialization: Models can be serialized, allowing for platform-independent loading and inference.

    For more insights into deployment, visit the C++ Deployment Guide. For on-device mobile deployment, PyTorch now recommends ExecuTorch, which uses its own separate torch.export() → .pte pipeline rather than TorchScript.

  • To install the required package for exporting YOLO26 models, use the following command:

    Installation
    # Install the required package for YOLO26
    pip install ultralytics

    For detailed instructions, visit the Ultralytics Installation guide. If any issues arise during installation, consult the Common Issues guide.

  • After exporting YOLO26 models to the TorchScript format, you can deploy them across a variety of platforms:

    • C++ API: Use LibTorch for low-overhead, highly efficient production environments.
    • Mobile Deployment: Use ExecuTorch, PyTorch's supported replacement with a separate .pte export pipeline.
    • Cloud Deployment: Use services like NVIDIA Triton Inference Server for scalable server-side deployment.

Comments9

Ask a question, share your results, or help someone else.

  1. amarnathreddy0201amarnathreddy0201GitHub

    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.

    1. Paula DerrengerPaula 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.

    2. amarnathreddy0201amarnathreddy0201GitHub(edited)

      @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 scores

      conf_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
    3. Paula DerrengerPaula DerrengerUltralytics

      It 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.

    4. clausMekoclausMekoGitHub(edited)

      @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
    5. Glenn JocherGlenn JocherUltralytics

      Thank 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!

  2. tryprncptryprncpGitHub

    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.

    1. Glenn JocherGlenn JocherUltralytics

      Hey 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_lite and org.pytorch:pytorch_android_torchvision_lite to 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!