RF-DETR Documentation

repository·develop·Indexed 27 days ago

https://github.com/roboflow/rf-detr

RF-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.

Tokens
55.4K
Snippets
124
Records
261
Agent score
92%

What's inside RF-DETR

  1. Add custom callbacks to RF-DETR training

    develop

    To add custom PyTorch Lightning callbacks to your training, you can pass them via trainer_kwargs to build_trainer.

    Warning: Passing callbacks= to build_trainer replaces 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_trainer first, then use .extend() on the trainer.callbacks list 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)
  2. Install the rfdetr[plus] extension for XLarge and 2XLarge models

    develop

    The RFDETRXLarge and RFDETR2XLarge models are provided by the rfdetr_plus extension. 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]
  3. Tune Learning Rates and Epoch Counts

    develop

    Learning Rate Tuning

    • Fine-tuning from COCO weights (default): Use lr=1e-4 and lr_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).
    Dataset SizeRecommended Epochs
    < 500 images100-200
    500-2000 images50-100
    2000-10000 images30-50
    > 10000 images20-30

    Note: Use early stopping to automatically determine the optimal stopping point.

  4. Deploy a trained RF-DETR model to Roboflow

    develop

    You 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 RFDETRNano class. For Image Segmentation, use the RFDETRSegMedium class.

    You must provide your Roboflow workspace, project_id, version, and api_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>",
    )
  5. Calculate effective batch size

    develop

    The 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_gpus

    To target an effective batch size of 16, use these recommended configurations:

    GPUVRAMbatch_sizegrad_accum_steps
    A10040-80GB161
    RTX 409024GB82
    RTX 309024GB82
    T416GB44
    RTX 30708GB28
  6. Export RF-DETR models to ExecuTorch (XNNPACK backend)

    develop

    The xnnpack backend is a portable, CPU-based backend that runs in fp32. It is the recommended backend for general CPU platforms. When using format="executorch", the backend parameter must be explicitly provided.

    Note: The exported file is named after the model variant (e.g., rfdetr-medium.pte) and is saved to the output/ directory by default.

    from rfdetr import RFDETRMedium
    
    model = RFDETRMedium(pretrain_weights="<path/to/checkpoint.pth>")
    
    model.export(format="executorch", backend="xnnpack")
  7. Export RF-DETR models to ONNX

    develop

    You can export trained Object Detection or Image Segmentation models to the ONNX format. By default, the exported model is saved to the output directory as inference_model.onnx.

    from rfdetr import RFDETRMedium
    
    model = RFDETRMedium(pretrain_weights="<path/to/checkpoint.pth>")
    
    model.export()
  8. Automatic Dataset Format Detection in RF-DETR

    develop

    RF-DETR automatically detects the dataset format when you call model.train(dataset_dir=<path>). It identifies the format based on the following criteria:

    1. COCO format: Presence of train/_annotations.coco.json.
    2. YOLO format: Presence of data.yaml (or data.yml) and a train/images/ directory.

    If neither is found, an error is raised.

  9. Run RF-DETR Keypoint detection on video, webcam, or RTSP streams

    develop

    To process continuous video, use OpenCV's cv2.VideoCapture to loop through frames. Convert each frame from BGR to RGB before passing it to model.predict(). Use sv.VertexAnnotator to 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()
  10. Quick Start: Train an Object Detection model

    develop

    Use the RFDETRMedium class to train an object detection model. The train() 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, adjust batch_size and grad_accum_steps (e.g., batch_size=4 and grad_accum_steps=4 for 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>",
    )