开始使用

YOLOE:实时开放词汇检测与分割

Ultralytics YOLOE(实时识万物)是一种开放词汇检测和实例分割模型:它不使用训练时固定的类别列表,而是在推理时接受你指定的类别,可以是文本提示、视觉示例,也可以是内置的 4,585 个名称词汇表。YOLOE 基于 Ultralytics YOLO 架构(YOLOv8、YOLO11 和 YOLO26)构建,并受 YOLO-World 启发,以接近闭集 YOLO 的速度实现了较高的零样本准确率。



观看: 如何使用 Ultralytics YOLOE-26(新功能)| 开放词汇与实时识万物

快速入门#

指定你想要的类别并运行即可。YOLOE-26 会返回模型从未训练过的类别对应的边界框和实例分割掩码。

检测你能说出名称的任何对象
from ultralytics import YOLOE

model = YOLOE("yoloe-26s-seg.pt")

# “double-decker bus”不是 COCO 类别;YOLOE 仅凭文字就能识别它
model.set_classes(["double-decker bus", "person"])

results = model.predict("https://ultralytics.com/images/bus.jpg")
results[0].show()

首次调用 set_classes() 时会下载文本编码器;在没有网络连接的机器上部署前,请参阅安装和要求。

选择提示模式#

YOLOE 支持三种提示模式,选择哪种模式决定了你要加载哪个检查点,以及类别标签的形式。选择与你在推理时能够提供的内容相符的行。

YOLOE 根据文本提示、视觉提示和无提示词汇表检测并分割对象

模式检查点你提供的内容结果中的类别名称适用场景
文本提示*-seg.pt字符串形式的类别名称与你传入的名称完全一致你可以用文字描述目标——最常用的选择
视觉提示*-seg.pt参考图像上的示例框通用的 object0、object1、…你无法用文字描述目标:例如特定部件、徽标或缺陷
无提示*-seg-pf.pt不提供任何内容内置 4,585 个名称词汇表中的名称你正在整理目录或探索,事先不知道要查找什么
两个常见的意外情况
  • 视觉提示不会携带你的标签。visual_prompts 中的类别 ID 会将示例分组;模型会将它们报告为 object0、object1 等。你需要自行将这些 ID 映射回自己的名称。
  • 无提示检查点不接受 set_classes()。在 *-seg-pf.pt 模型上调用它会引发 AssertionError: Prompt-free model does not support setting classes. Please try with Text/Visual prompt models.。需要使用自己的类别时,请改为加载 *-seg.pt 检查点。

安装和要求#

YOLOE 已包含在 Ultralytics 主软件包中:

pip install -U ultralytics

除此之外,文本提示还需要文本编码器。它会在首次使用时获取,而不是在安装时获取:

  • 首次调用 set_classes() 时,会通过 pip 从 GitHub 安装 ultralytics/CLIP(它提供分词器),并将 TorchScript 文本编码器下载到当前工作目录。YOLOE-26 会下载 mobileclip2_b.ts,大小约为 254 MB;YOLOE-11 和 YOLOE-v8 会下载 mobileclip_blt.ts。请在你准备运行的目录中执行一次下载,或将文件复制到该目录,否则系统会再次下载。
  • 这两个步骤都需要网络连接,因此请在部署到离线或隔离网络的机器前,先运行一次带提示的预测。
  • 视觉提示和无提示检查点完全不需要文本编码器。

YOLOE-26 检查点要求使用 ultralytics 8.4.0 或更高版本;YOLOE-11 和 YOLOE-v8 系列在更早的版本中也可用。运行一次带文本提示的预测即可验证整个流程——检查点下载、CLIP 安装、文本编码器和推理:

yolo predict model=yoloe-26s-seg.pt source="https://ultralytics.com/images/bus.jpg" classes="person"

若要完全跳过推理时的文本编码器下载,可以将提示一次性写入权重并重复使用——请参阅重用提示嵌入。

架构概览#

YOLOE architecture with RepRTA, SAVPE, and LRPC modules

YOLOE 保留了标准 YOLO 结构——用于特征提取的卷积主干网络、用于多尺度融合的颈部网络,以及用于预测类别和边界框的无锚点解耦头——并为每种提示模式添加一个模块:

  • 可重参数化区域-文本对齐(RepRTA)通过一个小型辅助网络优化来自 CLIP 的文本嵌入。该网络在每次 set_classes() 调用时运行一次,并在导出时折叠,因此不会增加逐帧开销。每次前向传播都会执行的是将存储的提示嵌入与区域特征进行比较;大型提示集带来的开销请参阅局限性。
  • 语义激活视觉提示编码器(SAVPE)从示例框中编码语义和激活特征,让模型以外观相似的对象为条件进行检测。这是一种单样本提示方式,适用于徽标或特定部件等难以命名的目标。
  • 惰性区域提示对比(LRPC)将区域嵌入与内置的 4,585 个名称词汇表进行匹配,因此无提示检查点无需外部提示或文本编码器即可识别对象。

与 YOLOv8-Seg 一样,实例分割由检测头上的掩码分支实现,每个预测结果在 results[0].masks 上都带有掩码。模型导出后,开放世界模块会重新参数化为标准 YOLO 检测头,因此导出的文件会运行常规的检测/分割流程。

可用模型#

以下每个检查点都是实例分割模型,支持 val、predict、export 和 track。加载 *-seg.pt 文件可使用文本或视觉提示,加载 *-seg-pf.pt 文件可进行无提示推理;两者不可互换,详见选择提示模式。只有 *-seg.pt 文件支持 train;无提示检查点由经过训练的文本提示模型生成,详见从头训练官方模型。

YOLOE 在 LVIS 上的性能#

在 640 像素下,基于 LVIS minival 的零样本结果,摘自 Ultralytics YOLO26 论文。

文本和视觉提示#

每个准确率和参数单元格均按文本提示 / 视觉提示的顺序显示;FLOPs 只列出一次。参数量和 FLOPs 对应论文评估的检测配置。准确率采用论文中的 Non-E2E 数值,这是论文为比较中的每个模型提供的唯一评测协议;YOLOE-26 端到端检测头的表现最多比该数值低 1.1 AP(文本提示)和 2.6 AP(视觉提示)。

