Bắt đầu

Export model YOLO26 sang TorchScript để triển khai nhanh chóng

PyTorch sẽ ngừng hỗ trợ TorchScript

PyTorch đã deprecate TorchScript và đang dần loại bỏ các tính năng của TorchScript. Đối với các đợt triển khai mới trên thiết bị di động và thiết bị biên, hãy sử dụng tích hợp ExecuTorch được hỗ trợ. Ultralytics vẫn duy trì tính năng export TorchScript thông thường để đảm bảo khả năng tương thích với mã C++ cũ.

Việc triển khai model thị giác máy tính trong môi trường C++ không có Python đòi hỏi một dạng biểu diễn được tuần tự hóa và có tính di động. TorchScript cung cấp khả năng tương thích đó cho các ứng dụng LibTorch cũ.

Xuất sang TorchScript để tuần tự hóa model Ultralytics YOLO26, tăng khả năng tương thích đa nền tảng và đơn giản hóa triển khai. Hướng dẫn này chỉ cách xuất model YOLO26 sang định dạng TorchScript để bạn có thể sử dụng model trong nhiều ứng dụng hơn.

Tại sao bạn nên export sang TorchScript?#

Tổng quan quy trình tuần tự hóa và triển khai model TorchScript

Được phát triển bởi những người tạo ra PyTorch, TorchScript là công cụ tối ưu hóa và triển khai model PyTorch trên nhiều nền tảng. Xuất model YOLO26 sang TorchScript giúp đưa model từ nghiên cứu vào ứng dụng thực tế. TorchScript, một phần của framework PyTorch, giúp quá trình chuyển đổi này diễn ra thuận lợi hơn bằng cách cho phép sử dụng model PyTorch trong môi trường không hỗ trợ Python.

Quy trình này gồm hai kỹ thuật: truy vết và viết script. Truy vết ghi lại các phép toán trong quá trình thực thi model, còn viết script cho phép định nghĩa model bằng một tập con của Python. Các kỹ thuật này cho phép model như YOLO26 chạy bên ngoài môi trường Python thông thường.

So sánh scripting và tracing trong TorchScript

Model TorchScript cũng có thể được tối ưu hóa bằng các kỹ thuật như hợp nhất toán tử và tinh chỉnh mức sử dụng bộ nhớ để đảm bảo thực thi hiệu quả. Một lợi thế khác của việc export sang TorchScript là khả năng tăng tốc thực thi model trên nhiều nền tảng phần cứng. TorchScript tạo ra dạng biểu diễn độc lập, sẵn sàng cho production của model PyTorch mà bạn có thể tích hợp vào môi trường C++.

Các tính năng chính của model TorchScript#

TorchScript, thành phần cốt lõi của hệ sinh thái PyTorch, cung cấp các tính năng để tối ưu hóa và triển khai model học sâu.

Tổng quan các tính năng chính của TorchScript

Dưới đây là những tính năng chính giúp TorchScript trở thành công cụ hữu ích cho developer:

  • Thực thi đồ thị tĩnh: TorchScript sử dụng biểu diễn đồ thị tĩnh cho phép tính của model, khác với cơ chế thực thi đồ thị động của PyTorch. Với thực thi đồ thị tĩnh, đồ thị tính toán được xác định và biên dịch một lần trước khi thực thi thực tế, giúp cải thiện hiệu năng trong quá trình inference.

  • Tuần tự hóa model: TorchScript cho phép bạn tuần tự hóa model PyTorch sang định dạng độc lập với nền tảng. Có thể tải model đã tuần tự hóa mà không cần mã Python ban đầu, nhờ đó cho phép triển khai model trong các môi trường runtime khác nhau.

  • Biên dịch JIT: TorchScript sử dụng biên dịch Just-In-Time (JIT) để chuyển đổi model PyTorch thành dạng biểu diễn trung gian đã tối ưu hóa. JIT biên dịch đồ thị tính toán của model, cho phép thực thi hiệu quả trên thiết bị mục tiêu.

  • Chuyển đổi từng bước: TorchScript cung cấp phương pháp chuyển đổi từng bước, cho phép bạn chuyển đổi dần từng phần của model PyTorch sang TorchScript. Tính linh hoạt này đặc biệt hữu ích khi xử lý model phức tạp hoặc khi bạn muốn tối ưu hóa một số phần cụ thể của mã.

Các tùy chọn triển khai trong TorchScript#

Trước khi xem mã xuất model YOLO26 sang định dạng TorchScript, dưới đây là các trường hợp sử dụng phổ biến của model TorchScript.

