Repository navigation
Expand file tree
/
Copy pathtest_models.py
More file actions
executable file
·1532 lines (1325 loc) · 53.8 KB
/
Copy pathtest_models.py
File metadata and controls
executable file
·1532 lines (1325 loc) · 53.8 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
import math
import pytest
pytest.importorskip("torch")
pytest.importorskip("torchvision")
import torch
import warnings
from oriented_det.geometry import RBox
from oriented_det.models import OrientedRCNN, RotatedRetinaNet, RotatedFasterRCNN
from oriented_det.models.backbones import build_resnet_fpn_backbone
from oriented_det.models.utils import derive_fpn_strides_from_grid, warn_if_fpn_strides_mismatch
def _dummy_inputs():
image = torch.rand(3, 128, 128)
target = {
"rboxes": [RBox(64, 64, 32, 16, 0.0)],
"labels": torch.tensor([1], dtype=torch.int64),
}
return image, target
@pytest.mark.parametrize(
"model_cls",
[OrientedRCNN, RotatedRetinaNet],
)
def test_model_forward_train(model_cls):
image, target = _dummy_inputs()
model = model_cls(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
)
model.train()
losses = model([image], [target])
assert isinstance(losses, dict)
# Different detectors expose different loss keys. Keep this test API-robust.
assert "loss_box_reg" in losses
assert any(k in losses for k in ("loss_objectness", "loss_classifier"))
for v in losses.values():
assert torch.is_tensor(v) or isinstance(v, (float, int))
@pytest.mark.parametrize(
"model_cls",
[OrientedRCNN, RotatedRetinaNet],
)
@torch.no_grad()
def test_model_forward_eval(model_cls):
image, _ = _dummy_inputs()
model = model_cls(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
)
model.eval()
outputs = model([image])
assert isinstance(outputs, list)
assert "rboxes" in outputs[0]
class TestOrientedRCNNConfiguration:
"""Tests for OrientedRCNN configuration options."""
def test_different_anchor_configurations(self):
"""Test OrientedRCNN with different scales/ratios (RPN priors stay horizontal)."""
model1 = OrientedRCNN(
num_classes=15,
anchor_scales=[8],
anchor_ratios=[0.5, 1.0, 2.0],
)
model2 = OrientedRCNN(
num_classes=15,
anchor_scales=[8],
anchor_ratios=[0.125, 0.5, 1.0, 2.0, 8.0],
)
assert model1.num_classes == 15
assert model2.num_classes == 15
assert model1.anchor_angles == [0.0]
assert model2.anchor_angles == [0.0]
assert model1.num_anchors == 3
assert model2.num_anchors == 5
model_custom = OrientedRCNN(
num_classes=15,
backbone_name="resnet18",
pretrained_backbone=False,
anchor_scales=[8],
anchor_ratios=[0.5, 1.0, 2.0],
anchor_angles=[-math.pi / 2, math.pi / 2],
)
assert model_custom.num_anchors == 6
def test_class_agnostic_vs_specific_regression(self):
"""Test class-agnostic vs class-specific regression."""
# Class-agnostic (default)
model_agnostic = OrientedRCNN(
num_classes=10,
backbone_name="resnet18",
pretrained_backbone=False,
)
# Check ROI head configuration
assert model_agnostic.roi_class_agnostic_regression == True
# Test forward pass
image, target = _dummy_inputs()
model_agnostic.train()
losses = model_agnostic([image], [target])
assert "loss_classifier" in losses
assert "loss_box_reg" in losses
def test_different_loss_types(self):
"""Test different loss types."""
# Cross-entropy (default)
model_ce = OrientedRCNN(
num_classes=10,
backbone_name="resnet18",
pretrained_backbone=False,
roi_loss_type="cross_entropy",
)
# Focal loss
model_focal = OrientedRCNN(
num_classes=10,
backbone_name="resnet18",
pretrained_backbone=False,
roi_loss_type="focal",
roi_focal_gamma=2.0,
)
image, target = _dummy_inputs()
model_ce.train()
losses_ce = model_ce([image], [target])
model_focal.train()
losses_focal = model_focal([image], [target])
assert "loss_classifier" in losses_ce
assert "loss_classifier" in losses_focal
def test_class_weights_dict(self):
"""Test class weights with dictionary format."""
class_weights = {
"class1": 2.0,
"class2": 0.5,
}
model = OrientedRCNN(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
roi_class_weights=class_weights,
)
# Set class mapping
class_map = {"class1": 1, "class2": 2}
model.set_class_weights(class_map)
# Check that weights were set
assert model.roi_class_weights is not None
assert model.roi_class_weights.shape[0] == 3 # background + 2 classes
def test_class_weights_tensor(self):
"""Test class weights with tensor format."""
class_weights = torch.tensor([1.0, 2.0, 0.5]) # background, class1, class2
model = OrientedRCNN(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
roi_class_weights=class_weights,
)
assert model.roi_class_weights is not None
assert torch.allclose(model.roi_class_weights, class_weights)
def test_target_normalization(self):
"""Test target normalization configuration."""
target_means = (0.0, 0.0, 0.0, 0.0, 0.0)
target_stds = (0.1, 0.1, 0.2, 0.2, 0.1)
model = OrientedRCNN(
num_classes=10,
backbone_name="resnet18",
pretrained_backbone=False,
target_means=target_means,
target_stds=target_stds,
)
assert model.target_means == target_means
assert model.target_stds == target_stds
# Test forward pass
image, target = _dummy_inputs()
model.train()
losses = model([image], [target])
assert "loss_rpn_box_reg" in losses
class TestOrientedRCNNEdgeCases:
"""Tests for OrientedRCNN edge cases."""
def test_empty_images(self):
"""Test with empty image list."""
model = OrientedRCNN(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
)
model.eval()
# Empty list should raise error
with pytest.raises((ValueError, IndexError, RuntimeError)):
model([])
def test_images_with_no_objects(self):
"""Test with images that have no objects."""
model = OrientedRCNN(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
)
image = torch.rand(3, 128, 128)
target = {
"rboxes": [],
"labels": torch.tensor([], dtype=torch.int64),
}
model.train()
losses = model([image], [target])
# Should still return valid loss dict
assert isinstance(losses, dict)
assert "loss_objectness" in losses
def test_batch_size_gt_1(self):
"""Test with batch size > 1."""
model = OrientedRCNN(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
)
images = [
torch.rand(3, 128, 128),
torch.rand(3, 128, 128),
]
targets = [
{"rboxes": [RBox(64, 64, 32, 16, 0.0)], "labels": torch.tensor([1])},
{"rboxes": [RBox(64, 64, 32, 16, 0.0)], "labels": torch.tensor([1])},
]
model.train()
losses = model(images, targets)
assert isinstance(losses, dict)
def test_keep_ratio_pad32_p6_canvas(self):
"""HRSC keep_ratio + Pad(32) can be 576x800; P6 must not raise."""
model = OrientedRCNN(
num_classes=1,
backbone_name="resnet18",
pretrained_backbone=False,
)
image = torch.rand(3, 576, 800)
target = {
"rboxes": [RBox(400.0, 288.0, 80.0, 20.0, 0.0)],
"labels": torch.tensor([1]),
}
model.train()
losses = model([image], [target])
assert "loss_objectness" in losses
def test_variable_image_sizes(self):
"""Test with variable image sizes."""
model = OrientedRCNN(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
)
# Model currently requires same-size images in a batch (due to torch.stack)
# Test with same-size images instead
images = [
torch.rand(3, 128, 128),
torch.rand(3, 128, 128),
]
targets = [
{"rboxes": [RBox(64, 64, 32, 16, 0.0)], "labels": torch.tensor([1])},
{"rboxes": [RBox(64, 64, 32, 16, 0.0)], "labels": torch.tensor([1])},
]
model.train()
losses = model(images, targets)
assert isinstance(losses, dict)
def test_multiple_classes(self):
"""Test with multiple classes."""
model = OrientedRCNN(
num_classes=15,
backbone_name="resnet18",
pretrained_backbone=False,
)
image = torch.rand(3, 128, 128)
target = {
"rboxes": [
RBox(64, 64, 32, 16, 0.0),
RBox(128, 128, 32, 16, 0.0),
],
"labels": torch.tensor([1, 5]),
}
model.train()
losses = model([image], [target])
assert isinstance(losses, dict)
model.eval()
with torch.no_grad():
outputs = model([image])
assert len(outputs) == 1
assert "labels" in outputs[0]
class TestOrientedRCNNIntegration:
"""Integration tests for OrientedRCNN."""
def test_full_training_forward(self):
"""Test full forward pass in training mode."""
model = OrientedRCNN(
num_classes=15,
backbone_name="resnet18",
pretrained_backbone=False,
)
image = torch.rand(3, 256, 256)
target = {
"rboxes": [
RBox(128, 128, 64, 32, 0.0),
RBox(200, 200, 40, 20, math.pi / 4),
],
"labels": torch.tensor([1, 5]),
}
model.train()
losses = model([image], [target])
# Check all expected losses are present
assert "loss_objectness" in losses
assert "loss_rpn_box_reg" in losses
assert "loss_classifier" in losses
assert "loss_box_reg" in losses
# Optimization losses should be scalar tensors.
for loss_name in ("loss_objectness", "loss_rpn_box_reg", "loss_classifier", "loss_box_reg"):
loss_value = losses[loss_name]
assert torch.is_tensor(loss_value)
assert loss_value.dim() == 0 # Scalar
def test_fpn_includes_pool_level_no_stride_warning(self):
"""OrientedRCNN RPN must see 5 FPN levels (P2–P6), matching RotatedFasterRCNN."""
import warnings
model = OrientedRCNN(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
fpn_strides=[4, 8, 16, 32, 64],
)
image = torch.rand(3, 512, 512)
target = {"rboxes": [RBox(256, 256, 64, 32, 0.0)], "labels": torch.tensor([1])}
model.train()
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
model([image], [target])
fpn_warnings = [w for w in caught if "fpn_strides from config" in str(w.message)]
assert not fpn_warnings
def test_full_inference_forward(self):
"""Test full forward pass in inference mode."""
model = OrientedRCNN(
num_classes=15,
backbone_name="resnet18",
pretrained_backbone=False,
)
image = torch.rand(3, 256, 256)
model.eval()
with torch.no_grad():
outputs = model([image])
assert len(outputs) == 1
output = outputs[0]
# Check output format (only rboxes, no boxes)
assert "rboxes" in output
assert "labels" in output
assert "scores" in output
assert "boxes" not in output # Should not have boxes format
# Check tensor shapes
assert len(output["labels"]) == len(output["scores"])
assert len(output["rboxes"]) == len(output["labels"])
def test_proposal_generation_end_to_end(self):
"""Test that proposals are generated correctly."""
model = OrientedRCNN(
num_classes=15,
backbone_name="resnet18",
pretrained_backbone=False,
)
image = torch.rand(3, 256, 256)
model.eval()
with torch.no_grad():
outputs = model([image])
# Should have some proposals (or empty if score threshold filters all)
assert len(outputs) == 1
assert "rboxes" in outputs[0]
assert isinstance(outputs[0]["rboxes"], list)
class TestBackbone:
"""Tests for backbone construction."""
@pytest.mark.parametrize("backbone_name", ["resnet18", "resnet50", "resnet101"])
def test_different_backbone_types(self, backbone_name):
"""Test different backbone types."""
backbone = build_resnet_fpn_backbone(
backbone_name,
pretrained=False,
)
# Test forward pass
dummy_input = torch.randn(1, 3, 256, 256)
features = backbone(dummy_input)
# Should return dict or list of feature maps
assert isinstance(features, (dict, list))
def test_backbone_pretrained_vs_random(self):
"""Test pretrained vs random initialization."""
# Random initialization
backbone_random = build_resnet_fpn_backbone(
"resnet18",
pretrained=False,
)
# Pretrained (if available)
backbone_pretrained = build_resnet_fpn_backbone(
"resnet18",
pretrained=True,
)
# Both should work
dummy_input = torch.randn(1, 3, 256, 256)
features_random = backbone_random(dummy_input)
features_pretrained = backbone_pretrained(dummy_input)
assert isinstance(features_random, (dict, list))
assert isinstance(features_pretrained, (dict, list))
def test_backbone_trainable_layers(self):
"""Test trainable layers configuration."""
backbone = build_resnet_fpn_backbone(
"resnet50",
pretrained=False,
trainable_layers=3,
)
# Count trainable parameters
trainable_params = sum(p.numel() for p in backbone.parameters() if p.requires_grad)
assert trainable_params > 0
class TestRotatedRetinaNet:
"""Tests for RotatedRetinaNet oriented detection."""
def test_rotated_retinanet_accepts_aux_loss_weight(self):
"""RetinaNet should accept the optional auxiliary box-reg weight."""
model = RotatedRetinaNet(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
box_reg_aux_weight=0.25,
box_reg_aux_loss_type="probiou",
)
assert model.box_reg_aux_weight == 0.25
def test_retinanet_head_separate_cls_reg_towers(self):
"""RetinaNet head uses MMRotate-style separate subnets and 3x3 prediction convs."""
from oriented_det.models.rotated_retinanet import OrientedRetinaNetHead
num_classes, num_anchors = 3, 9
head = OrientedRetinaNetHead(
in_channels=256,
num_classes=num_classes,
num_anchors=num_anchors,
stacked_convs=4,
)
assert len(head.cls_convs) == 4
assert len(head.reg_convs) == 4
assert not hasattr(head, "convs")
assert head.conv_cls.kernel_size == (3, 3)
assert head.conv_bbox.kernel_size == (3, 3)
feats = [torch.randn(1, 256, 32, 32)]
cls_logits, bbox_pred = head(feats)
assert cls_logits[0].shape == (1, num_anchors * num_classes, 32, 32)
assert bbox_pred[0].shape == (1, num_anchors * 5, 32, 32)
def test_rotated_retinanet_angle_prediction(self):
"""Test that RotatedRetinaNet predicts non-zero angles."""
model = RotatedRetinaNet(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
)
image = torch.rand(3, 256, 256)
target = {
"rboxes": [
RBox(128, 128, 64, 32, math.pi / 4), # Rotated box
RBox(200, 200, 40, 20, -math.pi / 6), # Another rotated box
],
"labels": torch.tensor([1, 2], dtype=torch.int64),
}
# Training forward
model.train()
losses = model([image], [target])
assert isinstance(losses, dict)
assert "loss_classifier" in losses
assert "loss_box_reg" in losses
# Inference forward - check that angles are predicted
model.eval()
with torch.no_grad():
outputs = model([image])
assert len(outputs) == 1
output = outputs[0]
assert "rboxes" in output
assert "labels" in output
assert "scores" in output
# If there are detections, verify they have angles (not all zero)
if len(output["rboxes"]) > 0:
angles = [rbox.angle for rbox in output["rboxes"]]
# Angles should be in reasonable range (not necessarily all non-zero due to thresholding)
assert all(-math.pi <= angle <= math.pi for angle in angles)
def test_rotated_retinanet_different_anchor_configs(self):
"""Test RotatedRetinaNet scales/ratios and optional multi-angle priors."""
model1 = RotatedRetinaNet(
num_classes=15,
anchor_scales=[8],
anchor_ratios=[0.5, 1.0, 2.0],
)
model2 = RotatedRetinaNet(
num_classes=15,
anchor_scales=[8, 16],
anchor_ratios=[0.5, 1.0, 2.0, 3.0],
)
assert model1.num_classes == 15
assert model2.num_classes == 15
assert model1.anchor_angles == [0.0]
assert model2.anchor_angles == [0.0]
assert model1.num_anchors == 3 # len(ratios) * single reference angle
assert model2.num_anchors == 4
assert model1.proj_xy is True
model_custom = RotatedRetinaNet(
num_classes=15,
backbone_name="resnet18",
pretrained_backbone=False,
anchor_scales=[8],
anchor_ratios=[0.5, 1.0, 2.0],
anchor_angles=[-math.pi / 4, 0.0, math.pi / 4],
octave_base_scale=4.0,
scales_per_octave=3,
)
assert model_custom.num_anchors == 27 # 3 scales × 3 ratios × 3 angles
assert len(model_custom.anchor_angles) == 3
assert model_custom.proj_xy is True
image = torch.rand(3, 128, 128)
target = {
"rboxes": [RBox(64, 64, 32, 16, math.pi / 4)],
"labels": torch.tensor([1], dtype=torch.int64),
}
model_custom.train()
losses = model_custom([image], [target])
assert losses["loss_classifier"].requires_grad
assert losses["loss_box_reg"].requires_grad
def test_rotated_retinanet_probiou_main_with_encoded_aux_backward(self):
"""ProbIoU primary + encoded L1 aux should backprop through bbox head."""
model = RotatedRetinaNet(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
box_reg_main_loss_type="probiou",
box_reg_probiou_mode="l1",
box_reg_aux_weight=0.1,
box_reg_aux_loss_type="smooth_l1",
box_reg_loss_type="l1",
reg_sample_size_per_image=512,
)
image = torch.rand(3, 128, 128)
target = {
"rboxes": [RBox(64, 64, 32, 16, 0.2)],
"labels": torch.tensor([1], dtype=torch.int64),
}
model.train()
losses = model([image], [target])
assert losses["loss_box_reg"].requires_grad
losses["loss_box_reg"].backward()
def test_retinanet_global_reg_sampling_caps_per_image(self):
"""Decoded reg loss should sample positives once per image across FPN levels."""
from unittest.mock import patch
from oriented_det.models.rotated_retinanet import compute_oriented_retinanet_loss
device = torch.device("cpu")
num_classes = 2
num_anchors = 3
gt_boxes = [torch.tensor([[64.0, 64.0, 32.0, 16.0, 0.0]], device=device)]
gt_labels = [torch.tensor([1], device=device, dtype=torch.int64)]
image_sizes = [(128, 128)]
cls_logits = []
bbox_regs = []
anchor_levels = []
for stride, size in [(8, 16), (16, 8)]:
h = w = size
cls_logits.append(
torch.randn(1, num_anchors * num_classes, h, w, device=device, requires_grad=True)
)
bbox_regs.append(
torch.randn(1, num_anchors * 5, h, w, device=device, requires_grad=True)
)
yy, xx = torch.meshgrid(
torch.arange(h, device=device, dtype=torch.float32),
torch.arange(w, device=device, dtype=torch.float32),
indexing="ij",
)
cx = (xx + 0.5) * stride
cy = (yy + 0.5) * stride
grid_cx = cx.reshape(-1)
grid_cy = cy.reshape(-1)
n_loc = grid_cx.numel()
anchors = torch.stack(
[
grid_cx.repeat(num_anchors),
grid_cy.repeat(num_anchors),
torch.full((n_loc * num_anchors,), 32.0, device=device),
torch.full((n_loc * num_anchors,), 16.0, device=device),
torch.zeros(n_loc * num_anchors, device=device),
],
dim=1,
)
anchor_levels.append(anchors)
seen_sizes = []
def _capture_reg_loss(bbox_pred, anchors, regression_targets, matched_gt, **kwargs):
seen_sizes.append(int(bbox_pred.shape[0]))
return bbox_pred.sum() * 0.0 + 1.0
with patch(
"oriented_det.models.rotated_retinanet._compute_retinanet_reg_loss_from_positives",
side_effect=_capture_reg_loss,
):
losses = compute_oriented_retinanet_loss(
classification_logits=cls_logits,
bbox_regression=bbox_regs,
anchors=anchor_levels,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
image_sizes=image_sizes,
num_classes=num_classes,
main_loss_type="probiou",
box_reg_loss_type="l1",
box_reg_aux_weight=0.1,
box_reg_aux_loss_type="smooth_l1",
reg_sample_size_per_image=512,
)
assert len(seen_sizes) == 1
assert seen_sizes[0] <= 512
assert losses["loss_box_reg"].requires_grad
def test_retinanet_loss_assigns_concatenated_fpn_levels_once_per_image(self):
"""MaxIoU should see cat(P3, P4) once, not each FPN level separately."""
from unittest.mock import patch
from oriented_det.models.retinanet_assign import match_retinanet_anchors_to_gt
from oriented_det.models.rotated_retinanet import compute_oriented_retinanet_loss
device = torch.device("cpu")
num_classes = 2
num_anchors = 3
gt_boxes = [torch.tensor([[64.0, 64.0, 32.0, 16.0, 0.0]], device=device)]
gt_labels = [torch.tensor([1], device=device, dtype=torch.int64)]
image_sizes = [(128, 128)]
cls_logits = []
bbox_regs = []
anchor_levels = []
for stride, size in [(8, 16), (16, 8)]:
h = w = size
cls_logits.append(
torch.randn(1, num_anchors * num_classes, h, w, device=device, requires_grad=True)
)
bbox_regs.append(
torch.randn(1, num_anchors * 5, h, w, device=device, requires_grad=True)
)
yy, xx = torch.meshgrid(
torch.arange(h, device=device, dtype=torch.float32),
torch.arange(w, device=device, dtype=torch.float32),
indexing="ij",
)
cx = (xx + 0.5) * stride
cy = (yy + 0.5) * stride
grid_cx = cx.reshape(-1)
grid_cy = cy.reshape(-1)
n_loc = grid_cx.numel()
anchors = torch.stack(
[
grid_cx.repeat(num_anchors),
grid_cy.repeat(num_anchors),
torch.full((n_loc * num_anchors,), 32.0, device=device),
torch.full((n_loc * num_anchors,), 16.0, device=device),
torch.zeros(n_loc * num_anchors, device=device),
],
dim=1,
)
anchor_levels.append(anchors)
seen = []
def _capture_match(anchors, gt_boxes, *args, **kwargs):
seen.append(int(anchors.shape[0]))
return match_retinanet_anchors_to_gt(anchors, gt_boxes, *args, **kwargs)
with patch(
"oriented_det.models.rotated_retinanet.match_retinanet_anchors_to_gt",
side_effect=_capture_match,
):
losses = compute_oriented_retinanet_loss(
classification_logits=cls_logits,
bbox_regression=bbox_regs,
anchors=anchor_levels,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
image_sizes=image_sizes,
num_classes=num_classes,
)
assert seen == [anchor_levels[0].shape[0] + anchor_levels[1].shape[0]]
assert losses["loss_classifier"].requires_grad
def test_rotated_retinanet_loss_computation(self):
"""Test that RotatedRetinaNet computes losses correctly."""
model = RotatedRetinaNet(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
)
image = torch.rand(3, 128, 128)
target = {
"rboxes": [RBox(64, 64, 32, 16, 0.0)],
"labels": torch.tensor([1], dtype=torch.int64),
}
model.train()
losses = model([image], [target])
# Check loss structure
assert isinstance(losses, dict)
assert "loss_classifier" in losses
assert "loss_box_reg" in losses
assert isinstance(losses["retinanet_num_pos"], float)
assert losses["retinanet_num_pos"] >= 0.0
# Losses should be scalars
assert losses["loss_classifier"].dim() == 0
assert losses["loss_box_reg"].dim() == 0
# Losses should be non-negative
assert losses["loss_classifier"].item() >= 0
assert losses["loss_box_reg"].item() >= 0
def test_rotated_retinanet_inference_format(self):
"""Test that RotatedRetinaNet inference returns correct format."""
model = RotatedRetinaNet(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
)
image = torch.rand(3, 256, 256)
model.eval()
with torch.no_grad():
outputs = model([image])
assert isinstance(outputs, list)
assert len(outputs) == 1
output = outputs[0]
assert "rboxes" in output
assert "labels" in output
assert "scores" in output
# Check types
assert isinstance(output["rboxes"], list)
assert torch.is_tensor(output["labels"])
assert torch.is_tensor(output["scores"])
# Check shapes match
assert len(output["rboxes"]) == len(output["labels"])
assert len(output["labels"]) == len(output["scores"])
# Check RBoxes have angles
for rbox in output["rboxes"]:
assert isinstance(rbox, RBox)
assert hasattr(rbox, 'angle')
def test_rotated_retinanet_empty_images(self):
"""Test RotatedRetinaNet with images that have no objects."""
model = RotatedRetinaNet(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
)
image = torch.rand(3, 128, 128)
target = {
"rboxes": [],
"labels": torch.tensor([], dtype=torch.int64),
}
model.train()
losses = model([image], [target])
# Should still return valid loss dict
assert isinstance(losses, dict)
assert "loss_classifier" in losses
assert "loss_box_reg" in losses
def test_rotated_retinanet_batch_processing(self):
"""Test RotatedRetinaNet with batch size > 1."""
model = RotatedRetinaNet(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
)
images = [
torch.rand(3, 128, 128),
torch.rand(3, 128, 128),
]
targets = [
{"rboxes": [RBox(64, 64, 32, 16, 0.0)], "labels": torch.tensor([1])},
{"rboxes": [RBox(64, 64, 32, 16, math.pi / 4)], "labels": torch.tensor([2])},
]
model.train()
losses = model(images, targets)
assert isinstance(losses, dict)
model.eval()
with torch.no_grad():
outputs = model(images)
assert len(outputs) == 2
def test_exposes_nms_class_agnostic_for_inference_overrides(self):
from oriented_det.train.config import ProductionConfig, apply_inference_config_to_model
model = RotatedRetinaNet(
num_classes=2,
backbone_name="resnet18",
pretrained_backbone=False,
)
assert hasattr(model, "nms_class_agnostic")
assert model.nms_class_agnostic is False
apply_inference_config_to_model(model, ProductionConfig(nms_class_agnostic=True))
assert model.nms_class_agnostic is True
def test_final_nms_class_aware_keeps_overlapping_car_and_truck(self):
from oriented_det.models.rotated_retinanet import _apply_retinanet_nms
boxes = torch.tensor(
[[100.0, 100.0, 40.0, 20.0, 0.0], [100.0, 100.0, 40.0, 20.0, 0.0]]
)
scores = torch.tensor([0.9, 0.8])
labels = torch.tensor([1, 2]) # car, truck
keep = _apply_retinanet_nms(
boxes,
scores,
labels,
iou_threshold=0.1,
max_detections_per_image=100,
use_gpu_nms=False,
class_agnostic=False,
)
assert keep.numel() == 2
assert set(labels[keep].tolist()) == {1, 2}
def test_final_nms_class_agnostic_suppresses_overlapping_car_and_truck(self):
from oriented_det.models.rotated_retinanet import _apply_retinanet_nms
boxes = torch.tensor(
[[100.0, 100.0, 40.0, 20.0, 0.0], [100.0, 100.0, 40.0, 20.0, 0.0]]
)
scores = torch.tensor([0.9, 0.8])
labels = torch.tensor([1, 2]) # car, truck
keep = _apply_retinanet_nms(
boxes,
scores,
labels,
iou_threshold=0.1,
max_detections_per_image=100,
use_gpu_nms=False,
class_agnostic=True,
)
assert keep.numel() == 1
assert labels[keep].tolist() == [1]
assert scores[keep].tolist() == pytest.approx([0.9])
class TestRotatedFasterRCNN:
"""Test that RotatedFasterRCNN works correctly."""
def test_class_exists(self):
"""Test that RotatedFasterRCNN class exists."""
assert RotatedFasterRCNN is not None
def test_is_different_from_oriented_rcnn(self):
"""Test that RotatedFasterRCNN is a different class from OrientedRCNN."""
# They are different implementations:
# - RotatedFasterRCNN: horizontal RPN anchors (angle 0), 4-param RPN, 5-param ROI (DeltaXYWHTH)
# - OrientedRCNN: horizontal RPN anchors, 6-param midpoint-offset ROI head
assert RotatedFasterRCNN != OrientedRCNN
def test_instantiation(self):
"""Test that RotatedFasterRCNN can be instantiated."""
model = RotatedFasterRCNN(
num_classes=10,
backbone_name="resnet18",
pretrained_backbone=False,
)
assert isinstance(model, RotatedFasterRCNN)
assert not isinstance(model, OrientedRCNN)
def test_optional_anchor_angles_constructor(self):
"""Python-only anchor_angles kwarg (not in JSON)."""
model = RotatedFasterRCNN(
num_classes=3,
backbone_name="resnet18",
pretrained_backbone=False,
anchor_ratios=[0.5, 1.0, 2.0],
anchor_angles=[0.0, math.pi / 2],
)
assert model.num_anchors == 6
def test_full_training_forward_and_backward(self):
"""Training forward + backward through horizontal RoIAlign (not ONNX export path)."""
model = RotatedFasterRCNN(
num_classes=5,
backbone_name="resnet18",
pretrained_backbone=False,
trainable_layers=5,
rpn_post_nms_top_n=128,
rpn_pre_nms_top_n=128,
)
image = torch.rand(3, 256, 256)
target = {
"rboxes": [
RBox(128, 128, 64, 32, 0.0),
RBox(200, 200, 40, 20, math.pi / 4),
],
"labels": torch.tensor([1, 2], dtype=torch.int64),
}
model.train()
losses = model([image], [target])
for key in ("loss_objectness", "loss_rpn_box_reg", "loss_classifier", "loss_box_reg"):
assert key in losses
assert torch.is_tensor(losses[key])
assert losses[key].dim() == 0
total = sum(v for k, v in losses.items() if k.startswith("loss_"))