模型mAP50-95mAPrmAPcmAPf参数
(M)
FLOPs
(B)
YOLOE-26n24.7 / 21.920.5 / 17.624.1 / 22.326.1 / 22.43.9 / 3.16.1
YOLOE-26s30.8 / 28.623.9 / 25.129.6 / 27.833.0 / 29.910.7 / 11.021.9
YOLOE-26m35.4 / 33.931.1 / 33.434.7 / 34.036.9 / 33.821.3 / 25.170.6
YOLOE-26l37.8 / 36.335.1 / 37.637.6 / 36.238.5 / 36.125.5 / 29.389.0
YOLOE-26x40.6 / 38.537.4 / 35.340.9 / 38.841.0 / 38.855.2 / 65.2197.7
YOLOE-11s27.5 / 26.321.4 / 22.526.8 / 27.129.3 / 26.410.7 / 10.922.7
YOLOE-11m33.0 / 31.426.9 / 27.132.5 / 31.934.5 / 31.721.0 / 24.870.4
YOLOE-11l35.2 / 33.729.1 / 28.135.0 / 34.636.5 / 33.826.0 / 29.889.5
YOLOE-v8s27.9 / 26.222.3 / 21.327.8 / 27.729.0 / 25.712.3 / 12.629.8
YOLOE-v8m32.6 / 31.026.9 / 27.031.9 / 31.734.4 / 31.126.4 / 28.480.7
YOLOE-v8l35.9 / 34.233.2 / 33.234.8 / 34.637.3 / 34.143.5 / 47.3167.6

无提示#

无提示检查点使用内置词汇表进行推理,无需提供提示。每个准确率单元格按端到端 / Non-E2E的顺序显示,这是论文对 YOLOE-26 评分时采用的两种协议;YOLO26 页面引用的是 Non-E2E 列。

模型mAP50-95mAPrmAPcmAPf参数
(M)
FLOPs
(B)
YOLOE-26n-pf16.6 / 17.715.7 / 15.815.3 / 16.417.9 / 19.22.35.3
YOLOE-26s-pf21.4 / 22.616.2 / 20.220.1 / 20.923.5 / 24.59.020.8
YOLOE-26m-pf25.7 / 26.426.7 / 24.524.0 / 25.026.9 / 27.919.468.4
YOLOE-26l-pf27.2 / 28.026.3 / 25.725.7 / 26.828.7 / 29.523.686.8
YOLOE-26x-pf29.9 / 31.127.5 / 28.929.1 / 30.731.1 / 31.753.1194.4

在文本提示和视觉提示下,YOLOE-26 模型在每个对应的规模上,mAP50-95 均领先于 YOLOE-11 和 YOLOE-v8 对应模型,同时参数量和 FLOPs 均低于 v8 系列。在同一数据划分上,论文报告 YOLO-Worldv2 的成绩为 24.4(S)、32.4(M)和 35.5(L);基于 Transformer 的检测器 GLIP-T、GDINO-T 和 DetCLIP-T 分别为 26.0、27.4 和 34.4,参数量均为 155 到 232 M。原始 YOLOE 论文还补充了其推出的 v8 规模模型的两项结果。在 LVIS 上,YOLOE-v8s 的 AP 比 YOLO-Worldv2-S 高 3.5,训练成本仅为其三分之一,推理速度则为其 1.4 倍。迁移到 COCO 后,YOLOE-v8l 的 box AP 比闭集 YOLOv8-L 高 0.6,mask AP 高 0.4,而训练时间几乎减少了 4 倍。

论文统计数据与已发布检查点的对比

YOLO26 论文评估的是检测配置。已发布的权重是分割检查点,包含掩码分支、SAVPE 和文本投影层,因此加载后的 yoloe-26l-seg.pt 显示为 35.4 M 和 142.0 B,而不是上文的 25.5 M 和 89.0 B。两种情况下,FLOPs 数值都不包括区域与文本之间的相似度计算,因此实际成本会随着提示集的规模增大,尽管表格中的数值不会变化;请参阅局限性。

使用示例#

以下每个 YOLOE 示例都通过 Python API 运行。文本提示预测、验证、导出、跟踪和普通训练也可以通过 CLI 执行;微调教程会传入训练器类,而视觉提示会传入 NumPy 提示数组,这两种参数只有 Python API 支持。

训练用法#

在你自己的 YOLO 数据集上微调任何已发布的 *-seg.pt 检查点。这大体遵循标准 YOLO 训练流程;区别在于你传入的训练器。YOLOEPESegTrainer 会将你的类别名称融合到检测头中,并从此处开始微调,这正适用于你自己的标签;默认训练器不会针对你的类别名称进行训练。生成的检查点会直接预测你数据集中的类别:其检测头不再读取提示,因此类别发生变化时,set_classes() 会报错,视觉提示也会如此。要检测其他类别,请使用原始检查点进行提示。



观看: 如何在汽车零部件分割数据集上训练 YOLOE | 开放词汇模型、预测与导出
示例
from ultralytics import YOLOE
from ultralytics.models.yolo.yoloe import YOLOEPESegTrainer

model = YOLOE("yoloe-26s-seg.pt")

results = model.train(
    data="coco128-seg.yaml",
    epochs=80,
    patience=10,
    trainer=YOLOEPESegTrainer,  # <- 重要:使用微调 trainer,而不是默认 trainer
)
改为训练检测模型

所有已发布的检查点都是分割模型。要训练检测器,请根据对应的 YAML 构建模型,加载相同规模的分割权重,并替换为检测 trainer。其他部分都不变。

from ultralytics import YOLOE
from ultralytics.models.yolo.yoloe import YOLOEPETrainer

model = YOLOE("yoloe-26s.yaml").load("yoloe-26s-seg.pt")

results = model.train(data="coco128.yaml", epochs=80, patience=10, trainer=YOLOEPETrainer)

预测用法#

文本提示调用方式如快速入门所示。视觉提示会增加一个 visual_prompts 参数,而无提示预测则会加载 -pf 检查点:

示例

视觉提示通过向模型展示示例来代替文字描述。visual_prompts 接受一个包含示例框的 bboxes 数组,以及一个包含类别 ID 的 cls 数组,每个框对应一个 ID。这些 ID 是临时分组,而不是标签——它们必须从 0 开始连续编号,返回结果也会使用 object0、object1、……,而不是你自定义的名称。

