Train one model on RF100-VL sources with size-balanced batch weights¶
RF100-VL is a benchmark of 100 small, independently-collected
detection datasets spanning aerial, industrial, flora/fauna, sport, document and lab-imaging domains -
used elsewhere in these docs to evaluate generalization (see Benchmarks), one
fine-tune per dataset. This cookbook instead uses three of them as an example of joint multi-dataset
training: one RFDETRSmall fine-tuned on all three at once with WeightedMultiSourceBatchSampler.
The three sources differ by more than 20x in size - wheel-defect-detection (216 train images),
aerial-cows (774), bees (4,776) - so a plain ConcatDataset would let bees dominate every batch
while the industrial defect set contributes almost nothing to the gradient. Rather than hand-picking
weights, this notebook computes them automatically as the inverse of each source's measured
train-split size, so the small sources are oversampled instead of drowned out by the large one.
See Training customization -> Mixing datasets for the sampler API reference.
Setup¶
Install rfdetr with the train extra (PyTorch Lightning, COCO eval) and the visual extra (matplotlib and
pandas for the training chart), plus the rf100vl package, which downloads RF100-VL datasets through the
Roboflow API. A GPU is recommended; drop BATCH_SIZE if you hit out-of-memory.
!pip install -q "rfdetr[train,visual]>=1.13.0" "rf100vl>=1.1.2"
"""Train one RF-DETR model on three RF100-VL sources with inverse-size-weighted batches."""
import json
import os
from bisect import bisect_right
from collections import Counter
from itertools import accumulate
from pathlib import Path
from typing import Any
import pandas as pd
from IPython.display import display
from PIL import Image
from rf100vl import get_rf100vl_projects
from torch.utils.data import ConcatDataset
from rfdetr import RFDETRSmall
from rfdetr.config import TrainConfig
from rfdetr.datasets import WeightedMultiSourceBatchSampler, compute_source_batch_sizes
from rfdetr.datasets.coco import CocoDetection, make_coco_transforms
from rfdetr.datasets.save_grids import DatasetGridSaver
from rfdetr.training import RFDETRDataModule, RFDETRModelModule, build_trainer
from rfdetr.utilities.reproducibility import seed_all
from rfdetr.visualize.training import plot_loss_metrics
DATASETS_DIR = Path("datasets")
OUTPUT_DIR = Path("output/multi_source_rf100vl")
# Project names in the "rf100-vl" Roboflow workspace. They span three very different domains and sizes
# on purpose - that size spread is what makes inverse-size weighting worth demonstrating.
SOURCES = ["wheel-defect-detection", "aerial-cows", "bees"]
SEED = 7
EPOCHS = 20
BATCH_SIZE = 8
GRAD_ACCUM_STEPS = 2
RESOLUTION = 512
1 - Download the datasets¶
Get a free Roboflow API key at app.roboflow.com/settings/api and expose it as ROBOFLOW_API_KEY
(an environment variable locally, or a Colab secret with the same name). The rf100vl package downloads
the latest export version of each project and removes Roboflow's synthetic grouping category, so every
export numbers its real classes 0..N-1. Re-running skips datasets that are already on disk.
ROBOFLOW_API_KEY = os.environ.get("ROBOFLOW_API_KEY", "")
if not ROBOFLOW_API_KEY:
try:
from google.colab import userdata
ROBOFLOW_API_KEY = userdata.get("ROBOFLOW_API_KEY") or ""
except Exception: # not in Colab, or the secret is not set
pass
assert ROBOFLOW_API_KEY, "ROBOFLOW_API_KEY not found: in Colab add it via Secrets (key icon), locally set the env var."
# Lists all 100 projects of the workspace; picking by name keeps SOURCES order and fails fast on a typo.
projects = {project.name: project for project in get_rf100vl_projects(api_key=ROBOFLOW_API_KEY)}
DATASET_DIRS = {name: DATASETS_DIR / name for name in SOURCES}
for name in SOURCES:
projects[name].download(str(DATASET_DIRS[name]), overwrite=False)
2 - Unify class names¶
Each RF100-VL export numbers its categories 0..N-1 independently. Concatenating the datasets as-is
would mix those label spaces. Build one class list (first-seen name wins) and a per-source
category_id -> label map so every source writes into the same head - here the three sources happen to
contribute disjoint classes, but the same union step is required whenever two sources could share a name.
TRAIN_COCO = {
name: json.loads((DATASET_DIRS[name] / "train" / "_annotations.coco.json").read_text()) for name in SOURCES
}
CLASS_NAMES = list(dict.fromkeys(cat["name"] for name in SOURCES for cat in TRAIN_COCO[name]["categories"]))
CAT2LABEL = {
name: {cat["id"]: CLASS_NAMES.index(cat["name"]) for cat in TRAIN_COCO[name]["categories"]} for name in SOURCES
}
NUM_CLASSES = len(CLASS_NAMES)
print(f"num_classes={NUM_CLASSES} class_names={CLASS_NAMES}")
3 - Compute inverse-size weights¶
WeightedMultiSourceBatchSampler takes relative weights, not raw sizes - passing the sizes themselves
back in would just reproduce plain ConcatDataset sampling, the behavior this sampler exists to avoid.
Weighting by 1 / size instead tilts every batch toward the small sources: with a batch of 8,
wheel-defect-detection (216 images) requests 6 slots, while bees (4,776 images, 22x larger) and
aerial-cows (774) get the one-slot minimum. The weights need not sum to 1 - the sampler normalises them.
TRAIN_SIZES = [len(TRAIN_COCO[name]["images"]) for name in SOURCES]
WEIGHTS = [1.0 / size for size in TRAIN_SIZES]
slots = compute_source_batch_sizes(BATCH_SIZE, WEIGHTS)
display(pd.DataFrame({"train_size": TRAIN_SIZES, "slots_per_batch": slots}, index=SOURCES))
4 - Subclass RFDETRDataModule¶
Build one CocoDetection per source, all writing into the shared label space from step 2. The
build_train_sampler hook of the data module then returns a WeightedMultiSourceBatchSampler instead of
a size-proportional shuffle, and RF-DETR's own train_dataloader builds the DataLoader around it - so the
loader keeps its configured collate_fn, worker count, pinning and per-worker augmentation seeding without
restating any of them. RFDETRModelModule.on_train_epoch_start forwards set_epoch to it automatically
every epoch, so no extra callback is needed to advance the within-source shuffle.
epoch_length="smallest" keeps this demo short: the epoch ends once the smallest source
(wheel-defect-detection) has been seen once, so the larger sources are sub-sampled rather than the small
one being recycled many times.
Note: Under DDP pass
use_distributed_sampler=Falsetobuild_trainer. The sampler shards batches itself vianum_replicas/rank; without this flag the run fails with aRuntimeErrornaming the fix.
# Only the train split is built: validation is skipped in step 6, so no per-source val/test sets are needed.
TRAIN_SETS = [
CocoDetection(
DATASET_DIRS[name] / "train",
DATASET_DIRS[name] / "train" / "_annotations.coco.json",
transforms=make_coco_transforms("train", RESOLUTION),
remap_category_ids=True,
cat2label=CAT2LABEL[name],
)
for name in SOURCES
]
class MultiSourceDataModule(RFDETRDataModule):
"""Train on several datasets with a fixed, weighted per-source composition of every batch."""
def __init__(
self,
model_config: Any,
train_config: TrainConfig,
train_sets: list[CocoDetection],
weights: list[float],
) -> None:
super().__init__(model_config, train_config)
self.train_sets = train_sets
self.weights = weights
def setup(self, stage: str) -> None:
super().setup(stage)
if stage == "fit":
self._dataset_train = ConcatDataset(self.train_sets)
def build_train_sampler(self, dataset: Any) -> WeightedMultiSourceBatchSampler:
"""Return the batch sampler; the base ``train_dataloader`` builds the DataLoader around it."""
return WeightedMultiSourceBatchSampler.from_concat_dataset(
dataset,
weights=self.weights,
batch_size=self._resolve_batch_size(),
num_replicas=self.trainer.world_size if self.trainer else 1,
rank=self.trainer.global_rank if self.trainer else 0,
seed=SEED,
epoch_length="smallest",
# Keep every gradient-accumulation window complete: the hook skips the dataset padding the
# default path relies on, so the sampler has to round its own epoch to a whole number of windows.
batch_multiple=self.train_config.grad_accum_steps,
)
5 - Inspect one epoch of batches¶
Before training, iterate the sampler and count how many indices came from each source. Every batch
should match compute_source_batch_sizes. A size-proportional ConcatDataset shuffle would instead
follow the source-size ratios printed below - bees would dominate nearly every batch.
seed_all(SEED)
variant = RFDETRSmall(num_classes=NUM_CLASSES, resolution=RESOLUTION)
variant.model_config.model_name = type(variant).__name__
# dataset_dir only feeds the base class's val/test setup; the train set comes from TRAIN_SETS.
train_config = TrainConfig(
dataset_file="roboflow",
dataset_dir=str(DATASET_DIRS[SOURCES[0]]),
output_dir=str(OUTPUT_DIR),
epochs=EPOCHS,
batch_size=BATCH_SIZE,
grad_accum_steps=GRAD_ACCUM_STEPS,
lr_encoder=1e-4,
warmup_epochs=1,
use_ema=False,
multi_scale=False, # the train transforms above use one fixed resolution
tensorboard=False,
class_names=CLASS_NAMES,
progress_bar="tqdm",
)
datamodule = MultiSourceDataModule(variant.model_config, train_config, TRAIN_SETS, WEIGHTS)
datamodule.setup("fit")
train_loader = datamodule.train_dataloader()
sampler = datamodule.train_batch_sampler
assert sampler is not None
A first look at the batches¶
Before reading the numbers, look at what the loader actually yields. DatasetGridSaver draws the images of
one training batch with their boxes and class indices (positions in CLASS_NAMES), after the training
augmentations, so it also shows whether the three sources are mixed inside a single batch.
DatasetGridSaver(train_loader, OUTPUT_DIR / "samples", max_batches=1, dataset_type="train").save_grid()
display(Image.open(OUTPUT_DIR / "samples" / "train_batch0_grid.jpg"))
Six of the eight images come from wheel-defect-detection (classes 0-3), one from aerial-cows (class 4) and one from bees (class 5). That is the 6 / 1 / 1 split computed in step 3: the small defect set dominates every batch while the large bees source appears once, which a plain ConcatDataset shuffle would invert.
# Batches hold indices into the concatenated dataset; the running sizes map each index back to its source.
bounds = list(accumulate(sampler.source_sizes))
compositions = []
for batch in sampler:
per_source = Counter(bisect_right(bounds, index) for index in batch)
compositions.append(tuple(per_source[source] for source in range(len(SOURCES))))
expected_slots = tuple(compute_source_batch_sizes(BATCH_SIZE, WEIGHTS))
composition_df = pd.DataFrame(compositions, columns=SOURCES)
print(f"batches_this_epoch={len(sampler)} expected_slots_per_batch={expected_slots}")
display(composition_df.head(8))
display(
pd.DataFrame(
{
"size_proportional_share": [size / sum(sampler.source_sizes) for size in sampler.source_sizes],
"samples_drawn_this_epoch": composition_df.sum(),
},
index=SOURCES,
).round(3)
)
assert set(compositions) == {expected_slots}, set(compositions)
6 - Fine-tune¶
Validation is skipped here (limit_val_batches=0): the val split of one source does not cover classes
that only appear in the other two, so COCO eval on that split would be misleading. Restore validation
once you have a held-out mix you actually want to score.
model = RFDETRModelModule(variant.model_config, train_config)
trainer = build_trainer(
train_config,
variant.model_config,
use_distributed_sampler=False,
num_sanity_val_steps=0,
limit_val_batches=0,
)
trainer.fit(model, datamodule=datamodule)
7 - Training loss¶
Lightning's CSV logger wrote one row per logged step to metrics.csv in the output directory.
plot_loss_metrics from rfdetr.visualize.training draws the aggregate loss and its components against
the epoch, with a band for the spread of the steps inside each epoch. Validation was skipped, so the loss
is the only signal here; a steady decline across the 20 epochs means the mixed batches are being learned.
# The inline backend shows the open figure at the end of the cell, so it is not displayed explicitly.
fig = plot_loss_metrics(str(OUTPUT_DIR / "metrics.csv"))
What to try next¶
- Swap in a different trio of RF100-VL projects - the
workspace holds 100 of them across aerial, industrial, flora/fauna, sport, document and lab-imaging
domains - by editing
SOURCESand re-running; the class-union and inverse-size-weighting steps need no changes. - Swap the three RF100-VL projects for your own COCO exports in the Roboflow layout (Universe or otherwise); keep the class-union step so labels stay aligned, and the size-measuring step so weights adapt automatically.
- Compare against proportional (size-based) weights by setting
WEIGHTS = TRAIN_SIZESand re-running the inspection cells -beeswill then claim most of every batch instead of a single slot. - Pass
epoch_length="largest"to see every image ofbeesonce per epoch;wheel-defect-detectionwill then be recycled, and the sampler logs a warning past a 10x recycle factor. - Full API:
WeightedMultiSourceBatchSamplerand Mixing datasets with a fixed per-batch ratio.