Ultralytics YOLO27: Tham gia danh sách chờ.
Bắt đầu

Xuất model YOLO26 sang ONNX

Inference ONNX trên CPU nhanh hơn ~43%: YOLO26n so với YOLO11n
  • YOLO26n chạy inference ONNX trên CPU nhanh hơn đến 43% so với YOLO11n (CPU Intel Xeon @ 2.00 GHz). Xem trang model YOLO26 để biết so sánh đầy đủ.

Thông thường, khi triển khai model thị giác máy tính, bạn sẽ cần một định dạng model vừa linh hoạt vừa tương thích với nhiều nền tảng.

Việc xuất model Ultralytics YOLO26 sang định dạng ONNX giúp đơn giản hóa quá trình triển khai trên nhiều runtime và nền tảng phần cứng. Hướng dẫn này trình bày cách chuyển đổi model YOLO26 sang ONNX và chạy model trong các ứng dụng thực tế.



Xem: Kiểm thử inference ONNX: Ultralytics YOLO26 so với Ultralytics YOLO11 | YOLO26 inference nhanh hơn khoảng 43% 🚀

ONNX và ONNX Runtime#

ONNX, tên viết tắt của Trao đổi mạng nơ-ron mở, là dự án cộng đồng do Facebook và Microsoft phát triển ban đầu. Quá trình phát triển ONNX hiện nay là nỗ lực hợp tác với sự hỗ trợ của nhiều tổ chức như IBM, Amazon (thông qua AWS) và Google. Dự án hướng đến tạo ra định dạng tệp mở để biểu diễn model machine learning, cho phép sử dụng model trên nhiều framework AI và phần cứng khác nhau.

Có thể dùng model ONNX để chuyển đổi giữa các framework. Ví dụ, model deep learning được huấn luyện bằng PyTorch có thể xuất sang định dạng ONNX rồi nhập vào TensorFlow.

ONNX model portability across deep learning frameworks

Ngoài ra, có thể sử dụng model ONNX với ONNX Runtime. ONNX Runtime là một bộ tăng tốc đa nền tảng linh hoạt dành cho model machine learning, tương thích với các framework như PyTorch, TensorFlow, scikit-learn, v.v.

ONNX Runtime tối ưu việc thực thi model ONNX bằng cách tận dụng các khả năng đặc thù của phần cứng. Tối ưu hóa này cho phép model chạy hiệu quả với hiệu năng cao trên nhiều nền tảng phần cứng, bao gồm CPU, GPU và bộ tăng tốc chuyên dụng.

ONNX Runtime cross-platform inference acceleration

Dù được sử dụng độc lập hay kết hợp với ONNX Runtime, ONNX đều cung cấp giải pháp linh hoạt cho việc triển khai model machine learning và khả năng tương thích.

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

Khả năng xử lý nhiều định dạng của ONNX có thể được quy về các tính năng chính sau:

  • Biểu diễn model phổ quát: ONNX định nghĩa một tập hợp toán tử chung (như phép tích chập, layer, v.v.) và một định dạng dữ liệu tiêu chuẩn. Khi chuyển model sang định dạng ONNX, kiến trúc và trọng số của model được chuyển đổi sang cách biểu diễn chung này. Tính đồng nhất đó đảm bảo mọi framework hỗ trợ ONNX đều có thể hiểu model.

  • Quản lý phiên bản và tương thích ngược: ONNX duy trì hệ thống quản lý phiên bản cho các toán tử. Nhờ đó, model được tạo bằng phiên bản cũ vẫn có thể sử dụng ngay cả khi tiêu chuẩn phát triển. Tương thích ngược là tính năng thiết yếu giúp model không nhanh chóng trở nên lỗi thời.

  • Biểu diễn model dựa trên đồ thị: ONNX biểu diễn model dưới dạng đồ thị tính toán. Cấu trúc dựa trên đồ thị này là cách biểu diễn model machine learning phổ quát, trong đó các nút biểu thị thao tác hoặc phép tính, còn các cạnh biểu thị tensor luân chuyển giữa chúng. Định dạng này dễ dàng thích ứng với nhiều framework cũng biểu diễn model dưới dạng đồ thị.

  • Công cụ và hệ sinh thái: ONNX có hệ sinh thái công cụ phong phú hỗ trợ chuyển đổi, trực quan hóa và tối ưu model. Những công cụ này giúp nhà phát triển dễ dàng làm việc với model ONNX và chuyển đổi model giữa các framework khác nhau.

Các ứng dụng phổ biến của ONNX#

Model ONNX thường được sử dụng trong các trường hợp sau.

