ONNX Export for YOLO26 Models
ONNX (Open Neural Network Exchange) is an open model format that most inference runtimes can load. Exporting an Ultralytics YOLO26 model with format="onnx" creates a single .onnx file that runs with ONNX Runtime on CPUs, NVIDIA and AMD GPUs, Apple silicon, and Windows devices.
At a Glance#
| Property | Details |
|---|---|
format argument | onnx |
| Output | yolo26n.onnx, one file with the class names, task, and image size stored as metadata; yolo26n_int8.onnx for a calibrated quantize=8 export |
| Runs on | CPUs, NVIDIA GPUs (CUDA), AMD GPUs (MIGraphX), Apple silicon (Core ML execution provider), and Windows ML devices |
| Runtime | ONNX Runtime, or OpenCV DNN with dnn=True |
| Precision | FP32, FP16, INT8. YOLO26n is 9.9 MB in FP32, 5.0 MB in FP16, and 3.1 MB in INT8 |
| Export host | Linux, macOS, or Windows, with or without a GPU |
Ultralytics Platform can export a trained model to ONNX for you, so you do not need a local export environment.
Quickstart#
Install the Ultralytics package. The first export installs onnx, onnxslim, and onnxruntime if they are missing (onnxruntime-gpu when you export with device=0 on an NVIDIA GPU).
pip install ultralyticsFor other installation methods, see the installation guide. Then export your model and load the exported file to run inference or validate its accuracy.
from ultralytics import YOLO
# Load a YOLO26 model
model = YOLO("yolo26n.pt")
# Export the model to ONNX format
model.export(format="onnx") # creates 'yolo26n.onnx'
# Export an INT8-quantized ONNX model with calibration data
model.export(format="onnx", quantize=8, data="coco8.yaml") # creates 'yolo26n_int8.onnx'# Export a YOLO26n PyTorch model to ONNX format
yolo export model=yolo26n.pt format=onnx # creates 'yolo26n.onnx'
# Export an INT8-quantized ONNX model with calibration data
yolo export model=yolo26n.pt format=onnx quantize=8 data=coco8.yaml # creates 'yolo26n_int8.onnx'from ultralytics import YOLO
# Load the exported ONNX model
model = YOLO("yolo26n.onnx")
# Run inference
results = model("https://ultralytics.com/images/bus.jpg")# Run inference with the exported ONNX model
yolo predict model=yolo26n.onnx source='https://ultralytics.com/images/bus.jpg'from ultralytics import YOLO
# Load the exported ONNX model
model = YOLO("yolo26n.onnx")
# Validate accuracy on the COCO8 dataset
metrics = model.val(data="coco8.yaml")# Validate the exported ONNX model
yolo val model=yolo26n.onnx data=coco8.yamlSupported Tasks#
ONNX export supports all seven Ultralytics tasks with YOLOv8, YOLO11, and YOLO26 models: detection, segmentation, semantic segmentation, depth estimation, classification, pose estimation, and OBB. Semantic segmentation and depth estimation are available only with YOLO26, the only family that ships those heads.
Export Arguments#
| Argument | Type | Default | Description |
|---|---|---|---|
format | str | 'onnx' | Target format for the exported model, defining compatibility with various deployment environments. |
imgsz | int or tuple | 640 | Image size of the model input: an integer for square images or a tuple (height, width). When not passed, the export uses the size the checkpoint was trained at. The official YOLO26 checkpoints use 640 for detect, segment, pose, and semantic models pretrained on ADE20K, 1024 for OBB and semantic models pretrained on Cityscapes, 768 for depth, and 224 for classify. |
quantize | int or str | None | Quantization precision: 16 (FP16; a CPU export keeps FP32 inputs and outputs, a GPU export makes them FP16 too) or 8 (INT8 static quantization with ONNX Runtime using calibration images from data, producing an _int8.onnx model); 32/unset is FP32. A checkpoint trained with quantize=8 exports INT8 with quantize unset or 8 (other values raise an error), as Q/DQ nodes from the ranges it carries, without calibration and under the plain .onnx name. Replaces the deprecated half/int8 flags. |
data | str | None | Dataset YAML used for INT8 calibration; classification instead takes a dataset directory or a built-in dataset name. If omitted with quantize=8, Ultralytics selects the default calibration dataset for the model task; a checkpoint trained with quantize=8 needs none. |
fraction | float, int, or list | 1.0 | Calibration subset as a ratio, image count, or [train, val, test] ratios/counts. Two-item lists leave test full, while 0 skips it. |
dynamic | bool | False | Makes the batch, height, and width of the input dynamic axes, so one file accepts different batch sizes (up to the export batch with nms=True) and image sizes. See dynamic export. |
simplify | bool | True | Simplifies the model graph with onnxslim. |
opset | int | None | Specifies the ONNX opset version for compatibility with different ONNX parsers and runtimes. If not set, uses opset 18 (lower on PyTorch < 2.4), capped at the installed onnx version. See minimum opset. |
nms | bool, optional | None | Select raw output (None, default), embedded NMS (True), or the NMS-free head (False). See output format. |
batch | int | 1 | Batch size of the exported model. A static export has this batch size fixed in the input shape. With dynamic=True and nms=True, set it to the largest batch size you plan to run. |
device | str | None | Device to export on: cpu (the default, also on a machine with a GPU), 0 for a CUDA GPU, or mps for Apple silicon. It changes the result only for quantize=16, see FP16 inputs. |
For the arguments shared by all formats, see the Export mode documentation.
INT8 Quantization#
For checkpoints not trained with quantization-aware training, quantize=8 applies ONNX Runtime static quantization to Conv, Gemm, and MatMul nodes only. All other nodes stay in float, including the ops that assemble output0: box coordinates (pixels) and class scores (0 to 1) share that tensor, so a single INT8 scale for it would round every class score to zero. Weights are quantized per channel at opset 13 and above. Exclude the same nodes and set per_channel=True if you run quantize_static on an exported FP32 model yourself:
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)Here calibration_reader is an onnxruntime.quantization.CalibrationDataReader that yields {"images": array} with the batch size of the model, preprocessed as for inference: letterboxed to the export size (resized and center-cropped for classification), RGB, NCHW, float32 in 0-1.
An INT8 model keeps the input and output types of the FP32 model, so inference code written for the FP32 model runs it unchanged. INT8 makes the file three to four times smaller than FP32, but it ran slower than FP32 with ONNX Runtime on the GPU and the CPU in the benchmarks. Measure latency on your target hardware before you choose a precision.
Output Format#
The exported model takes one input named images with shape (batch, 3, height, width), RGB and scaled to 0-1. The input is float32, except for GPU exports made with quantize=16, which take float16. The nms argument sets the layout of output0. The shapes below are for a YOLO26n detection model with 80 classes exported at imgsz=640:
nms | output0 shape | Contents |
|---|---|---|
None (default) | (1, 84, 8400) | For each of the 8400 anchors: box center x, center y, width, height in input pixels, then 80 class scores. Apply NMS yourself. |
True | (1, 300, 6) | NMS runs inside the model. Each row is x1, y1, x2, y2, score, class; rows past the last detection are zeros. |
False | (1, 300, 6) | NMS-free head. Each row is x1, y1, x2, y2, score, class, with no NMS step. Filter rows by score yourself. |
The other tasks use the same input and these outputs. The shapes are for the official YOLO26n checkpoints at their default export size, with the Cityscapes checkpoint yolo26n-sem.pt for semantic segmentation:
| Task | Default imgsz | Output with nms=None | Output with nms=False or 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) |
| Semantic | 1024 | output0 (1, 1024, 1024), uint8 class index for each pixel | Same as nms=None |
| Depth | 768 | output0 (1, 1, 768, 768), depth map | Same as nms=None |
| Classify | 224 | output0 (1, 1000), class probabilities after softmax | Same as nms=None for nms=False; nms=True raises an error |
| Pose | 640 | output0 (1, 56, 8400) | output0 (1, 300, 57): 6 box values, then 17 keypoints x 3 |
| OBB | 1024 | output0 (1, 20, 21504) | output0 (1, 300, 7): center x, center y, width, height, score, class, angle (radians) |
Segmentation rows carry 32 mask coefficients after the box values, and output1 holds the mask prototypes. In FP32 and INT8 models all outputs are float32 except the semantic class map.
With nms=True, the confidence threshold conf (default 0.25), the IoU threshold iou (default 0.5), agnostic_nms, and max_det (default 300) are fixed in the graph at export. A lower conf at prediction time cannot bring back detections the graph already removed, so export again to change these values. max_det and agnostic_nms also apply to nms=False: max_det=100 gives output0 shape (1, 100, 6).
YOLO("yolo26n.onnx") reads the layout from the file metadata, so you only need these shapes when you run the model in your own code. The metadata is also available to your code as strings: names, task, imgsz, stride, batch, end2end, and 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]Deploy#
YOLO("yolo26n.onnx") runs the model with ONNX Runtime and selects the execution provider from the device argument. On a machine with a CUDA GPU, the GPU is used when device is not set.
device | Execution provider |
|---|---|
cpu | CPUExecutionProvider |
0 on an NVIDIA GPU | CUDAExecutionProvider, from the onnxruntime-gpu package that is installed on first use |
0 on an AMD ROCm GPU | MIGraphXExecutionProvider, see AMD GPU Inference with MIGraphX |
mps on Apple silicon | CoreMLExecutionProvider for nodes with static shapes; nodes with dynamic shapes run on CPUExecutionProvider |
The log line Using ONNX Runtime 1.31.1 with CUDAExecutionProvider shows which provider is active. The behavior at inference time depends on how the model was exported:
- Static export (default): the model always runs at its export
imgszandbatch, which Ultralytics reads from the file metadata. Animgszpassed topredictis ignored. Larger batches are split into chunks of the export batch size and smaller ones are padded, so any number of images works. - Dynamic export (
dynamic=True):predictaccepts anyimgszthat is a multiple of the model stride. The batch size can vary, but withnms=Trueit is limited to thebatchvalue used at export, so set that to the largest batch you plan to run. - GPU memory: with
CUDAExecutionProvider, a static model uses ONNX Runtime IO binding, which keeps input and output tensors on the GPU. A dynamic model copies them through CPU memory on every call. - CPU threads: Ultralytics limits ONNX Runtime to 8 intra-op threads, or to the number of physical CPU cores available to the process if that is lower. Set the
ORT_INTRA_OP_NUM_THREADSenvironment variable to use a different number.
Pass dnn=True to predict or val to run the model on the CPU with OpenCV DNN in place of ONNX Runtime. OpenCV DNN supports fewer export options, see Limitations and Troubleshooting.
To run the model outside the Ultralytics package, see these resources:
- ONNX Runtime Python API: load and run an ONNX model in Python.
- ONNX Runtime execution providers: hardware backends such as CUDA, TensorRT, OpenVINO, Core ML, and DirectML.
- Ultralytics examples: ONNX Runtime inference in Python, C++, and Rust, and OpenCV DNN inference in Python.
- Ultralytics Inference for Rust: the official Rust library and CLI for running the exported model without Python.
- Triton Inference Server: serve the ONNX model over HTTP or gRPC with NVIDIA Triton.
- Deploying on edge devices: ONNX Runtime tutorials for IoT and edge hardware.
Windows ML Inference#
On Windows 11 24H2 (build 26100) or newer with Python 3.10+, you can install onnxruntime-windowsml in a separate environment to let Windows ML select execution providers for your hardware. Install it instead of other ONNX Runtime builds, then use the same exported .onnx model with YOLO("model.onnx"). The backend preserves the PyTorch thread count and supplied session options, including an explicit provider policy. Without a supplied policy, Windows ML selects hardware for maximum performance, even when the PyTorch device is cpu. Measure prediction latency on your device before choosing this runtime; it is optional and is not installed by default.
On integrated GPUs that share power with the CPU, idle PyTorch threads in preprocessing and postprocessing can slow Windows ML inference. Call torch.set_num_threads(1) before predicting to reduce this. It applies to the whole process, so other PyTorch models in that process also run on one thread.
import torch
from ultralytics import YOLO
torch.set_num_threads(1) # optional, measure on your device
results = YOLO("yolo26n.onnx")("https://ultralytics.com/images/bus.jpg")AMD GPU Inference with MIGraphX#
Ultralytics runs exported ONNX models on AMD GPUs through the ONNX Runtime MIGraphX execution provider. On a ROCm (HIP) system with Python 3.11 or newer on x86-64, the ONNX backend installs the onnxruntime-ep-migraphx plugin on first use and selects MIGraphXExecutionProvider automatically with no code changes, and all YOLO26 tasks are supported. See the AMD GPU inference guide for prerequisites, installation, usage, benchmarks, and the compiled-program cache.
Limitations and Troubleshooting#
- Minimum opset: the export fails with
ONNX export requires opset>=Nwhenopsetis too low for the model. The minimum is7for classification,9for detection, segmentation, semantic segmentation, pose, and OBB,11for depth estimation and for detection, segmentation, pose, and OBB models exported withnms=True, and16for RT-DETR. - FP16 inputs: an FP16 model exported on a GPU (
quantize=16 device=0) expects FP16 input tensors in your own code. An FP16 model exported on CPU keeps FP32 inputs and outputs and converts inside the graph.YOLO()feeds the right input type to both, on GPU and on CPU. - INT8 file name:
quantize=8writesyolo26n_int8.onnxand removes the intermediate FP32 file, so load the_int8file for inference. A checkpoint trained withquantize=8is the exception: its export writes Q/DQ nodes toyolo26n.onnxand skips calibration. - INT8 calibration size: for a checkpoint not trained with
quantize=8, the export warns when the calibration split has fewer than 300 images. Calibration uses thevalsplit by default, andcoco8.yamlhas only 4 validation images, so use your own dataset for a model you plan to deploy. - Embedded NMS:
nms=Truerequires PyTorch 1.13 or newer. It raises'nms=True' is not valid for classification modelsfor classification, and is ignored with a warning for semantic segmentation, depth estimation, and RT-DETR models. - NMS-free head:
nms=Falseneeds a model with an NMS-free head, such as YOLO26 or YOLOv10. For other models, for example YOLO11, the export warnsThis model has no one-to-one head; using one-to-many outputsand writes the raw(1, 84, 8400)output. - GPU not used: if the log shows
CUDA requested but CUDAExecutionProvider not available. Using CPU..., the installed ONNX Runtime build has no working CUDA provider. Installonnxruntime-gpuin place ofonnxruntimeand check that its CUDA and cuDNN versions match your system. - OpenCV DNN: with OpenCV 4.14.0,
dnn=Trueruns default,nms=False, INT8, and GPU-exported FP16 models. It fails to load models exported withnms=True, withdynamic=True, or withquantize=16on CPU. - Dynamic shapes with NMS: when you combine
dynamic=Truewithnms=True, also setbatchto the largest batch size you plan to run. The export warns ifbatchis left at1. - Graph simplification: if
onnxslimfails, the export logs a warning and saves the model without simplification. - IR version: the exporter caps the ONNX IR version at 10 so that older ONNX Runtime releases can load the file. A default export at opset 18 has IR version 8.
For other errors, see the Common Issues guide.
Benchmarks#
YOLO26n runs up to 43% faster than YOLO11n with ONNX Runtime on CPU (Intel Xeon CPU @ 2.00 GHz). The YOLO26 model page lists the CPU ONNX speed of every model for all tasks except semantic segmentation.
Watch: Ultralytics YOLO26 vs Ultralytics YOLO11 ONNX Inference Test | ~43% Faster Inference with YOLO26 🚀
FP32, FP16, and INT8 with ONNX Runtime#
The tables below compare PyTorch with FP32, FP16, and INT8 ONNX models of every YOLO26 detection model, run with the ONNX Runtime CUDAExecutionProvider. All GPU values were measured on one NVIDIA RTX PRO 6000 Blackwell Server Edition GPU.
Milliseconds per image, lower is better. The fastest format for each model is in bold.
| 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 |
mAPval 50-95 on COCO val2017, higher is better.
| Model | PyTorch | ONNX FP32 | ONNX FP16 | ONNX INT8 |
|---|---|---|---|---|
| YOLO26n | 40.8 | 40.9 | 40.9 | 38.7 |
| YOLO26s | 48.6 | 48.5 | 48.4 | 45.6 |
| YOLO26m | 53.1 | 53.2 | 53.2 | 50.4 |
| YOLO26l | 55.0 | 54.9 | 54.8 | 52.4 |
| YOLO26x | 57.5 | 57.5 | 57.4 | 54.5 |
File size in MB. The smallest exported file for each model is in bold.
| Model | PyTorch | ONNX FP32 | ONNX FP16 | ONNX INT8 |
|---|---|---|---|---|
| YOLO26n | 5.5 | 9.9 | 5.0 | 3.1 |
| YOLO26s | 20.4 | 38.3 | 19.2 | 10.3 |
| YOLO26m | 44.3 | 82.0 | 41.0 | 21.4 |
| YOLO26l | 53.2 | 99.6 | 49.9 | 26.0 |
| YOLO26x | 118.7 | 223.3 | 111.7 | 57.2 |
YOLO26n on CPU (AMD EPYC 9655, PyTorch and ONNX Runtime on 8 threads each; a different CPU from the one used for the YOLO26 model tables):
| Metric | PyTorch | ONNX FP32 | ONNX FP16 | ONNX INT8 |
|---|---|---|---|---|
| Latency (ms/image) | 13.2 | 13.4 | 13.2 | 56.5 |
| mAPval 50-95 | 40.8 | 40.9 | 40.9 | 38.7 |
- FP16 halved the file size within 0.1 mAP of FP32 and ran up to 1.4 times faster than FP32 on the GPU, with no speedup on the CPU.
- INT8 gave the smallest file but lost 2.2 to 3.0 mAP and ran slower than FP32 on both the GPU and the CPU.
Measured with ultralytics 8.4.211, ONNX Runtime 1.30.0, PyTorch 2.15.0, and CUDA 13.2 at batch=1 on November 13, 2026. Latency is the inference stage that val reports and does not include preprocessing or postprocessing.
About ONNX#
ONNX is a community project that Facebook and Microsoft started, now developed with organizations such as IBM, Amazon, and Google. It defines a common set of operators and a file format for machine learning models, so a model trained in one framework, such as PyTorch, can run in many runtimes and on many hardware platforms.
ONNX Runtime is a cross-platform inference engine for ONNX models. Its execution providers use hardware-specific libraries to run a model on CPUs, GPUs, and dedicated accelerators.
ONNX is also the intermediate step for other Ultralytics export formats, including TensorRT, and the input for vendor NPU toolchains such as Huawei Ascend, Qualcomm QNN, and Rockchip RKNN. For the specification, see the ONNX documentation.
FAQ#
Leave
opsetunset unless your runtime needs a specific version. The exporter then uses opset18on PyTorch 2.4 and newer, opset17on PyTorch 1.13 to 2.3, a lower opset on older PyTorch versions, and never more than the installedonnxpackage supports. The default stops at 18 because the ONNX Runtime CUDA provider runs some opset 19 and newer operators, such asResize, on the CPU. Set a lower value, for exampleopset=12, when an older runtime or converter rejects the default. The value cannot go below the minimum opset for the model.It depends on the
nmsargument you exported with. A default export returns raw predictions that need confidence filtering and NMS. An export withnms=Falseornms=Truereturns up tomax_det(default 300) final detections per image asx1, y1, x2, y2, score, classin input-image pixels, so you only filter by score and scale the boxes back to the original image. OBB rows holdcenter x, center y, width, heightin place of the corners, plus the angle. See Output Format for the shapes.Read NMS-free output with ONNX Runtime# Export first: yolo export model=yolo26n.pt format=onnx nms=False import numpy as np import onnxruntime as ort session = ort.InferenceSession("yolo26n.onnx") # exported with nms=False image = np.zeros((1, 3, 640, 640), dtype=np.float32) # your preprocessed image detections = session.run(None, {"images": image})[0][0] # shape (300, 6) detections = detections[detections[:, 4] > 0.25] # keep rows above the confidence thresholdSet
dynamic=True. Theimagesinput then has shape(batch, 3, height, width)with dynamic batch, height, and width, and a default (nms=None) detectionoutput0has shape(batch, 84, anchors), so the same file accepts different batch sizes and image sizes at inference time. Withnms=True, the batch size is limited to thebatchvalue used at export. Height and width must be multiples of the model stride, 32 for the official YOLO26 checkpoints other than classification. A dynamic model does not use IO binding on CUDA and does not load in OpenCV DNN, so keep the default static export when the input size is fixed.Dynamic exportfrom ultralytics import YOLO model = YOLO("yolo26n.pt") model.export(format="onnx", dynamic=True)yolo export model=yolo26n.pt format=onnx dynamic=TrueUse ONNX when one file must run on different hardware, or when the deployment machine is not the machine you export on. Use TensorRT for the lowest latency on a specific NVIDIA GPU: a TensorRT engine is built for one GPU architecture and TensorRT version and is not portable. For other targets, see the model deployment options guide.
Comments79
Ask a question, share your results, or help someone else.
som lee How about this one from ultralytics import YOLO import os import pandas as pd from sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score, roc_curve import matplotlib.pyplot as plt import numpy as np
DATA_YAML = "datasets/traffic_light/data.yaml"
EPOCHS = 50
BATCH_SIZE = 8 IMG_SIZE = 640
DEVICE = "cpu"model = YOLO("yolov8n.pt")
print("开始训练 YOLO 模型(CPU 模式)...") results = model.train( data=DATA_YAML, epochs=EPOCHS, batch=BATCH_SIZE, imgsz=IMG_SIZE, device=DEVICE, patience=10,
save=True,
project="aiapp", name="traffic_light_train", exist_ok=True )val_metrics = results.val.results_dict
accuracy = val_metrics.get("metrics/accuracy", 0.0)
precision = val_metrics.get("metrics/precision(B)", 0.0)
recall = val_metrics.get("metrics/recall(B)", 0.0)
f1 = val_metrics.get("metrics/f1(B)", 0.0)try:
y_true = np.array([1, 0, 1, 0, 1]) y_score = np.array([0.9, 0.1, 0.8, 0.2, 0.95]) fpr, tpr, _ = roc_curve(y_true, y_score) auc = roc_auc_score(y_true, y_score) plt.figure(figsize=(8, 6)) plt.plot(fpr, tpr, label=f"AUC = {auc:.4f}") plt.plot([0, 1], [0, 1], 'k--') plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("ROC Curve (Traffic Light Detection)") plt.legend() plt.savefig("roc_curve.png") plt.close()except Exception as e: print(f"ROC 曲线绘制失败:{e}") auc = 0.0
report_content = f"""
交通信号灯检测模型训练评估报告
核心指标
- 准确率 (Accuracy): {accuracy:.4f}
- 精确率 (Precision): {precision:.4f}
- 召回率 (Recall): {recall:.4f}
- F1 分数 (F1-Score): {f1:.4f}
- AUC 值: {auc:.4f}
训练配置
- 训练轮数: {EPOCHS}
- 批次大小: {BATCH_SIZE}
- 输入图像尺寸: {IMG_SIZE}
- 训练设备: CPU
- 模型版本: YOLOv8n """
with open("metrics_report.md", "w", encoding="utf-8") as f: f.write(report_content)
best_pt_path = "runs/detect/traffic_light_train/weights/best.pt" if os.path.exists(best_pt_path): os.rename(best_pt_path, "best.pt") print("最优模型已保存为 best.pt") else: print("未找到最优模型文件!")
print("训练完成,指标报告已生成:metrics_report.md")
1
Paula DerrengerUltralyticsThe CPU training setup is fine; the issue is in the reporting code.
model.train()already returns detection metrics, so useresults.results_dict, notresults.val.results_dict. That dict includes precision, recall, mAP50, and mAP50–95, but not accuracy or F1; useresults.box.f1for per-class F1. The hard-coded ROC inputs don’t measure your model, so replace that plot with the precision–recall curve from validation (model.val(data=DATA_YAML, device=DEVICE, plots=True)). For ONNX, leave the checkpoint in place and export it withYOLO(model.trainer.best).export(format="onnx")instead of renaming a file under a hard-codedruns/detectpath.
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(edited)@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(edited)@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(edited)
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(edited)
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(edited)@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?
