-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathtest_module_data.py
More file actions
1891 lines (1524 loc) · 82.4 KB
/
Copy pathtest_module_data.py
File metadata and controls
1891 lines (1524 loc) · 82.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ------------------------------------------------------------------------
# RF-DETR
# Copyright (c) 2025 Roboflow. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
"""Comprehensive unit tests for RFDETRDataModule (LightningDataModule wrapper)."""
import builtins
import logging
import warnings
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
import torch
import torch.utils.data
from PIL import Image
from torch.utils.data import DataLoader
from rfdetr.config import RFDETRBaseConfig, TrainConfig
from rfdetr.datasets.yolo import YoloDetection, YoloSplitUnavailableError
from rfdetr.training.module_data import RFDETRDataModule
from rfdetr.utilities.tensors import NestedTensor, PackedTargets, pack_targets
# ---------------------------------------------------------------------------
# Private helpers — used by both module-level fixtures and class-level _setup_*
# methods (which cannot inject pytest fixtures directly).
# Only define a private helper when it is called from more than one site;
# single-use logic belongs directly in the fixture body.
# ---------------------------------------------------------------------------
def _base_model_config(**overrides):
"""Return a minimal RFDETRBaseConfig with pretrain_weights disabled.
Examples:
>>> config = _base_model_config(num_classes=7)
>>> config.device, config.num_classes, config.pretrain_weights
('cpu', 7, None)
"""
defaults = dict(pretrain_weights=None, device="cpu", num_classes=5)
defaults.update(overrides)
return RFDETRBaseConfig(**defaults)
def _base_train_config(tmp_path=None, **overrides):
"""Return a minimal TrainConfig suitable for unit tests.
Examples:
>>> config = _base_train_config(batch_size=4)
>>> config.batch_size, config.dataset_dir.endswith("dataset"), config.output_dir.endswith("output")
(4, True, True)
"""
dataset_dir = str(tmp_path / "dataset") if tmp_path else "/nonexistent/dataset"
output_dir = str(tmp_path / "output") if tmp_path else "/nonexistent/output"
defaults = dict(
dataset_dir=dataset_dir,
output_dir=output_dir,
epochs=10,
lr=1e-4,
lr_encoder=1.5e-4,
batch_size=2,
weight_decay=1e-4,
lr_scheduler_kwargs={"lr_drop": 8},
warmup_epochs=1.0,
drop_path=0.0,
multi_scale=False,
expanded_scales=False,
do_random_resize_via_padding=False,
grad_accum_steps=1,
tensorboard=False,
)
defaults.update(overrides)
return TrainConfig(**defaults)
class _FakeDataset(torch.utils.data.Dataset):
"""Minimal dataset stub with a controllable length.
Args:
length: Number of items to report via ``__len__``.
with_coco: If True, attach a mock ``.coco`` attribute with ``cats``
so ``class_names`` can be tested.
"""
def __init__(self, length: int = 100, with_coco: bool = False) -> None:
self._length = length
if with_coco:
coco = MagicMock()
coco.cats = {1: {"name": "cat"}, 2: {"name": "dog"}}
self.coco = coco
else:
self.coco = None
def __len__(self) -> int:
return self._length
def __getitem__(self, idx):
raise NotImplementedError
def _fake_dataset(length: int = 100, with_coco: bool = False) -> _FakeDataset:
"""Return a minimal ``_FakeDataset`` with a controllable length.
Examples:
>>> dataset = _fake_dataset(length=3, with_coco=True)
>>> len(dataset), dataset.coco.cats[1]["name"]
(3, 'cat')
"""
return _FakeDataset(length, with_coco)
class _VisualDataset(torch.utils.data.Dataset):
"""Minimal transformed dataset item for DataModule sample visualization."""
def __len__(self) -> int:
"""Return the fixed fake dataset length."""
return 1
def __getitem__(self, idx: int) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
"""Return one normalized image tensor with box and keypoint targets."""
return (
torch.full((3, 16, 16), 0.5, dtype=torch.float32),
{
"boxes": torch.tensor([[0.5, 0.5, 0.5, 0.5]], dtype=torch.float32),
"labels": torch.tensor([0], dtype=torch.int64),
"keypoints": torch.tensor([[[0.25, 0.25, 2.0], [0.75, 0.75, 0.0]]], dtype=torch.float32),
"size": torch.tensor([16, 16], dtype=torch.int64),
},
)
def _make_batch(batch_size: int = 2, channels: int = 3, h: int = 16, w: int = 16):
"""Build a ``(NestedTensor, targets)`` tuple for transfer_batch_to_device tests.
Examples:
>>> samples, targets = _make_batch(batch_size=2, h=8, w=8)
>>> samples.tensors.shape, len(targets)
(torch.Size([2, 3, 8, 8]), 2)
"""
tensors = torch.randn(batch_size, channels, h, w)
mask = torch.zeros(batch_size, h, w, dtype=torch.bool)
samples = NestedTensor(tensors, mask)
targets = [
{
"boxes": torch.tensor([[0.5, 0.5, 0.1, 0.1]]),
"labels": torch.tensor([1]),
"image_id": torch.tensor(i),
"orig_size": torch.tensor([h, w]),
}
for i in range(batch_size)
]
return samples, targets
def _build_datamodule(model_config=None, train_config=None, tmp_path=None):
"""Construct RFDETRDataModule (build_dataset is not called at init time).
Examples:
>>> datamodule = _build_datamodule()
>>> datamodule.model_config.device, datamodule.train_config.batch_size
('cpu', 2)
"""
mc = model_config or _base_model_config()
tc = train_config or _base_train_config(tmp_path)
return RFDETRDataModule(mc, tc)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def fixture_training_setup():
"""Return the default model config, train config, and DataModule together."""
model_config = _base_model_config()
train_config = _base_train_config()
datamodule = _build_datamodule(model_config, train_config)
return model_config, train_config, datamodule
@pytest.fixture
def coco_datamodule(tmp_path):
"""Return an RFDETRDataModule configured for a COCO dataset."""
return _build_datamodule(
train_config=_base_train_config(tmp_path, dataset_file="coco"),
tmp_path=tmp_path,
)
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
class TestInit:
"""RFDETRDataModule.__init__ stores configs and initialises dataset slots."""
def test_stores_model_config(self, tmp_path, base_model_config):
"""model_config is accessible as an attribute after construction."""
mc = base_model_config(num_classes=3)
dm = _build_datamodule(model_config=mc, tmp_path=tmp_path)
assert dm.model_config is mc
def test_stores_train_config(self, tmp_path, base_train_config):
"""train_config is accessible as an attribute after construction."""
tc = base_train_config(epochs=42)
dm = _build_datamodule(train_config=tc, tmp_path=tmp_path)
assert dm.train_config is tc
def test_datasets_start_as_none(self, fixture_training_setup):
"""All three dataset slots are None before setup() is called."""
_, _, dm = fixture_training_setup
assert dm._dataset_train is None
assert dm._dataset_val is None
assert dm._dataset_test is None
def test_prefetch_factor_defaults_to_two_when_workers_enabled(self, tmp_path, base_train_config):
"""prefetch_factor defaults to 2 for worker-based DataLoaders."""
tc = base_train_config(num_workers=2, prefetch_factor=None)
dm = _build_datamodule(train_config=tc, tmp_path=tmp_path)
assert dm._prefetch_factor == 2
def test_prefetch_factor_honors_train_config(self, tmp_path, base_train_config):
"""prefetch_factor from TrainConfig is forwarded when workers are enabled."""
tc = base_train_config(num_workers=2, prefetch_factor=5)
dm = _build_datamodule(train_config=tc, tmp_path=tmp_path)
assert dm._prefetch_factor == 5
def test_prefetch_factor_none_when_workers_disabled(self, tmp_path, base_train_config):
"""prefetch_factor is None when num_workers == 0."""
tc = base_train_config(num_workers=0, prefetch_factor=5)
dm = _build_datamodule(train_config=tc, tmp_path=tmp_path)
assert dm._prefetch_factor is None
def test_pin_memory_override_is_respected(self, tmp_path, base_train_config):
"""pin_memory can be explicitly overridden from TrainConfig."""
tc = base_train_config(pin_memory=False)
dm = _build_datamodule(train_config=tc, tmp_path=tmp_path)
assert dm._pin_memory is False
@patch("rfdetr.config.DEVICE", "cuda")
def test_pin_memory_defaults_to_false_when_accelerator_is_cpu(self, tmp_path, base_train_config):
"""Default pin_memory stays off when training is explicitly CPU-only."""
tc = base_train_config(pin_memory=None, accelerator="cpu")
dm = _build_datamodule(train_config=tc, tmp_path=tmp_path)
assert dm._pin_memory is False
def test_persistent_workers_override_is_respected(self, tmp_path, base_train_config):
"""persistent_workers can be explicitly overridden from TrainConfig."""
tc = base_train_config(num_workers=2, persistent_workers=False)
dm = _build_datamodule(train_config=tc, tmp_path=tmp_path)
assert dm._persistent_workers is False
def test_ddp_notebook_preserves_num_workers(self, tmp_path, base_train_config):
"""ddp_notebook keeps num_workers as configured (spawn-based DDP children initialise CUDA fresh; DataLoader fork
workers are CPU-only and never touch CUDA, so nested forks are safe)."""
tc = base_train_config(num_workers=4, strategy="ddp_notebook")
dm = _build_datamodule(train_config=tc, tmp_path=tmp_path)
assert dm._num_workers == 4
assert dm._prefetch_factor == 2
def test_other_strategy_preserves_num_workers(self, tmp_path, base_train_config):
"""Non-ddp_notebook strategies also keep num_workers as configured."""
tc = base_train_config(num_workers=4, strategy="ddp")
dm = _build_datamodule(train_config=tc, tmp_path=tmp_path)
assert dm._num_workers == 4
assert dm._prefetch_factor == 2 # default prefetch_factor for num_workers>0
class TestPrivateShowSamples:
"""RFDETRDataModule._show_samples renders transformed input samples."""
def test_private_show_samples_returns_figure_for_keypoint_targets(self, fixture_training_setup, monkeypatch):
"""_show_samples should render transformed boxes and keypoints without raw COCO parsing."""
_, _, dm = fixture_training_setup
import matplotlib
matplotlib.use("Agg", force=True)
from matplotlib import pyplot as plt
from matplotlib.figure import Figure
monkeypatch.setattr(dm, "_get_dataset_for_visualization", lambda split: _VisualDataset())
figure = dm._show_samples(1, split="train", columns=1)
assert isinstance(figure, Figure)
assert len(figure.axes) == 1
plt.close(figure)
def test_private_show_samples_accepts_figure_size_and_shortens_long_titles(
self, fixture_training_setup, monkeypatch
):
"""_show_samples should keep long image names inside subplot titles."""
_, _, dm = fixture_training_setup
import matplotlib
matplotlib.use("Agg", force=True)
from matplotlib import pyplot as plt
monkeypatch.setattr(dm, "_get_dataset_for_visualization", lambda split: _VisualDataset())
monkeypatch.setattr(dm, "_source_image_path", lambda dataset, idx: Path(f"{'very_long_name_' * 8}.jpg"))
figure = dm._show_samples(1, split="train", columns=1, figure_size=(4.0, 3.0))
assert list(figure.get_size_inches()) == pytest.approx([4.0, 3.0])
title = figure.axes[0].get_title()
assert "..." in title
assert len(title) <= 48
plt.close(figure)
def test_private_show_samples_rejects_non_positive_count(self, fixture_training_setup):
"""_show_samples should fail fast for invalid counts."""
_, _, dm = fixture_training_setup
with pytest.raises(ValueError, match=r"count must be positive"):
dm._show_samples(0)
def test_private_show_samples_rejects_invalid_figure_size(self, fixture_training_setup):
"""_show_samples should fail fast for invalid figure sizes."""
_, _, dm = fixture_training_setup
with pytest.raises(ValueError, match=r"figure_size values must be positive"):
dm._show_samples(1, figure_size=(4.0, 0.0))
def test_private_show_samples_missing_visual_extra_has_install_hint(self, fixture_training_setup, monkeypatch):
"""_show_samples should explain how to install optional visualization dependencies."""
_, _, dm = fixture_training_setup
real_import = builtins.__import__
def fake_import(name, *args, **kwargs):
if name == "matplotlib.pyplot":
raise ImportError("matplotlib is intentionally unavailable")
return real_import(name, *args, **kwargs)
monkeypatch.setattr(dm, "_get_dataset_for_visualization", lambda split: _VisualDataset())
monkeypatch.setattr(builtins, "__import__", fake_import)
with pytest.raises(ImportError, match=r"rfdetr\[visual\]"):
dm._show_samples(1)
def test_private_show_samples_returns_figure_for_segmentation_targets(self, fixture_training_setup, monkeypatch):
"""_show_samples renders mask overlays when dataset targets include instance masks."""
_, _, dm = fixture_training_setup
import matplotlib
import numpy as np
matplotlib.use("Agg", force=True)
from unittest.mock import MagicMock
from unittest.mock import patch as _patch
from matplotlib import pyplot as plt
from matplotlib.figure import Figure
class _SegDataset(torch.utils.data.Dataset):
def __len__(self) -> int:
return 1
def __getitem__(self, idx: int):
return (
torch.full((3, 16, 16), 0.5, dtype=torch.float32),
{
"boxes": torch.tensor([[0.5, 0.5, 0.5, 0.5]], dtype=torch.float32),
"labels": torch.tensor([0], dtype=torch.int64),
"masks": torch.ones((1, 16, 16), dtype=torch.bool),
"size": torch.tensor([16, 16], dtype=torch.int64),
},
)
monkeypatch.setattr(dm, "_get_dataset_for_visualization", lambda split: _SegDataset())
mock_instance = MagicMock()
mock_instance.annotate.return_value = np.zeros((16, 16, 3), dtype=np.uint8)
with _patch("supervision.MaskAnnotator", return_value=mock_instance) as mock_mask_ann:
figure = dm._show_samples(1, split="train", columns=1)
assert isinstance(figure, Figure)
mock_mask_ann.assert_called_once()
mock_instance.annotate.assert_called_once()
plt.close(figure)
def test_private_show_samples_detection_only_does_not_call_mask_annotator(
self, fixture_training_setup, monkeypatch
):
"""_show_samples skips MaskAnnotator when dataset targets have no masks key."""
_, _, dm = fixture_training_setup
from unittest.mock import patch as _patch
import matplotlib
from matplotlib import pyplot as plt
matplotlib.use("Agg", force=True)
monkeypatch.setattr(dm, "_get_dataset_for_visualization", lambda split: _VisualDataset())
with _patch("supervision.MaskAnnotator") as mock_mask_ann:
figure = dm._show_samples(1, split="train", columns=1)
mock_mask_ann.assert_not_called()
plt.close(figure)
def test_private_show_samples_empty_masks_skips_mask_annotator(self, fixture_training_setup, monkeypatch):
"""_show_samples skips MaskAnnotator when masks tensor has zero instances (0, H, W)."""
_, _, dm = fixture_training_setup
from unittest.mock import patch as _patch
import matplotlib
from matplotlib import pyplot as plt
matplotlib.use("Agg", force=True)
class _EmptyMasksDataset(torch.utils.data.Dataset):
def __len__(self) -> int:
return 1
def __getitem__(self, idx: int):
return (
torch.full((3, 16, 16), 0.5, dtype=torch.float32),
{
"boxes": torch.tensor([[0.5, 0.5, 0.5, 0.5]], dtype=torch.float32),
"labels": torch.tensor([0], dtype=torch.int64),
"masks": torch.zeros((0, 16, 16), dtype=torch.bool),
"size": torch.tensor([16, 16], dtype=torch.int64),
},
)
monkeypatch.setattr(dm, "_get_dataset_for_visualization", lambda split: _EmptyMasksDataset())
with _patch("supervision.MaskAnnotator") as mock_mask_ann:
figure = dm._show_samples(1, split="train", columns=1)
mock_mask_ann.assert_not_called()
plt.close(figure)
class TestSetup:
"""Setup(stage) builds the correct dataset(s) for each PTL stage."""
def _setup_with_mock(self, tmp_path, stage, dataset_file="roboflow", **train_overrides):
"""Helper: construct DataModule and call setup(stage) with build_dataset mocked."""
mc = _base_model_config()
tc = _base_train_config(tmp_path, dataset_file=dataset_file, **train_overrides)
dm = RFDETRDataModule(mc, tc)
fake_train = _fake_dataset(100)
fake_val = _fake_dataset(20)
fake_test = _fake_dataset(10)
datasets = {"train": fake_train, "val": fake_val, "test": fake_test}
def _build(image_set, args, resolution):
return datasets[image_set]
with patch("rfdetr.training.module_data.build_dataset", side_effect=_build):
dm.setup(stage)
return dm, fake_train, fake_val, fake_test
def test_fit_builds_train_and_val(self, tmp_path):
"""Setup('fit') populates both _dataset_train and _dataset_val."""
dm, fake_train, fake_val, _ = self._setup_with_mock(tmp_path, "fit")
assert dm._dataset_train is fake_train
assert dm._dataset_val is fake_val
assert dm._dataset_test is None
def test_validate_builds_only_val(self, tmp_path):
"""Setup('validate') populates only _dataset_val."""
dm, _, fake_val, _ = self._setup_with_mock(tmp_path, "validate")
assert dm._dataset_train is None
assert dm._dataset_val is fake_val
assert dm._dataset_test is None
@pytest.mark.parametrize("dataset_file", [pytest.param("roboflow", id="roboflow"), pytest.param("yolo", id="yolo")])
def test_test_stage_uses_test_split(self, tmp_path, dataset_file):
"""Setup('test') requests the 'test' split for both Roboflow and YOLO datasets."""
dm, _, _, fake_test = self._setup_with_mock(tmp_path, "test", dataset_file=dataset_file)
assert dm._dataset_test is fake_test
@pytest.mark.parametrize("dataset_file", [pytest.param("roboflow", id="roboflow"), pytest.param("yolo", id="yolo")])
def test_test_stage_falls_back_to_val_without_test_split(self, tmp_path, dataset_file):
"""Setup('test') falls back to 'val' when the dataset declares no test split.
A ``dataset_file="roboflow"`` dataset whose detected format is YOLO-style
(``build_roboflow`` -> ``build_roboflow_from_yolo``, a common Roboflow export format)
routes through the exact same builder as ``dataset_file="yolo"`` and can raise the same
``YoloSplitUnavailableError`` -- Roboflow's export UI does not require a test split.
"""
dm = _build_datamodule(train_config=_base_train_config(tmp_path, dataset_file=dataset_file))
fake_val = _fake_dataset(20)
def _build(image_set, args, resolution):
if image_set == "test":
raise YoloSplitUnavailableError(str(tmp_path / "test" / "images"))
return fake_val
with patch("rfdetr.training.module_data.build_dataset", side_effect=_build):
dm.setup("test")
assert dm._dataset_test is fake_val
def _write_yolo_dataset_without_test_split(self, dataset_dir: Path) -> None:
"""Write an on-disk YOLO dataset with one ``train/`` image and two ``valid/`` images, no ``test/`` split.
The split sizes differ so that a length assertion on the dataset built for the ``test`` stage distinguishes the
``valid`` fallback from an accidental ``train`` one.
"""
for split, image_count in (("train", 1), ("valid", 2)):
(dataset_dir / split / "images").mkdir(parents=True)
(dataset_dir / split / "labels").mkdir(parents=True)
for idx in range(image_count):
image_path = dataset_dir / split / "images" / f"sample{idx}.png"
Image.new("RGB", (8, 6), color=(255, 255, 255)).save(image_path)
(dataset_dir / split / "labels" / f"sample{idx}.txt").write_text(
"0 0.5 0.5 0.5 0.5\n", encoding="utf-8"
)
(dataset_dir / "data.yaml").write_text("names:\n - person\n", encoding="utf-8")
def test_test_stage_roboflow_yolo_format_falls_back_to_val_end_to_end(self, tmp_path, caplog, monkeypatch):
"""A real, unmocked Roboflow-YOLO export without a ``test/`` split falls back to ``valid/``.
Exercises ``detect_roboflow_format`` -> ``build_roboflow_from_yolo`` end to end, not just the
``_build_test_dataset`` control flow around a mocked ``build_dataset``.
"""
dataset_dir = tmp_path / "dataset"
self._write_yolo_dataset_without_test_split(dataset_dir)
dm = _build_datamodule(
model_config=_base_model_config(num_classes=1),
train_config=_base_train_config(tmp_path, dataset_file="roboflow", dataset_dir=str(dataset_dir)),
)
# get_logger() sets propagate=False on the "rf-detr" logger, so caplog's root-level
# handler only sees its records while propagation is re-enabled.
monkeypatch.setattr(logging.getLogger("rf-detr"), "propagate", True)
with caplog.at_level(logging.WARNING, logger="rf-detr"):
dm.setup("test")
assert isinstance(dm._dataset_test, YoloDetection)
assert len(dm._dataset_test) == 2
assert any("No resolvable 'test' split" in record.getMessage() for record in caplog.records)
def test_test_stage_plain_yolo_falls_back_to_val_end_to_end(self, tmp_path):
"""A real, unmocked ``dataset_file="yolo"`` dataset without a ``test/`` split falls back to ``valid/``.
Unlike the ``roboflow`` route, this one never runs ``detect_roboflow_format``: ``build_dataset`` dispatches
straight to ``build_roboflow_from_yolo``.
"""
dataset_dir = tmp_path / "dataset"
self._write_yolo_dataset_without_test_split(dataset_dir)
dm = _build_datamodule(
model_config=_base_model_config(num_classes=1),
train_config=_base_train_config(tmp_path, dataset_file="yolo", dataset_dir=str(dataset_dir)),
)
dm.setup("test")
assert isinstance(dm._dataset_test, YoloDetection)
assert len(dm._dataset_test) == 2
@pytest.mark.parametrize("dataset_file", [pytest.param("roboflow", id="roboflow"), pytest.param("yolo", id="yolo")])
def test_test_stage_propagates_broken_test_split(self, tmp_path, dataset_file):
"""Setup('test') propagates builder failures after a test split is resolved."""
dm = _build_datamodule(train_config=_base_train_config(tmp_path, dataset_file=dataset_file))
def _build(image_set, args, resolution):
if image_set == "test":
raise FileNotFoundError("declared test annotation file is broken")
return _fake_dataset(20)
with patch("rfdetr.training.module_data.build_dataset", side_effect=_build):
with pytest.raises(FileNotFoundError, match="declared test annotation file is broken"):
dm.setup("test")
@pytest.mark.parametrize(
"dataset_file, dataset_label",
[pytest.param("roboflow", "Roboflow", id="roboflow"), pytest.param("yolo", "YOLO", id="yolo")],
)
def test_test_stage_warns_when_falling_back_to_val(self, tmp_path, dataset_file, dataset_label):
"""The test-to-val fallback is logged at WARNING rather than applied silently."""
dm = _build_datamodule(train_config=_base_train_config(tmp_path, dataset_file=dataset_file))
def _build(image_set, args, resolution):
if image_set == "test":
raise YoloSplitUnavailableError(str(tmp_path / "test" / "images"))
return _fake_dataset(20)
with (
patch("rfdetr.training.module_data.build_dataset", side_effect=_build),
patch("rfdetr.training.module_data.logger") as mock_logger,
):
dm.setup("test")
mock_logger.warning.assert_called_once_with(
"No resolvable 'test' split for this %s dataset (%s); evaluating the 'val' split instead.",
dataset_label,
str(tmp_path / "test" / "images"),
)
def test_test_stage_coco_uses_val_split(self, coco_datamodule):
"""Setup('test') falls back to 'val' for COCO, whose test2017 split is unlabelled test-dev."""
requested_splits = []
def _build(image_set, args, resolution):
requested_splits.append(image_set)
return _fake_dataset(10)
with patch("rfdetr.training.module_data.build_dataset", side_effect=_build):
coco_datamodule.setup("test")
assert "val" in requested_splits
assert "test" not in requested_splits
def test_test_stage_does_not_rebuild_after_val_fallback(self, tmp_path):
"""A second setup('test') reuses the val dataset resolved by the first fallback."""
dm = _build_datamodule(train_config=_base_train_config(tmp_path, dataset_file="yolo"))
fake_val = _fake_dataset(20)
def _build(image_set, args, resolution):
if image_set == "test":
raise YoloSplitUnavailableError(str(tmp_path / "test" / "images"))
return fake_val
with patch("rfdetr.training.module_data.build_dataset", side_effect=_build):
dm.setup("test")
with patch("rfdetr.training.module_data.build_dataset") as mock_build:
dm.setup("test")
mock_build.assert_not_called()
assert dm._dataset_test is fake_val
def test_fit_does_not_rebuild_if_already_set(self, tmp_path):
"""Setup('fit') skips building if datasets are already populated."""
mc = _base_model_config()
tc = _base_train_config(tmp_path)
dm = RFDETRDataModule(mc, tc)
existing_train = _fake_dataset(50)
existing_val = _fake_dataset(10)
dm._dataset_train = existing_train
dm._dataset_val = existing_val
with patch("rfdetr.training.module_data.build_dataset") as mock_build:
dm.setup("fit")
mock_build.assert_not_called()
assert dm._dataset_train is existing_train
assert dm._dataset_val is existing_val
def test_predict_stage_builds_val_dataset(self, tmp_path):
"""Setup('predict') populates _dataset_val with the 'val' split."""
dm, _, fake_val, _ = self._setup_with_mock(tmp_path, "predict")
assert dm._dataset_val is fake_val
assert dm._dataset_train is None
assert dm._dataset_test is None
def test_predict_stage_does_not_rebuild_existing_val(self, tmp_path):
"""Setup('predict') skips building when _dataset_val is already set."""
mc = _base_model_config()
tc = _base_train_config(tmp_path)
dm = RFDETRDataModule(mc, tc)
existing_val = _fake_dataset(20)
dm._dataset_val = existing_val
with patch("rfdetr.training.module_data.build_dataset") as mock_build:
dm.setup("predict")
mock_build.assert_not_called()
assert dm._dataset_val is existing_val
class TestKeypointAugmentationWarning:
"""Keypoint mode warns only for keypoint-unsafe GPU augmentation."""
def _build_dm(self, tmp_path, *, use_grouppose_keypoints: bool, augmentation_backend: str = "cpu"):
mc = _base_model_config(
use_grouppose_keypoints=use_grouppose_keypoints,
num_keypoints_per_class=[17] if use_grouppose_keypoints else [],
)
tc = _base_train_config(tmp_path, augmentation_backend=augmentation_backend)
return RFDETRDataModule(mc, tc)
def test_keypoint_mode_cpu_augmentation_no_warning(self, tmp_path):
"""Setup('fit') should not warn when keypoint mode uses Albumentations."""
dm = self._build_dm(tmp_path, use_grouppose_keypoints=True, augmentation_backend="cpu")
with (
patch("rfdetr.training.module_data.build_dataset", side_effect=lambda *a, **k: _fake_dataset(10)),
warnings.catch_warnings(record=True) as caught,
):
warnings.simplefilter("always")
dm.setup("fit")
assert not [w for w in caught if "Keypoint mode" in str(w.message)]
def test_keypoint_mode_gpu_augmentation_raises(self, tmp_path):
"""Setup('fit') should raise ValueError when keypoint mode uses a GPU augmentation backend."""
dm = self._build_dm(tmp_path, use_grouppose_keypoints=True, augmentation_backend="gpu")
with (
patch("rfdetr.training.module_data.build_dataset", side_effect=lambda *a, **k: _fake_dataset(10)),
patch.object(dm, "_setup_kornia_pipeline"),
pytest.raises(ValueError, match="does not support keypoint transforms"),
):
dm.setup("fit")
def test_non_keypoint_mode_no_augmentation_warning(self, tmp_path):
"""Setup('fit') should not emit the keypoint augmentation warning in detection mode."""
dm = self._build_dm(tmp_path, use_grouppose_keypoints=False)
with (
patch("rfdetr.training.module_data.build_dataset", side_effect=lambda *a, **k: _fake_dataset(10)),
warnings.catch_warnings(record=True) as caught,
):
warnings.simplefilter("always")
dm.setup("fit")
assert not [w for w in caught if "Keypoint mode is enabled" in str(w.message)]
class TestTrainDataloader:
"""train_dataloader() returns the correct DataLoader for large and small datasets."""
def _setup_dm_with_train(self, tmp_path, dataset_length, batch_size=2, grad_accum_steps=1, num_workers=0):
"""Construct DataModule and inject a fake _dataset_train of given length."""
mc = _base_model_config()
tc = _base_train_config(
tmp_path,
batch_size=batch_size,
grad_accum_steps=grad_accum_steps,
num_workers=num_workers,
)
dm = RFDETRDataModule(mc, tc)
dm._dataset_train = _fake_dataset(dataset_length)
return dm
def test_returns_dataloader(self, tmp_path):
"""train_dataloader() returns a DataLoader instance."""
dm = self._setup_dm_with_train(tmp_path, dataset_length=200)
loader = dm.train_dataloader()
assert isinstance(loader, DataLoader)
def test_large_dataset_uses_batch_sampler(self, tmp_path):
"""A large dataset uses a BatchSampler (drop_last=True, no replacement)."""
# 200 samples > 2*1*5=10 threshold → large path
dm = self._setup_dm_with_train(tmp_path, dataset_length=200, batch_size=2, grad_accum_steps=1)
loader = dm.train_dataloader()
assert loader.batch_sampler is not None
assert isinstance(loader.batch_sampler, torch.utils.data.BatchSampler)
assert loader.batch_sampler.drop_last is True
def test_small_dataset_uses_replacement_sampler(self, tmp_path):
"""A small dataset (< effective_batch * min_batches) uses a replacement sampler."""
# 3 samples < 2*1*5=10 threshold → small path
dm = self._setup_dm_with_train(tmp_path, dataset_length=3, batch_size=2, grad_accum_steps=1)
loader = dm.train_dataloader()
assert isinstance(loader.sampler, torch.utils.data.RandomSampler)
assert loader.sampler.replacement is True
def test_small_dataset_replacement_sampler_num_samples(self, tmp_path):
"""Replacement sampler has num_samples == effective_batch_size * _MIN_TRAIN_BATCHES."""
from rfdetr.training.module_data import _MIN_TRAIN_BATCHES
batch_size = 2
grad_accum_steps = 3
dm = self._setup_dm_with_train(
tmp_path,
dataset_length=3,
batch_size=batch_size,
grad_accum_steps=grad_accum_steps,
)
loader = dm.train_dataloader()
expected = batch_size * grad_accum_steps * _MIN_TRAIN_BATCHES
assert loader.sampler.num_samples == expected
def test_batch_size_forwarded(self, tmp_path):
"""The DataLoader's batch size matches the train config."""
dm = self._setup_dm_with_train(tmp_path, dataset_length=200, batch_size=8)
loader = dm.train_dataloader()
assert loader.batch_sampler.batch_size == 8
def test_num_workers_forwarded(self, tmp_path):
"""The DataLoader's num_workers matches the train config."""
dm = self._setup_dm_with_train(tmp_path, dataset_length=200, num_workers=0)
loader = dm.train_dataloader()
assert loader.num_workers == 0
def test_threshold_exact_boundary_uses_batch_sampler(self, tmp_path):
"""Dataset of exactly effective_batch_size * _MIN_TRAIN_BATCHES is NOT small."""
from rfdetr.training.module_data import _MIN_TRAIN_BATCHES
batch_size = 2
grad_accum = 1
length = batch_size * grad_accum * _MIN_TRAIN_BATCHES # exactly at threshold
dm = self._setup_dm_with_train(tmp_path, dataset_length=length, batch_size=batch_size)
loader = dm.train_dataloader()
assert isinstance(loader.batch_sampler, torch.utils.data.BatchSampler)
@pytest.mark.parametrize(
"dataset_length, batch_size, grad_accum_steps",
[
pytest.param(100, 2, 1, id="already_aligned_ga1"),
pytest.param(96, 2, 4, id="already_aligned_ga4"),
pytest.param(101, 2, 4, id="unaligned_one_extra"),
pytest.param(50, 2, 8, id="unaligned_ga8"),
pytest.param(59143, 2, 8, id="large_unaligned_coco_like"),
pytest.param(100, 3, 3, id="non_power_of_two_ga"),
],
)
def test_train_dataloader_length_is_multiple_of_grad_accum(
self, tmp_path, dataset_length, batch_size, grad_accum_steps
):
"""len(train_dataloader()) is always a multiple of grad_accum_steps.
Verifies the workaround for https://github.com/Lightning-AI/pytorch-lightning/issues/19987: the training
DataLoader must never present a partial accumulation window to PTL.
"""
dm = self._setup_dm_with_train(
tmp_path,
dataset_length=dataset_length,
batch_size=batch_size,
grad_accum_steps=grad_accum_steps,
)
loader = dm.train_dataloader()
assert len(loader) % grad_accum_steps == 0, (
f"len(loader)={len(loader)} is not a multiple of grad_accum_steps={grad_accum_steps}"
)
def test_train_dataloader_respects_trainer_world_size(self, tmp_path):
"""Large-dataset path aligns wrapped dataset length to effective_batch_size * world_size."""
dm = self._setup_dm_with_train(
tmp_path,
dataset_length=101,
batch_size=2,
grad_accum_steps=4,
)
dm.trainer = MagicMock(world_size=3)
loader = dm.train_dataloader()
assert len(loader.dataset) % (2 * 4 * 3) == 0
assert len(loader.dataset) == 120
@staticmethod
def _raw_sample(h: int = 16, w: int = 16) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
"""Build one (image, target) pair as a dataset __getitem__ would return it, for collate_fn input.
Examples:
>>> image, target = TestTrainDataloader._raw_sample()
>>> image.shape, sorted(target)
(torch.Size([3, 16, 16]), ['boxes', 'image_id', 'labels', 'orig_size'])
"""
image = torch.randn(3, h, w)
target = {
"boxes": torch.tensor([[0.5, 0.5, 0.1, 0.1]]),
"labels": torch.tensor([1]),
"image_id": torch.tensor(0),
"orig_size": torch.tensor([h, w]),
}
return image, target
@pytest.mark.parametrize(
("loader_name", "dataset_attribute"),
[
pytest.param("train_dataloader", "_dataset_train", id="train"),
pytest.param("val_dataloader", "_dataset_val", id="validation"),
pytest.param("test_dataloader", "_dataset_test", id="test"),
pytest.param("predict_dataloader", "_dataset_val", id="predict"),
],
)
def test_pack_targets_default_makes_every_loader_collate_packed_targets(
self, tmp_path, loader_name, dataset_attribute
):
"""The default must make each public DataLoader's collate function return PackedTargets."""
dm = RFDETRDataModule(_base_model_config(), _base_train_config(tmp_path))
setattr(dm, dataset_attribute, _fake_dataset(200))
loader = getattr(dm, loader_name)()
_, targets = loader.collate_fn([self._raw_sample(), self._raw_sample()])
assert isinstance(targets, PackedTargets)
def test_pack_targets_false_keeps_collate_fn_output_a_tuple_of_dicts(self, tmp_path):
"""An explicit TrainConfig.pack_targets=False leaves train_dataloader().collate_fn output unpacked."""
dm = RFDETRDataModule(_base_model_config(), _base_train_config(tmp_path, pack_targets=False))
dm._dataset_train = _fake_dataset(200)
loader = dm.train_dataloader()
_, targets = loader.collate_fn([self._raw_sample(), self._raw_sample()])
assert not isinstance(targets, PackedTargets)
assert all(isinstance(t, dict) for t in targets)
class TestGradAccumAlignedDataset:
"""Unit tests for the GradAccumAlignedDataset wrapper."""
def _make_dataset(self, length: int) -> torch.utils.data.TensorDataset:
"""Return a simple TensorDataset of given length."""
return torch.utils.data.TensorDataset(torch.arange(length))
def test_aligned_length_is_multiple_of_pad_unit(self):
"""Padded length is always a multiple of effective_batch_size * world_size."""
from rfdetr.training.module_data import GradAccumAlignedDataset
ds = self._make_dataset(50)
wrapped = GradAccumAlignedDataset(ds, effective_batch_size=16, world_size=1)
assert len(wrapped) % 16 == 0
def test_no_padding_needed_when_already_aligned(self):
"""If len(dataset) % pad_unit == 0, length is unchanged."""
from rfdetr.training.module_data import GradAccumAlignedDataset
ds = self._make_dataset(64)
wrapped = GradAccumAlignedDataset(ds, effective_batch_size=16, world_size=1)
assert len(wrapped) == 64
def test_padding_adds_correct_count(self):
"""Exactly (pad_unit - remainder) % pad_unit samples are added."""
from rfdetr.training.module_data import GradAccumAlignedDataset
ds = self._make_dataset(50) # 50 % 16 = 2 → pad 14
wrapped = GradAccumAlignedDataset(ds, effective_batch_size=16, world_size=1)
assert len(wrapped) == 64
def test_getitem_forwards_to_original_dataset(self):
"""Items in the original range map directly to the underlying dataset."""
from rfdetr.training.module_data import GradAccumAlignedDataset
ds = self._make_dataset(10)
wrapped = GradAccumAlignedDataset(ds, effective_batch_size=4, world_size=1)
for i in range(10):
(val,) = wrapped[i]
assert val.item() == i
def test_padded_indices_are_valid(self):
"""All padded indices point to valid positions in the original dataset."""
from rfdetr.training.module_data import GradAccumAlignedDataset
n = 10
ds = self._make_dataset(n)
wrapped = GradAccumAlignedDataset(ds, effective_batch_size=4, world_size=1)
for i in range(len(wrapped)):
(val,) = wrapped[i]
assert 0 <= val.item() < n
@pytest.mark.parametrize(
"n, eff_bs, world_size",
[
pytest.param(100, 4, 1, id="aligned_single_gpu"),
pytest.param(101, 4, 1, id="unaligned_single_gpu"),
pytest.param(100, 4, 2, id="aligned_ddp2"),
pytest.param(97, 4, 2, id="unaligned_ddp2"),
],
)
def test_length_always_multiple_of_pad_unit(self, n, eff_bs, world_size):
"""Len(wrapped) % (eff_bs * world_size) == 0 for all inputs."""
from rfdetr.training.module_data import GradAccumAlignedDataset
ds = self._make_dataset(n)
wrapped = GradAccumAlignedDataset(ds, effective_batch_size=eff_bs, world_size=world_size)
assert len(wrapped) % (eff_bs * world_size) == 0
@pytest.mark.parametrize(
"effective_batch_size, world_size",
[
pytest.param(0, 1, id="zero_effective_batch_size"),
pytest.param(-1, 1, id="negative_effective_batch_size"),
pytest.param(2, 0, id="zero_world_size"),
pytest.param(2, -1, id="negative_world_size"),
],
)
def test_raises_for_non_positive_alignment_inputs(self, effective_batch_size, world_size):
"""Non-positive alignment inputs fail with a clear ValueError."""
from rfdetr.training.module_data import GradAccumAlignedDataset
ds = self._make_dataset(10)
with pytest.raises(ValueError, match="must be >= 1"):
GradAccumAlignedDataset(
ds,
effective_batch_size=effective_batch_size,
world_size=world_size,
)
class TestValDataloader:
"""val_dataloader() returns a SequentialSampler with drop_last=False."""
def _setup_dm_with_val(self, tmp_path, dataset_length=50, batch_size=2, num_workers=0):
mc = _base_model_config()
tc = _base_train_config(tmp_path, batch_size=batch_size, num_workers=num_workers)
dm = RFDETRDataModule(mc, tc)
dm._dataset_val = _fake_dataset(dataset_length)
return dm
def test_returns_dataloader(self, tmp_path):
"""val_dataloader() returns a DataLoader instance."""
dm = self._setup_dm_with_val(tmp_path)
loader = dm.val_dataloader()
assert isinstance(loader, DataLoader)
def test_uses_sequential_sampler(self, tmp_path):
"""val_dataloader uses a SequentialSampler."""
dm = self._setup_dm_with_val(tmp_path)
loader = dm.val_dataloader()
assert isinstance(loader.sampler, torch.utils.data.SequentialSampler)