Xuất model YOLO26 sang ONNX
ONNX (Trao đổi mạng nơ-ron mở) là định dạng model mở mà hầu hết runtime suy luận đều có thể tải. Export model Ultralytics YOLO26 bằng format="onnx" sẽ tạo một file .onnx duy nhất, chạy được với ONNX Runtime trên CPU, GPU NVIDIA và AMD, Apple silicon và thiết bị Windows.
Tổng quan nhanh#
| Thuộc tính | Chi tiết |
|---|---|
Đối số format | onnx |
| Đầu ra | yolo26n.onnx, một file chứa tên lớp, tác vụ và kích thước ảnh được lưu dưới dạng metadata; yolo26n_int8.onnx cho export quantize=8 đã hiệu chuẩn |
| Chạy trên | CPU, GPU NVIDIA (CUDA), GPU AMD (MIGraphX), Apple silicon (execution provider Core ML) và thiết bị Windows ML |
| Runtime | ONNX Runtime, hoặc DNN của OpenCV với dnn=True |
| Precision | FP32, FP16, INT8. YOLO26n có kích thước 9.9 MB ở FP32, 5.0 MB ở FP16 và 3.1 MB ở INT8 |
| Máy export | Linux, macOS hoặc Windows, có hoặc không có GPU |
Ultralytics Platform có thể export model đã huấn luyện sang ONNX giúp bạn, vì vậy bạn không cần môi trường export cục bộ.
Bắt đầu nhanh#
Cài đặt package Ultralytics. Lần export đầu tiên sẽ cài onnx, onnxslim và onnxruntime nếu chưa có (onnxruntime-gpu khi bạn export bằng device=0 trên GPU NVIDIA).
pip install ultralyticsĐể biết các phương thức cài đặt khác, hãy xem hướng dẫn cài đặt. Sau đó export model của bạn và tải file đã export để chạy suy luận hoặc xác thực độ chính xác.
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'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")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 tác vụ được hỗ trợ#
Export ONNX hỗ trợ cả bảy tác vụ Ultralytics với các model YOLOv8, YOLO11 và YOLO26: phát hiện, phân đoạn, phân đoạn semantic, ước tính độ sâu, phân loại, ước tính tư thế và OBB. Phân đoạn semantic và ước tính độ sâu chỉ có trên YOLO26, dòng model duy nhất có các head này.
Các tham số xuất model#
| Đối số | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
format | str | '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. |
imgsz | int hoặc tuple | 640 | Kích thước ảnh đầu vào của model: số nguyên đối với ảnh vuông hoặc tuple (height, width). Nếu không truyền giá trị, quá trình export sẽ dùng kích thước mà checkpoint đã được huấn luyện. Các checkpoint YOLO26 chính thức dùng 640 cho detect, segment, pose và model semantic được pretrained trên ADE20K, 1024 cho OBB và model semantic được pretrained trên Cityscapes, 768 cho depth và 224 cho classify. |
quantize | int hoặc str | None | Độ chính xác lượng tử hóa: 16 (FP16; export trên CPU giữ đầu vào và đầu ra FP32, export trên GPU cũng chuyển chúng sang FP16) hoặc 8 (lượng tử hóa tĩnh INT8 bằng ONNX Runtime, sử dụng ảnh hiệu chuẩn từ data và tạo model _int8.onnx); 32/không đặt giá trị sẽ dùng FP32. Checkpoint được huấn luyện với quantize=8 sẽ export INT8 khi quantize không được đặt hoặc là 8 (các giá trị khác gây lỗi), dưới dạng các node Q/DQ từ những dải giá trị mà checkpoint chứa, 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. |
data | str | None | YAML 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. |
fraction | float, int hoặc list | 1.0 | Tậ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. |
dynamic | bool | False | Đặt batch, chiều cao và chiều rộng của đầu vào thành các trục động, để một file chấp nhận nhiều kích thước batch khác nhau (tối đa bằng batch khi export với nms=True) và nhiều kích thước ảnh. Xem export động. |
simplify | bool | True | Đơn giản hóa graph của model bằng onnxslim. |
opset | int | None | Chỉ định phiên bản opset ONNX để tương thích với các parser và runtime ONNX khác nhau. Nếu không đặt, sẽ dùng opset 18 (thấp hơn khi PyTorch < 2.4), nhưng không vượt quá phiên bản onnx đã cài đặt. Xem opset tối thiểu. |
nms | bool, không bắt buộc | None | Chọn đầu ra thô (None, mặc định), NMS nhúng (True) hoặc head không dùng NMS (False). Xem định dạng đầu ra. |
batch | int | 1 | Kích thước batch của model đã export. Với export tĩnh, kích thước batch này được cố định trong shape đầu vào. Khi dùng dynamic=True và nms=True, hãy đặt giá trị này bằng kích thước batch lớn nhất bạn dự định chạy. |
device | str | None | Thiết bị dùng để export: cpu (mặc định, kể cả trên máy có GPU), 0 cho GPU CUDA hoặc mps cho Apple silicon. Tùy chọn này chỉ thay đổi kết quả với quantize=16; xem đầu vào FP16. |
Để biết các đối số dùng chung cho mọi định dạng, hãy xem tài liệu chế độ Export.
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} với kích thước batch của model, được tiền xử lý như khi suy luận: letterbox theo kích thước export (resize và cắt giữa đối với phân loại), RGB, NCHW, float32 trong khoảng 0-1.
Model INT8 giữ nguyên kiểu dữ liệu đầu vào và đầu ra của model FP32, vì vậy mã suy luận viết cho model FP32 có thể chạy model INT8 mà không cần thay đổi. INT8 giúp file nhỏ hơn FP32 từ ba đến bốn lần, nhưng trong các benchmark, tốc độ chạy trên ONNX Runtime chậm hơn FP32 cả trên GPU lẫn CPU. Hãy đo độ trễ trên phần cứng mục tiêu trước khi chọn độ chính xác.
Định dạng đầu ra#
Model đã export nhận một đầu vào tên images có shape (batch, 3, height, width), RGB và được scale về khoảng 0-1. Đầu vào có kiểu float32, ngoại trừ các bản export GPU được tạo bằng quantize=16, vốn nhận float16. Đối số nms đặt layout của output0. Các shape dưới đây áp dụng cho model phát hiện YOLO26n có 80 lớp được export ở imgsz=640:
nms | Shape output0 | Nội dung |
|---|---|---|
None (mặc định) | (1, 84, 8400) | Với mỗi anchor trong số 8400 anchor: tâm hộp x, tâm hộp y, chiều rộng, chiều cao tính bằng pixel đầu vào, sau đó là 80 điểm số lớp. Tự áp dụng NMS. |
True | (1, 300, 6) | NMS chạy bên trong model. Mỗi hàng có dạng x1, y1, x2, y2, score, class; các hàng nằm sau phát hiện cuối cùng có giá trị bằng 0. |
False | (1, 300, 6) | Head không dùng NMS. Mỗi hàng có dạng x1, y1, x2, y2, score, class, không có bước NMS. Tự lọc hàng theo điểm số. |
Các tác vụ khác dùng cùng đầu vào và có các đầu ra sau. Các shape áp dụng cho checkpoint YOLO26n chính thức ở kích thước export mặc định, trong đó checkpoint Cityscapes yolo26n-sem.pt dùng cho phân đoạn semantic:
| Tác vụ | imgsz mặc định | Đầu ra với nms=None | Đầu ra với nms=False hoặc nms=True |
|---|---|---|---|
| Detect | 640 | output0 (1, 84, 8400) | output0 (1, 300, 6) |
| Segment | 640 | output0 (1, 116, 8400), output1 (1, 32, 160, 160) | output0 (1, 300, 38), output1 (1, 32, 160, 160) |
| Ngữ nghĩa | 1024 | output0 (1, 1024, 1024), uint8 chỉ số lớp cho mỗi pixel | Giống nms=None |
| Độ sâu | 768 | output0 (1, 1, 768, 768), bản đồ độ sâu | Giống nms=None |
| Phân loại | 224 | output0 (1, 1000), xác suất lớp sau softmax | Giống nms=None đối với nms=False; nms=True gây lỗi |
| Tư thế | 640 | output0 (1, 56, 8400) | output0 (1, 300, 57): 6 giá trị hộp, sau đó là 17 keypoint x 3 |
| OBB | 1024 | output0 (1, 20, 21504) | output0 (1, 300, 7): center x, center y, width, height, score, class, angle (radian) |
Các hàng phân đoạn chứa 32 hệ số mask sau các giá trị hộp, còn output1 chứa các prototype mask. Trong model FP32 và INT8, mọi đầu ra đều có kiểu float32, ngoại trừ bản đồ lớp semantic.
Với nms=True, ngưỡng confidence conf (mặc định là 0.25), ngưỡng IoU iou (mặc định là 0.5), agnostic_nms và max_det (mặc định là 300) được cố định trong graph khi export. Đặt conf thấp hơn lúc dự đoán không thể khôi phục những phát hiện mà graph đã loại bỏ, vì vậy hãy export lại để thay đổi các giá trị này. max_det và agnostic_nms cũng áp dụng cho nms=False: max_det=100 tạo shape (1, 100, 6) cho output0.
YOLO("yolo26n.onnx") đọc layout từ metadata của file, vì vậy bạn chỉ cần các shape này khi chạy model trong mã của riêng mình. Mã của bạn cũng có thể truy cập metadata dưới dạng chuỗi: names, task, imgsz, stride, batch, end2end và args.
import ast
import onnxruntime as ort
meta = ort.InferenceSession("yolo26n.onnx").get_modelmeta().custom_metadata_map
names = ast.literal_eval(meta["names"]) # {0: 'person', 1: 'bicycle', ...}
imgsz = ast.literal_eval(meta["imgsz"]) # [640, 640]Triển khai#
YOLO("yolo26n.onnx") chạy model bằng ONNX Runtime và chọn execution provider dựa trên đối số device. Trên máy có GPU CUDA, GPU sẽ được sử dụng nếu không đặt device.
device | Execution provider |
|---|---|
cpu | CPUExecutionProvider |
0 trên GPU NVIDIA | CUDAExecutionProvider, từ package onnxruntime-gpu được cài đặt trong lần sử dụng đầu tiên |
0 trên GPU AMD ROCm | MIGraphXExecutionProvider, xem Suy luận trên GPU AMD bằng MIGraphX |
mps trên Apple silicon | CoreMLExecutionProvider cho các node có shape tĩnh; node có shape động chạy trên CPUExecutionProvider |
Dòng log Using ONNX Runtime 1.31.1 with CUDAExecutionProvider cho biết provider nào đang hoạt động. Hành vi khi suy luận phụ thuộc vào cách model được export:
- Export tĩnh (mặc định): model luôn chạy ở
imgszvàbatchdùng khi export; Ultralytics đọc các giá trị này từ metadata của file. Giá trịimgszđược truyền chopredictsẽ bị bỏ qua. Batch lớn hơn được chia thành các phần bằng kích thước batch lúc export, còn batch nhỏ hơn được đệm, vì vậy có thể xử lý số lượng ảnh bất kỳ. - Export động (
dynamic=True):predictchấp nhận mọiimgszlà bội số của stride model. Kích thước batch có thể thay đổi, nhưng khi dùngnms=True, kích thước này bị giới hạn ở giá trịbatchđược dùng lúc export; vì vậy hãy đặt giá trị đó bằng kích thước batch lớn nhất bạn dự định chạy. - Bộ nhớ GPU: với
CUDAExecutionProvider, model tĩnh sử dụng IO binding của ONNX Runtime, giữ tensor đầu vào và đầu ra trên GPU. Model động sao chép chúng qua bộ nhớ CPU trong mỗi lần gọi. - Luồng CPU: Ultralytics giới hạn ONNX Runtime ở 8 luồng intra-op, hoặc ở số lõi CPU vật lý mà tiến trình có thể sử dụng nếu số đó thấp hơn. Đặt biến môi trường
ORT_INTRA_OP_NUM_THREADSđể sử dụng số luồng khác.
Truyền dnn=True cho predict hoặc val để chạy model trên CPU bằng DNN của OpenCV thay cho ONNX Runtime. DNN của OpenCV hỗ trợ ít tùy chọn export hơn; xem Giới hạn và khắc phục sự cố.
Để chạy model bên ngoài package Ultralytics, hãy xem các tài nguyên sau:
- API Python của ONNX Runtime: tải và chạy model ONNX trong Python.
- Execution provider của ONNX Runtime: các backend phần cứng như CUDA, TensorRT, OpenVINO, Core ML và DirectML.
- Ví dụ của Ultralytics: suy luận ONNX Runtime bằng Python, C++ và Rust, cùng suy luận DNN của OpenCV bằng Python.
- Triton Inference Server: cung cấp model ONNX qua HTTP hoặc gRPC bằng NVIDIA Triton.
- Triển khai trên thiết bị edge: hướng dẫn ONNX Runtime cho IoT và phần cứng edge.
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 đã export trên GPU AMD thông qua MIGraphX execution provider của ONNX Runtime. Trên hệ thống ROCm (HIP) với Python 3.11 trở lên trên x86-64, 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 mã; tất cả tác vụ YOLO26 đều được hỗ trợ. Xem hướng dẫn suy luận trên GPU AMD để biết điều kiện tiên quyết, cách cài đặt, cách sử dụng, benchmark và bộ nhớ đệm chương trình đã biên dịch.
Giới hạn và khắc phục sự cố#
- Opset tối thiểu: quá trình export thất bại với
ONNX export requires opset>=Nkhiopsetquá thấp so với yêu cầu của model. Giá trị tối thiểu là7cho phân loại,9cho phát hiện, phân đoạn, phân đoạn semantic, pose và OBB,11cho ước tính độ sâu cũng như model phát hiện, phân đoạn, pose và OBB được export bằngnms=True, và16cho RT-DETR. - Đầu vào FP16: model FP16 được export trên GPU (
quantize=16 device=0) yêu cầu tensor đầu vào FP16 trong mã của riêng bạn. Model FP16 được export trên CPU giữ đầu vào và đầu ra FP32 rồi chuyển đổi bên trong graph.YOLO()cung cấp đúng kiểu dữ liệu đầu vào cho cả hai trường hợp, trên GPU lẫn CPU. - Tên file INT8:
quantize=8ghiyolo26n_int8.onnxvà xóa file FP32 trung gian, vì vậy hãy tải file_int8để suy luận. Trường hợp ngoại lệ là checkpoint được huấn luyện vớiquantize=8: quá trình export ghi các node Q/DQ vàoyolo26n.onnxvà bỏ qua bước hiệu chuẩn. - Kích thước hiệu chuẩn INT8: với checkpoint không được huấn luyện bằng
quantize=8, quá trình export đưa ra cảnh báo khi tập hiệu chuẩn có ít hơn 300 ảnh. Mặc định, hiệu chuẩn sử dụng tậpval;coco8.yamlchỉ có 4 ảnh validation, vì vậy hãy dùng dataset riêng cho model dự định triển khai. - NMS nhúng:
nms=Trueyêu cầu PyTorch 1.13 trở lên. Tùy chọn này gây ra'nms=True' is not valid for classification modelsvới tác vụ phân loại và bị bỏ qua kèm cảnh báo đối với model phân đoạn semantic, ước tính độ sâu và RT-DETR. - Head không dùng NMS:
nms=Falseyêu cầu model có head không dùng NMS, chẳng hạn YOLO26 hoặc YOLOv10. Với các model khác, ví dụ YOLO11, quá trình export sẽ cảnh báoThis model has no one-to-one head; using one-to-many outputsvà ghi đầu ra thô(1, 84, 8400). - Không sử dụng GPU: nếu log hiển thị
CUDA requested but CUDAExecutionProvider not available. Using CPU..., bản ONNX Runtime đã cài không có CUDA provider hoạt động. Càionnxruntime-gputhay choonnxruntimevà kiểm tra để bảo đảm các phiên bản CUDA và cuDNN của bản cài đặt tương thích với hệ thống. - DNN của OpenCV: với OpenCV 4.14.0,
dnn=Truechạy được model mặc định,nms=False, INT8 và FP16 được export trên GPU. Tùy chọn này không tải được model được export bằngnms=True, bằngdynamic=Truehoặc bằngquantize=16trên CPU. - Shape động với NMS: khi kết hợp
dynamic=Truevớinms=True, hãy đặtbatchbằng kích thước batch lớn nhất bạn dự định chạy. Quá trình export sẽ cảnh báo nếubatchvẫn là1. - Đơn giản hóa graph: nếu
onnxslimthất bại, quá trình export sẽ ghi cảnh báo và lưu model mà không đơn giản hóa. - Phiên bản IR: bộ export giới hạn phiên bản ONNX IR ở mức 10 để các bản ONNX Runtime cũ hơn có thể tải file. Export mặc định với opset 18 có phiên bản IR là 8.
Đối với các lỗi khác, hãy xem hướng dẫn về các sự cố thường gặp.
Benchmark#
YOLO26n chạy nhanh hơn YOLO11n tới 43% với ONNX Runtime trên CPU (Intel Xeon CPU @ 2.00 GHz). Trang model YOLO26 liệt kê tốc độ ONNX trên CPU của mọi model cho tất cả tác vụ ngoại trừ phân đoạn semantic.
Xem: Kiểm thử inference ONNX: Ultralytics YOLO26 so với Ultralytics YOLO11 | YOLO26 inference nhanh hơn khoảng 43% 🚀
FP32, FP16 và INT8 với ONNX Runtime#
Các bảng dưới đây so sánh PyTorch với model ONNX FP32, FP16 và INT8 của mọi model phát hiện YOLO26, chạy bằng ONNX Runtime CUDAExecutionProvider. Tất cả giá trị GPU được đo trên cùng một GPU NVIDIA RTX PRO 6000 Blackwell Server Edition.
Số mili giây trên mỗi ảnh; càng thấp càng tốt. Định dạng nhanh nhất cho mỗi model được in đậm.
| Model | imgsz | PyTorch | ONNX FP32 | ONNX FP16 | ONNX INT8 |
|---|---|---|---|---|---|
| YOLO26n | 640 | 2.85 | 1.96 | 1.88 | 3.73 |
| YOLO26s | 640 | 2.98 | 2.14 | 1.73 | 4.31 |
| YOLO26m | 640 | 3.29 | 3.01 | 2.14 | 5.37 |
| YOLO26l | 640 | 4.70 | 4.09 | 3.08 | 7.51 |
| YOLO26x | 640 | 5.93 | 5.56 | 3.90 | 9.38 |
YOLO26n trên CPU (AMD EPYC 9655, PyTorch và ONNX Runtime mỗi bên dùng 8 luồng; CPU khác với CPU dùng cho các bảng model YOLO26):
| Chỉ số | PyTorch | ONNX FP32 | ONNX FP16 | ONNX INT8 |
|---|---|---|---|---|
| Độ trễ (ms/ảnh) | 13.2 | 13.4 | 13.2 | 56.5 |
| mAPval 50-95 | 40.8 | 40.9 | 40.9 | 38.7 |
- FP16 giảm một nửa kích thước file, độ mAP chênh không quá 0.1 so với FP32 và chạy nhanh hơn FP32 tới 1.4 lần trên GPU, nhưng không tăng tốc trên CPU.
- INT8 tạo ra file nhỏ nhất nhưng giảm 2.2 đến 3.0 mAP và chạy chậm hơn FP32 trên cả GPU lẫn CPU.
Được đo bằng ultralytics 8.4.211, ONNX Runtime 1.30.0, PyTorch 2.15.0 và CUDA 13.2 tại batch=1 vào ngày 13 tháng 11 năm 2026. Độ trễ là giai đoạn suy luận mà val báo cáo, không bao gồm tiền xử lý hoặc hậu xử lý.
Giới thiệu về ONNX#
ONNX là một dự án cộng đồng do Facebook và Microsoft khởi xướng, hiện được phát triển cùng các tổ chức như IBM, Amazon và Google. ONNX định nghĩa một tập hợp toán tử chung và định dạng tệp cho các model machine learning, nhờ đó model được huấn luyện trong một framework, chẳng hạn như PyTorch, có thể chạy trên nhiều runtime và nền tảng phần cứng.
ONNX Runtime là engine suy luận đa nền tảng dành cho các model ONNX. Các execution provider sử dụng thư viện chuyên biệt cho phần cứng để chạy model trên CPU, GPU và bộ tăng tốc chuyên dụng.
ONNX cũng là bước trung gian cho các định dạng export khác của Ultralytics, bao gồm TensorRT, đồng thời là đầu vào cho các chuỗi công cụ NPU của nhà cung cấp như Huawei Ascend, Qualcomm QNN và Rockchip RKNN. Xem tài liệu ONNX để biết thông số kỹ thuật.
Câu hỏi thường gặp#
Để
opsetchưa được đặt, trừ khi runtime của bạn cần một phiên bản cụ thể. Khi đó, exporter sẽ dùng opset18trên PyTorch 2.4 trở lên, opset17trên PyTorch 1.13 đến 2.3, opset thấp hơn trên các phiên bản PyTorch cũ hơn và không bao giờ vượt quá mức mà packageonnxđã cài hỗ trợ. Mặc định dừng ở opset 18 vì provider CUDA của ONNX Runtime chạy một số toán tử opset 19 trở lên, chẳng hạnResize, trên CPU. Hãy đặt giá trị thấp hơn, ví dụopset=12, khi runtime hoặc bộ chuyển đổi cũ hơn từ chối giá trị mặc định. Giá trị này không thể thấp hơn opset tối thiểu của model.Điều này phụ thuộc vào đối số
nmsdùng khi export. Export mặc định trả về các dự đoán thô cần được lọc theo độ tin cậy và xử lý NMS. Export vớinms=Falsehoặcnms=Truetrả về tối đamax_det(mặc định là 300) detection cuối cùng cho mỗi ảnh dưới dạngx1, y1, x2, y2, score, class, theo pixel của ảnh đầu vào; vì vậy bạn chỉ cần lọc theo điểm số và đưa các box về kích thước ảnh gốc. Các hàng OBB chứacenter x, center y, width, heightthay cho tọa độ góc, cùng với góc xoay. Xem Định dạng đầu ra để biết các shape.Đọc đầu ra không dùng NMS bằng ONNX Runtime# Export trước: yolo export model=yolo26n.pt format=onnx nms=False import numpy as np import onnxruntime as ort session = ort.InferenceSession("yolo26n.onnx") # được export với nms=False image = np.zeros((1, 3, 640, 640), dtype=np.float32) # ảnh đã tiền xử lý của bạn detections = session.run(None, {"images": image})[0][0] # shape (300, 6) detections = detections[detections[:, 4] > 0.25] # giữ các hàng vượt ngưỡng độ tin cậyĐặt
dynamic=True. Khi đó, đầu vàoimagescó shape(batch, 3, height, width)với batch, chiều cao và chiều rộng động; detectionoutput0mặc định (nms=None) có shape(batch, 84, anchors), nên cùng một tệp chấp nhận các kích thước batch và ảnh khác nhau khi suy luận. Vớinms=True, kích thước batch bị giới hạn ở giá trịbatchđã dùng khi export. Chiều cao và chiều rộng phải là bội số của stride model; với các checkpoint YOLO26 chính thức, giá trị này là 32, ngoại trừ model phân loại. Model động không dùng IO binding trên CUDA và không tải được trong OpenCV DNN, vì vậy hãy giữ export tĩnh mặc định khi kích thước đầu vào cố định.Export độngfrom ultralytics import YOLO model = YOLO("yolo26n.pt") model.export(format="onnx", dynamic=True)Dùng ONNX khi cần chạy một tệp trên nhiều phần cứng hoặc khi máy triển khai không phải máy dùng để export. Dùng TensorRT để đạt độ trễ thấp nhất trên một GPU NVIDIA cụ thể: engine TensorRT được xây dựng cho một kiến trúc GPU và phiên bản TensorRT nhất định nên không có tính di động. Với các mục tiêu khác, xem hướng dẫn các tùy chọn triển khai model.
Bình luận77
Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.
dopeggguy
The parameter "half" bost apperence in train and export, what’s difference. when we using this parameter what should we need attention.
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 usesquantize=16(the formerhalf=True, now deprecated) to write an FP16 model for runtimes that support FP16. During training preferamp; 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 thequantizeoption 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)dopeggguy
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.
Glenn JocherUltralytics(đã chỉnh sửa)@dopeggguy
half=Trueis deprecated in favor ofquantize=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
onnxPython API to confirm the weights arefloat16; 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.
bastinj98
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 ?
NgZiming
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?
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 函数参考.1NgZiming
thanks
Glenn JocherUltralyticsGlad it helped—if you later need a C++ reference for segmentation mask decoding and preprocessing alignment, the step-by-step overview is in the Segmentation task docs.
UserI 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?
denni281
You should keep the same preprocess way between python-inference and cpp-inference.
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 desiredIf 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.
UserThank you very much!
Glenn JocherUltralyticsGlad 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);
denni281(đã 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)denni281(đã 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
Glenn JocherUltralytics(đã chỉnh sửa)@DennisJcy thanks for the update. On older releases
half=Truehad no effect on CPU ONNX exports, so the file stayed FP32. Current Ultralytics usesquantize=16(replacing the deprecatedhalf) 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.
ShuaibZyx
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)的输出格式是正确的嘛? 期待您的帮助!感谢!
xiaoqiang-l
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
ShuaibZyx
感谢您的指导!
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).
UltralyticsAssistantUltralytics
👋 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
ultralyticspackage 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 ultralyticsEnvironments
YOLO can be run in these up-to-date verified environments, with all dependencies including CUDA/CUDNN, Python, and PyTorch preinstalled:
- Notebooks with free GPU:
- Google Cloud Deep Learning VM. See GCP Quickstart Guide
- Amazon Deep Learning AMI. See AWS Quickstart Guide
- Docker Image. See Docker Quickstart Guide
Status
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!
Glenn JocherUltralyticsHello! 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=Truefor FP16 precision,dynamic=Truefor variable input sizes, oropsetto 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!
- Notebooks with free GPU:
UltralyticsAssistantUltralytics
👋 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
ultralyticspackage, 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 ultralyticsEnvironments
YOLO can be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):
- Notebooks with free GPU:
- Google Cloud Deep Learning VM. See GCP Quickstart Guide
- Amazon Deep Learning AMI. See AWS Quickstart Guide
- Docker Image. See Docker Quickstart Guide
Status
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!
Glenn JocherUltralyticsYes, you can adjust the batch size dynamically when exporting to ONNX format by using the
dynamic=Trueparameter 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.
- Notebooks with free GPU:
skyceeee
First of all, thank you for everything. Can we adjust the batch size dynamically when exporting the model as onnx?
xiaoqiang-l
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
Glenn JocherUltralytics@xiaoqiang-l to resolve the ONNX IR version compatibility issue, you can specify an older
opsetversion during export. Try addingopset=13to 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.