Triển khai trên CPU#

Model ONNX thường được triển khai trên CPU nhờ khả năng tương thích với ONNX Runtime. Runtime này được tối ưu hóa để thực thi trên CPU. Runtime giúp cải thiện đáng kể tốc độ inference và khả thi hóa việc triển khai CPU theo thời gian thực.

Các tùy chọn triển khai được hỗ trợ#

Mặc dù model ONNX thường được sử dụng trên CPU, chúng cũng có thể được triển khai trên các nền tảng sau:

  • Tăng tốc GPU: ONNX hỗ trợ đầy đủ tăng tốc GPU trên GPU NVIDIA thông qua CUDA và trên GPU AMD thông qua ROCm và MIGraphX.

  • Thiết bị edge và di động: ONNX cũng hỗ trợ thiết bị edge và di động, phù hợp với các trường hợp suy luận ngay trên thiết bị và theo thời gian thực. ONNX nhẹ, tương thích với phần cứng edge và là nền tảng cho các định dạng NPU của nhà cung cấp như Huawei Ascend, Qualcomm QNN dành cho thiết bị Snapdragon và RKNN dành cho NPU Rockchip.

  • Trình duyệt web: ONNX có thể chạy trực tiếp trong trình duyệt web, hỗ trợ các ứng dụng AI tương tác và linh hoạt trên nền web.

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

Xuất ONNX hỗ trợ cả bảy tác vụ của Ultralytics. Phân đoạn ngữ nghĩa và ước tính độ sâu chỉ có trên YOLO26, dòng model duy nhất được phát hành kèm 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✅✅✅

Xuất model YOLO26 sang ONNX#

Bạn có thể mở rộng khả năng tương thích của model và tính linh hoạt khi triển khai bằng cách chuyển đổi model YOLO26 sang định dạng ONNX. Ultralytics YOLO26 cung cấp quy trình xuất đơn giản để chạy model trên nhiều nền tảng khác nhau.

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

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

Cách sử dụng#

Định dạng ONNX hỗ trợ các chế độ Xuất, Dự đoán và Xác thực. Hãy xuất model, sau đó tải model đã xuất để chạy suy luận hoặc xác thực độ chính xác.

Export
from ultralytics import YOLO

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

# # Xuất model sang định dạng ONNX
model.export(format="onnx")  # tạo 'yolo26n.onnx'

# Xuất model ONNX lượng tử hóa INT8 với dữ liệu hiệu chuẩn
model.export(format="onnx", quantize=8, data="coco8.yaml")  # tạo 'yolo26n_int8.onnx'
Dự đoán
from ultralytics import YOLO

# Nạp model ONNX đã xuất
model = YOLO("yolo26n.onnx")

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

# Nạp model ONNX đã xuất
model = YOLO("yolo26n.onnx")

# # Đá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#

Khi xuất model YOLO26 sang định dạng ONNX, bạn có thể tùy chỉnh quy trình bằng nhiều đối số để tối ưu hóa theo nhu cầu triển khai cụ thể:

Đối sốKiểuMặc địnhMô tả
formatstr'onnx'Đị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ể.
quantizeint hoặc strNoneĐộ chính xác lượng tử hóa: 16 (FP16) hoặc 8 (lượng tử hóa tĩnh INT8 bằng ONNX Runtime với ảnh hiệu chuẩn từ data, tạo ra model _int8.onnx); 32/không đặt là FP32. Checkpoint được huấn luyện với quantize=8 luôn xuất INT8 dưới dạng các node Q/DQ theo các phạm vi mà checkpoint lưu giữ, không cần hiệu chuẩn và dùng tên .onnx thông thường. Thay thế các flag half/int8 đã lỗi thời.
datastrNoneYAML dataset dùng để hiệu chuẩn INT8; với phân loại, thay vào đó hãy dùng thư mục dataset hoặc tên dataset tích hợp sẵn. Nếu không chỉ định quantize=8, Ultralytics sẽ chọn dataset hiệu chuẩn mặc định cho tác vụ của model; checkpoint được huấn luyện với quantize=8 thì không cần dataset.
fractionfloat, int hoặc list1.0Tập con hiệu chuẩn dưới dạng tỷ lệ, số lượng ảnh hoặc tỷ lệ/số lượng [train, val, test]. Danh sách gồm hai mục giữ test ở dạng đầy đủ, còn 0 sẽ bỏ qua mục này.
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.
simplifyboolTrueĐơn giản hóa đồ thị model bằng onnxslim, có khả năng cải thiện hiệu năng và khả năng tương thích.
opsetintNoneChỉ định phiên bản ONNX opset để đảm bảo tương thích với nhiều parser và runtime ONNX. Nếu không được thiết lập, phiên bản opset 18 sẽ được sử dụng (thấp hơn trên PyTorch < 2.4), tối đa bằng phiên bản onnx đã cài đặt.
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.