示例框可以位于你要进行预测的图像上:

import numpy as np

from ultralytics import YOLOE

model = YOLOE("yoloe-26l-seg.pt")

# 每个目标对应一个示例框,每个框都有自己的类别 ID
visual_prompts = {
    "bboxes": np.array([[221.52, 405.8, 344.98, 857.54], [120, 425, 160, 445]]),  # 人物、眼镜
    "cls": np.array([0, 1]),
}

results = model.predict(
    "ultralytics/assets/bus.jpg",
    visual_prompts=visual_prompts,
)
results[0].show()

也可以位于通过 refer_image 传入的独立参考图像上;此时,bboxes 和 cls 描述的是参考图像中的对象,而不是目标图像中的对象:

import numpy as np

from ultralytics import YOLOE

model = YOLOE("yoloe-26l-seg.pt")

visual_prompts = {"bboxes": np.array([[221.52, 405.8, 344.98, 857.54]]), "cls": np.array([0])}  # person

results = model.predict(
    "ultralytics/assets/zidane.jpg",  # 目标图像
    refer_image="ultralytics/assets/bus.jpg",  # 示例框所在位置
    visual_prompts=visual_prompts,
)
results[0].show()

# refer_image 也会永久设置类别,因此后续调用无需再传入提示
results = model("ultralytics/assets/bus.jpg")
model.export(format="onnx")  # 导出时也会保留这些类别
注意

当 source 是视频或流时,第一帧会自动成为 refer_image,因此你传入的提示会应用到该帧,并沿用到视频的其余部分。显式传入 refer_image 可选择其他帧。

source 和 refer_image 都可以直接接受 torch 张量;如果图像已来自现有流水线,这会很有用。请使用张量自身的像素坐标提供框:

import numpy as np
import torch

from ultralytics import YOLOE

model = YOLOE("yoloe-11l-seg.pt")

img_tensor = torch.rand(1, 3, 480, 480)  # (1, 3, H, W) 范围为 [0, 1] 的浮点张量
visual_prompts = {"bboxes": np.array([[10, 10, 50, 50]]), "cls": np.array([0])}

results = model.predict(
    img_tensor,
    refer_image=img_tensor,
    visual_prompts=visual_prompts,
    imgsz=640,
)

要一次预测多张图像,请将提示再嵌套一层:每张源图像分别对应一个 bboxes 数组和一个 cls 数组,顺序与源图像相同。

import numpy as np

from ultralytics import YOLOE

model = YOLOE("yoloe-26l-seg.pt")

visual_prompts = {
    "bboxes": [
        np.array([[221.52, 405.8, 344.98, 857.54], [120, 425, 160, 445]]),  # bus.jpg:人物、眼镜
        np.array([[150, 200, 1150, 700]]),  # zidane.jpg:人物
    ],
    "cls": [np.array([0, 1]), np.array([0])],
}

results = model.predict(
    ["ultralytics/assets/bus.jpg", "ultralytics/assets/zidane.jpg"],
    visual_prompts=visual_prompts,
)
results[0].show()

验证用法#

验证方式与其他分割数据集上的模型相同:

示例
from ultralytics import YOLOE

model = YOLOE("yoloe-26l-seg.pt")  # 其他尺寸可使用 yoloe-26s/m-seg.pt

metrics = model.val(data="coco128-seg.yaml")

data 也可以是 NDJSON 文件 或 Platform ul:// 数据集 URI;在构建文本或视觉提示之前,系统会先将其转换为 YOLO 格式。

另外两种提示模式可通过同一调用的两个变体实现:

  • 视觉提示 — model.val(data="coco128-seg.yaml", load_vp=True) 会直接从数据集中为每个类别提取视觉嵌入。添加 refer_data="coco.yaml",即可改为从另一个数据集中提取嵌入;两个数据集必须包含完全相同的类别。
  • 无提示 — 加载 *-seg-pf.pt 检查点并传入 single_cls=True。

导出用法#

提示嵌入可以保存一次,并在生成 ONNX、OpenVINO、TensorRT、CoreML、LiteRT 和 RKNN 等静态导出模型时重复使用。导出前,原始 PyTorch 模型会加载 NPZ 配置文件;它不是额外的运行时输入,导出的模型也不需要 NPZ 文件。

导出模型是静态的

通过 set_classes()(或视觉提示时通过 refer_image)配置的类别会固化到导出的权重中。导出后,模型无法再接受新提示:对已加载的导出模型调用 set_classes(),或向 predict() 传入 visual_prompts=...,都会失败。要更改检测类别,请使用新配置的提示从原始 .pt 检查点重新导出。导出的文件表现得像标准 YOLO 模型,也可以使用 YOLO() 而不是 YOLOE() 加载。

重复使用提示嵌入
from ultralytics import YOLOE

model = YOLOE("yoloe-26n-seg.pt")
model.set_classes(["person", "bus"])
model.save_prompt_embeddings("person-bus.npz")

# 该配置文件与源检查点绑定,可用于后续导出。
model = YOLOE("yoloe-26n-seg.pt")
model.load_prompt_embeddings("person-bus.npz")
model.export(format="onnx")

同一提示配置文件也可以用于配置从对应 YOLOE 架构构建的纯检测模型。这样会移除掩码分支,同时保留已提示的类别:

from ultralytics import YOLOE

model = YOLOE("yoloe-26n.yaml").load("yoloe-26n-seg.pt")
model.load_prompt_embeddings("person-bus.npz")
model.export(format="rknn", name="rk3588", quantize=16)

跟踪用法#

已提示的类别可以直接用于跟踪,因此你可以跟踪 tracker 从未训练过的对象:

示例
from ultralytics import YOLOE

model = YOLOE("yoloe-26s-seg.pt")
model.set_classes(["forklift", "pallet"])

# persist=True 可让跟踪 ID 在不同帧之间保持稳定
for result in model.track("path/to/video.mp4", stream=True, persist=True):
    print(result.boxes.id)

YOLOE 的对比#

