概要
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
FAQ (5)
トラブル対応なぜ amp_dtype="auto" を使用すると、Tesla T4 や V100 で RF-DETR のトレーニングが約2倍遅くなるのですか?
RF-DETR のデフォルトの amp_dtype="auto" は、bfloat16 がエミュレーションでしか利用できない場合でも、T4/V100 GPU 上で torch.cuda.is_bf16_supported() が True を返すため、bf16-mixed を選択します。T4(compute capability 7.5)と V100(7.0)にはネイティブの bf16 テンソルコアが搭載されていないため、エミュレートされた bf16 は fp16 よりも低速になります。
当面の回避策: TrainConfig で fp16 混合精度を強制します:
config = TrainConfig(
dataset_dir=dataset_dir,
amp_dtype="fp16",
)
トレーナーが bf16-mixed ではなく 16-mixed と報告していることを確認してください。T4 では、これにより学習ステップの時間を約 443 ms から 226 ms に短縮し、メモリ使用量も削減できます。
適切なコード修正は、エミュレーションによるサポートではなく、ネイティブの bf16 サポートをチェックすることです:
native_bf16 = torch.cuda.is_bf16_supported(including_emulation=False)
precision = "bf16-mixed" if native_bf16 else "16-mixed"
including_emulation 引数を持たない古い PyTorch バージョンでは、compute capability のチェックにフォールバックし、Ampere 以降の GPU、つまり compute capability が >= (8, 0) の場合にのみ bf16 を使用してください。T4/V100 で明示的に amp_dtype="bf16" を設定することは引き続き許可するべきですが、"fp16" を推奨する警告を出力するようにしてください。
トラブル対応RF-DETRでPythonを-Oフラグ付きで実行すると、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' を送出する時点になるまで、後になって初めて失敗する可能性があります。
トラブル対応勾配をclip_max_norm / 65536にクリップしたfp16混合精度で、RF-DETRのキーポイント学習が停滞するのはなぜですか?
キーポイントモデルは手動最適化(manual optimization)を使用しているため、この問題の影響を受けます。16-mixed/fp16 では、PyTorch Lightning は optimizer.step() まで勾配を GradScaler の係数で乗算された状態に保持しますが、RF-DETR はアンスケール前にそれらをクリッピングしていました。スケールが 65536 の場合、意図したクリップ値 0.1 は実質的に約 1.5e-6 となり、AdamW による更新がほぼ消滅してしまいます。
修正: PR #1549 / コミット 8f8d2d77 を含むリリースへ RF-DETR をアップグレードしてください。そのコミットを直接インストールするには、次を実行します:
pip install "rfdetr @ git+https://github.com/roboflow/rf-detr.git@8f8d2d77"
コードレベルの修正内容は、_step_optimizer において手動の勾配クリッピングを行う前にオプティマイザをアンスケールすることです。これは、clip_grad_norm_/clip_grad_value_ の前に Lightning のオプティマイザアンスケーリングメソッドを呼び出すことに相当します。
一時的な回避策:
- Ampere 以降の GPU など、bf16 をネイティブにサポートするハードウェアでは bf16-mixed を使用してください。
- キーポイントを fp32 で学習してください。
- アップグレードするまで、MPS、CUDA fp16、T4、V100 では precision="16-mixed" / amp_dtype="fp16" の明示的な指定を避けてください。
Detection(物体検出)とセグメンテーションは自動最適化(automatic optimization)を使用しており、Lightning がアンスケール後にクリッピングを行うため、影響を受けません。
トラブル対応## Root cause
RF-DETR checkpoints are resolution-specific. `checkpoint_best_total.pth` was saved at whatever `resolution` the model was trained with. When you re-instantiate the model, it builds the backbone and positional-embedding grid at the class default resolution unless you explicitly pass `resolution=`. If those don't match, the weights load onto a mismatched grid and the decoded boxes are garbage — often silently, with no shape error.
## Fix
Pass the exact resolution (and class count, and correct model variant) used during training:
```python
from rfdetr import RFDETRBase # must be the same variant you trained (Nano/Small/Medium/Base/Large)
model = RFDETRBase(
pretrain_weights="runs/checkpoint_best_total.pth",
resolution=640, # exactly the value used in training
num_classes=3, # your dataset's class count, if not COCO's 90
)
detections = model.predict("image.jpg", threshold=0.5)
```
## Checklist
- **Match `resolution` exactly.** Find it in your training script or the training logs/args saved in the output directory. Defaults if you never set it: 384 (Nano), 512 (Small), 576 (Medium/Base), 560 (Large) — verify against your installed version's docs.
- **Match `num_classes`.** A mismatch reinitializes the detection head and produces degenerate boxes even if the backbone loads fine.
- **Use the right variant class.** A checkpoint from `RFDETRLarge` won't load correctly into `RFDETRBase`.
- **Update the library:** `pip install -U rfdetr`. Older releases didn't restore resolution from the checkpoint and had related loading bugs.
- **Resuming training vs
この問題は 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 などのクラスのデフォルト値でモデルを再構築します。学習済みの重みは読み込まれますが、アーキテクチャがそれらと一致しません。
恒久的な修正: checkpoint_best_total.pth 内の model_config を保持する修正を含む RF-DETR リリースにアップグレードするか、パッチが適用されたブランチをインストールしてください:pip install -U git+https://github.com/roboflow/rf-detr.git@develop
即時の回避策:
1. 代わりに、strip 処理が行われていないソースチェックポイント(通常は EMA)を読み込んでください:RFDETR.from_checkpoint("output/checkpoint_best_ema.pth")
ソース名は、strip されたチェックポイントに best_total_source として保存されています。
2. または、strip された重みを読み込む前に、デフォルト以外のすべてのアーキテクチャ引数を指定してモデルを再構築してください: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 などの値も学習時と一致させる必要があります。一致しない場合、読み込みに失敗したり、予測やエクスポートが正しくなくなったりする可能性があります。
トラブル対応アップグレード後に、アンチエイリアス処理された画像で学習されたチェックポイントを使用している場合、RF-DETRの予測精度の低下やバウンディングボックスのずれを修正するにはどうすればよいですか?
これは、predict() が antialias=False をハードコードしているため、RF-DETR 1.9.0–1.10.1 に影響します。これは、デフォルトの 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 に置き換えてください。