Lượng tử hóa INT8#

Đối với các checkpoint không được huấn luyện bằng huấn luyện có nhận biết lượng tử hóa, quantize=8 áp dụng lượng tử hóa tĩnh của ONNX Runtime chỉ cho các node Conv, Gemm và MatMul. Tất cả node khác vẫn ở dạng float, bao gồm các phép toán kết hợp output0: tọa độ box (pixel) và điểm số lớp (từ 0 đến 1) dùng chung tensor đó, vì vậy một scale INT8 duy nhất cho tensor này sẽ làm tròn mọi điểm số lớp về 0. Trọng số được lượng tử hóa theo từng kênh ở opset 13 trở lên. Nếu tự chạy quantize_static trên model FP32 đã export, hãy loại trừ các node tương tự và đặt per_channel=True:

import onnx
from onnxruntime.quantization import quantize_static

model = "yolo26n.onnx"
exclude = [n.name for n in onnx.load(model).graph.node if n.op_type not in {"Conv", "Gemm", "MatMul"}]
quantize_static(model, "yolo26n_int8.onnx", calibration_reader, nodes_to_exclude=exclude, per_channel=True)

Ở đây, calibration_reader là một onnxruntime.quantization.CalibrationDataReader tạo ra {"images": array} cho mỗi ảnh hiệu chuẩn, được tiền xử lý như khi inference: letterbox theo kích thước export, RGB, NCHW, float32 trong khoảng 0-1.

Triển khai model YOLO26 ONNX đã xuất#

Sau khi xuất thành công model Ultralytics YOLO26 sang định dạng ONNX, bước tiếp theo là triển khai các model này trong nhiều môi trường khác nhau. Để biết hướng dẫn chi tiết về cách triển khai model ONNX, hãy xem các tài nguyên sau:

  • Tài liệu Python API của ONNX Runtime: Hướng dẫn này cung cấp thông tin thiết yếu về cách tải và chạy model ONNX bằng ONNX Runtime.

  • Triển khai trên thiết bị edge: Các ví dụ triển khai model ONNX trên thiết bị edge.

  • Hướng dẫn ONNX trên GitHub: Tập hợp các hướng dẫn trình bày nhiều khía cạnh khác nhau của việc sử dụng và triển khai model ONNX trong các trường hợp khác nhau.

  • Triton Inference Server: Tìm hiểu cách triển khai model ONNX bằng Triton Inference Server của NVIDIA để có các quy trình triển khai hiệu năng cao, có khả năng mở rộng.

Suy luận Windows ML#

Trên Windows 11 24H2 (build 26100) trở lên với Python 3.10+, bạn có thể cài đặt onnxruntime-windowsml trong một môi trường riêng để Windows ML chọn nhà cung cấp thực thi phù hợp với phần cứng của bạn. Hãy cài đặt gói này thay cho các bản dựng ONNX Runtime khác, sau đó dùng cùng model .onnx đã xuất với YOLO("model.onnx"). Backend giữ nguyên số luồng PyTorch và các tùy chọn phiên được cung cấp, bao gồm chính sách nhà cung cấp được chỉ định rõ ràng. Nếu không có chính sách được cung cấp, Windows ML sẽ chọn phần cứng để đạt hiệu năng tối đa, ngay cả khi thiết bị PyTorch là cpu. Hãy đo độ trễ dự đoán trên thiết bị của bạn trước khi chọn runtime này; runtime này là tùy chọn và không được cài đặt theo mặc định.

Trên GPU tích hợp dùng chung nguồn điện với CPU, các luồng PyTorch nhàn rỗi trong quá trình tiền xử lý và hậu xử lý có thể làm chậm quá trình suy luận Windows ML. Hãy gọi torch.set_num_threads(1) trước khi dự đoán để giảm tình trạng này. Thiết lập này áp dụng cho toàn bộ tiến trình, vì vậy các model PyTorch khác trong tiến trình đó cũng chỉ chạy trên một luồng.

import torch

from ultralytics import YOLO

torch.set_num_threads(1)  # tùy chọn, đo trên thiết bị của bạn
results = YOLO("yolo26n.onnx")("https://ultralytics.com/images/bus.jpg")

Inference trên GPU AMD với MIGraphX#