YOLOE 介于闭集检测器和大型开放词汇模型之间。以下三项对比有助于判断它是否适合你的需求:

  • 与闭集 YOLO 相比。设置提示后,YOLOE 会通过常规的检测/分割路径进行预测,导出方式也与其他模型相同。它的优势是在推理时更改类别列表,而无需重新训练;代价是零样本准确率远低于使用你自己的类别训练的模型。
  • 与早期 YOLOE 系列相比。YOLOE-26 继承了 YOLO26 的无 NMS 端到端检测头,覆盖五种规模(n/s/m/l/x),而早期版本只有三种(s/m/l),并且在性能中列出的每个对应规模上都领先。
  • 与基于 Transformer 的开放词汇检测器相比。GLIP 和 OWL-ViT 在推理时运行视觉语言 Transformer。YOLOE 则只对提示进行一次编码,然后在卷积检测头中将提示与区域特征进行比较。

最接近的替代方案都支持文本提示,但只有 YOLOE 和 SAM 3 会返回掩码,而且三者解决的问题各不相同:

YOLOESAM 3YOLO-World
适用场景对指定类别进行实时检测和分割概念分割和可提示跟踪实时开放词汇检测
掩码是,使用 *-seg.pt 检查点是否,仅支持边界框
视觉提示是(SAVPE)是否
无提示模式是,包含 4,585 个名称的词汇表否否
适合选择它的情况你需要高吞吐量,并且能说出类别名称你需要最强的概念分割能力,并且能承担相应的计算开销你已经在使用它——请参阅下方的迁移说明

从 YOLO-World 迁移?API 结构相同:将 YOLOWorld 替换为 YOLOE,加载 *-seg.pt 检查点,并保持现有的 set_classes() 调用不变。你将获得掩码和视觉提示功能;关于类别被冻结的导出说明同样适用。

用例和应用#

开放词汇检测无需针对每个类别重新训练;当你事先不知道目标列表时,这一点尤其重要:

  • 开放世界检测 — 机器人和安防系统会遇到训练时无人列举的对象。
  • 根据示例进行单样本检测 — 视觉提示可以通过单个参考框识别特定零件、徽标或缺陷,适用于工业检测。
  • 长尾目录整理 — 内置的 4,585 个名称词汇表足够广泛,可用于生物多样性监测或零售库存巡查。
  • 数据集引导 — 先用边界框和掩码预标注图像,再由人工审核,随后使用标注结果训练快速的闭集模型。
  • 任意目标分割 — 已发布的 *-seg.pt 检查点会为每个预测结果返回掩码,因此医学影像和卫星图像分析无需第二个模型即可获得像素级精确输出。

一种常见做法是组合两种模式:先运行一次无提示模式,发现当前场景中的对象,然后切换到文本提示,检测重要类别。

局限性#

YOLOE 以牺牲准确率为代价,换取在推理时更改类别的能力。使用前值得了解以下影响:

  • 零样本准确率远低于使用你自己的类别训练的模型。在 LVIS minival 上,带提示的检查点 mAP 大约为 22-40;使用你自己的数据训练的闭集 YOLO 在这些类别上的表现会更好。使用 YOLOE 来覆盖无法训练的类别,而不是取代训练。
  • 稀有类别是薄弱环节。性能中的 mAPr 列专门报告 LVIS 稀有类别上的准确率;在文本提示下,每一行的这一数值都低于常见和高频类别。若你的目标较为少见,请查看这一数值,而不是只看总体 mAP。
  • 提示描述外观,而非关系。检测通过将区域特征与提示嵌入进行比较来完成,因此依赖状态、上下文或比较的提示——例如“损坏的”“最左边的”“正在被搬运的那个”——没有可靠的匹配依据。尽量使用接近日常类别名称的表述。
  • 大型提示集会增加延迟。提示嵌入只计算一次,但每次前向传播都会将其与区域特征进行比较。在 CPU 上使用 yoloe-26s-seg.pt 测得,从 80 个类别增加到 1,203 个类别时,前向传播耗时会增加约 19%;使用完整的 4,585 个名称词汇表时,则会增加约 89%。报告的 FLOPs 完全不变,因为区域与文本之间的相似度计算未计入其中,因此性能分析结果不会提醒你。
  • 类别名称在设置提示前只是占位符。刚加载的 *-seg.pt 检查点会使用数字名称("0"、"1"、……)报告 nc=80,因此读取标签前请先调用 set_classes()。无提示检查点在发布时就已填入完整词汇表。

部署说明#

  • 硬件。推理需要配备 4-8 GB 显存的 NVIDIA GPU;n 和 s 规模的模型可以在 Jetson 等边缘 GPU 上运行,也可以降低分辨率后在 CPU 上运行。微调需要一块 GPU。
  • 默认情况下,NMS 与类别无关。YOLOE 使用 agnostic_nms=True 进行预测。默认情况下,它会抑制不同类别中得分较低且相互重叠的边界框,而不只是同一类别内的边界框,从而避免一个对象匹配多个类别时产生重复结果。使用 nms=False 时,YOLOE-26 不执行 IoU 抑制;类别无关模式只会为每个锚点保留得分最高的类别,而不会让一个锚点输出多个类别标签。传入 agnostic_nms=False 可覆盖此设置。
  • 视觉提示默认使用 conf=0.05。视觉提示框的实际效果往往优于其分数所显示的结果:在 LVIS minival 上,如果以某个类别的一个实例作为提示,conf=0.25 会漏掉 YOLOE-26 在 conf=0.05 下检测到的其他实例中的 44% 到 55%。对于零售货架或细胞等由大量近似相同对象组成的密集场景,可能需要使用较低的值;而使用 nms=False 时,YOLOE-26 的一对一检测头得分还会更低,其最佳阈值接近 0.01。其他所有调用都会保留 conf=0.25,包括后续调用、保存的嵌入,以及复用由 refer_image 设置的类别的导出。传入 conf 即可覆盖此设置。
  • 批处理。可以直接进行批量推理,并且同一次调用中的不同图像可以使用不同的视觉提示。

从头训练官方模型#

大多数读者不需要这样做。此流程会使用 Objects365、GQA 和 Flickr30k 复现已发布的开放词汇检查点——约 140 万个训练样本,使用 8 张 RTX 4090——与在你自己的数据上进行微调无关;后者已在上文的训练用法中介绍。

警告

