开始使用

使用 Ultralytics YOLO 导出模型

Ultralytics YOLO ecosystem and integrations

简介#

训练模型的目标通常是将其部署到实际应用中。Ultralytics YOLO26 的 Export 模式可将训练好的模型转换为不同格式,以便在各种平台和设备上运行。本指南涵盖导出用法、参数、支持的格式和量化选项。

查看尚未发布的 YOLO27 预览版,了解计划支持的导出功能。



观看: 如何将 Ultralytics YOLO26 导出为不同格式以供部署 | ONNX、TensorRT、CoreML 🚀

为什么选择 YOLO26 的导出模式?#

  • 灵活性:可导出为多种格式,包括 ONNX、TensorRT、CoreML 等。
  • 性能:使用 TensorRT,GPU 速度最高可提升 5 倍;使用 ONNX 或 OpenVINO,CPU 速度最高可提升 3 倍。
  • 兼容性:可在各种硬件和软件环境中部署模型。
  • 易用性:只需一条 CLI 命令或一次 Python 调用即可导出。

使用示例#

将 YOLO26n 模型导出为其他格式,例如 ONNX 或 TensorRT。

示例
from ultralytics import YOLO

# 加载模型
model = YOLO("yolo26n.pt")  # 加载官方模型
model = YOLO("path/to/best.pt")  # 加载自定义训练的模型

# 导出模型
model.export(format="onnx")

参数#

此表列出了将 YOLO 模型导出为不同格式时可用的参数。这些参数会影响导出模型的性能、大小,以及与目标平台和环境的兼容性。

