forked from roboflow/rf-detr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_coco_eval_callback.py
More file actions
2428 lines (2020 loc) · 111 KB
/
Copy pathtest_coco_eval_callback.py
File metadata and controls
2428 lines (2020 loc) · 111 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]
# ------------------------------------------------------------------------
"""Unit tests for COCOEvalCallback."""
import sys
from types import ModuleType, SimpleNamespace
from unittest.mock import MagicMock, call, patch
import numpy as np
import pytest
import torch
from rfdetr.evaluation.matching import build_matching_data, merge_matching_data
from rfdetr.training.callbacks.coco_eval import COCOEvalCallback
# ---------------------------------------------------------------------------
# Shared helpers
# ---------------------------------------------------------------------------
def _make_pl_module() -> MagicMock:
"""Return a minimal mock LightningModule."""
return MagicMock(name="pl_module")
def _make_trainer(datamodule=None, callbacks: list[object] | None = None) -> MagicMock:
"""Return a minimal mock Trainer with an optional DataModule."""
trainer = MagicMock(name="trainer")
trainer.datamodule = datamodule
trainer.callbacks = callbacks or []
return trainer
class _TQDMProgressBar:
"""Minimal progress-bar stand-in for callback detection tests."""
def _detection_preds(n: int = 0) -> list[dict]:
"""Return a list with one per-image prediction dict."""
return [
{
"boxes": torch.zeros(n, 4),
"scores": torch.zeros(n),
"labels": torch.zeros(n, dtype=torch.long),
}
]
def _detection_targets(cx=0.5, cy=0.5, w=0.1, h=0.1, label=1) -> list[dict]:
"""Return a single-image target dict with one box in normalised CxCyWH."""
return [
{
"boxes": torch.tensor([[cx, cy, w, h]]),
"labels": torch.tensor([label]),
"orig_size": torch.tensor([100, 200]), # H=100, W=200
}
]
def _minimal_metrics(pfx: str = "", max_dets: int = 500) -> dict:
"""Return a minimal torchmetrics-style metrics dict."""
return {
f"{pfx}map": torch.tensor(0.4),
f"{pfx}map_50": torch.tensor(0.6),
f"{pfx}map_75": torch.tensor(0.3),
f"{pfx}mar_{max_dets}": torch.tensor(0.5),
}
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
class TestSetup:
"""Setup() creates map_metric with correct configuration."""
def test_init_defaults_notebook_flag_to_false_without_ipython(self) -> None:
"""Constructor sets _in_notebook=False when IPython import is unavailable."""
original_import = __import__
def _import_with_missing_ipython(name: str, *args, **kwargs):
if name == "IPython":
raise ImportError("IPython not installed")
return original_import(name, *args, **kwargs)
with patch("builtins.__import__", side_effect=_import_with_missing_ipython):
cb = COCOEvalCallback(in_notebook=None)
assert cb._in_notebook is False
def test_detection_iou_type_is_bbox(self) -> None:
"""Detection mode uses iou_type='bbox'."""
cb = COCOEvalCallback(max_dets=300, segmentation=False)
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
assert "bbox" in cb.map_metric.iou_type
assert "segm" not in cb.map_metric.iou_type
def test_detection_max_detection_thresholds(self) -> None:
"""max_dets is forwarded to max_detection_thresholds."""
cb = COCOEvalCallback(max_dets=300, segmentation=False)
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
assert 300 in cb.map_metric.max_detection_thresholds
def test_segmentation_iou_type_includes_segm(self) -> None:
"""Segmentation mode uses iou_type=['bbox','segm']."""
cb = COCOEvalCallback(segmentation=True)
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
assert "segm" in cb.map_metric.iou_type
def test_map_metric_created_on_every_setup_call(self) -> None:
"""Repeated setup() calls replace map_metric (idempotent)."""
cb = COCOEvalCallback()
trainer, module = _make_trainer(), _make_pl_module()
cb.setup(trainer, module, stage="fit")
first = cb.map_metric
cb.setup(trainer, module, stage="validate")
assert cb.map_metric is not first
def test_detection_uses_faster_coco_eval_backend(self) -> None:
"""Detection mode always uses faster_coco_eval backend to avoid map=-1 bug."""
cb = COCOEvalCallback(segmentation=False)
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
assert cb.map_metric._coco_backend.backend == "faster_coco_eval"
def test_segmentation_uses_faster_coco_eval_backend(self) -> None:
"""Segmentation mode always uses faster_coco_eval backend."""
cb = COCOEvalCallback(segmentation=True)
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
assert cb.map_metric._coco_backend.backend == "faster_coco_eval"
def test_log_per_class_metrics_false_disables_class_metrics_compute(self) -> None:
"""log_per_class_metrics=False must disable torchmetrics per-class computation, not just logging.
Regression test for #416: skips the expensive per-class MeanAveragePrecision compute (not merely its table
rendering at epoch end) on both the regular and train-split metrics.
"""
cb = COCOEvalCallback(log_per_class_metrics=False)
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
assert cb.map_metric.class_metrics is False
assert cb.map_metric_train.class_metrics is False
def test_log_per_class_metrics_default_keeps_class_metrics_compute(self) -> None:
"""Default log_per_class_metrics=True keeps per-class AP computation on for both metrics.
Mirrors the disable-path test's symmetric map_metric_train assertion.
"""
cb = COCOEvalCallback()
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
assert cb.map_metric.class_metrics is True
assert cb.map_metric_train.class_metrics is True
def test_log_per_class_metrics_false_disables_class_metrics_on_ema_metric(self) -> None:
"""The EMA metric mirrors the per-class computation flag."""
cb = COCOEvalCallback(log_per_class_metrics=False)
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
with patch.object(cb, "_get_ema_callback", return_value=MagicMock()):
cb._prepare_ema_metric(_make_trainer())
assert cb.map_metric_ema is not None
assert cb.map_metric_ema.class_metrics is False
def test_ema_metric_stays_on_cpu_when_module_uses_an_accelerator(self) -> None:
"""The EMA metric itself remains on CPU because its accumulated state is CPU-only."""
cb = COCOEvalCallback()
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
with patch.object(cb, "_get_ema_callback", return_value=MagicMock()):
cb._prepare_ema_metric(_make_trainer())
assert cb.map_metric_ema is not None
assert cb.map_metric_ema.device.type == "cpu"
def test_keypoint_mode_does_not_enable_torchmetrics_keypoint_iou(self) -> None:
"""Keypoint mode must keep torchmetrics on bbox-only iou_type."""
cb = COCOEvalCallback(segmentation=True)
module = _make_pl_module()
module.model_config = SimpleNamespace(use_grouppose_keypoints=True)
cb.setup(_make_trainer(), module, stage="fit")
assert "bbox" in cb.map_metric.iou_type
assert "segm" not in cb.map_metric.iou_type
assert "keypoints" not in cb.map_metric.iou_type
def test_log_per_class_metrics_true_enables_class_metrics_compute(self) -> None:
"""log_per_class_metrics=True (default) keeps class_metrics compute enabled."""
cb = COCOEvalCallback(log_per_class_metrics=True)
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
assert cb.map_metric.class_metrics is True
class TestOnFitStart:
"""on_fit_start() populates class names from the datamodule."""
def test_class_names_loaded_from_datamodule(self) -> None:
"""Class names are taken from trainer.datamodule.class_names."""
dm = MagicMock()
dm.class_names = ["cat", "dog"]
cb = COCOEvalCallback()
cb.on_fit_start(_make_trainer(datamodule=dm), _make_pl_module())
assert cb._class_names == ["cat", "dog"]
def test_no_datamodule_leaves_class_names_empty(self) -> None:
"""Absent datamodule keeps class_names as empty list."""
trainer = _make_trainer(datamodule=None)
cb = COCOEvalCallback()
cb.on_fit_start(trainer, _make_pl_module())
assert cb._class_names == []
def test_datamodule_without_class_names_attr_leaves_empty(self) -> None:
"""DataModule without class_names attr keeps class_names empty."""
dm = MagicMock(spec=[]) # no attributes
cb = COCOEvalCallback()
cb.on_fit_start(_make_trainer(datamodule=dm), _make_pl_module())
assert cb._class_names == []
def test_cat_id_to_name_uses_label2cat_when_available(self) -> None:
"""When coco.label2cat is present (remap_category_ids=True) the mapping uses 0-based remapped label IDs so class
names align with predictions."""
coco = MagicMock()
coco.cats = {1: {"name": "fish"}, 2: {"name": "shark"}}
# label2cat: remapped_label → original_cat_id (cat2label inverse)
coco.label2cat = {0: 1, 1: 2}
dataset = MagicMock()
dataset.coco = coco
dm = MagicMock()
dm.class_names = ["fish", "shark"]
dm._dataset_val = dataset
dm._dataset_train = None
cb = COCOEvalCallback()
cb.on_fit_start(_make_trainer(datamodule=dm), _make_pl_module())
# 0-based label indices must map to names, not original cat IDs
assert cb._cat_id_to_name == {0: "fish", 1: "shark"}
def test_cat_id_to_name_falls_back_to_raw_cats_without_label2cat(self) -> None:
"""Without coco.label2cat (standard COCO), original category IDs are used."""
coco = MagicMock(spec=["cats"]) # no label2cat attribute
coco.cats = {1: {"name": "fish"}, 2: {"name": "shark"}}
dataset = MagicMock()
dataset.coco = coco
dm = MagicMock()
dm.class_names = ["fish", "shark"]
dm._dataset_val = dataset
dm._dataset_train = None
cb = COCOEvalCallback()
cb.on_fit_start(_make_trainer(datamodule=dm), _make_pl_module())
assert cb._cat_id_to_name == {1: "fish", 2: "shark"}
@pytest.mark.parametrize(
"hook,stage",
[
pytest.param("on_validation_batch_end", "fit", id="val"),
pytest.param("on_test_batch_end", "test", id="test"),
],
)
class TestBatchEndCommon:
"""map_metric accumulation shared by on_validation_batch_end and on_test_batch_end."""
def test_map_metric_update_called_once_per_batch(self, hook, stage) -> None:
"""map_metric.update is called exactly once per batch."""
cb = COCOEvalCallback()
cb.setup(_make_trainer(), _make_pl_module(), stage=stage)
cb.map_metric = MagicMock(name="map_metric")
outputs = {"results": _detection_preds(0), "targets": _detection_targets()}
getattr(cb, hook)(_make_trainer(), _make_pl_module(), outputs, None, 0)
assert cb.map_metric.update.call_count == 1
def test_map_metric_update_receives_cpu_state_inputs(self, hook, stage) -> None:
"""Metric updates must receive the CPU copies that avoid per-annotation device synchronizations."""
cb = COCOEvalCallback()
cb.setup(_make_trainer(), _make_pl_module(), stage=stage)
cb.map_metric = MagicMock(name="map_metric")
cpu_preds = _detection_preds(0)
cpu_targets = _detection_targets()
outputs = {"results": _detection_preds(0), "targets": _detection_targets()}
with patch.object(cb, "_move_metric_inputs_to_cpu", return_value=(cpu_preds, cpu_targets)) as move_to_cpu:
getattr(cb, hook)(_make_trainer(), _make_pl_module(), outputs, None, 0)
move_to_cpu.assert_called_once()
cb.map_metric.update.assert_called_once_with(cpu_preds, cpu_targets)
def test_f1_accumulator_grows_across_batches(self, hook, stage) -> None:
"""Calling the batch-end hook twice accumulates more GT in F1 state."""
cb = COCOEvalCallback()
cb.setup(_make_trainer(), _make_pl_module(), stage=stage)
cb.map_metric = MagicMock(name="map_metric")
outputs = {"results": _detection_preds(0), "targets": _detection_targets(label=1)}
getattr(cb, hook)(_make_trainer(), _make_pl_module(), outputs, None, 0)
total_after_1 = sum(v["total_gt"] for v in cb._f1_local.values())
getattr(cb, hook)(_make_trainer(), _make_pl_module(), outputs, None, 1)
total_after_2 = sum(v["total_gt"] for v in cb._f1_local.values())
assert total_after_2 == total_after_1 * 2
def test_targets_converted_before_update(self, hook, stage) -> None:
"""map_metric.update receives targets with absolute xyxy boxes."""
cb = COCOEvalCallback()
cb.setup(_make_trainer(), _make_pl_module(), stage=stage)
captured = {}
def _capture_update(preds, targets):
captured["targets"] = targets
cb.map_metric = MagicMock(name="map_metric")
cb.map_metric.update.side_effect = _capture_update
outputs = {
"results": _detection_preds(0),
"targets": _detection_targets(cx=0.5, cy=0.5, w=0.1, h=0.1),
}
getattr(cb, hook)(_make_trainer(), _make_pl_module(), outputs, None, 0)
# Expected: CxCyWH(0.5,0.5,0.1,0.1) × scale(W=200,H=100) → xyxy(90,45,110,55)
boxes = captured["targets"][0]["boxes"]
assert boxes.shape == (1, 4)
assert boxes[0, 0].item() == pytest.approx(90.0)
assert boxes[0, 1].item() == pytest.approx(45.0)
assert boxes[0, 2].item() == pytest.approx(110.0)
assert boxes[0, 3].item() == pytest.approx(55.0)
class TestOnTestBatchEnd:
"""Test-loop-specific behaviour of on_test_batch_end."""
def test_dataloader_idx_param_has_default(self) -> None:
"""on_test_batch_end must accept calls with an explicit dataloader_idx."""
cb = COCOEvalCallback()
cb.setup(_make_trainer(), _make_pl_module(), stage="test")
cb.map_metric = MagicMock(name="map_metric")
outputs = {"results": _detection_preds(0), "targets": _detection_targets()}
# Must not raise with explicit dataloader_idx=0
cb.on_test_batch_end(_make_trainer(), _make_pl_module(), outputs, None, 0, dataloader_idx=0)
class TestMetricStateInputs:
"""CPU mAP state conversion at the TorchMetrics boundary."""
def test_move_metric_inputs_to_cpu_preserves_metric_fields(self) -> None:
"""CPU conversion retains only mAP fields, including masks, and detaches state that still requires grad.
Feeds ``_move_metric_inputs_to_cpu`` the same shape it receives in production — ``_convert_preds``/
``_convert_targets`` output (``boxes``/``labels``/``masks``, no ``orig_size``) — instead of the raw pre-
conversion target dict, which carries ``orig_size`` and never reaches the helper in production. ``boxes`` starts
with ``requires_grad=True`` so detachment is asserted directly: ``.cpu()`` on an already-CPU tensor returns a
storage-sharing alias, making a bare device-type check vacuous on CPU-only CI runners, but ``.detach()`` clears
``requires_grad``/``grad_fn`` regardless of device.
"""
cb = COCOEvalCallback()
raw_preds = _detection_preds(1)
raw_preds[0]["boxes"].requires_grad_(True)
raw_preds[0]["masks"] = torch.zeros(1, 4, 4, dtype=torch.bool)
raw_preds[0]["keypoints"] = torch.zeros(1, 1, 3)
raw_preds[0]["keypoint_precision_cholesky"] = torch.zeros(1, 1, 3, 3)
raw_targets = _detection_targets()
raw_targets[0]["masks"] = torch.zeros(1, 4, 4, dtype=torch.bool)
preds = cb._convert_preds(raw_preds)
targets = cb._convert_targets(raw_targets, preds)
metric_preds, metric_targets = cb._move_metric_inputs_to_cpu(preds, targets)
assert metric_preds[0].keys() == {"boxes", "scores", "labels", "masks"}
assert metric_targets[0].keys() == targets[0].keys()
assert metric_preds[0] is not preds[0]
assert metric_targets[0] is not targets[0]
assert "orig_size" not in metric_targets[0]
assert "keypoints" not in metric_preds[0]
assert "keypoint_precision_cholesky" not in metric_preds[0]
torch.testing.assert_close(metric_preds[0]["boxes"], preds[0]["boxes"].detach())
torch.testing.assert_close(metric_targets[0]["boxes"], targets[0]["boxes"])
torch.testing.assert_close(metric_preds[0]["masks"], preds[0]["masks"])
torch.testing.assert_close(metric_targets[0]["masks"], targets[0]["masks"])
assert preds[0]["boxes"].requires_grad is True
assert metric_preds[0]["boxes"].requires_grad is False
assert metric_preds[0]["boxes"].grad_fn is None
class TestValidationBatchEndDeviceRouting:
"""Device split between the CPU-resident mAP metric state and the GPU-original F1/keypoint inputs."""
@pytest.mark.gpu
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available")
def test_build_matching_data_still_receives_cuda_tensors_while_map_metric_state_is_cpu(self) -> None:
"""build_matching_data must keep receiving the original CUDA tensors while map_metric's stored state is CPU-
resident — no CPU-only test can encode this device split.
A future refactor that passes the CPU-converted ``metric_preds``/``metric_targets`` into ``build_matching_data``
instead of the GPU originals would silently move ``[N, H, W]`` mask/box IoU onto the accelerator's slower CPU
sibling, a regression far larger than this PR's sync-removal win, with green CPU-only tests and zero numerical
change.
"""
cb = COCOEvalCallback()
trainer = _make_trainer()
module = _cpu_module()
cb.setup(trainer, module, stage="fit")
outputs = {
"results": [
{
"boxes": torch.zeros(1, 4, device="cuda"),
"scores": torch.zeros(1, device="cuda"),
"labels": torch.zeros(1, dtype=torch.long, device="cuda"),
}
],
"targets": [
{
"boxes": torch.tensor([[0.5, 0.5, 0.1, 0.1]], device="cuda"),
"labels": torch.tensor([1], device="cuda"),
"orig_size": torch.tensor([100, 200]),
}
],
}
with patch(
"rfdetr.training.callbacks.coco_eval.build_matching_data", wraps=build_matching_data
) as matching_spy:
cb.on_validation_batch_end(trainer, module, outputs, None, 0)
matching_spy.assert_called_once()
matching_preds, matching_targets = matching_spy.call_args[0][:2]
assert all(value.is_cuda for item in matching_preds + matching_targets for value in item.values())
assert all(t.device.type == "cpu" for t in cb.map_metric.detection_box)
class TestOnTrainBatchEnd:
"""Train-loop-specific behaviour for optional train mAP logging."""
def test_train_metrics_update_only_when_enabled(self) -> None:
"""on_train_batch_end should accumulate train predictions only with compute_train_metrics=True."""
cb = COCOEvalCallback()
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
cb.map_metric_train = MagicMock(name="map_metric_train")
module = _make_pl_module()
module.train_config = SimpleNamespace(compute_train_metrics=True)
outputs = {"results": _detection_preds(1), "targets": _detection_targets()}
cb.on_train_batch_end(_make_trainer(), module, outputs, None, 0)
cb.map_metric_train.update.assert_called_once()
def test_train_batch_end_uses_cpu_metric_inputs(self) -> None:
"""map_metric_train.update must receive the CPU copies from _move_metric_inputs_to_cpu.
The train hot path runs this conversion on every batch; unit tests run CPU-only, so tensors are CPU either way
and a dropped conversion call is invisible to a call-count-only assertion. Only an explicit args check against
the mocked conversion output catches a silent revert.
"""
cb = COCOEvalCallback()
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
cb.map_metric_train = MagicMock(name="map_metric_train")
module = _make_pl_module()
module.train_config = SimpleNamespace(compute_train_metrics=True)
cpu_preds = _detection_preds(1)
cpu_targets = _detection_targets()
outputs = {"results": _detection_preds(1), "targets": _detection_targets()}
with patch.object(cb, "_move_metric_inputs_to_cpu", return_value=(cpu_preds, cpu_targets)) as move_to_cpu:
cb.on_train_batch_end(_make_trainer(), module, outputs, None, 0)
move_to_cpu.assert_called_once()
cb.map_metric_train.update.assert_called_once_with(cpu_preds, cpu_targets)
def test_train_metrics_do_not_use_test_hook(self) -> None:
"""Train mAP must be logged under train/* via the train epoch hook, not through test/* hooks."""
cb = COCOEvalCallback()
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
cb.map_metric_train = MagicMock(name="map_metric_train")
cb.map_metric_train.compute.return_value = _minimal_metrics()
module = _make_pl_module()
module.train_config = SimpleNamespace(compute_train_metrics=True)
cb.on_train_epoch_end(_make_trainer(), module)
logged_keys = {c.args[0] for c in module.log.call_args_list}
assert "train/mAP_50_95" in logged_keys
assert "test/mAP_50_95" not in logged_keys
def test_train_epoch_end_skips_compute_when_no_train_updates(self) -> None:
"""Train mAP should not call torchmetrics compute() when no train batches updated it."""
cb = COCOEvalCallback()
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
cb.map_metric_train = MagicMock(name="map_metric_train")
cb.map_metric_train._update_count = 0
module = _make_pl_module()
module.train_config = SimpleNamespace(compute_train_metrics=True)
cb.on_train_epoch_end(_make_trainer(), module)
cb.map_metric_train.compute.assert_not_called()
cb.map_metric_train.reset.assert_called_once()
def test_validation_start_does_not_clear_train_metric_state(self) -> None:
"""In-fit validation should reset only validation accumulators, leaving train metrics isolated."""
cb = COCOEvalCallback()
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
cb.map_metric = MagicMock(name="val_map_metric")
cb.map_metric_train = MagicMock(name="train_map_metric")
cb.on_validation_epoch_start(_make_trainer(), _make_pl_module())
cb.map_metric.reset.assert_called_once()
cb.map_metric_train.reset.assert_not_called()
def test_train_batch_end_segm_without_masks_skips_metric_update(self) -> None:
"""Segm callback skips map_metric_train.update when preds lack a masks key."""
cb = COCOEvalCallback(segmentation=True)
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
cb.map_metric_train = MagicMock(name="map_metric_train")
module = _make_pl_module()
module.train_config = SimpleNamespace(compute_train_metrics=True)
# _detection_preds returns preds without "masks" — mimics sparse_forward training mode
outputs = {"results": _detection_preds(1), "targets": _detection_targets()}
cb.on_train_batch_end(_make_trainer(), module, outputs, None, 0)
cb.map_metric_train.update.assert_not_called()
def test_train_batch_end_segm_with_masks_calls_metric_update(self) -> None:
"""Segm callback calls map_metric_train.update when preds include a masks key."""
cb = COCOEvalCallback(segmentation=True)
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
cb.map_metric_train = MagicMock(name="map_metric_train")
module = _make_pl_module()
module.train_config = SimpleNamespace(compute_train_metrics=True)
preds_with_masks = [
{
"boxes": torch.zeros(1, 4),
"scores": torch.zeros(1),
"labels": torch.zeros(1, dtype=torch.long),
"masks": torch.zeros(1, 16, 16, dtype=torch.bool),
}
]
outputs = {"results": preds_with_masks, "targets": _detection_targets()}
cb.on_train_batch_end(_make_trainer(), module, outputs, None, 0)
cb.map_metric_train.update.assert_called_once()
def test_train_batch_end_segm_empty_preds_falls_through(self) -> None:
"""Segm callback with empty preds list falls through guard and calls update."""
cb = COCOEvalCallback(segmentation=True)
cb.setup(_make_trainer(), _make_pl_module(), stage="fit")
cb.map_metric_train = MagicMock(name="map_metric_train")
module = _make_pl_module()
module.train_config = SimpleNamespace(compute_train_metrics=True)
# Empty preds: `preds and ...` short-circuits to False → no early return → update called
outputs = {"results": [], "targets": _detection_targets()}
cb.on_train_batch_end(_make_trainer(), module, outputs, None, 0)
cb.map_metric_train.update.assert_called_once()
def test_train_batch_end_skips_accumulation_on_non_matching_epoch(self) -> None:
"""With eval_interval>1, batches on non-interval epochs must not pay accumulation cost.
Regression guard: previously every train batch ran the CPU-syncing accumulation block even
on epochs whose accumulated state on_train_epoch_end discards unread, wasting a blocking
.cpu() sync (and matching-data work) on every skipped epoch.
"""
cb = COCOEvalCallback(eval_interval=3)
trainer = _make_trainer()
trainer.current_epoch = 0 # epoch 1 (1-based) is not divisible by 3
trainer.max_epochs = 10
cb.setup(trainer, _make_pl_module(), stage="fit")
cb.map_metric_train = MagicMock(name="map_metric_train")
module = _make_pl_module()
module.train_config = SimpleNamespace(compute_train_metrics=True)
outputs = {"results": _detection_preds(1), "targets": _detection_targets()}
cb.on_train_batch_end(trainer, module, outputs, None, 0)
cb.map_metric_train.update.assert_not_called()
def test_train_batch_end_accumulates_on_matching_epoch(self) -> None:
"""With eval_interval>1, batches on interval-aligned epochs still accumulate normally."""
cb = COCOEvalCallback(eval_interval=3)
trainer = _make_trainer()
trainer.current_epoch = 2 # epoch 3 (1-based) is divisible by 3
trainer.max_epochs = 10
cb.setup(trainer, _make_pl_module(), stage="fit")
cb.map_metric_train = MagicMock(name="map_metric_train")
module = _make_pl_module()
module.train_config = SimpleNamespace(compute_train_metrics=True)
outputs = {"results": _detection_preds(1), "targets": _detection_targets()}
cb.on_train_batch_end(trainer, module, outputs, None, 0)
cb.map_metric_train.update.assert_called_once()
class TestMetricsTablePrinting:
"""Metric table terminal/notebook rendering behavior.
Covers: terminal (console.print path), Rich-missing warning, teardown
cleanup, RichProgressBar console routing, notebook in-place updates.
"""
@pytest.mark.parametrize(
"split,title_pfx",
[
pytest.param("val", "Val", id="val"),
pytest.param("test", "Test", id="test"),
],
)
def test_terminal_metrics_tables_print_to_console(self, split: str, title_pfx: str) -> None:
"""Terminal metric tables print directly through the Rich console each epoch."""
cb = COCOEvalCallback(in_notebook=False)
trainer = _make_trainer()
trainer.is_global_zero = True
console = MagicMock(name="console")
with (
patch("rfdetr.training.callbacks.coco_eval._get_rich_console", return_value=console),
patch(
"rfdetr.training.callbacks.coco_eval._render_overall_merged",
side_effect=["overall-1", "overall-2"],
),
patch("rfdetr.training.callbacks.coco_eval._render_summary_tables") as render_tables,
):
cb._print_metrics_tables(trainer, split, {"mAP": 0.1}, [])
cb._print_metrics_tables(trainer, split, {"mAP": 0.2}, [])
assert render_tables.call_count == 2
assert render_tables.call_args_list[0].args[0] is console
assert render_tables.call_args_list[0].args[1].startswith(title_pfx)
assert "(Epoch" in render_tables.call_args_list[0].args[1]
assert render_tables.call_args_list[0].args[2] == "overall-1"
def test_missing_rich_warns_once_and_skips_metric_tables(self) -> None:
"""Missing Rich emits one warning and skips noisy table rendering."""
cb = COCOEvalCallback(in_notebook=False)
trainer = _make_trainer()
trainer.is_global_zero = True
with (
patch("rfdetr.training.callbacks.coco_eval._IS_RICH_AVAILABLE", False),
patch("rfdetr.training.callbacks.coco_eval.logger.warning") as warning,
patch("rfdetr.training.callbacks.coco_eval._get_rich_console") as get_console,
):
cb._print_metrics_tables(trainer, "val", {"mAP": 0.1}, [])
cb._print_metrics_tables(trainer, "val", {"mAP": 0.2}, [])
warning.assert_called_once_with(
"Rich is not installed; skipping metric table rendering. Install `rich` to enable tables."
)
assert cb._missing_rich_warning_emitted is True
get_console.assert_not_called()
def test_teardown_releases_notebook_widget(self) -> None:
"""Teardown clears the notebook output widget reference."""
cb = COCOEvalCallback(in_notebook=True)
cb._output_widget = MagicMock(name="output_widget")
cb.teardown(_make_trainer(), _make_pl_module(), "fit")
assert cb._output_widget is None
@pytest.mark.parametrize("stage", ["fit", "validate", "test", "predict"])
def test_teardown_no_op_when_no_widget(self, stage: str) -> None:
"""Teardown does not raise when no output widget was created."""
cb = COCOEvalCallback(in_notebook=False)
assert cb._output_widget is None
cb.teardown(_make_trainer(), _make_pl_module(), stage)
assert cb._output_widget is None
def test_terminal_prints_through_rich_progress_bar_console(self) -> None:
"""Metric tables route through RichProgressBar._console when active."""
# Create a fake callback whose class name is RichProgressBar so
# _get_rich_console picks it up without importing PTL.
rich_progress_bar_fake = type("RichProgressBar", (), {})
rich_console = MagicMock(name="rich_console")
fake_pb = rich_progress_bar_fake()
fake_pb._console = rich_console # type: ignore[attr-defined]
cb = COCOEvalCallback(in_notebook=False)
trainer = _make_trainer(callbacks=[fake_pb])
trainer.is_global_zero = True
with patch(
"rfdetr.training.callbacks.coco_eval._render_overall_merged",
return_value="overall",
):
cb._print_metrics_tables(trainer, "val", {"mAP": 0.5}, [])
rich_console.print.assert_called_once()
def test_notebook_metrics_tables_reuse_and_clear_output_widget(self) -> None:
"""Notebook metric tables update one output widget instead of appending one table block per epoch."""
class FakeOutput:
"""Minimal ipywidgets.Output stand-in."""
def __init__(self) -> None:
self.clear_output = MagicMock(name="clear_output")
self.enter_count = 0
def __enter__(self) -> "FakeOutput":
self.enter_count += 1
return self
def __exit__(self, exc_type: object, exc: object, tb: object) -> bool:
return False
output_widget = FakeOutput()
display = MagicMock(name="display")
widgets_module = ModuleType("ipywidgets")
widgets_module.Output = MagicMock(return_value=output_widget)
ipython_module = ModuleType("IPython")
ipython_module.__path__ = []
display_module = ModuleType("IPython.display")
display_module.display = display
cb = COCOEvalCallback(in_notebook=True)
trainer = _make_trainer()
trainer.is_global_zero = True
with (
patch.dict(
sys.modules,
{
"ipywidgets": widgets_module,
"IPython": ipython_module,
"IPython.display": display_module,
},
),
patch("rfdetr.training.callbacks.coco_eval._render_overall_merged", side_effect=["overall-1", "overall-2"]),
patch("rfdetr.training.callbacks.coco_eval._render_summary_tables") as render_summary_tables,
):
cb._print_metrics_tables(trainer, "val", {"mAP": 0.1}, [])
cb._print_metrics_tables(trainer, "val", {"mAP": 0.2}, [])
widgets_module.Output.assert_called_once()
display.assert_called_once_with(output_widget)
assert cb._output_widget is output_widget
assert [call.kwargs for call in output_widget.clear_output.call_args_list] == [
{"wait": True},
{"wait": True},
]
assert output_widget.enter_count == 2
assert render_summary_tables.call_count == 2
@pytest.mark.parametrize(
"stage,hook,prefix",
[
pytest.param("fit", "on_validation_epoch_end", "val/", id="val"),
pytest.param("test", "on_test_epoch_end", "test/", id="test"),
],
)
class TestEpochEndCommon:
"""Metric logging and state reset shared by on_validation_epoch_end and on_test_epoch_end."""
def test_detection_core_metrics_are_logged(self, stage, hook, prefix) -> None:
"""mAP_50_95, mAP_50, mAP_75, mAR are always logged under the correct prefix."""
cb = COCOEvalCallback(max_dets=500)
cb.setup(_make_trainer(), _make_pl_module(), stage=stage)
cb.map_metric = MagicMock(name="map_metric")
cb.map_metric.compute.return_value = _minimal_metrics()
module = _make_pl_module()
getattr(cb, hook)(_make_trainer(), module)
logged_keys = {c.args[0] for c in module.log.call_args_list}
assert f"{prefix}mAP_50_95" in logged_keys
assert f"{prefix}mAP_50" in logged_keys
assert f"{prefix}mAP_75" in logged_keys
assert f"{prefix}mAR" in logged_keys
def test_f1_metrics_logged_when_gt_present(self, stage, hook, prefix) -> None:
"""F1, precision, recall are logged when GT exists."""
cb = COCOEvalCallback()
cb.setup(_make_trainer(), _make_pl_module(), stage=stage)
cb.map_metric = MagicMock(name="map_metric")
cb.map_metric.compute.return_value = _minimal_metrics()
cb._f1_local = {
0: {
"scores": np.array([0.9], dtype=np.float32),
"matches": np.array([1], dtype=np.int64),
"ignore": np.array([False]),
"total_gt": 1,
}
}
module = _make_pl_module()
getattr(cb, hook)(_make_trainer(), module)
logged_keys = {c.args[0] for c in module.log.call_args_list}
assert f"{prefix}F1" in logged_keys
assert f"{prefix}precision" in logged_keys
assert f"{prefix}recall" in logged_keys
def test_f1_metrics_zero_when_no_gt(self, stage, hook, prefix) -> None:
"""F1 == 0.0 when no predictions were accumulated (empty epoch)."""
cb = COCOEvalCallback()
cb.setup(_make_trainer(), _make_pl_module(), stage=stage)
cb.map_metric = MagicMock(name="map_metric")
cb.map_metric.compute.return_value = _minimal_metrics()
module = _make_pl_module()
getattr(cb, hook)(_make_trainer(), module)
f1_call = next(c for c in module.log.call_args_list if c.args[0] == f"{prefix}F1")
assert f1_call.args[1] == pytest.approx(0.0)
def test_state_reset_after_epoch(self, stage, hook, prefix) -> None:
"""map_metric.reset() is called and _f1_local is cleared after epoch end."""
cb = COCOEvalCallback()
cb.setup(_make_trainer(), _make_pl_module(), stage=stage)
cb.map_metric = MagicMock(name="map_metric")
cb.map_metric.compute.return_value = _minimal_metrics()
cb._f1_local = {
0: {
"scores": np.array([0.9], dtype=np.float32),
"matches": np.array([1], dtype=np.int64),
"ignore": np.array([False]),
"total_gt": 1,
}
}
getattr(cb, hook)(_make_trainer(), _make_pl_module())
cb.map_metric.reset.assert_called_once()
assert cb._f1_local == {}
def test_segmentation_extra_metrics_logged(self, stage, hook, prefix) -> None:
"""segm_mAP_50_95 and segm_mAP_50 are logged in segmentation mode."""
cb = COCOEvalCallback(segmentation=True)
cb.setup(_make_trainer(), _make_pl_module(), stage=stage)
cb.map_metric = MagicMock(name="map_metric")
segm_metrics = _minimal_metrics(pfx="bbox_")
segm_metrics["segm_map"] = torch.tensor(0.35)
segm_metrics["segm_map_50"] = torch.tensor(0.55)
cb.map_metric.compute.return_value = segm_metrics
module = _make_pl_module()
getattr(cb, hook)(_make_trainer(), module)
logged_keys = {c.args[0] for c in module.log.call_args_list}
assert f"{prefix}segm_mAP_50_95" in logged_keys
assert f"{prefix}segm_mAP_50" in logged_keys
class TestKeypointCocoEvalRouting:
"""Tests for keypoint COCO evaluation routing in keypoint mode."""
def test_coco_evaluator_accepts_keypoint_predictions(self) -> None:
"""Keypoint mode should forward keypoint predictions to COCO evaluator update()."""
cb = COCOEvalCallback(max_dets=500)
module = _make_pl_module()
module.model_config = SimpleNamespace(use_grouppose_keypoints=True)
trainer = _make_trainer()
cb.setup(trainer, module, stage="fit")
evaluator = MagicMock(name="keypoint_coco_eval")
cb._get_or_create_keypoint_oks_metric = MagicMock(return_value=evaluator) # type: ignore[method-assign]
outputs = {
"results": [
{
"boxes": torch.tensor([[0.0, 0.0, 10.0, 10.0]], dtype=torch.float32),
"scores": torch.tensor([0.9], dtype=torch.float32),
"labels": torch.tensor([0], dtype=torch.int64),
"keypoints": torch.tensor([[[1.0, 2.0, 0.8]]], dtype=torch.float32),
}
],
"targets": [{"image_id": torch.tensor([12])}],
}
cb._update_keypoint_oks_metric(trainer, outputs, split="val")
evaluator.update.assert_called_once()
predictions = evaluator.update.call_args.args[0]
assert 12 in predictions
assert "keypoints" in predictions[12]
assert predictions[12]["keypoints"].shape == (1, 1, 3)
def test_keypoint_coco_eval_exposes_keypoint_ap_and_ar_metrics(self) -> None:
"""Epoch-end logging should expose keypoint AP and AR metrics from MetricKeypointOKS.compute()."""
cb = COCOEvalCallback(max_dets=500)
module = _make_pl_module()
module.model_config = SimpleNamespace(use_grouppose_keypoints=True)
trainer = _make_trainer()
trainer.callback_metrics = {}
cb.setup(trainer, module, stage="fit")
cb.map_metric = MagicMock(name="map_metric")
cb.map_metric.compute.return_value = _minimal_metrics()
keypoint_metric = MagicMock(name="keypoint_oks_metric")
keypoint_metric.has_updates = True
keypoint_metric.compute.return_value = {"map": 0.42, "map_50": 0.72, "map_75": 0.31, "mar": 0.55}
cb._keypoint_oks_metrics["val"] = keypoint_metric
cb.on_validation_epoch_end(trainer, module)
logged = {call.args[0]: call.args[1] for call in module.log.call_args_list}
assert "val/keypoint_map_50_95" in logged
assert "val/keypoint_map_50" in logged
assert "val/keypoint_map_75" in logged
assert "val/keypoint_mAR" in logged
assert float(logged["val/keypoint_map_50_95"]) == pytest.approx(0.42)
assert float(logged["val/keypoint_map_50"]) == pytest.approx(0.72)
assert float(logged["val/keypoint_map_75"]) == pytest.approx(0.31)
assert float(logged["val/keypoint_mAR"]) == pytest.approx(0.55)
keypoint_log_calls = [call for call in module.log.call_args_list if call.args[0] == "val/keypoint_map_50_95"]
assert keypoint_log_calls[0].kwargs.get("prog_bar") is True
assert trainer.callback_metrics["val/keypoint_map_50_95"].item() == pytest.approx(0.42)
assert trainer.callback_metrics["val/keypoint_map_50"].item() == pytest.approx(0.72)
assert trainer.callback_metrics["val/keypoint_map_75"].item() == pytest.approx(0.31)
assert trainer.callback_metrics["val/keypoint_mAR"].item() == pytest.approx(0.55)
keypoint_metric.compute.assert_called_once()
def test_keypoint_coco_eval_exposes_ema_keypoint_ap_and_ar_metrics(self) -> None:
"""EMA keypoint epoch-end logging should expose val/ema_keypoint_* metrics."""
cb = COCOEvalCallback(max_dets=500)
module = _make_pl_module()
module.model_config = SimpleNamespace(use_grouppose_keypoints=True)
trainer = _make_trainer()
trainer.callback_metrics = {}
cb.setup(trainer, module, stage="fit")
keypoint_metric = MagicMock(name="ema_keypoint_oks_metric")
keypoint_metric.has_updates = True
keypoint_metric.compute.return_value = {"map": 0.25, "map_50": 0.5, "map_75": 0.2, "mar": 0.45}
cb._keypoint_oks_metrics["val_ema"] = keypoint_metric
cb._compute_and_log_keypoint_map("val_ema", module, trainer, log_split="val", metric_prefix="ema_")
logged = {call.args[0]: call.args[1] for call in module.log.call_args_list}
assert "val/ema_keypoint_map_50_95" in logged
assert "val/ema_keypoint_map_50" in logged
assert "val/ema_keypoint_map_75" in logged
assert "val/ema_keypoint_mAR" in logged
assert float(logged["val/ema_keypoint_map_50_95"]) == pytest.approx(0.25)
assert float(logged["val/ema_keypoint_map_50"]) == pytest.approx(0.5)
assert float(logged["val/ema_keypoint_map_75"]) == pytest.approx(0.2)
assert float(logged["val/ema_keypoint_mAR"]) == pytest.approx(0.45)
keypoint_log_calls = [
call for call in module.log.call_args_list if call.args[0] == "val/ema_keypoint_map_50_95"
]
assert keypoint_log_calls[0].kwargs.get("prog_bar") is True
assert trainer.callback_metrics["val/ema_keypoint_map_50_95"].item() == pytest.approx(0.25)
assert trainer.callback_metrics["val/ema_keypoint_map_50"].item() == pytest.approx(0.5)
assert trainer.callback_metrics["val/ema_keypoint_map_75"].item() == pytest.approx(0.2)
assert trainer.callback_metrics["val/ema_keypoint_mAR"].item() == pytest.approx(0.45)
keypoint_metric.compute.assert_called_once()
def test_keypoint_oks_metric_created_with_correct_args(self) -> None:
"""_get_or_create_keypoint_oks_metric must construct MetricKeypointOKS with coco_api and sigmas."""
cb = COCOEvalCallback(max_dets=500, keypoint_oks_sigmas=[0.05])
dataset = MagicMock(name="dataset")
datamodule = MagicMock()
datamodule._dataset_val = dataset
datamodule._dataset_test = None
datamodule._dataset_train = None
trainer = _make_trainer(datamodule=datamodule)
coco_api = MagicMock(name="coco_api")
with (
patch("rfdetr.training.callbacks.coco_eval.get_coco_api_from_dataset", return_value=coco_api),
patch("rfdetr.training.callbacks.coco_eval.MetricKeypointOKS") as oks_metric_cls,
):
result = cb._get_or_create_keypoint_oks_metric(trainer, split="val")
assert result is oks_metric_cls.return_value
oks_metric_cls.assert_called_once_with(coco_api, keypoint_oks_sigmas=[0.05], max_dets=500)
def test_keypoint_train_eval_uses_train_dataset(self) -> None:
"""Train keypoint mAP must construct MetricKeypointOKS from the train dataset."""
cb = COCOEvalCallback(max_dets=500, keypoint_oks_sigmas=[0.05])
train_dataset = MagicMock(name="train_dataset")
val_dataset = MagicMock(name="val_dataset")
datamodule = MagicMock()
datamodule._dataset_train = train_dataset
datamodule._dataset_val = val_dataset
datamodule._dataset_test = None
trainer = _make_trainer(datamodule=datamodule)
train_coco_api = MagicMock(name="train_coco_api")
val_coco_api = MagicMock(name="val_coco_api")
def _get_coco_api(dataset):
if dataset is train_dataset:
return train_coco_api
if dataset is val_dataset:
return val_coco_api
return None
with (
patch("rfdetr.training.callbacks.coco_eval.get_coco_api_from_dataset", side_effect=_get_coco_api),
patch("rfdetr.training.callbacks.coco_eval.MetricKeypointOKS") as oks_metric_cls,
):
cb._get_or_create_keypoint_oks_metric(trainer, split="train")
assert oks_metric_cls.call_args.args[0] is train_coco_api