所有继承 YOLOETrainer 的 trainer 都不接受 compile=True,包括默认的 YOLOESegTrainer 和下文所有从头训练的 trainer。请传入 compile=False(默认值)。上文使用的两个微调 trainer YOLOEPESegTrainer 和 YOLOEPETrainer 不受此限制。

训练需要分割标注。你可以下载下方处理好的文件,也可以使用官方团队提供的脚本自行生成;该脚本由 SAM 2.1提供支持。验证使用 LVIS minival。

数据集类型样本框处理后的分割标注
Objects365v1检测609k9621kobjects365_train_segm.json
GQAGrounding621k3681kfinal_mixed_train_no_coco_segm.json
Flickr30kGrounding149k641kfinal_flickr_separateGT_train_segm.json

首先训练文本提示模型,另外两种提示模式则在此基础上进行改进:

from ultralytics import YOLOE
from ultralytics.models.yolo.yoloe import YOLOESegTrainerFromScratch

data = {
    "train": {
        "yolo_data": ["Objects365.yaml"],
        "grounding_data": [
            {
                "img_path": "flickr/full_images/",
                "json_file": "flickr/annotations/final_flickr_separateGT_train_segm.json",
            },
            {
                "img_path": "mixed_grounding/gqa/images",
                "json_file": "mixed_grounding/annotations/final_mixed_train_no_coco_segm.json",
            },
        ],
    },
    "val": {"yolo_data": ["lvis.yaml"]},
}

model = YOLOE("yoloe-26l-seg.yaml")
model.train(
    data=data,  # 或提供包含相同结构的 YAML 文件路径
    batch=128,
    epochs=30,
    close_mosaic=2,
    optimizer="AdamW",
    lr0=2e-3,
    warmup_bias_lr=0.0,
    weight_decay=0.025,
    momentum=0.9,
    workers=4,
    trainer=YOLOESegTrainerFromScratch,
    device="0,1,2,3,4,5,6,7",
)

视觉提示和无提示检查点都从经过训练的文本提示模型开始,并各自更新一个模块。YOLOESegVPTrainer 是视觉提示方案,YOLOEPEFreeTrainer 是无提示方案,但这两个类本身都不会冻结任何内容:选择性训练由你一并传入的 freeze 列表控制,该列表会列出除 savpe 之外的每个检测头子模块(分类塔则是除对应项之外的每个分类塔),而无提示运行还需要 single_cls=True。YOLOE 上游仓库包含 v8 尺度模型的完整方案。

无提示运行完成后,会重新参数化为一个检查点,该检查点在推理时无需提示即可报告类别名称,使用 get_vocab 和 set_vocab:

from ultralytics import YOLOE

# 由无提示运行生成的权重,以及它所基于的文本提示运行生成的权重。每个
# 重新运行都会创建一个新目录(train-2、train-3,...),因此请使用运行输出的路径。
model = YOLOE("runs/segment/train-2/weights/best.pt")  # 无提示运行,其检测头已经融合
text_model = YOLOE("runs/segment/train/weights/best.pt")  # 文本提示运行,其检测头仍未融合

names = list(YOLOE("yoloe-26l-seg-pf.pt").model.names.values())  # 4,585 个名称的词汇表,或你自己的列表
vocab = text_model.get_vocab(names)

model.set_vocab(vocab, names)
model.save("yoloe-26l-seg-pf-custom.pt")  # 切勿覆盖已发布的检查点

get_vocab 会返回由模型的 end2end 标志所选的分支,而 set_vocab 会对该分支重新参数化。已发布的 YOLOE-26 文件会为每个分支分别携带一个词汇表,这样 nms 才能在分支间进行选择;要复现这一点,请从另一份文本提示模型副本中获取第二个词汇表。YOLOE-11 和 YOLOE-v8 只有一个分支,因此直接使用上面的调用即可。

one2one_model = YOLOE("runs/segment/train/weights/best.pt")  # get_vocab 会融合它读取的检测头,因此要加载第二个副本
one2one_model.model.end2end = True  # 读取无 NMS 分支

model.set_vocab(vocab, names, one2one_vocab=one2one_model.get_vocab(names))

引用与致谢#

如果 YOLOE 对你的研究或项目有所帮助,请引用 清华大学的 Ao Wang、Lihao Liu、Hui Chen、Zijia Lin、Jungong Han 和 Guiguang Ding 撰写的原始论文:

