RF-DETR: Real-Time Transformer Based Object Detection Without NMS
Hey everyone, today we look at an object detection model that has drawn a lot of attention recently: RF-DETR from the Roboflow team. If you reach for YOLO for every detection need, this tutorial gives you an alternative worth taking seriously, because its architecture is fundamentally different and brings practical advantages people often overlook.
RF-DETR belongs to the DETR (Detection Transformer) family, optimized for real-time speed. What makes it interesting is that it combines two things once considered in tension: transformer-grade accuracy and inference speed competitive with YOLO. On top of that, it needs no Non-Maximum Suppression, which makes your pipeline simpler and more predictable.
We will cover how DETR differs from YOLO conceptually, installation, first inference, training on your own dataset, evaluation, export for deployment, and an honest guide to when you should use this and when YOLO remains the better call.
Introduction
Why the DETR Architecture Is Different
To understand why RF-DETR is interesting, you need to know how it differs from the YOLO approach.
YOLO and other classic detectors work with anchors or grids. The model predicts a very large number of candidate boxes, thousands or tens of thousands per image. Those candidates are then filtered by an algorithm called Non-Maximum Suppression, which discards overlapping boxes and keeps the highest scoring ones.
NMS has several weaknesses. It is a post-processing step that is not trained, so it is not optimized jointly with the model. It has its own hyperparameter (the IoU threshold) you must tune by hand. And most annoyingly, it struggles with genuinely overlapping objects, such as a crowd of people, because NMS can discard detections that were actually correct.
DETR takes a completely different approach. It frames detection as a set prediction problem. The model holds a fixed number of "object queries", say 300, and each query predicts either one object or "no object". Because the architecture uses attention, queries can see each other and coordinate, so naturally no two queries predict the same object. No NMS at all.
The original DETR's weakness was extremely slow convergence during training, needing hundreds of epochs, and heavy inference. RF-DETR, along with variants like Deformable DETR and RT-DETR, fixes that with architectural optimizations.
Practical Advantages of RF-DETR
Several things are genuinely useful in practice.
No NMS means one fewer hyperparameter to tune, and your inference latency becomes more stable because it does not depend on how many objects are in the frame. That matters for real-time applications needing consistent latency.
Its backbone uses DINOv2, a self-supervised model whose features are highly general. In practice RF-DETR often performs well on domains far from COCO, such as medical imagery, aerial imagery, or industrial inspection. That is a real advantage for many production projects.
The model also supports flexible input resolution, letting you trade accuracy for speed without retraining.
And its license is Apache 2.0, meaning free commercial use without open sourcing your own code, unlike some YOLO versions distributed under AGPL.
Installation
python -m venv venv
source venv/bin/activate # Linux / Mac
venv\Scripts\activate # Windows
pip install rfdetr
pip install supervision # for visualization
Verify:
import torch
from rfdetr import RFDETRBase
print("cuda available:", torch.cuda.isavailable())
First Inference
import io
import requests
from PIL import Image
import supervision as sv
from rfdetr import RFDETRBase
from rfdetr.util.cococlasses import COCOCLASSES
model = RFDETRBase()
url = "https://media.roboflow.com/dog.jpeg"
img = Image.open(io.BytesIO(requests.get(url).content))
detections = model.predict(img, threshold=0.5)
labels = [
f"{COCOCLASSES[clsid]} {conf:.2f}"
for clsid, conf in zip(detections.classid, detections.confidence)
]
out = sv.BoxAnnotator().annotate(img.copy(), detections)
out = sv.LabelAnnotator().annotate(out, detections, labels)
out.save("detections.jpg")
print(f"detected {len(detections)} objects")
for clsid, conf, box in zip(detections.classid, detections.confidence, detections.xyxy):
print(f" {COCOCLASSES[clsid]:15s} {conf:.3f} {box.astype(int)}")
Note the result is a Detections object from the supervision library. That is a good design decision, because supervision has become the de facto standard for computer vision utilities, so all its tooling is immediately available: annotation, tracking, counting objects inside zones, and so on.
The threshold parameter is the only knob you really need to tune for inference. 0.5 is a reasonable starting point. Lower it if you miss objects, raise it if you get too many false positives.
Choosing a Model Variant
RF-DETR comes in several sizes.
from rfdetr import RFDETRBase, RFDETRLarge
Faster, suits real-time
model = RFDETRBase()
More accurate, needs a stronger GPU
model = RFDETRLarge()
You can also set input resolution, which strongly affects the speed and accuracy trade-off:
model = RFDETRBase(resolution=560) # faster
model = RFDETRBase(resolution=728) # default
model = RFDETRBase(resolution=896) # better for small objects
Rule of thumb: if your objects are small relative to the image, such as detecting small surface defects or counting people from a distant camera, raise the resolution. If objects are large and obvious, a lower resolution is enough and you get speed for free.
Important note: resolution must be a multiple of 56 because of the backbone's patch structure.
Preparing a Dataset
RF-DETR uses COCO format. The expected directory structure is:
dataset/
train/
annotations.coco.json
image1.jpg
image2.jpg
valid/
annotations.coco.json
...
test/
annotations.coco.json
...
The annotation file is JSON in the standard COCO layout:
{
"images": [
{"id": 1, "filename": "image1.jpg", "width": 1920, "height": 1080}
],
"categories": [
{"id": 1, "name": "helmet"},
{"id": 2, "name": "vest"}
],
"annotations": [
{"id": 1, "imageid": 1, "categoryid": 1, "bbox": [x, y, width, height], "area": 5000, "iscrowd": 0}
]
}
Note that COCO bbox format is [topleftx, toplefty, width, height], not [x1, y1, x2, y2]. This is a very common source of bugs when converting from other formats.
If your dataset is in YOLO format, here is a conversion function:
import json
import os
from PIL import Image
def yolotococo(imagedir, labeldir, classnames, outputjson):
coco = {"images": [], "categories": [], "annotations": []}
for i, name in enumerate(classnames, start=1):
coco["categories"].append({"id": i, "name": name})
annid = 1
for imageid, fname in enumerate(sorted(os.listdir(imagedir)), start=1):
if not fname.lower().endswith((".jpg", ".jpeg", ".png")):
continue
path = os.path.join(imagedir, fname)
with Image.open(path) as im:
width, height = im.size
coco["images"].append({
"id": imageid, "filename": fname,
"width": width, "height": height,
})
labelpath = os.path.join(labeldir, os.path.splitext(fname)[0] + ".txt")
if not os.path.exists(labelpath):
continue
for line in open(labelpath):
parts = line.split()
if len(parts) < 5:
continue
cls, xc, yc, w, h = int(parts[0]), map(float, parts[1:5])
# YOLO uses normalized center coordinates
x = (xc - w / 2) width
y = (yc - h / 2) height
bw = w width
bh = h height
coco["annotations"].append({
"id": annid, "imageid": imageid,
"categoryid": cls + 1,
"bbox": [x, y, bw, bh],
"area": bw bh, "iscrowd": 0,
})
annid += 1
with open(outputjson, "w") as f:
json.dump(coco, f)
print(f"done: {len(coco['images'])} images, {len(coco['annotations'])} annotations")
Training on Your Own Dataset
Once the dataset is ready, training is simple.
from rfdetr import RFDETRBase
model = RFDETRBase()
model.train(
datasetdir="dataset",
epochs=30,
batchsize=4,
gradaccumsteps=4, # effective batch = 4 x 4 = 16
lr=1e-4,
outputdir="output",
)
A few notes on those parameters.
batchsize times gradaccumsteps is your effective batch. The Roboflow team recommends an effective batch around 16. With a large GPU, raise batchsize and lower gradaccumsteps for speed. With a small GPU, do the reverse.
A learning rate of 1e-4 is a good starting point for fine-tuning. For small datasets under 500 images, try 5e-5 so the model does not destroy its pretrained features.
Epoch count depends on dataset size. For a few thousand images, 30 to 50 epochs is usually enough. For small datasets you may need more epochs at a lower learning rate.
During training, the best checkpoint is saved automatically in outputdir.
Monitoring Training
from rfdetr import RFDETRBase
history = []
def log(data):
history.append(data)
print(f"epoch {data.get('epoch')} "
f"trainloss {data.get('trainloss', 0):.4f} "
f"mAP {data.get('testcocoevalbbox', [0])[0]:.4f}")
model = RFDETRBase()
model.callbacks["onfitepochend"].append(log)
model.train(datasetdir="dataset", epochs=30, batchsize=4, gradaccumsteps=4)
The metric to watch is validation mAP, not training loss. Loss falling while mAP plateaus is the classic signature of overfitting.
Using Your Trained Model
from rfdetr import RFDETRBase
import supervision as sv
from PIL import Image
model = RFDETRBase(pretrainweights="output/checkpointbesttotal.pth")
CLASSNAMES = {1: "helmet", 2: "vest"}
img = Image.open("workerphoto.jpg")
detections = model.predict(img, threshold=0.5)
labels = [
f"{CLASSNAMES[cid]} {conf:.2f}"
for cid, conf in zip(detections.classid, detections.confidence)
]
out = sv.BoxAnnotator().annotate(img.copy(), detections)
out = sv.LabelAnnotator().annotate(out, detections, labels)
out.save("result.jpg")
Video Detection
For video, the efficient pattern is processing frames in a loop and combining with a tracker.
import supervision as sv
from rfdetr import RFDETRBase
model = RFDETRBase(pretrainweights="output/checkpointbesttotal.pth")
tracker = sv.ByteTrack()
boxannotator = sv.BoxAnnotator()
labelannotator = sv.LabelAnnotator()
def processframe(frame, index):
detections = model.predict(frame[:, :, ::-1], threshold=0.5) # BGR to RGB
detections = tracker.updatewithdetections(detections)
labels = [f"#{tid} {conf:.2f}"
for tid, conf in zip(detections.trackerid, detections.confidence)]
out = boxannotator.annotate(frame.copy(), detections)
return labelannotator.annotate(out, detections, labels)
sv.processvideo(
sourcepath="input.mp4",
targetpath="output.mp4",
callback=processframe,
)
With ByteTrack, each object receives a consistent ID across frames, so you can count unique objects passing through rather than raw detections per frame.
Exporting for Deployment
For production, export to ONNX so you can run it with a lighter runtime.
from rfdetr import RFDETRBase
model = RFDETRBase(pretrainweights="output/checkpointbest_total.pth")
model.export() # writes an ONNX file to the output directory
Once in ONNX, run it with ONNX Runtime, TensorRT, or OpenVINO depending on your target hardware. It also removes the PyTorch dependency from production, shrinking your Docker image considerably.
RF-DETR or YOLO?
Let me be honest here, since many tutorials are one-sided.
Pick RF-DETR when your domain is far from COCO and you need strong transfer learning, when your objects overlap heavily so NMS becomes a problem, when you need consistent latency regardless of object count, or when an Apache 2.0 license matters for your commercial product.
Pick YOLO (particularly Ultralytics) when you want a very mature ecosystem with abundant tutorials and integrations, when you need tasks beyond detection such as segmentation, pose, and classification in one framework, when you deploy to very constrained edge devices where the nano models still win on size, or when your team already knows the workflow.
And the most honest advice: test both on your own dataset. COCO benchmarks do not always predict performance in your specific domain. Two days spent comparing models is far cheaper than picking wrong and discovering it six months later.
Tips and Best Practices
Treat annotation quality far more seriously than architecture selection. Any model fails on inconsistent labels.
For small objects, raise input resolution before reaching for a bigger model. Resolution is usually more effective and cheaper.
Watch validation mAP rather than loss, and save prediction images at several epochs so you can visually inspect what the model learned.
If your dataset is imbalanced, say one class appears ten times more often, consider oversampling images containing the minority class.
Keep your dataset version and training config in git. Reproducibility in computer vision projects is neglected right up until someone asks why last month's model was better.
Conclusion
RF-DETR is a refreshing addition to object detection and deserves a spot on your shortlist. The summary:
The DETR architecture frames detection as set prediction with object queries, removing the need for NMS entirely.
The DINOv2 backbone makes it strong on domains far from common training data, a real advantage for industrial and medical projects.
Input resolution is a speed and accuracy dial you can turn without retraining.
Datasets use COCO format, and converting from YOLO is straightforward as long as you remember the bounding box format difference.
Integration with supervision makes visualization, tracking, and video analysis very easy.
Exporting to ONNX removes the PyTorch dependency in production and opens the door to TensorRT or OpenVINO.
Take a detection dataset you already have, train both RF-DETR and YOLO for comparable epochs, and compare mAP and latency on your target hardware. The result is sometimes surprising, and a data driven decision always beats following a trend. Happy detecting.