RF-DETR Documentation
repository·develop·Indexed 27 days ago
https://github.com/roboflow/rf-detrRF-DETR is a real-time transformer architecture by Roboflow for object detection, instance segmentation, and keypoint detection, utilizing a DINOv2 vision transformer backbone. The rfdetr package (v1.8.3) provides various model sizes (Nano to 2XLarge) optimized for accuracy and latency. It includes support for training with custom Albumentations augmentation presets, integration with the inference library, and specialized classes for different computer vision tasks.
What's inside RF-DETR
- RF-DETR Seg (Preview) provides state-of-the-art instance segmentation. Documentation is available regarding the segmentation architecture and training procedures.
Add custom callbacks to RF-DETR training
developTo add custom PyTorch Lightning callbacks to your training, you can pass them via
trainer_kwargstobuild_trainer.Warning: Passing
callbacks=tobuild_trainerreplaces the entire default callback list (including EMA, COCO evaluation, and best-model checkpointing).To extend the default callback list instead of replacing it, call
build_trainerfirst, then use.extend()on thetrainer.callbackslist before calling.fit().from pytorch_lightning.callbacks import LearningRateMonitor, ModelSummary from rfdetr.training import build_trainer # Option 1: Replace all default callbacks extra_callbacks = [ LearningRateMonitor(logging_interval="step"), ModelSummary(max_depth=3), ] trainer = build_trainer( train_config, model_config, callbacks=extra_callbacks, # replaces the default callback list entirely ) # Option 2: Extend the default callback list (Recommended) trainer = build_trainer(train_config, model_config) trainer.callbacks.extend( [ LearningRateMonitor(logging_interval="step"), ] ) trainer.fit(module, datamodule)Install the rfdetr[plus] extension for XLarge and 2XLarge models
developThe
RFDETRXLargeandRFDETR2XLargemodels are provided by therfdetr_plusextension. To use these larger models, you must install the extension using the following command. Note that these models require a Roboflow account and are licensed under PML 1.0.pip install rfdetr[plus]Tune Learning Rates and Epoch Counts
developLearning Rate Tuning
- Fine-tuning from COCO weights (default): Use
lr=1e-4andlr_encoder=1.5e-4. - Small datasets (<1000 images): Use a lower
lr(e.g.,5e-5) to prevent overfitting. - Large datasets (>10000 images): Consider a higher
lr(e.g.,2e-4).
Recommended Epoch Counts
Dataset Size Recommended Epochs < 500 images 100-200 500-2000 images 50-100 2000-10000 images 30-50 > 10000 images 20-30 Note: Use early stopping to automatically determine the optimal stopping point.
- Fine-tuning from COCO weights (default): Use
Deploy a trained RF-DETR model to Roboflow
developYou can deploy fine-tuned RF-DETR detection or segmentation models to Roboflow using the
deploy_to_roboflow()method. This enables cloud inference, edge hardware deployment, and multi-step vision workflows.For Object Detection, use the
RFDETRNanoclass. For Image Segmentation, use theRFDETRSegMediumclass.You must provide your Roboflow
workspace,project_id,version, andapi_key.# For Object Detection from rfdetr import RFDETRNano x = RFDETRNano(pretrain_weights="<path/to/pretrain/weights/dir>") x.deploy_to_roboflow( workspace="<your-workspace>", project_id="<your-project-id>", version=1, api_key="<YOUR_API_KEY>", ) # For Image Segmentation from rfdetr import RFDETRSegMedium x = RFDETRSegMedium(pretrain_weights="<path/to/pretrain/weights/dir>") x.deploy_to_roboflow( workspace="<your-workspace>", project_id="<your-project-id>", version=1, api_key="<YOUR_API_KEY>", )Calculate effective batch size
developThe effective batch size is determined by the combination of your local batch size, gradient accumulation steps, and the number of GPUs used:
effective_batch_size = batch_size × grad_accum_steps × num_gpusTo target an effective batch size of 16, use these recommended configurations:
GPU VRAM batch_sizegrad_accum_stepsA100 40-80GB 16 1 RTX 4090 24GB 8 2 RTX 3090 24GB 8 2 T4 16GB 4 4 RTX 3070 8GB 2 8 Deploy RF-DETR with LitServe (Lightning AI)
developFor scalable inference serving, you can deploy RF-DETR using LitServe, the AI model serving framework from Lightning AI.Export RF-DETR models to ExecuTorch (XNNPACK backend)
developThe
xnnpackbackend is a portable, CPU-based backend that runs infp32. It is the recommended backend for general CPU platforms. When usingformat="executorch", thebackendparameter must be explicitly provided.Note: The exported file is named after the model variant (e.g.,
rfdetr-medium.pte) and is saved to theoutput/directory by default.from rfdetr import RFDETRMedium model = RFDETRMedium(pretrain_weights="<path/to/checkpoint.pth>") model.export(format="executorch", backend="xnnpack")Export RF-DETR models to ONNX
developYou can export trained Object Detection or Image Segmentation models to the ONNX format. By default, the exported model is saved to the
outputdirectory asinference_model.onnx.from rfdetr import RFDETRMedium model = RFDETRMedium(pretrain_weights="<path/to/checkpoint.pth>") model.export()Automatic Dataset Format Detection in RF-DETR
developRF-DETR automatically detects the dataset format when you call
model.train(dataset_dir=<path>). It identifies the format based on the following criteria:- COCO format: Presence of
train/_annotations.coco.json. - YOLO format: Presence of
data.yaml(ordata.yml) and atrain/images/directory.
If neither is found, an error is raised.
- COCO format: Presence of
Run RF-DETR Keypoint detection on video, webcam, or RTSP streams
developTo process continuous video, use OpenCV's
cv2.VideoCaptureto loop through frames. Convert each frame from BGR to RGB before passing it tomodel.predict(). Usesv.VertexAnnotatorto draw the results on the original BGR frame for display.import cv2 import supervision as sv from rfdetr import RFDETRKeypointPreview model = RFDETRKeypointPreview() # Replace with <SOURCE_VIDEO_PATH>, <WEBCAM_INDEX>, or <RTSP_STREAM_URL> video_capture = cv2.VideoCapture("<SOURCE_VIDEO_PATH>") if not video_capture.isOpened(): raise RuntimeError("Failed to open video source") while True: success, frame_bgr = video_capture.read() if not success: break frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB) key_points = model.predict(frame_rgb, threshold=0.5) annotated_frame = sv.VertexAnnotator().annotate(frame_bgr, key_points) cv2.imshow("RF-DETR Keypoint Video", annotated_frame) if cv2.waitKey(1) & 0xFF == ord("q"): break video_capture.release() cv2.destroyAllWindows()Quick Start: Train an Object Detection model
developUse the
RFDETRMediumclass to train an object detection model. Thetrain()method automatically detects if your dataset is in COCO or YOLO format based on the directory structure. To maintain an effective total batch size of 16 on different hardware, adjustbatch_sizeandgrad_accum_steps(e.g.,batch_size=4andgrad_accum_steps=4for a T4 GPU).from rfdetr import RFDETRMedium model = RFDETRMedium() model.train( dataset_dir="<DATASET_PATH>", epochs=100, batch_size=4, grad_accum_steps=4, lr=1e-4, output_dir="<OUTPUT_PATH>", )