引用
@misc{wang2025yoloerealtimeseeing,
      title={YOLOE: Real-Time Seeing Anything},
      author={Ao Wang and Lihao Liu and Hui Chen and Zijia Lin and Jungong Han and Guiguang Ding},
      year={2025},
      eprint={2503.07465},
      archivePrefix={arXiv},
      primaryClass={cs.CV},
      url={https://arxiv.org/abs/2503.07465},
}

如需进一步阅读,可在 arXiv 上查看 YOLOE 原始论文。你可以通过项目的 GitHub 仓库访问源代码和其他资源。

常见问题#

  • Ultralytics YOLOE 增加了 YOLO-World 不具备的两种能力:视觉提示,即用示例框代替类别名称;以及无提示检查点,可直接根据内置的 4,585 个名称词汇表作答,无需任何提示。已发布的 *-seg.pt 检查点生成的每个预测还会附带一个实例分割掩码。在准确率方面,YOLOE 原始论文显示,在 LVIS 上,YOLOE-v8s 的 AP 比 YOLO-Worldv2-S 高 3.5,训练成本仅为其三分之一,推理速度则快 1.4 倍。迁移只需改一行代码——请参阅YOLOE 对比。

  • Ultralytics YOLOE 支持三种提示模式。文本提示是在 *-seg.pt 检查点上以字符串形式提供类别名称,通常优先选择这种方式。视觉提示是在参考图像上提供一个或多个示例框,适用于难以用语言描述的目标。无提示推理使用单独的 *-seg-pf.pt 检查点,根据内置的 4,585 个名称词汇表作答,无需提供任何内容。文本提示和视觉提示共用相同的检查点;无提示模式使用不同的文件,并且不接受 set_classes()。完整对比请参阅选择提示模式。

  • 从 yoloe-26s-seg.pt 开始:YOLOE-26 系列在所有对应尺度上都优于 YOLOE-11 和 YOLOE-v8,而 s 尺度是 LVIS minival 上 mAP 超过 30 的最小型号。当稀有类别的准确率比延迟更重要时,可升级到 m、l 或 x——请比较性能中的 mAPr列。只有在边缘设备部署时才降级到 n。如果你想使用内置词汇表,而不是自己的类别名称,请改为加载同一尺度的 *-seg-pf.pt 文件。

  • object0 和 object1 这样的标签表示预测来自视觉提示:示例框会被归为临时编号类别,而不会保留你的名称。你在 visual_prompts["cls"] 中传入的类别 ID 只用于分组。模型会按你分配 ID 的顺序,将这些类别报告为 object0、object1 等,因此需要在结果中将它们映射回你自己的标签。如果你希望输出中显示自己的名称,请改用文本提示。

  • 无需提示的检查点(*-seg-pf.pt)通过自身内置的词汇表解析类别,并使用 AssertionError: Prompt-free model does not support setting classes. Please try with Text/Visual prompt models. 拒绝 set_classes()。视觉提示会引发 AssertionError: Visual prompts need an unfused YOLOE model.。需要使用自己的类别列表时,请加载 *-seg.pt 检查点。请参阅选择提示模式。

  • 首次使用文本提示时,Ultralytics YOLOE 会通过 pip 从 GitHub 安装 ultralytics/CLIP,并将 TorchScript 文本编码器下载到当前工作目录——YOLOE-26 所需约 254 MB;各模型系列对应的确切资源请参阅安装和要求。视觉提示和无提示检查点都不需要这些内容。要避免在目标机器上下载,请先设置提示,然后用 save_prompt_embeddings() 保存,或者导出已配置类别的模型。

  • 不可以——YOLOE 会在导出时将提示类别写入权重,因此已加载的导出模型会拒绝 set_classes() 和 visual_prompts=。请从原始 .pt 检查点重新导出,并配置新的提示。导出的文件与标准 YOLO 模型行为一致,既可以通过 YOLO() 加载,也可以通过 YOLOE() 加载。

  • 如果你需要实时吞吐量,而且能够说出类别名称,请使用 YOLOE;如果概念分割质量比速度更重要,请使用 SAM 3。两者都接受视觉示例,但只有 YOLOE 支持无提示模式。完整对比请参阅YOLOE 对比。

评论60

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

    1. Glenn JocherUltralytics

      你好,目前 YOLOE 的视觉提示能力是通过 model.predict(..., visual_prompts=..., refer_image=..., predictor=YOLOEVPSegPredictor) 使用的,文档里还没有 auto_annotate() 直接接入这套流程的现成示例;另外 yoloe-26*-seg.pt 本身就会输出分割掩码,所以这类自动标注场景通常不需要再额外叠加 SAM,你可以先按 YOLOE 文档 和 YOLOE.predict() 参考 跑出提示式分割结果再保存为标签;如果你愿意,也欢迎把你的目标流程和样例数据贴在这个讨论里,方便团队一起看。

  1. zhangxiancaiGitHub

    你好,请问yoloe如何使用多张图片里的视觉对象作为参考进行推理。因为一张图片不能全面反映要检测对象的特征,容易漏检。

    1. User

      我也有想过建立一个供yoloe提取多角度多图片特征的小型数据库,但是发现效果并不好。官方通道似乎不支持多特征融合成一个标签。

  2. q9cardGitHub

    Hello, I would like to ask about training YOLOE with a custom grounding dataset.

    My current goal is to use YOLOE for open-vocabulary detection on remote-sensing small objects, and I am trying to integrate my own dataset, AI-TOD-v2, into the open-text / grounding training pipeline.

    So far, I have completed the following steps:

    1. Converted AI-TOD-v2 from standard COCO detection annotations into a grounding-style JSON added caption for each image added tokens_positive for each instance
    2. Successfully ran generate_grounding_cache.py so the custom grounding JSON / cache generation itself seems to work

    However, when I try to continue with the official open-text / from-scratch training pipeline, I run into many issues, for example:

    (1)hard-coded checks in GroundingDataset.verify_labels() for official dataset names / instance counts (2)mismatch between yolo_data and grounding_data text slot / tensor shapes (3)later shape mismatch again in training loss / bbox decode

    So I would like to ask:

    Has anyone successfully trained YOLOE open-text / text-prompt models with a custom grounding dataset (not only the official Flickr/GQA/Objects365 data)? If yes, is there any recommended dataset organization or minimal working setup? Does the official pipeline currently support mixing custom grounding data with official grounding datasets such as Flickr/GQA? For a case like mine, would you recommend: continuing to adapt the current from-scratch training pipeline, or switching to another route based on official pretrained weights? If possible, could you share a minimal working example for training with a custom grounding dataset, even a very small toy example?

    My current impression is that the main difficulty may not be the grounding JSON / cache generation itself, but rather that the current training code has strong assumptions about the official data pipeline. If there is any official recommendation or similar community experience, I would really appreciate it.

    Thank you very much!

    1. Glenn JocherUltralytics

      Thanks for the detailed report — the current public YOLOE from-scratch open-text pipeline is mainly validated around the official Objects365/Flickr/GQA recipe shown in the YOLOE training docs, so a fully custom grounding dataset is not yet a documented plug-and-play path; for AI-TOD-v2, the safer route is usually to start from pretrained yoloe-26*-seg.pt weights and the supported fine-tuning flow in the YOLOE usage docs rather than continuing from scratch. Please open a new issue with a minimal reproducible example, full traceback, yolo checks, and a tiny sample of the grounding JSON/cache so the team can check the dataset verification and shape assumptions directly.

    2. q9cardGitHub

      我按照你说的用yoloe-s26-seg.pt进行微调,出现AttributeError: Can't get attribute 'YOLOESegment26' on <module 'ultralytics.nn.modules.head' from '/mnt/workspace/projects/yoloe/ultralytics/nn/modules/head.py'>错误,改用最新版 pip 安装的 Ultralytics 再试仍然存在这个问题。 目前我的yolo check输出如下: OS Linux-5.10.134-18.0.9.lifsea8.x86_64-x86_64-with-glibc2.35 Environment Linux Python 3.10.19 Install pip Path /root/miniconda3/envs/yoloe/lib/python3.10/site-packages/ultralytics RAM 31.34 GB Disk 94.8/97.9 GB CPU Intel Xeon Platinum 8163 CPU @ 2.50GHz CPU count 8 GPU Tesla V100-SXM2-16GB, 16144MiB GPU count 1 CUDA 12.8

      numpy ✅ 2.2.6>=1.23.0 matplotlib ✅ 3.10.8>=3.3.0 opencv-python ✅ 4.13.0.92>=4.6.0 pillow ✅ 12.1.1>=7.1.2 pyyaml ✅ 6.0.3>=5.3.1 requests ✅ 2.32.5>=2.23.0 scipy ✅ 1.15.3>=1.4.1 torch ✅ 2.10.0>=1.8.0 torch ✅ 2.10.0!=2.4.0,>=1.8.0; sys_platform == "win32" torchvision ✅ 0.25.0>=0.9.0 psutil ✅ 7.2.2>=5.8.0 polars ✅ 1.39.3>=0.20.0 ultralytics-thop ✅ 2.0.18>=2.0.18

    3. Glenn JocherUltralytics

      这个报错基本就是“权重版本和实际导入的代码版本不一致”:yolo checks 显示你用的是 site-packages,但异常却来自 /mnt/workspace/projects/yoloe/ultralytics/...,说明本地仓库覆盖了 pip 安装;而 YOLOESegment26 在当前 head.py 文档里是存在的,所以请先移除或重命名该本地 ultralytics 目录并重启 Python/Notebook 会话,确认 ultralytics.__file__ 指向同一环境后再试;如果还报错,请贴完整 traceback 和精确训练命令。

  3. User

    视觉提示只能支持一种类型吗,当我使用视觉提示进行检测之后,再次设置新的类别就会出现shape '[1, 66, -1]' is invalid for input of size 416000

    1. Glenn JocherUltralytics

      视觉提示不只支持一种类别,visual_prompts 里可以给多组 bboxes/cls(要求 cls 从 0..N-1 连续且与框数量一致),细节见中文 YOLOE 文档;你这个 shape '[1, 66, -1]' is invalid... 通常是跑过视觉提示(尤其用过 refer_image)后又 set_classes() 切新类别导致旧的 prompt/embedding 状态残留,建议直接重新初始化一个新 YOLOE(...) 实例(Notebook 里也请重启 kernel)再设置新类别/新视觉提示。若仍复现,请把最小可复现代码、完整 traceback(文本)以及 yolo checks 输出贴在这里我们才能定位。

    2. User

      好的,问题可以解决。不过衍生出相机模式下,反复创建销毁yoloe()实例,同时相机推理的帧率也很低。我会继续进行优化

    3. User

      感谢,已经将初始化逻辑改成文本/视觉提示发送改变时触发,同时开启GPU加速,问题基本解决,再次感谢答疑

    4. Glenn JocherUltralytics

      很好,感谢你回报进展;相机/视频场景下建议始终复用同一个 YOLOE 实例,只在提示词变化时才更新 set_classes() 或 visual_prompts,且注意传了 visual_prompts 时视频/流会自动用第一帧作为 refer_image(详见 中文 YOLOE 文档),这样能避免反复构建带来的卡顿并提升 FPS。

      from ultralytics import YOLOE
      
      model = YOLOE("yoloe-26s-seg.pt")  # 可按需求换更小尺度提升速度
      # 仅在提示变化时调用:model.set_classes(...) 或传 visual_prompts
      
      for r in model.predict(source=0, stream=True, device=0, half=True, imgsz=640):
          pass  # 在这里处理 r(不要每帧重新初始化模型)
    5. User

      在使用yoloe-26模型时出现模型加载错误Can't get attribute 'YOLOESegment26' on <module 'ultralytics.nn.modules.head' from 'd:\YOLO E\yoloe-main\ultralytics\nn\modules\head.py' YOLOE的库有进行开源更新吗

    6. Glenn JocherUltralytics

      这个报错基本就是“权重文件里引用的模块/类名”和你当前导入的本地 ultralytics 代码不一致导致的;从路径看你现在加载的是 d:\YOLO E\yoloe-main\ultralytics\... 这份源码,它不包含权重所需的 YOLOESegment26,建议先排除本地目录把包“遮住”了的情况,改用最新版 pip 安装的 Ultralytics 再试(用法见中文 YOLOE 文档)。

      pip uninstall -y ultralytics
      pip install -U ultralytics
      yolo checks

      如果仍复现,请把“完整 traceback(文本)”、你是如何加载模型的最小代码(例如 YOLOE("yoloe-26s-seg.pt") / YOLO("yoloe-26s-seg.pt"))、以及上面 yolo checks 的输出贴出来;如果你刚升级过包且在 Notebook 里运行,也请先重启 kernel 再测。

  4. qbigGitHub

    Hello,

    Can I ask why the exported Core ML model doesn't have labels metadata like normal YOLO or even exported YOLO-World models?

    from ultralytics import YOLOE, YOLO
    from pathlib import Path
    from ultralytics.utils import YAML
    
    model_name = "yoloe-11m-seg.pt"
    file_name = "lvis.yaml"
    
    model = YOLOE(model_name)
    model.eval()
    
    # Please replace names with yours
    data = YAML.load(file_name)
    names = [n.split('/')[0] for n in data["names"].values()]
    
    model.set_classes(names, model.get_text_pe(names))
    coreml_path = model.export(format='coreml', half=True, nms=False)
    
    1. Glenn JocherUltralytics

      That’s expected right now: YOLOE’s classes are prompt-defined (and can be changed via set_classes()), so the CoreML exporter doesn’t reliably embed a fixed label list in the model metadata—especially when exporting “raw” outputs with nms=False; if you need labels inside the .mlmodel/.mlpackage, either export with nms=True or post-edit the CoreML package metadata after export (see the YOLOE export notes and the YOLOE API).

  5. tomer196GitHub

    Hi, Is there a way to get the embeddings of each detection when I use model.predict? Similar to the way I can get the embeddings of the visual and text prompts.

  6. ratomGitHub

    I want to perform semantic segmentation with 6 classes (multi-class semantic segmentation task) using YOLOv8, YOLOv11, and YOLOe. My questions are is this possible with existing YOLO models? If yes, how can I create the data for YOLO format? I have the segmentation data with images in one folder and their respective masks in another format. @glenn-jocher

    1. ratomGitHub

      Hi @glenn-jocher, I want to perform semantic segmentation with 6 classes (multi-class semantic segmentation task) using YOLOv8, YOLOv11, and YOLOe. My questions are is this possible with existing YOLO models? If yes, how can I create the data for YOLO format? I have the segmentation data with images in one folder and their respective masks in another format.

    2. Glenn JocherUltralytics(已编辑)

      @tomer196 Fine-tuning and open-vocabulary prompting are mutually exclusive in the current implementation: after fine-tuning with YOLOEPESegTrainer, the checkpoint predicts your dataset’s classes directly and set_classes() raises an error, so keep the original checkpoint for prompting. Details are under Train Usage in the YOLOE docs; we can’t share timelines for other changes.

      @ram-from-tvl For production use you’ll need to choose between AGPL-3.0 compliance (open‑source your entire derivative) or an Enterprise License for proprietary deployment; see options and terms at the Ultralytics License page. For deployment hardening, benchmark and export to your target runtime (ONNX/TensorRT/CoreML/etc.) per the Export section in the YOLOE docs.

      @ram-from-tvl To convert a UNet-style binary mask dataset to YOLO segmentation format, create one TXT per image with polygon coordinates per instance (normalized x,y). Format and examples are in the Segmentation task data format. Minimal conversion example for a single-class binary mask:

      import cv2, numpy as np, os
      
      def mask_to_yolo_segments(mask):
          h, w = mask.shape[:2]
          contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
          segs = []
          for c in contours:
              if len(c) < 3:
                  continue
              pts = c.squeeze(1).astype(float)
              pts[:, 0] /= w
              pts[:, 1] /= h
              segs.append(pts.reshape(-1))
          return segs
      
      mask = cv2.imread("mask.png", 0) > 0
      segs = mask_to_yolo_segments(mask.astype(np.uint8))
      os.makedirs("labels", exist_ok=True)
      with open("labels/image.txt", "w") as f:
          for seg in segs:
              f.write("0 " + " ".join(f"{v:.6f}" for v in seg.tolist()) + "\n")

      @Swetha4545 YOLOE isn’t limited to 80 classes—text prompts are open‑vocab, and the prompt‑free variants use a large vocabulary; for harder concepts like “cotton” try synonyms (e.g., “cotton plant”, “cotton bale”, “fabric”) or switch to visual prompts with a clear reference exemplar; see Text/Visual/Prompt‑free usage in the YOLOE docs and the predictor API for visual prompts: YOLOEVPSegPredictor.

      @ratom For per-pixel class maps (semantic segmentation), YOLO26 provides dedicated -sem models such as yolo26n-sem.pt (task=semantic); see the Semantic Segmentation docs. YOLOv8/YOLO11/YOLOE are instance segmentation models: if you use them, convert your masks to per‑instance polygons and save in YOLO segmentation TXT format (one line per instance: cls x1 y1 x2 y2 ..., normalized); the expected structure and examples are in the Segmentation task data format.

    1. Glenn JocherUltralytics(已编辑)

      @daiyangyang945 ONNX runtime doesn’t support passing visual prompts at inference; bake them before export by running one PyTorch pass with refer_image (which fixes classes), then export the fused model; this preserves the same classes in ONNX and you can still use dynamic batch input: see Visual Prompting and Export sections in the YOLOE docs for details. Example:

      from ultralytics import YOLOE
      from ultralytics.models.yolo.yoloe import YOLOEVPSegPredictor
      
      m = YOLOE("yoloe-11l-seg.pt")
      visual_prompts = {"bboxes": ..., "cls": ...}  # your examples
      m.predict("img.jpg", refer_image="ref.jpg", visual_prompts=visual_prompts, predictor=YOLOEVPSegPredictor)
      m.export(format="onnx", dynamic=True, simplify=True)

      For guidance see the YOLOE page under Predict and Export usage. Refer: YOLOE: Real‑Time Seeing Anything, YOLOEVPSegPredictor API.

      @Chappie123 With bbox-only data, convert to YOLO detection TXT labels and train a detection model. Convert each box from {minx,miny,maxx,maxy} to normalized xc,yc,w,h:

      def to_yolo(minx, miny, maxx, maxy, W, H):
          xc = (minx + maxx) / 2 / W
          yc = (miny + maxy) / 2 / H
          w  = (maxx - minx) / W
          h  = (maxy - miny) / H
          return xc, yc, w, h

      Dataset YAML (minimal):

      path: /data/myset
      train: images/train
      val: images/val
      names: {0: class0, 1: class1}

      Train:

      from ultralytics import YOLOE
      model = YOLOE("yoloe-11s.yaml")
      model.train(data="data.yaml", epochs=100, imgsz=640)

      More in Train mode and Detection task.

      @HLHSM The error is from installing the wrong clip package. Uninstall the PyPI clip and install the official CLIP (per its README), or use a compatible wheel like clip-anytorch, then restart Python:

      pip uninstall -y clip
      pip install clip-anytorch

      If it persists, please run yolo checks and paste the full text output. Reference for the APIs you’re calling: YOLOE API reference.

      @Maya7991 Current ONNX exports accept a single images input; runtime text/visual prompts aren’t exposed as additional ONNX inputs. Use offline prompts: set and fuse classes before export, or use the prompt‑free path.

      from ultralytics import YOLOE
      m = YOLOE("yoloe-11s-seg.pt")
      names = ["person", "bus"]
      m.set_classes(names, m.get_text_pe(names))  # fuse prompts
      m.export(format="onnx", dynamic=True, simplify=True)

      With dynamic=True, you can pass [N,3,H,W] batches in onnxruntime even though the input name is just images. See Export mode and YOLOE Export examples on the docs page: YOLOE docs.

      @beichen2012 Swapping YOLO11’s CNN backbone for a DINOv3‑distilled ViT isn’t supported and would require a custom backbone module plus shape/plumbing changes; we recommend using YOLO26 as‑is or a transformer model like RT‑DETR. If you prototype this, please keep any PR minimal, well‑tested, and scoped to the new backbone only.