Ultralytics chạy model ONNX đã xuất trên GPU AMD thông qua execution provider MIGraphX của ONNX Runtime. Trên hệ thống ROCm (HIP), backend ONNX cài plugin onnxruntime-ep-migraphx trong lần sử dụng đầu tiên và tự động chọn MIGraphXExecutionProvider mà không cần thay đổi code; tất cả tác vụ YOLO26 đều được hỗ trợ. Xem hướng dẫn inference trên GPU AMD để biết các yêu cầu tiên quyết, cách cài đặt, cách sử dụng, kết quả benchmark và bộ nhớ đệm chương trình đã biên dịch.

Tóm tắt#

Trong hướng dẫn này, bạn đã tìm hiểu cách xuất model Ultralytics YOLO26 sang định dạng ONNX để tăng khả năng tương tác và hiệu năng trên nhiều nền tảng. Bạn cũng đã được giới thiệu về ONNX Runtime và các tùy chọn triển khai ONNX.

Xuất ONNX chỉ là một trong nhiều định dạng xuất được Ultralytics YOLO26 hỗ trợ, cho phép bạn triển khai model trong hầu như mọi môi trường. Tùy theo nhu cầu cụ thể, bạn cũng có thể tìm hiểu các tùy chọn xuất khác như TensorRT để đạt hiệu năng GPU tối đa hoặc CoreML dành cho thiết bị Apple.

Để 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 ONNX.

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

  • Để xuất model YOLO26 sang định dạng ONNX bằng Ultralytics, hãy làm theo các bước sau:

    Cách sử dụng
    from ultralytics import YOLO
    
    # Nạp model YOLO26
    model = YOLO("yolo26n.pt")
    
    # # Xuất model sang định dạng ONNX
    model.export(format="onnx")  # tạo 'yolo26n.onnx'
    
    # Nạp model ONNX đã xuất
    onnx_model = YOLO("yolo26n.onnx")
    
    # Chạy suy luận
    results = onnx_model("https://ultralytics.com/images/bus.jpg")

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

  • Sử dụng ONNX Runtime để triển khai model YOLO26 mang lại một số lợi ích:

    • Tương thích đa nền tảng: ONNX Runtime hỗ trợ nhiều nền tảng như Windows, macOS và Linux, đảm bảo model chạy ổn định trên các môi trường khác nhau.
    • Tăng tốc phần cứng: ONNX Runtime có thể sử dụng các tối ưu hóa đặc thù phần cứng cho CPU, GPU và bộ tăng tốc chuyên dụng để cung cấp khả năng suy luận hiệu năng cao.
    • Khả năng tương tác giữa các framework: Có thể chuyển đổi model được huấn luyện bằng các framework phổ biến như PyTorch hoặc TensorFlow sang định dạng ONNX và chạy bằng ONNX Runtime.
    • Tối ưu hiệu năng: ONNX Runtime thường nhanh hơn suy luận PyTorch gốc trên CPU, hữu ích trong các trường hợp triển khai có tài nguyên GPU hạn chế.

    Tìm hiểu thêm trong tài liệu ONNX Runtime.

  • Có thể triển khai các model YOLO26 được export sang ONNX trên nhiều nền tảng, bao gồm:

    • CPU: Sử dụng ONNX Runtime để tối ưu suy luận trên CPU.
    • GPU NVIDIA: Sử dụng NVIDIA CUDA để tăng tốc GPU hiệu năng cao.
    • GPU AMD: Sử dụng AMD ROCm và nhà cung cấp thực thi MIGraphX để tăng tốc GPU hiệu năng cao trên Linux.
    • Thiết bị biên: Chạy các model nhẹ trên thiết bị biên và thiết bị di động để suy luận trực tiếp trên thiết bị theo thời gian thực.
    • Trình duyệt web: Thực thi model trực tiếp trong trình duyệt web cho các ứng dụng web tương tác.
    • Dịch vụ đám mây: Triển khai trên các nền tảng đám mây hỗ trợ định dạng ONNX để suy luận có khả năng mở rộng.

    Để biết thêm thông tin, hãy xem hướng dẫn về các tùy chọn triển khai model của chúng tôi.

  • Sử dụng định dạng ONNX cho model Ultralytics YOLO26 mang lại một số lợi ích:

    • Khả năng tương tác: ONNX cho phép chuyển model giữa các framework machine learning khác nhau.
    • Tối ưu hóa hiệu năng: ONNX Runtime có thể cải thiện hiệu năng model bằng cách tận dụng các tối ưu hóa dành riêng cho phần cứng.
    • Tính linh hoạt: ONNX hỗ trợ nhiều môi trường triển khai, cho phép bạn dùng cùng một model trên các nền tảng khác nhau mà không cần chỉnh sửa.
    • Chuẩn hóa: ONNX cung cấp một định dạng tiêu chuẩn được hỗ trợ rộng rãi trong ngành, đảm bảo khả năng tương thích lâu dài.
  • Khi export model YOLO26 sang ONNX, bạn có thể gặp một số sự cố phổ biến như dependency không khớp hoặc thao tác không được hỗ trợ. Để khắc phục các vấn đề này:

    1. Xác minh rằng bạn đã cài đặt đúng phiên bản của các dependency cần thiết.
    2. Kiểm tra tài liệu ONNX chính thức để biết các toán tử và tính năng được hỗ trợ.
    3. Xem lại thông báo lỗi để tìm manh mối và tham khảo hướng dẫn Các sự cố thường gặp của Ultralytics.
    4. Thử dùng các đối số export khác, chẳng hạn như simplify=True, hoặc điều chỉnh phiên bản opset.
    5. Nếu gặp sự cố với kích thước đầu vào động, hãy đặt dynamic=True trong quá trình export.

    Nếu sự cố vẫn tiếp diễn, hãy liên hệ bộ phận hỗ trợ Ultralytics để được trợ giúp thêm.

