rf-detr

库

roboflow/rf-detr

实时目标检测、分割与关键点检测的Transformer模型。

项目简介

RF-DETR 是基于 DINOv2 视觉 Transformer 骨干的实时目标检测与实例分割模型,专为高效微调而设计,在 COCO 上达到顶尖精度,并提供关键点检测预览功能。该仓库提供 rfdetr 的 Python 包供训练和部署使用。

README 预览

# RF-DETR: Real-Time SOTA Object Detection, Instance Segmentation, and Keypoint Detection\n\n\n\n[](https://badge.fury.io/py/rfdetr) [](https://pypistats.org/packages/rfdetr) [](https://codecov.io/gh/roboflow/rf-detr) [](https://badge.fury.io/py/rfdetr) [](https://github.com/roboflow/rf-detr/blob/main/LICENSE)\n\n[](https://arxiv.org/abs/2511.09554) [](https://huggingface.co/spaces/SkalskiP/RF-DETR) [](https://colab.research.google.com/github/roboflow-ai/notebooks/blob/main/notebooks/how-to-finetune-rf-detr-on-detection-dataset.ipynb) [](https://blog.roboflow.com/rf-detr) [](https://discord.gg/GbfgXGJ8Bk)\n\n\n\n\n\n\n\n---\n\nRF-DETR is a real-time transformer architecture for object detection, instance segmentation, and keypoint detection (preview) developed by Roboflow. Built on a DINOv2 vision transformer backbone, RF-DETR delivers state-of-the-art accuracy and latency trade-offs on [Microsoft COCO](https://cocodataset.org/#home) and [RF100-VL](https://github.com/roboflow/rf100-vl).\n\nRF-DETR uses a DINOv2 vision transformer backbone and supports object detection, instance segmentation, and keypoint detection (preview) in a single, consistent API. The open-source `rfdetr` package and Apache-designated models are released under Apache 2.0, while Plus components (`rfdetr_plus`, including RF-DETR-XL/2XL detection models) are licensed under PML 1.0.\n\nThe published RF-DETR sizes were created with neural architecture search (NAS) — and the same NAS method is now available on the [Roboflow platform](https://app.roboflow.com/), so you can discover the best architecture for your own dataset. Learn more in the [NAS docs](https://docs.roboflow.com/train/neural-architecture-search).\n\nhttps://github.com/user-attachments/assets/add23fd1-266f-4538-8809-d7dd5767e8e6\n\n## Install\n\nTo install RF-DETR, install the `rfdetr` package in a [**Python>=3.10**](https://www.python.org/) environment with `pip`.\n\n```bash\npip install rfdetr\n```\n\n\nInstall from source\n\n\n\nBy 

常见问题 (5)

故障排除
为什么 RF-DETR 在 Tesla T4 或 V100 上使用 amp_dtype="auto" 时训练速度会慢约 2 倍?

RF-DETR 的默认设置 amp_dtype="auto" 会选择 bf16-mixed,因为 torch.cuda.is_bf16_supported() 在 T4/V100 GPU 上即使 bfloat16 只是通过模拟实现也会返回 True。T4(计算能力 7.5)和 V100(7.0)缺少原生 bf16 tensor core,因此模拟的 bf16 比 fp16 更慢。

临时解决方法:在 TrainConfig 中强制使用 fp16 混合精度:

config = TrainConfig(
    dataset_dir=dataset_dir,
    amp_dtype="fp16",
)

验证训练器报告的是 16-mixed,而不是 bf16-mixed。在 T4 上,这可以将训练步耗时从约 443 毫秒降至 226 毫秒,并降低显存占用。

正确的代码修复方式是检查原生 bf16 支持,而不是模拟支持:

native_bf16 = torch.cuda.is_bf16_supported(including_emulation=False)
precision = "bf16-mixed" if native_bf16 else "16-mixed"

对于没有 including_emulation 参数的旧版本 PyTorch,应回退到计算能力检查,并仅在 Ampere 或更新的 GPU 上(即计算能力 >= (8, 0))使用 bf16。在 T4/V100 上显式设置 amp_dtype="bf16" 应仍然被允许,但应发出一条警告,建议使用 "fp16"。

来源 Issue #1535
故障排除
为什么在 RF-DETR 中以 -O 运行 Python 时,BestMetricSingle 会接受无效的 'better' 值?

Python 的 -O/-OO 模式会移除 assert 语句,因此 BestMetricSingle.__init__() 中的验证会被跳过。请将 src/rfdetr/training/model_ema.py 中的断言替换为在优化模式下也会执行的显式检查:

if better not in {"large", "small"}:
    raise ValueError(
        f"'better' must be either 'large' or 'small', got {better!r}"
    )
self.better = better