TorchScript cung cấp nhiều tùy chọn triển khai model machine learning, chẳng hạn như:

  • C++ API: Trường hợp sử dụng TorchScript phổ biến nhất là LibTorch C++ API, cho phép bạn tải và thực thi trực tiếp model TorchScript đã tối ưu hóa trong ứng dụng C++. Đây là lựa chọn lý tưởng cho môi trường production, nơi Python có thể không phù hợp hoặc không khả dụng. C++ API cho phép thực thi model TorchScript hiệu quả với overhead thấp, giúp tối đa hóa tiềm năng hiệu năng.

  • Triển khai trên thiết bị di động: Để có inference độ trễ thấp, hoạt động offline và bảo vệ quyền riêng tư dữ liệu trên thiết bị di động, hãy sử dụng ExecuTorch, giải pháp thay thế TorchScript Mobile của PyTorch.

  • Triển khai trên đám mây: Có thể triển khai các model TorchScript lên máy chủ đám mây bằng các giải pháp như NVIDIA Triton Inference Server. Giải pháp này cung cấp các tính năng như quản lý phiên bản model, xử lý theo lô và giám sát chỉ số để triển khai có khả năng mở rộng trong môi trường production. Triển khai TorchScript trên đám mây giúp các model của bạn có thể được truy cập thông qua API hoặc các dịch vụ web khác.

Các tác vụ được hỗ trợ#

Export TorchScript hỗ trợ cả bảy tác vụ của Ultralytics. Phân đoạn ngữ nghĩa và ước lượng độ sâu chỉ khả dụng với YOLO26, dòng model duy nhất có các head này.

Tác vụYOLOv8YOLO11YOLO26
Phát hiện✅✅✅
Phân đoạn✅✅✅
Ngữ nghĩa❌❌✅
Độ sâu❌❌✅
Phân loại✅✅✅
Tư thế✅✅✅
OBB✅✅✅

Export sang TorchScript: Chuyển đổi model YOLO26#

Xuất model YOLO26 sang TorchScript giúp chạy model bên ngoài Python dễ dàng hơn, chẳng hạn trong các ứng dụng C++ được xây dựng trên LibTorch.

Cài đặt#

Để cài đặt package cần thiết, hãy chạy:

Cài đặt
# Install the required package for YOLO26
pip install ultralytics

Để biết hướng dẫn chi tiết và các phương pháp tốt nhất về quy trình cài đặt, hãy xem hướng dẫn cài đặt Ultralytics. Nếu gặp khó khăn khi cài đặt các package cần thiết cho YOLO26, hãy tham khảo hướng dẫn khắc phục sự cố thường gặp để tìm giải pháp và mẹo hữu ích.

Cách sử dụng#

Tất cả model Ultralytics YOLO26 đều được thiết kế để hỗ trợ xuất ngay từ đầu, giúp bạn dễ dàng tích hợp chúng vào quy trình triển khai mong muốn. Bạn có thể xem danh sách đầy đủ các định dạng xuất được hỗ trợ và tùy chọn cấu hình để chọn thiết lập phù hợp nhất cho ứng dụng.

Định dạng TorchScript hỗ trợ các chế độ Export, Predict và Validate. Hãy export model, sau đó tải model đã export để chạy inference hoặc xác thực độ chính xác.

Export
from ultralytics import YOLO

# Nạp model YOLO26
model = YOLO("yolo26n.pt")

# Export model sang định dạng TorchScript
model.export(format="torchscript")  # tạo 'yolo26n.torchscript'
Dự đoán
from ultralytics import YOLO

# Tải model TorchScript đã export
model = YOLO("yolo26n.torchscript")

# Chạy suy luận
results = model("https://ultralytics.com/images/bus.jpg")
Xác thực
from ultralytics import YOLO

# Tải model TorchScript đã export
model = YOLO("yolo26n.torchscript")

# # Đánh giá độ chính xác trên bộ dữ liệu COCO8
metrics = model.val(data="coco8.yaml")

Các tham số xuất model#

Đối sốKiểuMặc địnhMô tả
formatstr'torchscript'Định dạng đích của model đã xuất, xác định khả năng tương thích với nhiều môi trường triển khai.
imgszint hoặc tuple640Kích thước ảnh mong muốn cho đầu vào model. Có thể là số nguyên cho ảnh vuông hoặc tuple (height, width) để chỉ định kích thước cụ thể.
dynamicboolFalseCho phép kích thước đầu vào động, tăng tính linh hoạt khi xử lý ảnh có kích thước khác nhau.
quantizeint hoặc strNoneĐộ chính xác lượng tử hóa: 16 (FP16) yêu cầu export bằng GPU với device=0; 32/không thiết lập sẽ dùng FP32. Thay thế flag half đã bị deprecated.
nmsbool, không bắt buộcNoneChọn đầu ra thô (None, mặc định), NMS nhúng (True) hoặc head không có NMS (False).
batchint1Chỉ định kích thước batch suy luận của model khi xuất hoặc số lượng ảnh tối đa mà model đã xuất xử lý đồng thời ở chế độ predict.
devicestrNoneChỉ định thiết bị dùng để xuất: GPU (device=0), CPU (device=cpu), MPS cho Apple silicon (device=mps).

Để biết thêm chi tiết về quy trình xuất, hãy truy cập trang tài liệu Ultralytics về xuất model.

Triển khai model YOLO26 TorchScript đã export#

