Baidu's RT-DETR: A Vision Transformer-Based Real-Time Object Detector#
Overview#
Real-Time Detection Transformer (RT-DETR), developed by Baidu, is an end-to-end object detector that provides real-time performance while maintaining high accuracy. It builds on DETR, an NMS-free transformer detection framework, and adds a convolutional backbone and an efficient hybrid encoder to reach real-time speed. RT-DETR efficiently processes multiscale features by decoupling intra-scale interaction and cross-scale fusion. The model is highly adaptable, supporting flexible adjustment of inference speed using different decoder layers without retraining. RT-DETR performs best on accelerated backends such as CUDA with TensorRT.
Watch: How to Use Baidu's RT-DETR for Object Detection | Inference and Benchmarking with Ultralytics
Overview of Baidu's RT-DETR. The RT-DETR model architecture diagram shows the last three stages of the backbone {S3, S4, S5} as the input to the encoder. The efficient hybrid encoder transforms multiscale features into a sequence of image features through intrascale feature interaction (AIFI) and cross-scale feature-fusion module (CCFM). The IoU-aware query selection is employed to select a fixed number of image features to serve as initial object queries for the decoder. Finally, the decoder with auxiliary prediction heads iteratively optimizes object queries to generate boxes and confidence scores (source).
Key Features#
- Efficient Hybrid Encoder: Baidu's RT-DETR uses an efficient hybrid encoder that processes multiscale features by decoupling intra-scale interaction and cross-scale fusion. This transformer-based design reduces computational costs and allows for real-time object detection.
- IoU-aware Query Selection: Baidu's RT-DETR improves object query initialization with IoU-aware query selection. This allows the model to focus on the most relevant objects in the scene, enhancing the detection accuracy.
- Adaptable Inference Speed: Baidu's RT-DETR supports flexible adjustments of inference speed by using different decoder layers without the need for retraining. This adaptability facilitates practical application in various real-time object detection scenarios.
- NMS-Free Framework: Based on DETR, RT-DETR eliminates the need for non-maximum suppression post-processing, simplifying the detection pipeline and potentially improving efficiency.
- Anchor-Free Detection: As an anchor-free detector, RT-DETR simplifies the detection process and may improve generalization across different datasets.
Pretrained Models#
The Ultralytics Python API provides pretrained PaddlePaddle RT-DETR models with different scales:
- RT-DETR-L: 53.0% AP on COCO val2017, 114 FPS on T4 GPU
- RT-DETR-X: 54.8% AP on COCO val2017, 74 FPS on T4 GPU
Baidu released RTDETRv2 in July 2024, which further improves on the original architecture.
Usage Examples#
The examples below show simple RT-DETR training and inference. Models can also be trained on cloud GPUs through Ultralytics Platform.
from ultralytics import RTDETR
# Load a COCO-pretrained RT-DETR-l model
model = RTDETR("rtdetr-l.pt")
# Display model information (optional)
model.info()
# Train the model on the COCO8 example dataset for 100 epochs
results = model.train(data="coco8.yaml", epochs=100, imgsz=640)
# Run inference with the RT-DETR-l model on the 'bus.jpg' image
results = model("path/to/bus.jpg")Set deterministic=False when training RT-DETR on CUDA with PyTorch 2.0 or later. Its deformable attention uses F.grid_sample, which has no deterministic CUDA backward, so deterministic=True cannot make the run reproducible and can reduce training throughput. seed still controls weight initialization, data order, and augmentation sampling.
RT-DETR pretrained weights support two inference-time settings to reduce latency without retraining:
eval_idx: Stop decoding early. For the default 6-layer decoder, use a zero-based index (0–5).eval_idx=5uses all layers;eval_idx=3uses 4 layers. On a T4 GPU with TensorRT v10.11, RT-DETR-L improves from 8.0 ms / 52.7 mAP to 7.4 ms / 52.5 mAP with 4 layers.num_queries: Reduce object queries (default: 300). Lowering to 100 can reach 7.4 ms / 51.7 mAP on COCO in the same setup. On datasets with fewer objects per image the mAP drop is typically smaller, but keep the value above the maximum expected objects per image.
Both settings can lower mAP — validate the trade-off on your dataset before deployment.
from ultralytics import RTDETR
rtdetr = RTDETR("rtdetr-l.pt")
head = rtdetr.model.model[-1]
# Choose one or both settings after validating the speed/accuracy trade-off.
head.decoder.eval_idx = 3 # Use 4 of 6 decoder layers.
head.num_queries = 100 # Use fewer object queries.
results = rtdetr("path/to/image.jpg")
# Export uses the same decoder and query settings, including TensorRT exports.
rtdetr.export(format="engine", device=0, quantize=16)Supported Tasks and Modes#
This table presents the model types, the specific pretrained weights, the tasks supported by each model, and the supported modes (Train, Val, Predict, Export), indicated by ✅ emojis.
| Model Type | Pretrained Weights | Tasks Supported | Training | Validation | Inference | Export |
|---|---|---|---|---|---|---|
| RT-DETR Large | rtdetr-l.pt | Object Detection | ✅ | ✅ | ✅ | ✅ |
| RT-DETR Extra-Large | rtdetr-x.pt | Object Detection | ✅ | ✅ | ✅ | ✅ |
rtdetr-resnet50.yaml and rtdetr-resnet101.yaml are shipped as YAML architectures only. Ultralytics releases pretrained weights only for rtdetr-l and rtdetr-x. Instantiate the ResNet variants from YAML (for example, RTDETR("rtdetr-resnet50.yaml")) and train or fine-tune them as needed.
Ideal Use Cases#
RT-DETR is particularly well-suited for applications requiring both high accuracy and real-time performance:
- Autonomous Driving: For reliable environmental perception in self-driving systems where both speed and accuracy are critical.
- Advanced Robotics: Enabling robots to perform complex tasks requiring accurate object recognition and interaction in dynamic environments.
- Medical Imaging: For applications in healthcare where precision in object detection can be crucial for diagnostics.
- Surveillance Systems: For security applications requiring real-time monitoring with high detection accuracy. Learn about security alarm systems.
- Satellite Image Analysis: For detailed analysis of high-resolution imagery where global context understanding is important. Read about computer vision in satellite imagery.
Citations and Acknowledgments#
If you use Baidu's RT-DETR in your research or development work, please cite the original paper:
@misc{lv2023detrs,
title={DETRs Beat YOLOs on Real-time Object Detection},
author={Wenyu Lv and Shangliang Xu and Yian Zhao and Guanzhong Wang and Jinman Wei and Cheng Cui and Yuning Du and Qingqing Dang and Yi Liu},
year={2023},
eprint={2304.08069},
archivePrefix={arXiv},
primaryClass={cs.CV}
}For RTDETRv2, you can cite the 2024 paper:
@misc{lv2024rtdetrv2,
title={RT-DETRv2: Improved Baseline with Bag-of-Freebies for Real-Time Detection Transformer},
author={Wenyu Lv and Yian Zhao and Qinyao Chang and Kui Huang and Guanzhong Wang and Yi Liu},
year={2024},
eprint={2407.17140},
archivePrefix={arXiv},
primaryClass={cs.CV}
}We would like to acknowledge Baidu and the PaddlePaddle team for creating and maintaining this valuable resource for the computer vision community. Their development of the transformer-based real-time object detector RT-DETR is greatly appreciated.
FAQ#
Baidu's RT-DETR (Real-Time Detection Transformer) is a real-time, transformer-based object detector. It efficiently processes multiscale features by decoupling intra-scale interaction and cross-scale fusion through its efficient hybrid encoder. By employing IoU-aware query selection, the model focuses on the most relevant objects, enhancing detection accuracy. Its adaptable inference speed, achieved by adjusting decoder layers without retraining, makes RT-DETR suitable for various real-time object detection scenarios.
Use the Ultralytics Python API to load the pretrained PaddlePaddle RT-DETR models. For example, to load the COCO-pretrained RT-DETR-l model, fine-tune it, and run inference:
Examplefrom ultralytics import RTDETR # Load a COCO-pretrained RT-DETR-l model model = RTDETR("rtdetr-l.pt") # Display model information (optional) model.info() # Train the model on the COCO8 example dataset for 100 epochs results = model.train(data="coco8.yaml", epochs=100, imgsz=640) # Run inference with the RT-DETR-l model on the 'bus.jpg' image results = model("path/to/bus.jpg")Baidu's RT-DETR combines an efficient hybrid encoder with IoU-aware query selection, which reduces computational cost while maintaining high accuracy. Its ability to adjust inference speed by using different decoder layers without retraining adds flexibility, which is useful for real-time applications on accelerated backends such as CUDA with TensorRT. The transformer architecture also captures more global context than traditional CNN-based detectors.
Baidu's RT-DETR allows flexible adjustments of inference speed by using different decoder layers without requiring retraining. This lets you balance speed and accuracy across real-time object detection tasks: use fewer decoder layers for faster processing with slightly lower accuracy, or all layers for the most accurate detections. This feature is particularly valuable when deploying models across devices with varying computational capabilities.
No. For RT-DETR,
max_detcaps how many predictions are returned after inference, but it does not increase the number of object queries produced by the decoder. The Ultralytics RT-DETR pretrained checkpoints use 300 object queries, so they cannot return more than 300 detections per image even if you setmax_detto a larger value.Use
max_detto reduce returned detections, for examplemax_det=100, when you only need fewer high-confidence predictions. If your dataset can contain more than 300 objects per image, train a custom RT-DETR model with a higher decoder query count (nq) in the model YAML; changing this value on a pretrained checkpoint after training is not equivalent and requires retraining to learn the additional queries.Yes, RT-DETR models support the Ultralytics training, validation, prediction, and export modes. The Ultralytics framework provides a consistent API across model architectures, so RT-DETR uses the same workflow as YOLO models.
Comments148
Ask a question, share your results, or help someone else.
PhucPhamSy
Hi all, Could you please let me know how to use all parameters in the appendix of the original paper, "https://arxiv.org/pdf/2304.08069"? Thanks!
1
Glenn JocherUltralyticsHey there! 👋
We're really glad you're interested in diving deep into the parameters detailed in the original paper. Specifically, for utilizing parameters as mentioned in the RT-DETR paper ("DETRs Beat YOLOs on Real-time Object Detection"), I recommend focusing on the key components such as the Efficient Hybrid Encoder, IoU-aware Query Selection, and adaptability in Inference Speed adjustments that make RT-DETR efficient.
Details on these components can be extrapolated to parameter usage within your model through our Python API. For instance, when initializing the RT-DETR model or adjusting inference speed, you would consider the different scales of pre-trained models available:
from ultralytics import RTDETR # For a larger model with potentially higher accuracy but lower FPS (Frames Per Second) model = RTDETR('rtdetr-l.pt') # For an extra-large model prioritizing accuracy over speed model_x = RTDETR('rtdetr-x.pt')Adjustments for inference speed and applying IoU-aware query selection can directly correlate with your focus during the
.train()or.predict()processes, especially understanding what goes behind each configuration setting in these functions.Unfortunately, we don't provide a direct mapping for every parameter mentioned in the appendix to code-level argument settings as the implementation abstracts many complexities for user convenience and to maintain the API's simplicity. However, understanding the RT-DETR's key features and translating that understanding into practical API usage is a great way to leverage the power of RT-DETR. 😊
For more tailored guidance, always feel free to ask or refer to our official documentation for specific examples and deeper insights.
Happy coding! 🚀
Murat Raimbekovhey @wba-zzu, thanks for raising this.
quick rundown of where things stand:
resnet50 / resnet101 - the architectures are already shipped as yaml configs:
you can build and train them straight from yaml:
from ultralytics import RTDETR model = RTDETR("rtdetr-resnet50.yaml") model.train(data="coco.yaml", epochs=100, imgsz=640)however, ultralytics does not publish pretrained weights for these. the only official rt-detr checkpoints in the ultralytics/assets releases are
rtdetr-l.ptandrtdetr-x.pt, both of which use the hgnetv2 backbone (not resnet). this is also flagged in the model docs under "architecture-only variants".resnet18 - not shipped. there is no
rtdetr-resnet18.yamlin the repo, so a resnet18 variant would need its own yaml and corresponding modules added.loading external pretrained weights: ultralytics builds the model from yaml, so the state_dict keys follow a pattern like
model.<index>.layer.<...>.conv.weight. weights from another implementation will not load directly - they would need a key-mapping / conversion step to match this layout.hope this helps!
Boao Wang想要将原版RT-DETR中的ResNet50和ResNet18以及ResNet101完全移植到Ultralytics,并且获得其预训练模型
995742853
您好,我想请问一下,在哪里有基于rtdetr-resnet50的预训练pt权重,我知道看到rtdetr-l以及x的预训练权重
Glenn JocherUltralytics目前 RT-DETR 文档 里公开提供的 Ultralytics 预训练权重只有
rtdetr-l.pt和rtdetr-x.pt;如果你找的是 ResNet50 版本,建议查看 Baidu 官方的 RT-DETR PyTorch 权重列表,其中提供的是rtdetr_r50vd_*.pth,不是 Ultralytics 直接发布的rtdetr-resnet50.pt,也欢迎直接在这里继续提问,方便 Ultralytics 团队跟进。 (docs.ultralytics.com)995742853
谢谢您的回复
maitianstudio-arch
How to use RT-DETRv2?
Glenn JocherUltralyticsUltralytics currently exposes the original RT-DETR pretrained weights (
rtdetr-l.pt,rtdetr-x.pt) via theRTDETRAPI; RT-DETRv2 pretrained weights/configs aren’t packaged inultralyticsyet, so if you share what RT-DETRv2 checkpoint you have (Paddle vs PyTorch) and how you’re trying to run it, we can point you to the right conversion/workflow—meanwhile you can use RT-DETR as shown in the RT-DETR docs.from ultralytics import RTDETR model = RTDETR("rtdetr-l.pt") results = model("path/to/image.jpg")
fxc0627
你好,请问RE-DETR模型适用于小目标工业缺陷检测吗?对于小目标检测有什么天然的优势?
wang18382140151-hub
你好,最近deim,dfine等对于rtdetr有了很好的改进,尤其是deim能很好的加速训练的速度,能将其整合进rtdetr中吗?
yuwencool
您好RT-DETR模型的推理支持model.track模式吗?
liyansong123456
RT-DETRv3 has been released. Does Ultralytics have plans to integrate it?
AK993
你好,rt-detr支持在转为rknn格式,并在rk3588上部署吗