作为临时解决方案,可以不使用 -O 运行,或者确保 better 始终是 "large" 或 "small"。如果不修复,无效值可能要到之后 isbetter() 抛出 ValueError: Unexpected value for 'better' 时才会报错。

来源 Issue #1575
故障排除
为什么在 fp16 混合精度下,RF-DETR 关键点训练会停滞,且梯度被裁剪到 clip_max_norm / 65536?

这会影响关键点(keypoint)模型,因为它们使用手动优化(manual optimization)。在 16-mixed/fp16 模式下,PyTorch Lightning 会让梯度一直保持乘以 GradScaler 缩放因子的状态,直到 optimizer.step() 时才取消缩放,但 RF-DETR 在取消缩放之前就执行了梯度裁剪。当缩放因子为 65536 时,原本预期的裁剪值 0.1 实际上会变成约 1.5e-6,导致 AdamW 的更新几乎消失。

修复方法:将 RF-DETR 升级到包含 PR #1549 / 提交 8f8d2d77 的版本。要直接安装该提交:

pip install "rfdetr @ git+https://github.com/roboflow/rf-detr.git@8f8d2d77"

代码层面的修复是:在 _step_optimizer 中,先对优化器执行取消缩放(unscale),再进行手动梯度裁剪,这相当于在 clip_grad_norm_/clip_grad_value_ 之前调用 Lightning 的优化器取消缩放方法。

临时解决方案:
- 在原生支持 bf16 的硬件(如 Ampere 或更新的 GPU)上使用 bf16-mixed。
- 使用 fp32 训练关键点模型。
- 在升级之前,避免在 MPS、CUDA fp16、T4 或 V100 上显式设置 precision="16-mixed" / amp_dtype="fp16"。

检测(detection)和分割(segmentation)不受影响,因为它们使用自动优化(automatic optimization),Lightning 会在取消缩放之后才执行裁剪。

来源 Issue #1536
故障排除
如何修复 RF-DETR 以默认分辨率加载 checkpoint_best_total.pth 并生成错误边界框的问题?

此问题影响 RF-DETR 1.8.0–1.11.0。strip_checkpoint() 会从 checkpoint_best_total.pth 中移除 model_config,因此 RFDETR.from_checkpoint() 会使用类默认值(如 resolution=384、num_select=300 或 dec_layers=2)重建模型。训练好的权重会被加载,但模型架构与之不匹配。

永久修复:升级到包含该修复的 RF-DETR 版本(该修复会在 checkpoint_best_total.pth 中保留 model_config),或安装已打补丁的分支:
pip install -U git+https://github.com/roboflow/rf-detr.git@develop

即时临时解决方案:
1. 改为加载未经剥离的源检查点,通常是 EMA:
RFDETR.from_checkpoint("output/checkpoint_best_ema.pth")
源文件名会以 best_total_source 的形式存储在已剥离的检查点中。
2. 或者在加载已剥离的权重之前,使用所有非默认的架构参数重建模型:
RFDETRNano(pretrain_weights="checkpoint_best_total.pth", resolution=224, num_select=50, dec_layers=3, device="cpu")
你必须传入所有更改过的架构值——而不仅仅是 resolution。诸如 num_queries、mask_downsample_ratio 和 dec_layers 等值也必须与训练时一致,否则加载可能失败,或预测/导出结果将不正确。

来源 Issue #1533
故障排除
如果检查点是在经过抗锯齿处理的图像上训练的,升级后该如何修复 RF-DETR 的预测准确率或边界框漂移问题?

这会影响 RF-DETR 1.9.0–1.10.1,因为 predict() 硬编码了 antialias=False,即使对于使用默认 torchvision 后端、RF-DETR ≤1.4 或 Roboflow 平台 Resize 预处理训练的模型也是如此,而这些方式全都使用抗锯齿缩放。

修复方法:升级到包含 PR #1525 的 RF-DETR 版本(或安装最新的 develop 分支),并显式启用:

pip install -U rfdetr
# 或者,如果已发布的版本尚未包含该修复:
pip install "rfdetr @ git+https://github.com/roboflow/rf-detr.git@develop"

result = model.predict(image, antialias=True)

为保持兼容性,默认值仍为 antialias=False,因此对于抗锯齿检查点,必须传入 antialias=True。在此类检查点上的测试中,这重现了 RF-DETR 1.8.3 的输出,检测结果零差异。

1.9.0–1.10.1 的临时解决方法:在调用 predict() 之前自行预先缩放图像。使用 PIL 双线性重采样或 torchvision.transforms.functional.resize(..., antialias=True) 将图像缩放到 model.model.resolution,然后将返回的边界框从缩放后的分辨率按比例还原到原始图像尺寸。此方法依赖于内部属性,升级后应改用 antialias=True。

来源 Issue #1516