参数类型默认值说明
formatstr'torchscript'导出模型的目标格式,例如 'onnx'、'torchscript'、'engine'(TensorRT)或其他格式。每种格式都支持不同的部署环境。
namestrNone需要指定目标硬件的格式所用的硬件目标名称:Hailo 架构('hailo8'、'hailo8l'、'hailo10h'、'hailo15h'、'hailo15l';默认为 'hailo8l')、Rockchip RKNN 芯片(默认为 'rk3588')、Huawei Ascend SoC(CANN --soc_version;默认为 'Ascend310B4')、Qualcomm QNN HTP 目标(默认为 '73'),或 AMD Xilinx Versal AI Edge Series Gen 2 设备(默认为 've2-xc2ve3858',即 VEK385 评估套件)。这与其他模式使用的 project/name 运行命名组合不同。
imgszint 或 tuple640模型输入的目标图像尺寸。可以是整数(表示正方形图像,例如,640 表示 640×640),也可以是元组 (height, width)(表示指定尺寸)。如果未传入,导出时会复用已加载检查点中记录的训练尺寸:官方 YOLO26 检查点中,基于 Cityscapes(yolo26n-sem.pt)预训练的语义模型记录为 1024,深度模型记录为 768,分类模型记录为 224,OBB 模型记录为 1024,其他任务(包括基于 ADE20K(yolo26n-sem-ade20k.pt)预训练的语义模型)记录为 640;微调模型则记录其训练时使用的 imgsz。由 YAML 构建的模型没有记录训练尺寸,会使用 640。
optimizeboolFalse为 DEEPX 启用更高等级的编译器优化,以降低推理延迟,但会增加编译时间。
quantizeint 或 strNone量化精度:16(FP16,可减小模型体积,并在受支持的硬件上加快推理速度)或 8(INT8/PTQ,可进一步压缩模型,同时将精度损失降至最低,主要用于边缘设备;需要校准 data/fraction);32 会在支持的情况下选择 FP32;如果未设置,则使用 FP32,除非目标设备要求量化,例如 NXP 要求 INT8。使用 quantize=8 训练的检查点始终导出为 INT8:onnx 和 engine 无需校准,即可根据检查点包含的范围进行导出;其他格式或精度则不受支持。'w8a8' 和 'w16a16' 是 8 和 16 的别名;混合精度 'w8a16'(INT8 权重与 16 位激活:CoreML、LiteRT、QNN)和 'w8a32'(动态 INT8:LiteRT)仅受对应格式支持。此参数取代了已弃用的 half/int8 标志(half=True → 16,int8=True → 8,这些标志仍可使用,但会显示弃用警告)。仅允许使用目标格式支持的精度(见下文)。
dynamicboolFalse允许 TorchScript、ONNX、OpenVINO、TensorRT、CoreML 和 MNN 导出采用动态输入尺寸,提高处理不同图像尺寸时的灵活性。
simplifyboolTrue对于会构建 ONNX 中间图的导出,使用 onnxslim 简化该图(参见导出格式),可能提高性能并改善与推理引擎的兼容性。
opsetintNone指定用于构建 ONNX 图的导出格式的 ONNX opset 版本(参见导出格式),以兼容不同的 ONNX 解析器和运行时。如果未设置,则使用 opset 18(PyTorch < 2.4 时使用较低版本),且不高于已安装的 onnx 版本。RKNN、Ascend、AMD Xilinx、Hailo 和 RT-DETR TensorFlow 导出会设置各自的 opset。
workspacefloat 或 NoneNone设置 TensorRT 优化的最大工作区大小(单位为 GiB),以平衡内存使用量和性能。使用 None 可让 TensorRT 自动分配工作区,最大不超过设备上限。
nmsbool,可选NoneNone 会导出原始的一对多预测结果,以便进行外部 NMS(YOLO26 在 Axelera 上保留其无 NMS 检测头);True 会在支持的情况下嵌入 NMS;False 会在可用时选择无 NMS 检测头。CoreML 嵌入式 NMS 支持静态形状的 detect、segment 和 pose。请参阅端到端检测指南。
conffloatNone用于所有导出时生成 NMS 的置信度阈值:nms=True 导出、Hailo 的非端到端 detect 导出,以及 IMX 的 detect、pose 和 segment 导出;后者会在内部强制使用 nms=True。未设置时默认为 0.25。
ioufloat0.5用于所有导出时生成 NMS 的 IoU 阈值:nms=True 导出、Hailo 的非端到端 detect 导出,以及 IMX 的 detect、pose 和 segment 导出;后者会在内部强制使用 nms=True。
max_detint300导出模型输出中保留的最大检测数量。适用于所有格式的 nms=True 导出,但 CoreML 检测除外,其原生 NMS 流程没有检测数量上限;也适用于无 NMS 的端到端检测导出(YOLO26、YOLOv10,上限限制为可用锚点数量)以及 IMX 的 detect、pose 和 segment 导出。
agnostic_nmsboolFalse在通过标准 nms=True 流程生成导出时的 NMS(包括 CoreML 自带的 NMS 阶段)中启用类别无关 NMS,抑制不同类别之间得分较低且重叠的框,而不只是同一类别内的框。Hailo 或 IMX 自行生成的 NMS 配置不支持此选项,因此不会采用该设置,仍会按类别进行处理。此选项也会应用于无 NMS 的端到端导出(YOLO26、YOLOv10),但仅用于防止同一检测结果带有多个类别标签(IoU=1.0 的重复项),不会根据 IoU 阈值抑制不同的框。
batchint1指定导出模型的批量推理大小,或导出模型在 predict 模式下将并发处理的最大图像数。导出参数中不包含 batch 的格式会以批量大小 1 导出,并拒绝其他值。
devicestrNone指定用于导出的设备:GPU(device=0)、CPU(device=cpu)、Apple 芯片的 MPS(device=mps)、华为昇腾 NPU(device=npu 或 device=npu:0),或 NVIDIA Jetson 的 DLA(device=dla:0 或 device=dla:1)。TensorRT 导出会自动使用 GPU,但 TensorRT 11 不支持 DLA。使用 device=npu 的 OpenVINO INT8 导出针对 Intel NPU 进行了优化。
verboseboolFalse在 format='engine' 导出期间,将 TensorRT 构建器日志级别提高到 VERBOSE。其他导出格式会忽略此设置。
datastrNone校准数据集:YAML 路径(非分类任务)、NDJSON 路径或 URL、平台数据集 URI(ul://owner/datasets/name)或网页 URL。平台数据集需要 API 密钥和 Python 3.11+。分类任务还接受数据集目录或内置数据集名称。如果启用了 INT8 但未指定校准数据集,Ultralytics 会在需要时选择特定任务的校准数据集,否则使用模型任务的默认数据集。使用 quantize=8 训练的检查点自带 INT8 范围,无需校准数据。
splitstr'val'用于从 data 构建 INT8 量化校准数据加载器的数据集划分('train'、'val' 或 'test')。
fractionfloat、int 或 list1.0用于 INT8 校准的数据集子集:比例、图像数量或 [train, val, test] 值。1 表示完整数据划分,大于 1 的整数表示图像数量;只有可选的 test 条目接受 0/0.0 表示不使用任何数据。两项列表会保留完整的 test。

选择符合部署环境、硬件限制和性能目标的格式与设置,以便在模型大小、速度和准确性之间取得最佳平衡。

导出格式#

下表列出了 YOLO26 可用的导出格式。你可以使用 format 参数导出为任意格式,例如 format='onnx' 或 format='engine'。导出模型后,你可以直接对其进行预测或验证,例如 yolo predict model=yolo26n.onnx。导出完成后,系统会显示适用于你模型的用法示例。你也可以直接在浏览器中通过 Ultralytics Platform 导出模型,无需进行任何本地设置。

格式format 参数模型元数据参数
PyTorch-yolo26n.pt✅-
TorchScripttorchscriptyolo26n.torchscript✅imgsz, quantize, dynamic, nms, batch, device
ONNXonnxyolo26n.onnx✅imgsz, quantize, dynamic, simplify, opset, nms, batch, data, fraction, device
OpenVINOopenvinoyolo26n_openvino_model/✅imgsz, quantize, dynamic, nms, batch, data, fraction, device
TensorRTengineyolo26n.engine✅imgsz, quantize, dynamic, simplify, opset, workspace, nms, batch, data, fraction, device
CoreMLcoremlyolo26n.mlpackage✅imgsz, dynamic, quantize, nms, batch, device
Apple Core AIcoreaiyolo26n.aimodel✅imgsz, batch, quantize
TF SavedModelsaved_modelyolo26n_saved_model/✅imgsz, quantize, opset, nms, batch, data, fraction, device
TF GraphDefpbyolo26n.pb❌imgsz, opset, batch, device
TF Edge TPUedgetpuyolo26n_edgetpu.tflite✅imgsz, quantize, opset, data, fraction, device
LiteRTlitertyolo26n.tflite✅imgsz, quantize, batch, data, fraction, device
PaddlePaddlepaddleyolo26n_paddle_model/✅imgsz, batch, device
MNNmnnyolo26n.mnn✅imgsz, batch, dynamic, quantize, simplify, opset, nms, device
NCNNncnnyolo26n_ncnn_model/✅imgsz, quantize, device
IMX500imxyolo11n_imx_model/✅imgsz, quantize, data, fraction, nms, device
RKNNrknnyolo26n_rknn_model/✅imgsz, batch, name, quantize, simplify, opset, data, fraction, device
ExecuTorchexecutorchyolo26n_executorch_model/✅imgsz, quantize, batch, data, fraction, device
Axeleraaxelerayolo26n_axelera_model/✅imgsz, batch, quantize, data, fraction, device
DEEPXdeepxyolo26n_deepx_model/✅imgsz, quantize, simplify, opset, data, optimize, device
Qualcomm QNNqnnyolo26n_qnn.onnx✅imgsz, batch, name, quantize, simplify, opset, data, fraction, device
Hailohailoyolo26n_hailo_model/✅imgsz, name, quantize, data, fraction, simplify, conf, iou, device
Huawei Ascendascendyolo26n_ascend_model/✅imgsz, batch, name, quantize, opset, simplify, nms, device
AMD Xilinxxilinxyolo26n_xilinx_model/✅imgsz, name, quantize, data, fraction, opset, simplify, device
NXPnxpyolo26n_nxp.tflite✅imgsz, quantize, data, fraction, device
ST Edge AIstedgeaiyolo26n_stedgeai.onnx✅imgsz, quantize, data, fraction, opset, simplify, device

nms=None 默认输出原始结果,以便进行外部 NMS(YOLO26 在 Axelera 上保留其无 NMS 检测头)。设置 nms=False 以选择可用的无 NMS 检测头;不支持的格式会回退到其原生输出路径。上方的 nms 条目指出可通过 nms=True 嵌入 NMS 的格式。

自动安装导出依赖项

大多数格式都需要未随 ultralytics 一起安装的软件包。如果缺少某个软件包,导出时会在运行阶段通过 uv 或 pip 安装;在 Linux 上,还会通过 apt 安装 Java 等系统软件包(例如 IMX 所需的软件包)。Edge TPU 编译器会在不使用 apt 或 sudo 的情况下下载。若要保持环境不变(例如在容器镜像、CI 作业或生产服务中),请设置 YOLO_AUTOINSTALL=False。此时,导出仍会检查缺少的软件包并报告,但不会更改环境;在安装这些软件包之前,导出会失败。

export YOLO_AUTOINSTALL=False

量化选项#

使用 quantize 参数指定导出精度。字符串值不区分大小写,Ultralytics 会在导出前将可接受的别名规范化:

请求值规范值含义
8, "8", "int8", "w8a8"8INT8 权重和激活值
16, "16", "fp16", "w16a16"16FP16 权重和激活值
32, "32", "fp32", "w32a32"32导出为 FP32;与未设置时相同,但 CoreML NMS ML Programs 默认使用 FP16
"w8a16""w8a16"INT8 权重搭配 16 位激活值(FP16;LiteRT 中为 INT16)
"w8a32""w8a32"INT8 权重搭配 FP32 激活值(LiteRT 动态 INT8,无需校准)

仍接受旧版 half=True 和 int8=True 标志,但会发出弃用警告,并转发到 quantize=16 和 quantize=8。

并非每种导出格式都支持所有精度。显式请求 quantize 时,要么生成相应精度的模型,要么在导出前失败:

格式FP32(32/未设置)FP16(16)INT8(8)W8A16("w8a16")备注
PyTorch✅不适用不适用不适用原生训练/检查点格式。
TorchScript✅✅ 仅限 GPU❌❌导出 FP16 TorchScript 需要 device=0;CPU 导出为 FP32。
ONNX✅✅✅❌INT8 使用 ONNX Runtime 静态量化和校准数据。
OpenVINO✅✅✅❌INT8 使用 NNCF 训练后量化。
TensorRT✅✅✅❌INT8 需要有代表性的校准数据。
CoreML✅¹✅✅✅CoreML INT8 是权重量化;W8A16 使用 INT8 权重和 FP16 激活值。¹未设置时,NMS ML Programs 默认使用 FP16,分割/姿态 nms=True 导出始终使用 FP16。
Core AI✅✅❌❌默认使用 FP32;也可以通过 quantize=16 指定 FP16 .aimodel 资产;不支持 INT8 路径。
TF SavedModel✅❌✅❌INT8 文件会写入与 FP32 SavedModel 同级的 .tflite 目录。
TF GraphDef✅❌❌❌导出时不转换精度。
Edge TPU❌❌✅ 自动❌Edge TPU 必须使用 INT8;未设置时会自动启用。
LiteRT✅❌✅✅静态 INT8(8)和 "w8a16"(int8 权重 + int16 激活值)使用校准数据;此外还支持 "w8a32" 动态 INT8(无需校准)。quantize=16 并非单独的导出格式;FP32 模型会在运行时通过 GPU delegate 以 FP16 运行。
PaddlePaddle✅❌❌❌导出时不转换精度。
MNN✅✅✅❌INT8 是通过 MNN 转换进行的权重量化。
NCNN✅✅❌❌移动端/嵌入式运行时格式。
IMX500❌❌✅ 自动❌IMX500 需要量化;未设置时会自动启用 INT8。
RKNN❌✅ 取决于芯片✅❌RK3588/RK3576/RK3566/RK3568/RK3562/RK2118/RV1126B 支持 FP16 或 INT8;RV1103/RV1106 系列仅支持 INT8。
ExecuTorch✅❌✅❌静态 INT8(8)使用校准数据,并使检测、分割、姿态和 OBB 头保持 FP32。
Axelera❌❌✅ 自动❌Axelera 导出必须使用 INT8;未设置时会自动启用。
DEEPX❌❌✅ 自动❌DEEPX 导出必须使用 INT8;未设置时会自动启用。
Qualcomm QNN❌❌❌✅ 自动QNN HTP 导出固定使用 INT8 权重和 16 位激活值。
Hailo❌❌✅ 自动❌Hailo 导出必须使用 INT8;未设置时会自动启用。
Huawei Ascend❌✅ 自动❌❌Ascend AI Core 卷积仅接受 FP16/INT8 输入,因此 ATC 会编译为 FP16;未设置时会自动启用。
AMD Xilinx❌❌✅ 自动❌AMD Xilinx 导出需要 Vitis AI INT8(VINT8);如果未设置,此选项会自动启用。
NXP❌❌✅ 自动❌NXP i.MX95 导出需要使用 Neutron SDK 3.3.0 和 INT8;如果未设置,将自动启用。
ST Edge AI✅❌✅❌INT8 会以 ONNX Runtime QDQ 格式量化整个计算图;边界框和关键点输出会归一化到 [0, 1],以便检测头也能参与量化。

对于 INT8 和 W8A16 导出,请使用 data 提供有代表性的校准数据,例如 data="coco8.yaml",除非目标集成文档说明了默认行为或自动启用行为。LiteRT "w8a32"(动态 INT8)方案无需校准数据。

量化感知训练#

上述 INT8 导出采用训练后量化 (PTQ):系统会在对 data 执行单次校准时观察取值范围。量化感知训练(QAT)则通过在微调过程中加入伪量化,让模型学习能够适应 INT8 的权重,从而恢复仅靠校准会损失的准确性。将 quantize=8 传入 train,对预训练检查点进行微调,然后照常导出:

示例
from ultralytics import YOLO

model = YOLO("yolo26n.pt")
model.train(
    data="coco.yaml",
    quantize=8,
    epochs=5,
    batch=64,
    optimizer="AdamW",
    lr0=0.00001,
    lrf=0.1,
    warmup_epochs=0.5,
    cos_lr=True,
    mosaic=0.0,
)
model.export(format="engine", quantize=8)  # 数值范围会随检查点保存,无需校准数据

微调预训练检查点时请使用较小的学习率。QAT 初期可能会降低精度,而它相较于训练后量化的优势取决于模型、数据集和训练预算。请将导出的模型与原始检查点和训练后量化导出模型都进行验证;训练期间的伪量化得分并不能证明模型在部署时的精度。

QAT 是否值得采用,取决于导出后端自身的校准对模型的处理效果。以下数值是在 COCO val2017 上测得的 mAP50-95,使用 TensorRT 10.16 引擎、imgsz=640 和批次大小 1;每个 QAT 检查点均使用 epochs=20 patience=3 训练:

模型FP32 引擎PTQ INT8 引擎QAT INT8 引擎
yolo26n0.40320.39340.3935
yolo26s0.47940.44120.4711
yolo26m0.52690.46960.5137
yolo26l0.54400.48890.5307
yolo26x0.57010.51380.5527

在整个模型范围内,与 FP32 相比,QAT 会损失 0.008 到 0.017 的 mAP50-95;训练后量化在 yolo26n 上会损失 0.010,在较大的模型上会损失 0.038 到 0.057。因此,在校准已经表现良好的最小模型上,QAT 几乎没有收益;在其他模型上则可提升 0.030 到 0.044。换用其他数据集、导出格式或 TensorRT 版本时,结果可能不同,请自行测量。

QAT 模型需要 compile=False;ModelOpt 的量化模块不支持 torch.compile。

头部的输出层,即其 Conv 块之外的原始卷积层和线性层,会刻意保留为浮点精度,以限制 INT8 带来的精度损失;TensorRT 会为未量化的层启用 FP16 混合精度。QAT 通过 NVIDIA TensorRT 模型优化器运行,该工具会在首次使用时自动安装,而要加载生成的检查点,必须先安装该工具。这些范围会随检查点一起保存,onnx 和 engine 导出会将它们生成为 Q/DQ 节点;其他格式则会读取校准数据,并拒绝 QAT 检查点。

接下来做什么#

查阅目标部署平台的集成指南,了解如何运行导出的模型——ONNX、TensorRT、CoreML 等指南均列在完整集成列表中。

常见问题#

  • 通过 Python API 或 CLI 将 YOLO26 模型导出为 ONNX:

    示例
    from ultralytics import YOLO
    
    # 加载模型
    model = YOLO("yolo26n.pt")  # 加载官方模型
    model = YOLO("path/to/best.pt")  # 加载自定义训练的模型
    
    # 导出模型
    model.export(format="onnx")

    如需了解有关此流程的更多详情,包括处理不同输入尺寸等高级选项,请参阅 ONNX 集成指南。

  • 使用 TensorRT 导出模型可显著提升 NVIDIA GPU 上的性能。导出为 TensorRT 的 YOLO26 模型可实现最高 5 倍的 GPU 加速,因此 TensorRT 非常适合实时推理应用。

    • 灵活性:针对特定硬件配置优化模型。
    • 速度:通过高级优化实现更快的推理。
    • 兼容性:与 NVIDIA 硬件无缝集成。

    如需详细了解如何集成 TensorRT,请参阅 TensorRT 集成指南。

  • INT8 量化可以压缩模型并加快推理速度,尤其适用于边缘设备。使用 quantize=8 启用:

    示例
    from ultralytics import YOLO
    
    model = YOLO("yolo26n.pt")  # 加载模型
    model.export(format="onnx", quantize=8, data="coco8.yaml")

    INT8 量化可应用于 ONNX、TensorRT、OpenVINO、CoreML、Rockchip RKNN 和 AMD Xilinx 等格式。为获得最佳量化效果,请使用 data 参数提供一个有代表性的数据集。有关可接受的 quantize 值和支持的格式,请参阅量化选项。

  • 动态输入尺寸让导出的模型能够处理不同的图像尺寸,为不同用例提供灵活性并优化处理效率。导出为 ONNX 或 TensorRT 等格式时,启用动态输入尺寸即可让模型接受不同的输入形状。

    导出时使用 dynamic=True 标志即可启用此功能:

    示例
    from ultralytics import YOLO
    
    model = YOLO("yolo26n.pt")
    model.export(format="onnx", dynamic=True)

    动态输入尺寸特别适用于输入尺寸可能变化的应用,例如视频处理,或处理来自不同来源的图像。

    使用 YOLO() 加载的动态导出模型会以导出时的 imgsz(非正方形导出的较长边)进行预测和验证,就像 PyTorch 模型使用训练时的 imgsz 一样。传入 imgsz,即可使用其他尺寸运行模型。

  • PyTorch 模型和动态导出默认使用最小矩形填充,而静态导出会填充到完整的 imgsz,因此置信度阈值附近的检测结果可能不同。若要匹配静态导出,请使用 rect=False 进行原生推理;也可以在支持的情况下使用 dynamic=True 导出。

  • 这些导出参数对模型性能的影响最大:

    • format: 导出模型的目标格式(例如 onnx、torchscript、saved_model)。
    • imgsz: 模型输入所需的图像尺寸(例如 640 或 (height, width))。
    • quantize: 量化精度,例如 8/"int8"、16/"fp16"、32/"fp32",或支持格式中的混合权重/激活值方案 "w8a16" 和 "w8a32"(LiteRT 动态 INT8)。请参阅量化选项。
    • dynamic: 在支持动态形状的格式(如 ONNX、OpenVINO 和 TensorRT)中接受可变输入尺寸。
    • nms: 选择原始输出以进行外部 NMS(None;YOLO26 在 Axelera 上保留其无 NMS 检测头)、嵌入式 NMS(True)或无 NMS 检测头(False)。
    • device: 导出期间用于追踪模型的设备,例如用于第一块 CUDA GPU 的 cpu 或 0;FP16 TorchScript 需要 GPU。

    若要部署到特定硬件平台,可考虑使用专用导出格式,例如用于 NVIDIA GPU 的 TensorRT、用于 Apple 设备的 CoreML,或用于 Google Coral 设备的 Edge TPU。

  • 将 YOLO 模型导出为 ONNX 或 TensorRT 等格式时,输出张量结构取决于模型任务。了解这些输出对于实现自定义推理至关重要。

    对于使用 nms=False 导出的 YOLO26 检测模型(例如 yolo26n.pt),受支持的格式会生成无 NMS 输出,其形状类似 (batch_size, max_detections, 6),包含 [x1, y1, x2, y2, confidence, class_id] 个值。使用默认的 max_det=300 时,这通常是 (batch_size, 300, 6)。某些受限格式在不支持端到端算子时,会自动回退到传统输出布局。

    默认情况下(nms=None),包括 YOLO26 在内的检测模型会导出原始的一对多预测结果(YOLO26 在 Axelera 上保留其无 NMS 检测头)。输出通常是形状类似于 (batch_size, 4 + num_classes, num_predictions) 的单个张量,其中各通道表示边界框坐标和每个类别的分数;num_predictions 取决于导出时的输入分辨率(也可以是动态的)。端到端检测指南介绍了哪些格式会保留端到端输出。

    对于 分割模型(例如 yolo26n-seg.pt),通常会得到两个输出:第一个张量的形状类似 (batch_size, 4 + num_classes + mask_dim, num_predictions)(包含边界框、类别分数和掩码系数),第二个张量的形状类似 (batch_size, mask_dim, proto_h, proto_w),其中包含掩码原型,可与这些系数配合生成实例掩码。张量大小取决于导出时的输入分辨率(也可以是动态的)。

    对于 姿态模型(例如 yolo26n-pose.pt),输出张量的形状通常类似 (batch_size, 4 + num_classes + keypoint_dims, num_predictions),其中 keypoint_dims 取决于姿态规范(例如关键点数量以及是否包含置信度),而 num_predictions 取决于导出时的输入分辨率(也可以是动态的)。

    ONNX 推理示例展示了如何处理各类模型的这些输出。

  • Ultralytics 目前不为 YOLO 模型提供专用的 C++ 推理 API。对于 C++ 部署,请将模型导出为 ONNX、TensorRT、TorchScript 或 MNN 等运行时格式,然后使用相应运行时的原生 C++ API 加载导出的模型文件。

    例如,使用 yolo export model=yolo26n.pt format=onnx 导出检测模型,然后通过 ONNX Runtime C++ 运行 .onnx 文件;或者使用 format=engine 导出,再从 TensorRT C++ 应用运行 TensorRT 引擎。使用自定义 C++ 后处理时,请确保输出张量布局与你的任务和导出设置相匹配;默认的 YOLO26 检测导出会返回需要外部 NMS 处理的原始预测张量。使用 nms=False 导出无 NMS 检测结果,其形状为 (batch, max_det, 6);或者使用 nms=True 在受支持的格式中嵌入 NMS。

  • 使用 quantize=16(FP16)或 quantize=8(INT8)导出时,大多数张量都会转换为较低精度,以减小模型体积并提升性能。但是,启用 nms=False 时,后处理(包括类别索引)会直接嵌入导出的计算图中。

    output0 张量包含类别索引,这些索引在内部以浮点数表示。由于尾数精度有限,FP16 无法可靠地表示大于 2048 的整数值。为避免潜在的精度损失或类别 ID 错误,output0 会有意保留为 FP32。

    如果需要完整的 FP16 输出,请在 GPU 上使用 nms=None 导出,并在外部执行后处理。无论如何,CPU 上的 FP16 ONNX 导出都会保留 FP32 输入和输出,仅转换内部计算图。

评论447

提出问题、分享结果,或帮助其他人。

  1. yubaobao-GPUGitHub

    你好,请问为什么我转onnx的时候会显示end2end参数非法 (ywh_26) root@ai-avcon:/data/ywh_folder/yolo/yolo26# python to_onnx.py WARNING ⚠️ Ultralytics settings reset to default values. This may be due to a possible problem with your settings or a recent ultralytics package update. View Ultralytics Settings with 'yolo settings' or at '/root/.config/Ultralytics/settings.json' Update Settings with 'yolo settings key=value', i.e. 'yolo settings runs_dir=path/to/dir'. For help see https://docs.ultralytics.com/quickstart/#ultralytics-settings. Traceback (most recent call last): File "/data/ywh_folder/yolo/yolo26/to_onnx.py", line 12, in model.export( File "/data/ywh_folder/yolo/yolo26/ultralytics/engine/model.py", line 710, in export return Exporter(overrides=args, _callbacks=self.callbacks)(model=self.model) File "/data/ywh_folder/yolo/yolo26/ultralytics/engine/exporter.py", line 312, in init self.args = get_cfg(cfg, overrides) File "/data/ywh_folder/yolo/yolo26/ultralytics/cfg/init.py", line 308, in get_cfg check_dict_alignment(cfg, overrides) File "/data/ywh_folder/yolo/yolo26/ultralytics/cfg/init.py", line 505, in check_dict_alignment raise SyntaxError(string + CLI_HELP_MSG) from e SyntaxError: 'end2end' is not a valid YOLO argument.

    我是用的8.4.6版本的ultralytics

    1
    1. Glenn JocherUltralytics

      ultralytics==8.4.6 还不支持 end2end 这个导出参数(它是给支持 NMS-free 的新模型/新版本用的),所以你这边要么把 model.export() 里的 end2end=... 去掉,要么升级到最新 Ultralytics;另外你的报错路径显示实际导入的是本地仓库 .../yolo26/ultralytics,建议先跑一次 yolo checks 并把文本输出贴上来确认是否存在多套安装/路径冲突(参数列表可参考 Model.export() 参考文档)。

      pip install -U ultralytics
      yolo checks
  2. qcnameGitHub

    您好,使用.pt和导出为.onnx进行yolov8模型的图片中目标检测时,参数设置一致,但是最终检测框数量,位置不完全一致。比如.onnx比.pt多画一个或者检测到.pt检测不出来的类别,请问是什么问题导致的呢?

    1
    1. Paula DerrengerUltralytics

      @nacenace 您好,

      感谢您提出这个问题!在导出模型时遇到检测结果不一致的情况确实令人困惑。以下是一些可能的原因和解决方法:

      1. 版本一致性:请确保您使用的是最新版本的 torch 和 ultralytics。您可以通过以下命令进行升级:

        pip install --upgrade torch ultralytics
      2. 模型导出参数:导出为 ONNX 时,某些参数可能会影响模型的行为。请确保在导出时使用了适当的参数,例如 dynamic、simplify 等。以下是一个导出为 ONNX 的示例:

        from ultralytics import YOLO
        
        # 加载模型
        model = YOLO("path/to/best.pt")
        
        # 导出模型
        model.export(format="onnx", dynamic=True, simplify=True)
      3. 推理设置:在进行推理时,确保使用相同的图像尺寸和其他推理参数。以下是一个推理示例:

        # 使用 .pt 模型进行推理
        results_pt = model.predict(source="path/to/image.jpg", imgsz=640)
        
        # 使用 .onnx 模型进行推理
        model_onnx = YOLO("path/to/model.onnx")
        results_onnx = model_onnx.predict(source="path/to/image.jpg", imgsz=640)
      4. 最小可复现示例:为了更好地帮助您解决问题,请提供一个最小可复现的代码示例。您可以参考我们的最小可复现示例指南来创建一个示例。

      请尝试以上建议,如果问题仍然存在,请提供更多详细信息和代码示例,以便我们进一步调查。

      希望这些信息对您有所帮助!如果有任何其他问题,请随时告知。

      祝好, Ultralytics 团队

    2. Glenn JocherUltralytics

      您好,感谢您的反馈。导出为不同格式(如ONNX)时,检测结果可能会有所不同,通常是由于模型转换过程中精度损失或推理引擎差异导致的。建议您确保使用最新版本的Ultralytics和相关库,并尝试调整导出参数,如dynamic=True或half=True。更多详情请参考导出文档。

  3. Ibraheem-AhmadGitHub

    Hello! Would anyone be able to tell me why this code does not work: model.export(format=='onnx', int8 = True, dyamic = True, imgsz = (width,height))

    the error I get is "TypeError: Model.export() takes 1 positional argument but 2 were given"

    1
    1. Glenn JocherUltralytics

      @Ibraheem-Ahmad hello! It looks like there's a small typo in your code that's causing the issue. In Python, when you're calling a function and passing arguments, you should use = for assignment rather than ==, which is used for comparison. Also, there's a typo in dyamic, it should be dynamic. Here's the corrected line of code:

      model.export(format='onnx', int8=True, dynamic=True, imgsz=(width, height))

      This should work without any errors. If you have any more questions or run into issues, feel free to ask. Happy coding! 😊

    2. Glenn JocherUltralytics

      @Aisha-Hassan1 hey there! 🌟 To pass multiple pictures for processing, you can use a directory, list, or wildcard as your source. For example:

      # For a directory full of images
      model.predict(source='path/to/images/') 
      
      # For specific images
      model.predict(source=['path/to/image1.jpg', 'path/to/image2.jpg'])
      
      # Using a wildcard
      model.predict(source='path/to/images/*.jpg')

      As for how many pictures, there's no strict limit—it depends on your system's capabilities. Just ensure your images comply with the model's input size, which you can adjust with the imgsz parameter if necessary. Happy coding! 😊

      1
    3. Aisha-Hassan1GitHub

      When I don't put batch_size, the result is batch_size=1 .... code => [ Ultralytics YOLOv8.1.29 🚀 Python-3.11.5 torch-2.2.1+cpu CPU (Intel Core(TM) i5-3320M 2.60GHz) YOLOv8n summary (fused): 168 layers, 3151904 parameters, 0 gradients, 8.7 GFLOPs

      PyTorch: starting from 'yolov8n.pt' with input shape (1, 3, 640, 640) BCHW and output shape(s) (1, 84, 8400) (6.2 MB)

      ONNX: starting export with onnx 1.15.0 opset 17... ONNX: export success ✅ 2.1s, saved as 'yolov8n.onnx' (12.1 MB)

      Export complete (5.9s) Results saved to C:\Users\shosho Predict: yolo predict task=detect model=yolov8n.onnx imgsz=640 int8 Validate: yolo val task=detect model=yolov8n.onnx imgsz=640 data=coco.yaml int8 Visualize: https://netron.app

      ] .........batch_size = 4 model.export(format='onnx', int8=True, dynamic=True, batch=batch_size) res=>[Ultralytics YOLOv8.1.29 🚀 Python-3.11.5 torch-2.2.1+cpu CPU (Intel Core(TM) i5-3320M 2.60GHz) YOLOv8n summary (fused): 168 layers, 3151904 parameters, 0 gradients, 8.7 GFLOPs

      PyTorch: starting from 'yolov8n.pt' with input shape (4, 3, 640, 640) BCHW and output shape(s) (4, 84, 8400) (6.2 MB)

      ONNX: starting export with onnx 1.15.0 opset 17... ONNX: export success ✅ 3.6s, saved as 'yolov8n.onnx' (12.1 MB)

      Export complete (11.2s) Results saved to C:\Users\shosho Predict: yolo predict task=detect model=yolov8n.onnx imgsz=640 int8 Validate: yolo val task=detect model=yolov8n.onnx imgsz=640 data=coco.yaml int8 Visualize: https://netron.app 'yolov8n.onnx'] Is this the number of photos I should enter?

    4. Aisha-Hassan1GitHub

      import cv2 from ultralytics import YOLO

      model = YOLO('yolov8n.pt') model.export(format='onnx', int8=True, dynamic=True) predicted_images = model.predict(source='G:/img') for i, result in enumerate(predicted_images): print(result) image = result.orig_img save_path = f'predicted_image_{i}.jpg'
      cv2.imwrite(save_path, image)
      print(f"Done{save_path}")

      The code works for me and saves the images, but I have two questions

      1- How will i deal with an onnx file with JS and send it an array of images? 2- I want to export yolov5n-seg.pt to onnx to put a mask on the images?

    5. Glenn JocherUltralytics

      @Aisha-Hassan1 hey there! 😊

      1. To deal with an ONNX file in JS and send it an array of images, you can use onnxjs for browser environments or onnxruntime-node for Node.js. Here’s an example using onnxjs:
      async function runModel(inputImages) {
        const session = new onnx.InferenceSession();
        await session.loadModel("path/to/your/model.onnx");
        
        const inputTensors = inputImages.map(image => // convert your images to tensors);
        
        // Assuming you're working with one input named 'input'
        const feeds = { input: inputTensors };
        const results = await session.run(feeds);
        
        return results;
      }
      1. For exporting yolov5n-seg.pt to ONNX with a mask, ensure your model supports segmentation tasks, then follow similar steps to exporting a detection model but make sure the output includes the segmentation masks. Your export code seems fine, but replace yolov8n.pt with yolov5n-seg.pt. Check model compatibility and output processing as per your needs!

      If you need any more guidance, don't hesitate to ask. Have fun coding! ✨

      1
    6. Aisha-Hassan1GitHub

      The yolov5n-seg.pt export part show this error........[ ModuleNotFoundError Traceback (most recent call last) File G:\anaconda3\Lib\site-packages\ultralytics\nn\tasks.py:714, in torch_safe_load(weight) 707 with temporary_modules( 708 { 709 "ultralytics.yolo.utils": "ultralytics.utils", (...) 712 } 713 ): # for legacy 8.0 Classify and Pose models --> 714 ckpt = torch.load(file, map_location="cpu") 716 except ModuleNotFoundError as e: # e.name is missing module name

      File G:\anaconda3\Lib\site-packages\torch\serialization.py:1026, in load(f, map_location, pickle_module, weights_only, mmap, **pickle_load_args) 1025 raise pickle.UnpicklingError(UNSAFE_MESSAGE + str(e)) from None -> 1026 return _load(opened_zipfile, 1027 map_location, 1028 pickle_module, 1029 overall_storage=overall_storage, 1030 **pickle_load_args) 1031 if mmap:

      File G:\anaconda3\Lib\site-packages\torch\serialization.py:1438, in _load(zip_file, map_location, pickle_module, pickle_file, overall_storage, **pickle_load_args) 1437 unpickler.persistent_load = persistent_load -> 1438 result = unpickler.load() 1440 torch._utils._validate_loaded_sparse_tensors()

      File G:\anaconda3\Lib\site-packages\torch\serialization.py:1431, in _load..UnpicklerWrapper.find_class(self, mod_name, name) 1430 mod_name = load_module_mapping.get(mod_name, mod_name) -> 1431 return super().find_class(mod_name, name)

      ModuleNotFoundError: No module named 'models'

      The above exception was the direct cause of the following exception:

      TypeError Traceback (most recent call last) Cell In[2], line 1 ----> 1 model = YOLO('yolov5n-seg.pt')

      File G:\anaconda3\Lib\site-packages\ultralytics\models\yolo\model.py:23, in YOLO.init(self, model, task, verbose) 20 self.dict = new_instance.dict 21 else: 22 # Continue with default YOLO initialization ---> 23 super().init(model=model, task=task, verbose=verbose)

      File G:\anaconda3\Lib\site-packages\ultralytics\engine\model.py:142, in Model.init(self, model, task, verbose) 140 self._new(model, task=task, verbose=verbose) 141 else: --> 142 self._load(model, task=task) 144 self.model_name = model

      File G:\anaconda3\Lib\site-packages\ultralytics\engine\model.py:229, in Model._load(self, weights, task) 227 suffix = Path(weights).suffix 228 if suffix == ".pt": --> 229 self.model, self.ckpt = attempt_load_one_weight(weights) 230 self.task = self.model.args["task"] 231 self.overrides = self.model.args = self._reset_ckpt_args(self.model.args)

      File G:\anaconda3\Lib\site-packages\ultralytics\nn\tasks.py:788, in attempt_load_one_weight(weight, device, inplace, fuse) 786 def attempt_load_one_weight(weight, device=None, inplace=True, fuse=False): 787 """Loads a single model weights.""" --> 788 ckpt, weight = torch_safe_load(weight) # load ckpt 789 args = {**DEFAULT_CFG_DICT, **(ckpt.get("train_args", {}))} # combine model and default args, preferring model args 790 model = (ckpt.get("ema") or ckpt["model"]).to(device).float() # FP32 model

      File G:\anaconda3\Lib\site-packages\ultralytics\nn\tasks.py:718, in torch_safe_load(weight) 716 except ModuleNotFoundError as e: # e.name is missing module name 717 if e.name == "models": --> 718 raise TypeError( 719 emojis( 720 f"ERROR ❌️ {weight} appears to be an Ultralytics YOLOv5 model originally trained " 721 f"with https://github.com/ultralytics/yolov5.\nThis model is NOT forwards compatible with " 722 f"YOLOv8 at https://github.com/ultralytics/ultralytics." 723 f"\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to " 724 f"run a command with an official YOLOv8 model, i.e. 'yolo predict model=yolov8n.pt'" 725 ) 726 ) from e 727 LOGGER.warning( 728 f"WARNING ⚠️ {weight} appears to require '{e.name}', which is not in ultralytics requirements." 729 f"\nAutoInstall will run now for '{e.name}' but this feature will be removed in the future." 730 f"\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to " 731 f"run a command with an official YOLOv8 model, i.e. 'yolo predict model=yolov8n.pt'" 732 ) 733 check_requirements(e.name) # install missing module

      TypeError: ERROR yolov5n-seg.pt appears to be an Ultralytics YOLOv5 model originally trained with https://github.com/ultralytics/yolov5. This model is NOT forwards compatible with YOLOv8 at https://github.com/ultralytics/ultralytics. Recommend fixes are to train a new model using the latest 'ultralytics' package or to run a command with an official YOLOv8 model, i.e. 'yolo predict model=yolov8n.pt'

      ] part of the code in JS ...[

      ] show erro .........Access to fetch at 'file:///G:/pg_betch/yolov8n.onnx' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted. session.ts:61 GET file:///G:/pg_betch/yolov8n.onnx net::ERR_FAILED

      (anonymous) @ session.ts:61 (anonymous) @ onnx.min.js:14 (anonymous) @ onnx.min.js:14 a @ onnx.min.js:14 Promise.then (async) s @ onnx.min.js:14 (anonymous) @ onnx.min.js:14 r @ onnx.min.js:14 (anonymous) @ session.ts:48 t.event @ instrument.ts:294 (anonymous) @ session.ts:48 (anonymous) @ onnx.min.js:14 (anonymous) @ onnx.min.js:14 (anonymous) @ onnx.min.js:14 r @ onnx.min.js:14 e.loadModel @ onnx.min.js:14 t.loadModel @ inference-session-impl.ts:27 runModel @ index.html:11 (anonymous) @ index.html:27 session.ts:61

         Uncaught (in promise) TypeError: Failed to fetch
      at e.<anonymous> (session.ts:61:34)
      at onnx.min.js:14:255680
      at Object.next (onnx.min.js:14:255785)
      at a (onnx.min.js:14:254499)

      (anonymous) @ session.ts:61 (anonymous) @ onnx.min.js:14 (anonymous) @ onnx.min.js:14 a @ onnx.min.js:14 Promise.then (async) (anonymous) @ index.html:27

    7. Glenn JocherUltralytics

      Hey there! It looks like you're encountering two different issues here:

      1. Using an ONNX model with JavaScript: For running ONNX models in a browser with JavaScript, you're on the right track with onnx.js. However, loading local files directly can lead to CORS policy violations, as seen in your error. To fix this, serve your ONNX model from a server or use a cloud storage URL with proper CORS settings. Ensure your server or cloud storage is configured to allow such requests.

      2. Exporting YOLOv5n-seg.pt to ONNX: The error suggests that the file yolov5n-seg.pt might be confused as a YOLOv5 model and you're trying to load it using YOLOv8, which leads to compatibility issues. If yolov5n-seg.pt is indeed a YOLOv5 model, ensure you're using the correct toolchain for export. For segmentation models with YOLOv8 (assuming yolov8n-seg.pt exists and it's what you meant), the export command you've used seems correct. Make sure you're within the Ultralytics ecosystem for YOLOv8 and its segmentation models, and check if there's a typo in the filename or a version mismatch. Correct model paths and compatible Ultralytics YOLO versions are crucial.

      For working with segmentation models and applying masks to images post-export, you'll typically handle the output tensors from the ONNX model to extract segmentation masks and overlay them on the original images. This step will heavily depend on the output structure of your specific model.

      Hope that helps! Keep experimenting, and feel free to reach out if you hit more snags. 😊

      1
    8. Aisha-Hassan1GitHub

      Can you help me how to handle the output tensors from the ONNX model to extract segmentation masks and overlay them on the original images ?

    9. Glenn JocherUltralytics

      Hey there! 🙌 To handle output tensors from an ONNX model for segmentation tasks, you'll typically:

      1. Run the Model: First, feed your input image to the ONNX model using your preferred ONNX runtime environment. This step returns the output tensors.

      2. Process Output Tensors: For segmentation models, the output tensor usually represents either a pixel-wise class prediction or a set of masks for each detected object. You'll need to decode these tensors to get the segmentation masks. The exact processing will depend on your model's output format.

      3. Overlay Masks on Original Images: Once you have the segmentation masks, you can overlay them on your original images. Here's a quick example in Python, assuming you have a mask:

      import cv2
      import numpy as np
      
      # Assuming 'image' is your original image and 'mask' is the segmentation mask
      # Ensure the mask is a binary mask (0 or 1) where 1 represents the segmented object
      overlay = cv2.addWeighted(image, 1, np.dstack((mask, mask, mask)) * 255, 0.5, 0)
      cv2.imwrite('segmented_image.jpg', overlay)

      For exporting yolov5n-seg.pt or similar models to ONNX, you seem to have encountered an incompatibility issue indicating that you might be trying to load a YOLOv5 model with a YOLOv8 setup. Ensure you're using the proper version and tools for your specific YOLO model. YOLOv8 now has its dedicated ecosystem and might not directly support models trained with previous versions without conversion or specific handling.

      If YOLOv5 segmentation is what you need and you're dealing with yolov5n-seg.pt, consider checking the YOLOv5 documentation for the precise export guidance. For segmentation tasks, you might need to adjust your approach tailored to the model's specific output layer design.

      Hope this helps! Let me know if there's anything else I can do for you. 😊

    10. Aisha-Hassan1GitHub

      Thank you very much for your help 1-Using an ONNX model with JavaScript:

      Document
      <script>
          const labels = [
          "person",
          "bicycle",
          "car",
          "motorcycle",
          "airplane",
          "bus",
          "train",
          "truck",
          "boat",
          "traffic light",
          "fire hydrant",
          "stop sign",
          "parking meter",
          "bench",
          "bird",
          "cat",
          "dog",
          "horse",
          "sheep",
          "cow",
          "elephant",
          "bear",
          "zebra",
          "giraffe",
          "backpack",
          "umbrella",
          "handbag",
          "tie",
          "suitcase",
          "frisbee",
          "skis",
          "snowboard",
          "sports ball",
          "kite",
          "baseball bat",
          "baseball glove",
          "skateboard",
          "surfboard",
          "tennis racket",
          "bottle",
          "wine glass",
          "cup",
          "fork",
          "knife",
          "spoon",
          "bowl",
          "banana",
          "apple",
          "sandwich",
          "orange",
          "broccoli",
          "carrot",
          "hot dog",
          "pizza",
          "donut",
          "cake",
          "chair",
          "couch",
          "potted plant",
          "bed",
          "dining table",
          "toilet",
          "tv",
          "laptop",
          "mouse",
          "remote",
          "keyboard",
          "cell phone",
          "microwave",
          "oven",
          "toaster",
          "sink",
          "refrigerator",
          "book",
          "clock",
          "vase",
          "scissors",
          "teddy bear",
          "hair drier",
          "toothbrush",
          ];
          const modelName = "yolov8n-seg.onnx";
          const modelInputShape = [4, 3, 640, 640];
          let mySession;
          const useState = (defaultValue) => {
              let value = defaultValue;
              const getValue = () => value;
              const setValue = (newValue) => (value = newValue);
              return [getValue, setValue];
            };
            const numClass = labels.length;
            const [session, setSession] = useState(null);
         
            cv["onRuntimeInitialized"] = async () => {
              // create session
              const [yolov8] = await Promise.all([
                  ort.InferenceSession.create(modelName),
              ]);
      
              mySession = setSession({ net: yolov8 });
      
              const inputImages = [
                  "img/bb.jpg",
                  "img/iam.jpg"
                  
              ];
      
             const inputTensors = await Promise.all(inputImages.map(async (imageUrl) => {
                  const response = await fetch(imageUrl);
                  if (!response.ok) {
                      throw new Error(`Failed to fetch image: ${imageUrl}`);
                  }
                  const blob = await response.blob();
                  const image = await cv.imreadAsync(blob); 
                  const tensor = cv.tensorFromImageData(image);
                  image.delete();
                  return tensor;
              }));
      
              // Assuming you're working with one input named 'input'
              const feeds = { input: inputTensors };
              const results = await yolov8.run(feeds);
              console.log(results);
      
              // Assuming you need to handle the results here
              // Handle results...
      
              
             
      
              
          };
          </script>

      problem of code In partial convert your images to tensors

      Do you have a solution to the problem?

    11. Glenn JocherUltralytics

      @Aisha-Hassan1 hey there! Thanks for reaching out 🌟. It looks like you're having a bit of trouble converting images to tensors in your JavaScript code while working with an ONNX model.

      For the conversion part, using OpenCV.js to convert images to tensors might not directly align with the expected input format for ONNX models. Instead, you'll typically need to preprocess the images into a format that matches the expected input tensor of your ONNX model, including resizing images and normalizing pixel values if required.

      A simplified approach (without OpenCV.js) could involve using standard JavaScript or browser APIs to load and preprocess your images before converting them into tensors. Unfortunately, detailed code for image preprocessing highly depends on the specific requirements of your ONNX model, such as input dimensions and pixel-value scaling.

      Regarding overlaying segmentation masks (like from yolov5n-seg.pt exported as ONNX) onto images using JavaScript:

      1. Once you have your segmentation output from the model, it'll typically be a tensor where each value corresponds to a class prediction per pixel or a probability distribution across classes for each pixel.
      2. Convert this segmentation mask tensor back into an image format, applying any necessary thresholding to identify your classes of interest.
      3. Overlay this processed mask onto your original image. You can achieve this by manipulating the DOM directly in JavaScript or using canvas operations to blend images.

      Both the conversion and overlay steps are somewhat intricate and depend heavily on the details of your model's output format as well as the web environment you're working in (pure JavaScript in the browser, Node.js, etc.).

      For precise assistance, we might need more details on the output format of your segmentation model and the specific environment you're working in. Meanwhile, the Ultralytics Docs and YOLOv8's export mode provide a great starting point for deploying models efficiently across various platforms 🚀.

      Hope this helps a bit! Keep exploring and don't hesitate to share more details or ask further questions. Happy coding!

    12. Aisha-Hassan1GitHub

      I would like answers to two other questions, please

      1- If I want to enter an array of images in js to use batch, should I export onnx this way ? model.export(format='onnx', int8=True, dynamic=True) or Do I have to limit the number of photos like this? model.export(format='onnx', int8=True, dynamic=True, batch =number of images)

      2- I want to run onnx in the GPU, what should I do?

    13. Glenn JocherUltralytics

      Hey there! 😀 Glad you're exploring YOLOv8's capabilities. Let's dive into your questions:

      1. Array of Images for Batch Inference in JS:

        • Utilizing dynamic=True during export is the way to go if you plan on varying the batch size dynamically. There's no need to specify the batch size at export time for ONNX models, as dynamic=True enables the model to handle variable batch sizes. So, your first export command is spot on:
          model.export(format='onnx', int8=True, dynamic=True)
        • This setup allows you to feed different batch sizes at runtime without having to re-export the model for each specific batch size.
      2. Running ONNX on GPU:

        • To run ONNX models on the GPU, ensure you have an ONNX runtime that supports GPU inference, such as ONNX Runtime-GPU. When initializing your inference session in your code, specify the GPU device. Here's a quick example if you're using Python:
          import onnxruntime as ort
          
          # Specify the GPU device
          ort_session = ort.InferenceSession("your_model.onnx", providers=['CUDAExecutionProvider'])
          
          # Now you can run inference with ort_session and it should use the GPU
        • For JavaScript, the availability of GPU inference might be limited and typically runs on the CPU. ONNX.js primarily supports WebGL for some level of GPU acceleration in the browser, but true GPU computing might not be feasible directly in JS as it depends on the browser's capabilities and the onnxruntime-web package's support.

      I hope this clears up your questions! Keep experimenting with YOLOv8, and don't hesitate to reach out if you have more questions. Happy coding! 🚀

    14. Aisha-Hassan1GitHub

      thank you so much code

      ![](img/bb.jpg) ![](img/iam.jpg)
      <script>
          var inputTensors=[];
          const modelInputShape = [1, 3, 640, 640];
          const divStride = (stride, width, height) => {
              if (width % stride !== 0) {
                if (width % stride >= stride / 2)
                  width = (Math.floor(width / stride) + 1) * stride;
                else width = Math.floor(width / stride) * stride;
              }
              if (height % stride !== 0) {
                if (height % stride >= stride / 2)
                  height = (Math.floor(height / stride) + 1) * stride;
                else height = Math.floor(height / stride) * stride;
              }
              return [width, height];
            };
          const preprocessing = (source, modelWidth, modelHeight, stride = 32) => {
              //const mat = cv.imread(source); // read from img tag
              const mat = cv.imread(document.getElementById(source));
              const matC3 = new cv.Mat(mat.rows, mat.cols, cv.CV_8UC3); // new image matrix
              cv.cvtColor(mat, matC3, cv.COLOR_RGBA2BGR); // RGBA to BGR
          
              const [w, h] = divStride(stride, matC3.cols, matC3.rows);
              cv.resize(matC3, matC3, new cv.Size(w, h));
          
              // padding image to [n x n] dim
              const maxSize = Math.max(matC3.rows, matC3.cols); // get max size from width and height
              const xPad = maxSize - matC3.cols, // set xPadding
                xRatio = maxSize / matC3.cols; // set xRatio
              const yPad = maxSize - matC3.rows, // set yPadding
                yRatio = maxSize / matC3.rows; // set yRatio
              const matPad = new cv.Mat(); // new mat for padded image
              cv.copyMakeBorder(
                matC3,
                matPad,
                0,
                yPad,
                0,
                xPad,
                cv.BORDER_CONSTANT,
                [0, 0, 0, 255]
              ); // padding black
          
              const input = cv.blobFromImage(
                matPad,
                1 / 255.0, // normalize
                new cv.Size(modelWidth, modelHeight), // resize to model input size
                new cv.Scalar(0, 0, 0),
                true, // swapRB
                false // crop
              ); // preprocessing image matrix
          
              // release mat opencv
              mat.delete();
              matC3.delete();
              matPad.delete();
              
          
              return [input, xRatio, yRatio];
            };
          const inputImages = [
          "image1",
          "image2"
          ];
          async function runModel(inputImages) {
              const [yolov8] = await Promise.all([
                  ort.InferenceSession.create("yolov8n-seg.onnx")
              ]);
              const [modelWidth, modelHeight] = modelInputShape.slice(2);
              for(let i=0 ; i<inputImages.length; i++){
                  const [input, xRatio, yRatio] = preprocessing(
                  inputImages[i],
                  modelWidth,
                  modelHeight
                  );
                  const tensor = new ort.Tensor("float32", input.data32F, modelInputShape);
                  inputTensors[i]=tensor;
                  console.log(inputTensors)
              }
              const { output0, output1 } = await yolov8.run({images:inputTensors});
              console.log(output0);
          };
          runModel(inputImages)
          </script>

      In the runModel function, I send it an array of images, and it makes an error in part

      const { output0, output1 } = await yolov8.run({images:inputTensors})

      Because inputTensors is an array

      This is the form of error Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'byteLength') at t.run (wasm-core-impl.ts:219:31) at t.run (proxy-wrapper.ts:215:17) at t.OnnxruntimeWebAssemblySessionHandler.run (session-handler.ts:84:15) at i.run (inference-session-impl.js:94:44) at runModel (main.html:94:55) t.run@wasm-core-impl.ts:219 t.run@proxy-wrapper.ts:215 run@session-handler.ts:84 run@inference-session-impl.js:94 runModel@main.html:94 await in runModel (async) (anonymous)@main.html:97

      What is the solution to enter an array of images into the model?

    15. Glenn JocherUltralytics

      Hey there! Thanks for bringing this to our attention 🌟. When using an array of objects for inference with YOLOv8 in JavaScript, you'd typically batch the input images before sending them to the model. If you find that only the first object in your array is being processed, it might be related to how you're structuring the input data for the ONNX model.

      For batch processing, ensure all your images are preprocessed (resized and normalized) correctly and then stacked into a single tensor that matches the ONNX model's expected input shape. The shape for a batch of images usually follows the format [batch_size, channels, height, width]. It sounds like you might need to adjust how you're constructing inputTensors to fit this expectation.

      Regarding running ONNX on a GPU, note that ONNX.js primarily targets web environments where direct access to the GPU through Web APIs (e.g., WebGL) might not fully leverage all GPU capabilities like a desktop environment would. If you're using ONNX in a server-side JavaScript environment (like with Node.js and onnxruntime-node), specifying the GPU for inference would depend on the capabilities of your specific backend setup and the ONNX runtime you're using. Onnxruntime-web currently doesn't offer direct control over executing models on GPU vs. CPU—it automatically utilizes available hardware acceleration like WebGL.

      Here's a simplified structure for how you might handle batching:

      async function runBatchModel(session, inputTensors) {
          // Ensure inputTensors is a batched tensor of the right shape
          const results = await session.run({input: inputTensors});
          // Process results...
      }

      Remember to adjust the runBatchModel function based on how your specific model expects inputs. Happy coding and don't hesitate to reach out if you have more questions! 😊

    16. Glenn JocherUltralytics

      @Aisha-Hassan1 hey there! 🌟 The inputTensors is expected to be an array of ort.Tensor objects where each tensor represents an image that has been correctly processed (resized, normalized) to match the input shape that your model expects.

      For instance, if you're preprocessing images for batch inference, each ort.Tensor would hold image data shaped according to the model's input specifications, typically [batch_size, channels, height, width]. If your model expects a single image of shape [1, 3, 640, 640], preprocess each image accordingly, and then stack them into an array.

      Here's a quick example on how you might prepare a single image:

      const imageTensor = new ort.Tensor("float32", processedImageData, [1, 3, height, width]);

      And when you have multiple images prepared as tensors (imageTensor1, imageTensor2, ...), you can put them in an array:

      const inputTensors = [imageTensor1, imageTensor2];

      Make sure each tensor in inputTensors follows the model's expected input shape. Keep up the great work with ONNX models, and happy coding! 😄

    17. Aisha-Hassan1GitHub

      erro ... wasm-core-impl.ts:219 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'byteLength') at t.run (wasm-core-impl.ts:219:31) at t.run (proxy-wrapper.ts:215:17) at t.OnnxruntimeWebAssemblySessionHandler.run (session-handler.ts:84:15) at i.run (inference-session-impl.js:94:44) at runModel (main.html:96:55) ........

      when inputTensors => array const inputTensors = [imageTensor1, imageTensor2];

    18. Glenn JocherUltralytics

      Hey there! 👋 When converting a YOLOv8 model for batch processing, you generally don't need to specify the batch size during export, especially with dynamic batching enabled. 🔄 Your export command:

      model.export(format='onnx', int8=True, dynamic=True)

      is perfectly fine for creating an ONNX model that can handle arrays of images. Just ensure your data is prepped correctly when making actual predictions! 📊

      For GPU acceleration with ONNX, leveraging frameworks like ONNX Runtime with CUDA support would be the way to go! 🔥 Make sure your environment is set up for GPU use, and you're specifying the execution provider accordingly.

      Feel free to check out more on dynamic batching and ONNX export on the Ultralytics docs page! Hope this helps, and happy coding! 🚀

    19. Aisha-Hassan1GitHub

      code

      const inputs = { images: [inputTensors[0], inputTensors[1]] };

      const { output0, output1 } = await yolov8.run(inputs);

      erro

      Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'byteLength') at t.run (wasm-core-impl.ts:219:31) at t.run (proxy-wrapper.ts:215:17) at t.OnnxruntimeWebAssemblySessionHandler.run (session-handler.ts:84:15) at i.run (inference-session-impl.js:94:44) at runModel (main.html:107:53)

    20. Glenn JocherUltralytics

      Hey there! 👋 It looks like there might be a slight mix-up in how you're constructing the input to your model run. When dealing with arrays of tensors in ONNX.js, you should pass a single tensor that concatenates your image tensors along the batch dimension if the model is set up for batch processing.

      For your issue with inputTensors causing an error about byteLength, it's likely because the model expects one tensor that combines all input images. Instead of:

      const inputs = {
          images: [inputTensors[0], inputTensors[1]]
      };

      You should concatenate your inputTensors into one tensor if your model expects a batch input. Unfortunately, directly passing an array like this might not work as expected with ONNX.js since it seems to expect the input as a single tensor representing the batch. The error you're encountering (TypeError: Cannot read properties of undefined (reading 'byteLength')) usually occurs when the input format to the session.run method is not as expected.

      This could look different based on how your model is trained and how ort.Tensor handles batches. Ensure your model is trained with dynamic batch size if you want to process multiple images in a single forward pass. If you're not sure how to concatenate tensors in JavaScript (as direct tensor concatenation might not be as straightforward as in Python), you might have to loop over your images and process them one at a time, or look into adjusting your model to accept variable batch sizes more gracefully.

      Given your current setup, if your model does not explicitly support batched inputs, you might need to process each image individually:

      for(const tensor of inputTensors) {
          const inputs = { images: tensor };
          const outputs = await yolov8.run(inputs);
          // Process the outputs for each image here
      }

      Remember, different models expect the input in specific formats, including batch size. Ensure your preprocessing aligns with these expectations! 🚀

  4. SugarSolGitHub

    请问一下,YOLO26 在导出 onnx 时,imgsz参数取(384, 672)和(640, 640) 推理结果差异很大,是什么原因导致的呢?

    1. Glenn JocherUltralytics

      这是正常现象,imgsz 会直接改变导出时的输入分辨率和输出候选框数量,而 (384, 672) 与 (640, 640) 还会带来不同的缩放/补边比例;如果你的 ONNX 部署前处理没有与导出尺寸严格一致,尤其是 letterbox、归一化和 NMS,结果就会明显不同。建议尽量让训练、验证、导出和推理使用同一 imgsz,或导出时启用 dynamic=True 并保持完全一致的前后处理,更多说明可参考 导出文档 和 ONNX 集成说明;如果方便,也欢迎直接在这里补一个最小可复现示例,我们再一起看。

    2. SugarSolGitHub

      我使用的是官方提供的coco预训练权重直接导出onnx的,导出和预测都是使用的官方提供的代码,并未做任何修改,不同之处只有导出时的尺寸不同。奇怪的是,这种现象在YOLOv8中并未发现。

    3. Glenn JocherUltralytics(已编辑)

      这更像是 YOLO26 的导出特性而不是 ONNX 本身的问题:YOLO26 的检测头是原生端到端(NMS-free)的,而 YOLOv8 是传统 NMS 流程,所以更换 imgsz 时两者的一致性表现不一定相同;建议先在相同 imgsz 下对比 .pt 与 .onnx 的结果。end2end 参数现已弃用并映射为 nms:默认(不设置 nms)导出与 YOLOv8 类似的原始预测,nms=False 导出 NMS-free 输出,nms=True 在支持的格式中内置 NMS,详见 导出文档 和 End-to-End 检测指南;如果方便,请贴出完整的导出/推理命令和 yolo checks 输出,我们再继续定位。

    4. SugarSolGitHub

      YOLO26导出的onnx在相同形状下end2end与非end2end的推理输出是一致的。而.pt与.onnx的结果只有在导出为(640,640)的情况下一致,在此形状下的输出也与YOLOv8是一致的。下面是我的导出和预测脚本: from ultralytics import YOLO model = YOLO("./yolo26n.pt") path = model.export(format="onnx", imgsz=(384, 672), end2end=False) model = YOLO("./yolo26n.onnx") results = model("../../coco128/train2017/000000000049.jpg") results[0].save() 下面是不同形状的推理结果: (384,672): image 1/1 /home/easyits/ai/wpf/Employee/100/ultralytics/tools/../../coco128/train2017/000000000049.jpg: 384x672 1 person, 2 horses, 1 potted plant, 136.5ms Speed: 18.2ms preprocess, 136.5ms inference, 47.0ms postprocess per image at shape (1, 3, 384, 672) (640,640): image 1/1 /home/easyits/ai/wpf/Employee/100/ultralytics/tools/../../coco128/train2017/000000000049.jpg: 640x640 4 persons, 2 horses, 103.7ms Speed: 7.5ms preprocess, 103.7ms inference, 16.5ms postprocess per image at shape (1, 3, 640, 640)

    5. Glenn JocherUltralytics

      你这个脚本里最需要先排除的是“对比条件不一致”:.pt 推理如果没显式传 imgsz=(384, 672),通常还是按默认 640 跑,而导出的 .onnx 输入已经固定成 (384, 672),所以这不算同尺度对比;建议先让 .pt 和 .onnx 在完全相同的 imgsz 下分别执行 predict 或直接 val,导出模型本身也支持直接验证,可参考 检测任务中的导出说明;如果这样仍只有 YOLO26 在非 640 下不一致,请把两边的完整日志和 yolo checks 输出贴上来,我们继续查。

    6. SugarSolGitHub

      抱歉,表达不是很清楚,我想表达的是导出和预测使用的是这样的命令,我在不同imgsz和end2end的组合下都对同一张图片进行了预测,确实是只有YOLO26在非640形状下与640形状下的结果不一致,只与imgsz有关,与是否为end2end无关。

    7. Glenn JocherUltralytics

      感谢补充,这里基本可以定位到“矩形 ONNX 导出”的当前限制了:从当前 Exporter 实现参考 看,非 PyTorch 后端对非方形 imgsz 不保证与 .pt 完全一致,导出完成时也会提示非方形 imgsz 的 non-PyTorch val 不可用,所以你看到 (384, 672) 与 640,640 结果分叉、且与 end2end 无关,是符合现状的;如果目标是尽量和 .pt 对齐,建议优先用方形尺寸导出,例如 imgsz=640 或 672,如果你希望我们继续跟进矩形输入场景,也请新开一个 issue 并附上完整日志和 yolo checks 输出。

    8. SugarSolGitHub

      感谢您的回复,我提了issue#24428,并附上了完整日志和yolo checks输出。

    9. Glenn JocherUltralytics

      感谢,已收到;这个问题我们就集中在 #24428 里继续跟进,后续如能补充同一张图在 .pt/.onnx 下显式指定相同 imgsz 的 model.predict() 或 model.val() 对比结果,会更有助于确认是否是矩形导出的边界情况。

  5. nwpu-caikunGitHub

    I trained an image classification model. How can I perform incremental learning to add new class? Are there any methods other than retraining the model? big thanks

    908637049 @.***

    1. Glenn JocherUltralytics

      Adding a new class changes the classifier head, so there isn’t a “no-training” way to truly add classes incrementally in Ultralytics YOLO classification; the recommended approach is to fine-tune from your existing checkpoint on a dataset that includes both the original classes and the new class to avoid catastrophic forgetting (see the Classification docs). Please remove the phone/email and keep details here in the discussion (public) so the team can help.

      from ultralytics import YOLO
      
      model = YOLO("path/to/best.pt")  # your previous classifier
      model.train(data="path/to/cls_dataset")  # dataset now includes the new class
  6. nwpu-caikunGitHub

    we use a customed dataset to train a image classify model,when calculate the result conf,we meet a problem。 in the last layer, we manualy calculate the conf by logits output, and then ,softmax to generate the conf ,but the conf number is very low。 however,we try to print the rusult.prob, (results = model(image_path, verbose=False),results_probs_obj = results[0].probs ) we found the result.probs is not equal to manualy conf we calculate. the result.probs is much higher than manualy conf. result.probs is 99.998%, and manualy conf is only 6.1982%. what the difference between them? how the model calculate the conf, and get the 99.998% conf?

    1. Glenn JocherUltralytics

      results[0].probs is already the final per-class probability vector (Softmax has been applied in the classification head during inference), so if you “manual softmax” a tensor that’s already probabilities you’ll get very different (often much smaller) numbers like your ~6%; if you want to reproduce Ultralytics’ confidence from logits, make sure you’re using the raw logits output (the classification head returns (probs, logits) in inference) and compute torch.softmax(logits, dim=1) once—see the Results/Probs API reference and the Classify head forward behavior.

    2. nwpu-caikunGitHub

      how do I get the raw logits output after model(image), has any methods? when I get the raw logits output ,I can manual calculate the probs? thanks!

    3. Glenn JocherUltralytics

      model(image_path) goes through ClassificationPredictor.postprocess(), which intentionally keeps only the first element (preds[0]) when the model returns a tuple, so the raw logits aren’t exposed in Results; to get logits you need to run a PyTorch forward pass on the preprocessed tensor. (docs.ultralytics.com)

      import cv2
      import torch
      from ultralytics import YOLO
      
      model = YOLO("path/to/best.pt")  # classification .pt
      _ = model("path/to/image.jpg", verbose=False)  # init predictor/transforms once
      
      img0 = cv2.imread("path/to/image.jpg")  # BGR
      im = model.predictor.preprocess([img0])
      
      with torch.no_grad():
          probs, logits = model.model(im)  # head returns (probs, logits) in inference
          probs_manual = torch.softmax(logits, dim=1)

      Note this tuple output is only available for PyTorch models; in export mode the head returns probabilities only. (docs.ultralytics.com)

  7. sidsheteGitHub

    I have trained model for instance segmentation and I ma trying to export to run on DPU. Here is the code mentioned below

    from ultralytics import YOLO

    best_weights_path = "../weights/yolo11_s/yolo11_s.pt" data_yaml = "../yolo_seg/dataset.yaml"

    model = YOLO(best_weights_path)

    Export for DPU (INT8)

    model.export( format="onnx", data=data_yaml,
    int8=True,
    simplify=True, nms=False
    )

    I get the following error.

    UnpicklingError Traceback (most recent call last) Cell In[18], line 6 3 best_weights_path = "../weights/yolo11_s/yolo11_s.pt" 4 calib_data_yaml = "../dataset.yaml" ----> 6 model = YOLO(best_weights_path) 8 # Export for DPU (INT8) 9 model.export( 10 format="onnx", 11 data=calib_data_yaml, # calibration dataset required for INT8 (...) 14 nms=False # often applied post-inference 15 )

    File ~/testing_env/lib/python3.10/site-packages/ultralytics/models/yolo/model.py:23, in YOLO.init(self, model, task, verbose) 20 self.dict = new_instance.dict 21 else: 22 # Continue with default YOLO initialization ---> 23 super().init(model=model, task=task, verbose=verbose)

    File ~/testing_env/lib/python3.10/site-packages/ultralytics/engine/model.py:151, in Model.init(self, model, task, verbose) 149 self._new(model, task=task, verbose=verbose) 150 else: --> 151 self._load(model, task=task)

    File ~/testing_env/lib/python3.10/site-packages/ultralytics/engine/model.py:240, in Model._load(self, weights, task) 237 weights = checks.check_model_file_from_stem(weights) # add suffix, i.e. yolov8n -> yolov8n.pt 239 if Path(weights).suffix == ".pt": --> 240 self.model, self.ckpt = attempt_load_one_weight(weights) 241 self.task = self.model.args["task"] 242 self.overrides = self.model.args = self._reset_ckpt_args(self.model.args)

    File ~/testing_env/lib/python3.10/site-packages/ultralytics/nn/tasks.py:806, in attempt_load_one_weight(weight, device, inplace, fuse) 804 def attempt_load_one_weight(weight, device=None, inplace=True, fuse=False): 805 """Loads a single model weights.""" --> 806 ckpt, weight = torch_safe_load(weight) # load ckpt 807 args = {**DEFAULT_CFG_DICT, **(ckpt.get("train_args", {}))} # combine model and default args, preferring model args 808 model = (ckpt.get("ema") or ckpt["model"]).to(device).float() # FP32 model

    File ~/testing_env/lib/python3.10/site-packages/ultralytics/nn/tasks.py:732, in torch_safe_load(weight) 724 try: 725 with temporary_modules( 726 { 727 "ultralytics.yolo.utils": "ultralytics.utils", (...) 730 } 731 ): # for legacy 8.0 Classify and Pose models --> 732 ckpt = torch.load(file, map_location="cpu") 734 except ModuleNotFoundError as e: # e.name is missing module name 735 if e.name == "models":

    File ~/testing_env/lib/python3.10/site-packages/torch/serialization.py:1524, in load(f, map_location, pickle_module, weights_only, mmap, **pickle_load_args) 1516 return _load( 1517 opened_zipfile, 1518 map_location, (...) 1521 **pickle_load_args, 1522 ) 1523 except pickle.UnpicklingError as e: -> 1524 raise pickle.UnpicklingError(_get_wo_message(str(e))) from None 1525 return _load( 1526 opened_zipfile, 1527 map_location, (...) 1530 **pickle_load_args, 1531 ) 1532 if mmap:

    UnpicklingError: Weights only load failed. This file can still be loaded, to do so you have two options, do those steps only if you trust the source of the checkpoint. (1) In PyTorch 2.6, we changed the default value of the weights_only argument in torch.load from False to True. Re-running torch.load with weights_only set to False will likely succeed, but it can result in arbitrary code execution. Do it only if you got the file from a trusted source. (2) Alternatively, to load with weights_only=True please check the recommended steps in the following error message. WeightsUnpickler error: Unsupported global: GLOBAL ultralytics.nn.modules.block.C3k2 was not an allowed global by default. Please use torch.serialization.add_safe_globals([ultralytics.nn.modules.block.C3k2]) or the torch.serialization.safe_globals([ultralytics.nn.modules.block.C3k2]) context manager to allowlist this global if you trust this class/function.

    1. Glenn JocherUltralytics(已编辑)

      That error is coming from PyTorch 2.6's new default torch.load(weights_only=True), which blocks custom Ultralytics layers like ultralytics.nn.modules.block.C3k2. First upgrade with pip install -U ultralytics; if you still hit it and trust the checkpoint, either pin PyTorch <2.6 or allowlist C3k2 before calling YOLO():

      import torch
      from ultralytics import YOLO
      from ultralytics.nn.modules.block import C3k2
      
      torch.serialization.add_safe_globals([C3k2])  # only if you trust the .pt source
      model = YOLO("../weights/yolo11_s/yolo11_s.pt")

      Also note that INT8 ONNX export is supported in current Ultralytics: use quantize=8 (the older int8=True is mapped to it) together with data pointing to your calibration dataset. If your DPU toolchain needs its own quantizer, you can instead export FP32 ONNX and quantize with your vendor toolchain; see the supported export args in the Export mode docs and ONNX export guide.

      If you paste !yolo checks (and restart the notebook kernel if you recently upgraded PyTorch/Ultralytics), I can confirm the exact version combo that's triggering this on your side.

  8. GeThi255GitHub

    Hi, export to "tflite" and other is not working with python 3.13, 3.10. or 3.08 due to incompatibility of e.g. tensorflow version (Ultralytics requirement ['tensorflow>=2.0.0,<=2.19.0'] ). Tested on windows 11 and Raspi. Could you please check. Thanks Gerd

  9. 404-NOTFOUND-CoderGitHub

    Title: int8 argument not supported when exporting to ONNX in Ultralytics 8.3.162

    Description:

    I encountered an error when trying to export a trained YOLOv8 model to ONNX format with the following code:

    model = YOLO('/kb210/wrs/tennis-analysis/tennis_analysis/training/runs/detect/train27/weights/best.pt') model.export(format="onnx", imgsz=(1024,1280), nms=True, int8=True, dynamic=True) The error traceback is as follows:

    Traceback (most recent call last): File "/kb210/wrs/tennis-analysis/tennis_analysis/yolo_inference.py", line 15, in model.export(format="onnx", imgsz=(1024,1280), nms=True, int8=True, dynamic=True) File "/kb210/conda/envs/tennis_analysis/lib/python3.9/site-packages/ultralytics/engine/model.py", line 819, in export return Exporter(overrides=args, _callbacks=self.callbacks)(model=self.model) File "/kb210/conda/envs/tennis_analysis/lib/python3.9/site-packages/ultralytics/engine/exporter.py", line 311, in call validate_args(fmt, self.args, fmt_keys) File "/kb210/conda/envs/tennis_analysis/lib/python3.9/site-packages/ultralytics/engine/exporter.py", line 171, in validate_args assert arg in valid_args, f"ERROR ❌️ argument '{arg}' is not supported for format='{format}'" AssertionError: ERROR ❌️ argument 'int8' is not supported for format='onnx' From the error message, it seems that the int8=True argument is not supported for ONNX export. However, I believe INT8 quantization could be useful for optimizing models even before deployment to certain runtimes (e.g., TensorRT).

    Question:

    Is there any plan to support INT8 during ONNX export? If not, what would be the recommended way to apply INT8 quantization after exporting to ONNX?

    Environment:

    Ultralytics version: 8.3.162 Python version: 3.9.19 PyTorch version: 1.13.1 OS: Linux Hardware: Intel Xeon E5-2680 v4 2.40GHz Thanks for your help!

  10. rememberBrGitHub

    Does using dynamic=True on Nvidia's Jetson development board not include batch dimension? It seems that only w and h have become dynamic dimensions, while batch is fixed at 1?