Bình luận77

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

  1. dopeggguyGitHub

    The parameter "half" bost apperence in train and export, what’s difference. when we using this parameter what should we need attention.

    1. Glenn JocherUltralytics(đã chỉnh sửa)

      @dopeggguy Good question—summary: training uses mixed precision via amp=True (weights stay FP32; compute is FP16 where safe), while export uses quantize=16 (the former half=True, now deprecated) to write an FP16 model for runtimes that support FP16. During training prefer amp; use FP16 only at export/inference, and don't combine it with INT8 (quantize=8). See the train overview and AMP notes in the Train mode docs and the quantize option details in Model Export – Arguments and Configuration – Export Settings.

      from ultralytics import YOLO
      
      # Mixed-precision training (recommended)
      YOLO("yolo26n.yaml").train(data="data.yaml", amp=True)
      
      # FP16 export for FP16-capable runtimes (e.g., CUDA/TensorRT/OpenVINO FP16)
      YOLO("best.pt").export(format="onnx", quantize=16)
    2. dopeggguyGitHub

      yoloModel = YOLO(path_dir) yoloModel.export(format='onnx', dynamic=False, half=True, imgsz=(640, 640))

      I'm not sure why. I enabled half=True, but the actual size of the exported model doesn't seem to change at all.

    3. Glenn JocherUltralytics(đã chỉnh sửa)

      @dopeggguy half=True is deprecated in favor of quantize=16. On older releases a CPU-only ONNX export ignored the flag and stayed FP32, so the file size was almost identical. Current releases convert CPU ONNX exports to FP16 too (keeping float32 inputs/outputs), and GPU exports are FP16 natively. If you have a GPU, you can force export on it and re-check:

      from ultralytics import YOLO
      
      YOLO(path_dir).export(format="onnx", imgsz=(640, 640), dynamic=False, quantize=16, device=0)

      You can then open the ONNX in Netron or inspect it with the onnx Python API to confirm the weights are float16; for pure CPU deployments it is often better to keep ONNX as FP32 or use a CPU‑oriented backend (e.g. OpenVINO) for FP16/INT8 optimization instead, with some general ONNX background outlined in the ONNX: Open Neural Network Exchange overview.

  2. bastinj98GitHub

    Hi, I trained d a YOLOV8-segn model to detect and segment a single class (nc=1) and then exported in to onnx (simplify, nms, half are all False) with opset = 17. The output shape is 1x37x8400.

    I am building a C++ pipeline to use this model to run inference. How can I process this output to get the final segmentation mask ?

  3. NgZimingGitHub

    I exported a yolo 11 segment model to onnx format, and used onnx-runtime to infer. It responded two ndarrays of shapes (1, 37, 21504) and (1, 32, 256, 256). (imgsz=1024) So, how can i extract masks from these two arrays?

    1. Glenn JocherUltralytics

      @NgZiming 这两个输出正是分割模型的“检测头 + 原型掩码”:(1, 37, 21504) = 4(xywh) + nc + 32(mask系数),(1, 32, 256, 256) 为32个原型;掩码可由原型与对应检测的32维系数线性组合并裁剪到框内,最小示例(Python/NumPy)如下:

      import numpy as np
      import cv2
      
      def sigmoid(x): return 1 / (1 + np.exp(-x))
      
      def mask_from_outputs(det, proto, img_h, img_w, det_idx):
          # det: (1, C, N) -> (C, N), proto: (1, 32, 256, 256) -> (32, 256, 256)
          det = det[0]; proto = proto[0]
          nm, ph, pw = proto.shape  # 32, 256, 256
          nc = det.shape[0] - 4 - nm
      
          # 1) 取该检测的框、类别分数与32维掩码系数
          cx, cy, w, h = det[0, det_idx], det[1, det_idx], det[2, det_idx], det[3, det_idx]
          coeff = det[4+nc:4+nc+nm, det_idx]  # (32,)
      
          # 2) 原型 × 系数 -> 原始掩码 (ph, pw)
          m = sigmoid((proto.reshape(nm, -1).T @ coeff).reshape(ph, pw))
      
          # 3) 可选:按框在原型分辨率下裁剪(坐标为[0,1]比例)
          x0 = int(max(0, (cx - w/2) * pw)); x1 = int(min(pw, (cx + w/2) * pw))
          y0 = int(max(0, (cy - h/2) * ph)); y1 = int(min(ph, (cy + h/2) * ph))
          crop = np.zeros_like(m); crop[y0:y1, x0:x1] = m[y0:y1, x0:x1]
      
          # 4) 上采样到原图尺寸并二值化
          mask = cv2.resize(crop, (img_w, img_h), interpolation=cv2.INTER_LINEAR)
          return (mask > 0.5).astype(np.uint8)

      要点:确保与推理时的预处理一致(letterbox 缩放与填充、RGB/归一化等),否则框与掩码会错位。关于分割导出产生两个输出(output0 检测+系数,output1 原型)的由来,可见导出实现参考的 export_onnx 说明:export_onnx 函数参考.

      1
  4. User

    I have a question. If it's convenient, please answer it. Thank you! I'm working with cell images, and the image size is 3072*2048. I trained with imagesize=3072, but if I use imagesize=640, I can't detect objects. I can predict with a 3072 imagesize using a pt file, but now I'm trying to switch to C++ and call onnx, and the 3072 inference is very slow. Is this normal?

    1. denni281GitHub

      You should keep the same preprocess way between python-inference and cpp-inference.

    2. Glenn JocherUltralytics

      @giter915 Yes—running 3072×2048 through ONNX/C++ will be much slower; inference time grows quickly with input area. Two practical options: use a faster backend or reduce effective input while keeping accuracy. For GPU, prefer TensorRT; for CPU, OpenVINO FP16/INT8 gives the largest gains. Examples:

      from ultralytics import YOLO
      
      # GPU-optimized
      YOLO("best.pt").export(format="engine", imgsz=1536, half=True, dynamic=True)
      
      # CPU-optimized
      YOLO("best.pt").export(format="openvino", imgsz=1536, half=True)  # add int8=True with calibration if desired

      If you must keep 3072, tile the image (e.g., 1024×1024 patches), run ONNX per tile, then merge detections with NMS in C++; this is a common approach for microscopy. Also ensure preprocessing in C++ exactly matches Python (letterbox padding, RGB order, 1/255 scaling)—agree with @DennisJcy here. For backend choices and supported export targets, see the export formats table in Object Detection – Ultralytics YOLO Docs, and for high‑throughput GPU serving consider Triton Inference Server with YOLO11.

    3. Glenn JocherUltralytics

      Glad it helped—one extra tip for ONNX Runtime C++: enable full graph optimizations and tune threads to squeeze more speed from large inputs like 3072×2048.

      #include <onnxruntime_cxx_api.h>
      #include <thread>
      
      Ort::Env env(ORT_LOGGING_LEVEL_WARNING, "yolo");
      Ort::SessionOptions so;
      so.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL);
      so.SetIntraOpNumThreads(std::thread::hardware_concurrency());
      so.SetInterOpNumThreads(1);  // often fine to leave at 1
      
      Ort::Session session(env, "best.onnx", so);
  5. denni281GitHub(đã chỉnh sửa)

    Hello, I use ultratics to export YOLO11 half-Precision onnx model, but when I load the .onnx model to eval by onnxruntime, exception shows :Unexpected input data type. Actual: (tensor(float16)) , expected: (tensor(float)). And I compare the Float32 and Float16(half) .onnx model,These two files are exactly the same in size and input type.So the "half" keyword doesn't take effect when exporting ONNX, right? I remember Ultralytics didn't have this issue last year.

    Here is my python script to export half-precision onnx model:

    def main(opt):
        model = YOLO(opt.model)
        model.export(
            format="onnx",
            # opset=12,
            simplify=True,
            dynamic=False,
            imgsz=opt.imgsz,
            half=opt.half,
            batch=opt.batch,
        )
    
    
    if __name__ == "__main__":
        multiprocessing.freeze_support()
        parser = argparse.ArgumentParser()
        parser.add_argument(
            "--model",
            type=str,
            default="/home/ultralytics/runs/detect/SHFY/weights/best.pt",
        )
        parser.add_argument("--imgsz", type=int, default=640)
        parser.add_argument("--half", type=bool, default=True)
        parser.add_argument("--batch", type=int, default=1)
        opt, unparsed = parser.parse_known_args()
        print(opt)
        main(opt)
    
    1. denni281GitHub(đã chỉnh sửa)

      Fine... It's my fault. My docker environment is Python-3.11.9 torch-2.4.1+cu118 CPU (unknown). The error is made by my cpu environment

    2. Glenn JocherUltralytics(đã chỉnh sửa)

      @DennisJcy thanks for the update. On older releases half=True had no effect on CPU ONNX exports, so the file stayed FP32. Current Ultralytics uses quantize=16 (replacing the deprecated half) and also converts CPU ONNX exports to FP16 while keeping float32 inputs/outputs, whereas GPU exports (device=0) are FP16 natively and need an FP16-capable ONNX Runtime provider. For CPU-optimized FP16 you can also export OpenVINO. For example:

      from ultralytics import YOLO
      
      # FP16 ONNX
      YOLO("best.pt").export(format="onnx", quantize=16)
      
      # CPU-optimized FP16 (OpenVINO)
      YOLO("best.pt").export(format="openvino", quantize=16)

      Details on OpenVINO export are in the export_openvino reference.

  6. ShuaibZyxGitHub

    def yolo_to_onnx(model_path, input_shape=(600, 600)): # Load the YOLOv8 model model = YOLO(model_path)

    # Export the model to ONNX format
    model.export(format='onnx', 
                 imgsz=input_shape,
                 dynamic=True,
                 batch=1,
                 device="0")

    Ultralytics YOLOv8.0.220 🚀 Python-3.9.18 torch-2.1.1+cu121 CUDA:0 (Tesla T4, 14931MiB) Model summary (fused): 268 layers, 43610463 parameters, 0 gradients, 164.8 GFLOPs

    PyTorch: starting from 'best.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) (1, 9, 8400) (83.6 MB)

    ONNX: starting export with onnx 1.18.0 opset 17... ONNX: export success ✅ 3.3s, saved as 'best.onnx' (166.5 MB) 我的模型在训练时是5个类别的目标检测,导出的模型的输出格式是(1, 9, 8400)。 我想请问您其中9具体代表的是什么呢? 如果是为了预测5个类别(1, 9, 8400)的输出格式是正确的嘛? 期待您的帮助!感谢!

    1. xiaoqiang-lGitHub

      9指的是:[x,y,w,h,class1_scores,class2_scores,class3_scores,class4_scores,class5_scores],即四个坐标及N个类别分数。 8400指的是:640下采样8倍、16倍、32倍特征图的anchor总数,(640/8)(640/8)+(640/16)(640/16)+(640/32)(640/32)=8080+4040+2020=8400

    2. Glenn JocherUltralytics

      @ShuaibZyx you're welcome! @xiaoqiang-l provided an excellent explanation. Just to confirm, the output shape (1, 9, 8400) is indeed correct for your 5-class detection model - the 9 channels represent the 4 bounding box coordinates (x, y, w, h) plus 5 class confidence scores. The 8400 represents all detection anchors across the three feature map scales (80×80 + 40×40 + 20×20 = 8400 total anchors).

  7. UltralyticsAssistantGitHubUltralytics

    👋 Hello, thank you for your interest in Ultralytics 🚀! We recommend a visit to the Docs for new users where you can find many Python and CLI usage examples, as well as detailed guides about exporting YOLO models to ONNX and other formats.

    If this is a 🐛 Bug Report, please provide a minimum reproducible example to help us debug it.

    If you have a custom training ❓ Question or require help with ONNX export, please include as much detail as possible—such as your command, model version, logs, and environment details. Also, check out our Tips for Best Training Results for optimal performance.

    Join the Ultralytics community where it suits you best! For real-time chat, head to Discord 🎧. For in-depth discussions, try Discourse, or join the conversation on our Subreddit.

    Upgrade

    Upgrade to the latest ultralytics package including all requirements in a Python>=3.8 environment with PyTorch>=1.8 to ensure you’re using the most up-to-date features and bug fixes:

    pip install -U ultralytics

    Environments

    YOLO can be run in these up-to-date verified environments, with all dependencies including CUDA/CUDNN, Python, and PyTorch preinstalled:

    Status

    Ultralytics CI

    If this badge is green, all Ultralytics CI tests are currently passing. CI tests verify correct operation of all YOLO Modes and Tasks on macOS, Windows, and Ubuntu every 24 hours and on every commit.

    This is an automated response 🤖. An Ultralytics engineer will review your discussion and assist you soon!

    1. Glenn JocherUltralytics

      Hello! Thanks for your interest in exporting YOLO11 models to ONNX format. This is a great option for deployment across different platforms with performance benefits.

      Exporting to ONNX is straightforward with Ultralytics:

      from ultralytics import YOLO
      
      # Load model
      model = YOLO("yolo11n.pt")  # or your custom trained model
      
      # Export to ONNX with optional parameters
      model.export(format="onnx", dynamic=True, simplify=True)  # creates 'yolo11n.onnx'
      
      # Use the exported model
      onnx_model = YOLO("yolo11n.onnx")
      results = onnx_model("https://ultralytics.com/images/bus.jpg")

      ONNX export can provide up to 3x CPU speedup compared to PyTorch models. You can customize the export with several parameters like half=True for FP16 precision, dynamic=True for variable input sizes, or opset to specify the ONNX version.

      For deployment, you can use ONNX Runtime or integrate with platforms like NVIDIA Triton Inference Server for production-scale serving.

      If you have specific questions about exporting your models or encounter any issues during the process, please let us know!

  8. UltralyticsAssistantGitHubUltralytics

    👋 Hello, thank you for your interest in Ultralytics 🚀! For users exploring ONNX integration and YOLO11, we recommend checking out the Docs where you’ll find dedicated Python and CLI tutorials, as well as specific ONNX integration guidance.

    If this is a 🐛 Bug Report, please provide a minimum reproducible example to help us investigate further.

    For custom deployment or export ❓ questions, please include as many details as possible, such as your export commands, model versions, and error logs. Make sure you review our Tips for Best Training Results for optimal performance.

    Join the Ultralytics community where it suits you best: jump into real-time conversations on Discord 🎧, post or search on Discourse, or connect on our Subreddit.

    Upgrade

    Upgrade to the latest ultralytics package, including all requirements, in a Python>=3.8 environment with PyTorch>=1.8 to ensure you have the latest features and fixes:

    pip install -U ultralytics

    Environments

    YOLO can be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):

    Status

    Ultralytics CI

    If this badge is green, all Ultralytics CI tests are currently passing. CI tests verify correct operation of all YOLO Modes and Tasks on macOS, Windows, and Ubuntu every 24 hours and on every commit.

    This is an automated response. An Ultralytics engineer will assist you here soon!

    1. Glenn JocherUltralytics

      Yes, you can adjust the batch size dynamically when exporting to ONNX format by using the dynamic=True parameter in your export call. When this is enabled, the batch dimension becomes dynamic, allowing you to use various batch sizes during inference without reexporting the model.

      Here's a simple example:

      from ultralytics import YOLO
      
      # Load your model
      model = YOLO("yolo11n.pt")
      
      # Export with dynamic input size
      model.export(format="onnx", dynamic=True)

      This creates dynamic dimensions in the exported ONNX model, where the batch dimension (as well as height and width) can vary during inference. The resulting model will be more flexible for production deployments where batch size requirements might change.

  9. skyceeeeGitHub

    First of all, thank you for everything. Can we adjust the batch size dynamically when exporting the model as onnx?

  10. xiaoqiang-lGitHub

    When I export the YOLOV11 onnx model, I use: model.export(format='onnx', imgsz=640, device='cpu'). Then I use onnxruntime (1.14.0) to deploy it on the C++ side, but an error is reported during runtime: onnxruntime::Model::Model Unsupported model IR version: 9, max supported IR version: 8. Is there any parameter or method to set the exported model to support IR version: 8? Because I cannot upgrade onnxruntime to other higher versions locally, I look forward to your help

    1. Glenn JocherUltralytics

      @xiaoqiang-l to resolve the ONNX IR version compatibility issue, you can specify an older opset version during export. Try adding opset=13 to your export command:

      model.export(format='onnx', imgsz=640, device='cpu', opset=13)

      This will generate an ONNX model compatible with IR version 8. For detailed version mapping, see the ONNX operator version matrix in the ONNX documentation.