Sau khi export thành công các model Ultralytics YOLO26 sang định dạng TorchScript, bạn có thể triển khai chúng. Bước đầu tiên chính và được khuyến nghị để chạy model TorchScript là sử dụng phương thức YOLO("model.torchscript"), như minh họa trong đoạn mã sử dụng ở phần trước. Để xem hướng dẫn chi tiết về cách triển khai model TorchScript trong các môi trường khác, hãy tham khảo các tài nguyên sau:

  • Tìm hiểu về triển khai trên thiết bị di động: Sử dụng pipeline torch.export() → .pte riêng biệt của ExecuTorch để triển khai PyTorch trên thiết bị di động theo phương thức hiện hành.

  • Làm chủ triển khai phía máy chủ: Tìm hiểu cách phục vụ các model TorchScript bằng backend PyTorch của NVIDIA Triton Inference Server để phục vụ model hiệu quả và có khả năng mở rộng.

  • Triển khai C++: Tìm hiểu sâu về hướng dẫn tải model TorchScript trong C++, hỗ trợ tích hợp model TorchScript vào ứng dụng C++ để tăng hiệu năng và tính linh hoạt.

Tóm tắt#

Hướng dẫn này đã trình bày cách xuất model Ultralytics YOLO26 sang định dạng TorchScript. Bằng cách làm theo hướng dẫn, bạn có thể tối ưu hóa hiệu năng của model YOLO26 và linh hoạt triển khai model trên nhiều nền tảng và môi trường.

Để biết thêm chi tiết về cách sử dụng, hãy truy cập tài liệu chính thức của TorchScript.

Câu hỏi thường gặp#

  • Export model Ultralytics YOLO26 sang TorchScript cho phép triển khai linh hoạt trên nhiều nền tảng. TorchScript, một phần của hệ sinh thái PyTorch, hỗ trợ tuần tự hóa model để model có thể thực thi trong những môi trường không hỗ trợ Python. Điều này giúp TorchScript hữu ích khi triển khai model trong môi trường C++.

  • Để export model YOLO26 sang TorchScript, bạn có thể sử dụng mã ví dụ sau:

    Cách sử dụng
    from ultralytics import YOLO
    
    # Nạp model YOLO26
    model = YOLO("yolo26n.pt")
    
    # Export model sang định dạng TorchScript
    model.export(format="torchscript")  # tạo 'yolo26n.torchscript'
    
    # Tải model TorchScript đã export
    torchscript_model = YOLO("yolo26n.torchscript")
    
    # Chạy suy luận
    results = torchscript_model("https://ultralytics.com/images/bus.jpg")

    Để biết thêm chi tiết về quy trình export, hãy tham khảo tài liệu Ultralytics về export.

  • Sử dụng TorchScript để triển khai model YOLO26 mang lại một số ưu điểm:

    • Tính di động: Model đã export có thể chạy trong ứng dụng C++ mà không cần Python.
    • Tối ưu hóa: TorchScript hỗ trợ thực thi đồ thị tĩnh và biên dịch Just-In-Time (JIT), giúp tối ưu hóa hiệu năng model.
    • Tích hợp đa ngôn ngữ: Có thể tích hợp model TorchScript vào các ngôn ngữ lập trình khác, giúp tăng tính linh hoạt và khả năng mở rộng.
    • Tuần tự hóa: Có thể tuần tự hóa model, cho phép tải và chạy inference độc lập với nền tảng.

    Để tìm hiểu thêm về triển khai, hãy xem Hướng dẫn triển khai C++. Đối với triển khai trên thiết bị di động, PyTorch hiện khuyến nghị ExecuTorch, sử dụng pipeline torch.export() → .pte riêng thay vì TorchScript.

  • Để cài đặt package cần thiết cho việc export model YOLO26, hãy sử dụng lệnh sau:

    Cài đặt
    # Install the required package for YOLO26
    pip install ultralytics

    Để xem hướng dẫn chi tiết, hãy truy cập Hướng dẫn cài đặt Ultralytics. Nếu gặp sự cố trong quá trình cài đặt, hãy tham khảo Hướng dẫn xử lý sự cố thường gặp.

  • Sau khi export model YOLO26 sang định dạng TorchScript, bạn có thể triển khai chúng trên nhiều nền tảng:

    • API C++: Sử dụng LibTorch cho môi trường production yêu cầu overhead thấp và hiệu suất cao.
    • Triển khai trên thiết bị di động: Sử dụng ExecuTorch, giải pháp thay thế được PyTorch hỗ trợ với pipeline export .pte riêng.
    • Triển khai trên đám mây: Sử dụng các dịch vụ như NVIDIA Triton Inference Server để triển khai phía máy chủ có khả năng mở rộng.

Bình luận9

Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.

  1. amarnathreddy0201GitHub

    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 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. amarnathreddy0201GitHub(đã chỉnh sửa)

      @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 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. clausMekoGitHub(đã chỉnh sửa)

      @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 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. tryprncpGitHub

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