Repository navigation
Expand file tree
/
Copy pathtest_roi.py
More file actions
1168 lines (994 loc) · 41.6 KB
/
Copy pathtest_roi.py
File metadata and controls
1168 lines (994 loc) · 41.6 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
"""Tests for ROI (Region of Interest) components."""
import math
from unittest import mock
import pytest
pytest.importorskip("torch")
pytest.importorskip("torchvision")
import torch
import torch.nn.functional as F
from oriented_det.geometry import RBox
from oriented_det.models.oriented_roi import (
OrientedROIHead,
OrientedROIAlign,
oriented_roi_align,
horizontal_roi_align,
assign_roi_fpn_levels_mmrotate,
match_oriented_proposals_to_gt,
compute_oriented_roi_loss,
compute_horizontal_roi_loss,
compute_horizontal_roi_loss_mmrotate,
_smooth_l1_encoded_regression_loss,
focal_loss,
)
@pytest.fixture
def dummy_roi_features():
"""Create dummy ROI features."""
# ROI features after pooling/align: [N, C*H*W] where C=256, H=W=7
return torch.randn(10, 256 * 7 * 7)
@pytest.fixture
def dummy_proposals():
"""Create dummy proposals."""
return torch.tensor([
[64.0, 64.0, 32.0, 16.0, 0.0],
[128.0, 128.0, 32.0, 16.0, 0.0],
[192.0, 192.0, 32.0, 16.0, 0.0],
])
@pytest.fixture
def dummy_gt_boxes():
"""Create dummy ground truth boxes."""
return torch.tensor([
[64.0, 64.0, 30.0, 15.0, 0.0],
[128.0, 128.0, 35.0, 18.0, 0.0],
])
@pytest.fixture
def dummy_feature_maps():
"""Create dummy FPN feature maps."""
return [
torch.randn(1, 256, 32, 32), # Level 0
torch.randn(1, 256, 16, 16), # Level 1
]
class TestOrientedROIHead:
"""Tests for OrientedROIHead."""
def test_forward_class_agnostic(self, dummy_roi_features):
"""Test forward pass with class-agnostic regression."""
head = OrientedROIHead(
in_channels=256 * 7 * 7,
num_classes=15,
class_agnostic_regression=True,
)
class_logits, box_regression = head(dummy_roi_features)
# Classification: [N, num_classes + 1]
assert class_logits.shape == (10, 16) # 15 classes + background
# Regression: [N, 5] (class-agnostic)
assert box_regression.shape == (10, 5)
def test_forward_class_specific(self, dummy_roi_features):
"""Test forward pass with class-specific regression."""
head = OrientedROIHead(
in_channels=256 * 7 * 7,
num_classes=15,
class_agnostic_regression=False,
)
class_logits, box_regression = head(dummy_roi_features)
# Classification: [N, num_classes + 1]
assert class_logits.shape == (10, 16)
# Regression: [N, num_classes * 5] (class-specific)
assert box_regression.shape == (10, 15 * 5)
def test_forward_empty_features(self):
"""Test forward pass with empty ROI features."""
head = OrientedROIHead(
in_channels=256 * 7 * 7,
num_classes=15,
)
empty_features = torch.zeros((0, 256 * 7 * 7))
class_logits, box_regression = head(empty_features)
assert class_logits.shape[0] == 0
assert box_regression.shape[0] == 0
def test_forward_different_input_sizes(self):
"""Test forward pass with different input sizes."""
head = OrientedROIHead(
in_channels=256 * 7 * 7,
num_classes=10,
)
# Test with different batch sizes
for batch_size in [1, 5, 20]:
features = torch.randn(batch_size, 256 * 7 * 7)
class_logits, box_regression = head(features)
assert class_logits.shape[0] == batch_size
assert box_regression.shape[0] == batch_size
class TestOrientedROIAlign:
"""Tests for OrientedROIAlign."""
def test_forward_basic(self, dummy_feature_maps, dummy_proposals):
"""Test basic ROI align forward pass."""
roi_align = OrientedROIAlign(
output_size=(7, 7),
spatial_scales=[1.0 / 4, 1.0 / 8],
fpn_strides=[4, 8],
)
features = roi_align(
feature_maps=dummy_feature_maps,
boxes=dummy_proposals,
image_sizes=[(128, 128)],
)
# Should have [N, C, H, W] shape
assert features.shape[0] == len(dummy_proposals)
assert features.shape[1] == 256 # Feature channels
assert features.shape[2] == 7 # Output height
assert features.shape[3] == 7 # Output width
def test_forward_chunked_processing(self, dummy_feature_maps, dummy_proposals):
"""Test ROI align with chunked processing."""
roi_align = OrientedROIAlign(
output_size=(7, 7),
spatial_scales=[1.0 / 4, 1.0 / 8],
fpn_strides=[4, 8],
chunk_size=2, # Process 2 boxes at a time
)
features = roi_align(
feature_maps=dummy_feature_maps,
boxes=dummy_proposals,
image_sizes=[(128, 128)],
)
assert features.shape[0] == len(dummy_proposals)
assert features.shape[1:] == (256, 7, 7)
def test_forward_different_output_sizes(self, dummy_feature_maps, dummy_proposals):
"""Test ROI align with different output sizes."""
for output_size in [(7, 7), (14, 14), (3, 3)]:
roi_align = OrientedROIAlign(
output_size=output_size,
spatial_scales=[1.0 / 4, 1.0 / 8],
fpn_strides=[4, 8],
)
features = roi_align(
feature_maps=dummy_feature_maps,
boxes=dummy_proposals,
image_sizes=[(128, 128)],
)
assert features.shape[2] == output_size[0]
assert features.shape[3] == output_size[1]
def test_forward_empty_boxes(self, dummy_feature_maps):
"""Test ROI align with empty boxes."""
roi_align = OrientedROIAlign(
output_size=(7, 7),
spatial_scales=[1.0 / 4],
fpn_strides=[4],
)
empty_boxes = torch.zeros((0, 5))
features = roi_align(
feature_maps=[dummy_feature_maps[0]],
boxes=empty_boxes,
image_sizes=[(128, 128)],
)
assert features.shape[0] == 0
assert features.shape[1:] == (256, 7, 7)
def test_forward_multiple_images(self, dummy_feature_maps):
"""Test ROI align with multiple images."""
roi_align = OrientedROIAlign(
output_size=(7, 7),
spatial_scales=[1.0 / 4],
fpn_strides=[4],
)
# Create feature maps for batch size 2
batch_features = [torch.randn(2, 256, 32, 32)]
# Create proposals for 2 images
proposals = torch.tensor([
[64.0, 64.0, 32.0, 16.0, 0.0],
[128.0, 128.0, 32.0, 16.0, 0.0],
])
# Map boxes to images
box_to_image = torch.tensor([0, 1])
features = roi_align(
feature_maps=batch_features,
boxes=proposals,
image_sizes=[(128, 128), (128, 128)],
box_to_image=box_to_image,
)
assert features.shape[0] == len(proposals)
def test_assign_roi_fpn_levels_mmrotate_sqrt_area_mapping():
strides = [4, 8, 16, 32]
finest = 56.0
# sqrt(area) = 56 -> level 0
b0 = torch.tensor([[0.0, 0.0, 56.0, 56.0, 0.0]])
# sqrt(area) = 112 -> level 1
b1 = torch.tensor([[0.0, 0.0, 112.0, 112.0, 0.0]])
# sqrt(area) = 224 -> level 2
b2 = torch.tensor([[0.0, 0.0, 224.0, 224.0, 0.0]])
lv = assign_roi_fpn_levels_mmrotate(torch.cat([b0, b1, b2], dim=0), strides, finest_scale=finest, box_format="obb")
assert lv.tolist() == [0, 1, 2]
class TestProposalMatching:
"""Tests for proposal matching."""
def test_match_positive_proposals(self, dummy_proposals, dummy_gt_boxes):
"""Test matching proposals to GT boxes."""
gt_labels = torch.tensor([1, 2]) # Class labels
labels, matched_indices, matched_boxes = match_oriented_proposals_to_gt(
dummy_proposals,
dummy_gt_boxes,
gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
)
assert labels.shape == (len(dummy_proposals),)
assert matched_indices.shape == (len(dummy_proposals),)
assert matched_boxes.shape == (len(dummy_proposals), 5)
# Should have some positive matches
assert torch.any(labels > 0)
def test_match_empty_proposals(self, dummy_gt_boxes):
"""Test matching with empty proposals."""
empty_proposals = torch.zeros((0, 5))
gt_labels = torch.tensor([1, 2])
# GPU ops may not handle empty proposals, so handle gracefully
try:
labels, matched_indices, matched_boxes = match_oriented_proposals_to_gt(
empty_proposals,
dummy_gt_boxes,
gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
)
assert len(labels) == 0
assert len(matched_indices) == 0
assert len(matched_boxes) == 0
except (IndexError, RuntimeError):
# GPU ops may raise error for empty proposals - this is acceptable
pytest.skip("GPU ops don't handle empty proposals")
def test_match_empty_gt(self, dummy_proposals):
"""Test matching with empty GT boxes."""
empty_gt = torch.zeros((0, 5))
empty_labels = torch.tensor([], dtype=torch.int64)
labels, matched_indices, matched_boxes = match_oriented_proposals_to_gt(
dummy_proposals,
empty_gt,
empty_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
)
# All proposals should be background
assert torch.all(labels == 0)
assert torch.all(matched_indices == -1)
def test_match_iou_thresholds(self, dummy_proposals, dummy_gt_boxes):
"""Test that IoU thresholds work correctly."""
gt_labels = torch.tensor([1, 2])
# High positive threshold
labels_high, _, _ = match_oriented_proposals_to_gt(
dummy_proposals,
dummy_gt_boxes,
gt_labels,
positive_iou_threshold=0.9,
negative_iou_threshold=0.3,
)
# Low positive threshold
labels_low, _, _ = match_oriented_proposals_to_gt(
dummy_proposals,
dummy_gt_boxes,
gt_labels,
positive_iou_threshold=0.3,
negative_iou_threshold=0.1,
)
# Lower threshold should have at least as many positives
assert (labels_low > 0).sum() >= (labels_high > 0).sum()
def test_match_low_quality_true_forces_best_proposal_positive(self):
"""With match_low_quality=True and min_pos_iou=0, best proposal per GT is forced positive when IoU > 0."""
proposals = torch.tensor([
[1.0, 0.0, 2.0, 2.0, 0.0], # IoU ~= 1/3 against GT at origin
[10.0, 10.0, 2.0, 2.0, 0.0], # no overlap
])
gt_boxes = torch.tensor([[0.0, 0.0, 2.0, 2.0, 0.0]])
gt_labels = torch.tensor([4], dtype=torch.int64)
labels, matched_indices, _ = match_oriented_proposals_to_gt(
proposals,
gt_boxes,
gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
match_low_quality=True,
min_pos_iou=0.0, # force best proposal when IoU > 0
)
assert labels[0].item() == 4
assert matched_indices[0].item() == 0
def test_match_low_quality_false_does_not_force_low_iou_positive(self):
"""With match_low_quality=False, low-IoU best proposal stays ignore/background."""
proposals = torch.tensor([
[1.0, 0.0, 2.0, 2.0, 0.0], # IoU ~= 1/3 against GT at origin
[10.0, 10.0, 2.0, 2.0, 0.0],
])
gt_boxes = torch.tensor([[0.0, 0.0, 2.0, 2.0, 0.0]])
gt_labels = torch.tensor([2], dtype=torch.int64)
labels, _, _ = match_oriented_proposals_to_gt(
proposals,
gt_boxes,
gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
match_low_quality=False,
)
assert labels[0].item() == -1 # ignore band, not forced positive
def test_match_threshold_boundaries(self):
"""Boundary semantics: IoU == pos is positive, IoU == neg is not background."""
proposals = torch.tensor([
[0.0, 0.0, 2.0, 2.0, 0.0], # IoU = 1 with GT
[20.0, 20.0, 2.0, 2.0, 0.0], # IoU = 0 with GT
])
gt_boxes = torch.tensor([[0.0, 0.0, 2.0, 2.0, 0.0]])
gt_labels = torch.tensor([1], dtype=torch.int64)
labels, _, _ = match_oriented_proposals_to_gt(
proposals,
gt_boxes,
gt_labels,
positive_iou_threshold=1.0,
negative_iou_threshold=0.0,
match_low_quality=False,
)
assert labels[0].item() == 1 # IoU == positive threshold
assert labels[1].item() == -1 # IoU == negative threshold is not "< neg"
def test_match_ignore_band_labels_minus_one(self):
"""Proposals in [neg, pos) are labeled as ignore (-1)."""
proposals = torch.tensor([[1.0, 0.0, 2.0, 2.0, 0.0]]) # IoU ~= 1/3
gt_boxes = torch.tensor([[0.0, 0.0, 2.0, 2.0, 0.0]])
gt_labels = torch.tensor([3], dtype=torch.int64)
labels, _, _ = match_oriented_proposals_to_gt(
proposals,
gt_boxes,
gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
match_low_quality=False,
)
assert labels[0].item() == -1
class TestROILoss:
"""Tests for ROI loss computation."""
def test_roi_loss_cross_entropy(self, dummy_proposals, dummy_gt_boxes):
"""Test ROI loss with cross-entropy."""
num_classes = 15
num_proposals = len(dummy_proposals)
# Create dummy predictions
class_logits = torch.randn(num_proposals, num_classes + 1)
box_regression = torch.randn(num_proposals, 5) # Class-agnostic
gt_labels = torch.tensor([1, 2])
losses = compute_oriented_roi_loss(
class_logits=class_logits,
box_regression=box_regression,
proposals=dummy_proposals,
gt_boxes=dummy_gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
loss_type="cross_entropy",
)
assert "loss_classifier" in losses
assert "loss_box_reg" in losses
# Losses should be non-negative
assert losses["loss_classifier"] >= 0
assert losses["loss_box_reg"] >= 0
def test_roi_loss_focal(self, dummy_proposals, dummy_gt_boxes):
"""Test ROI loss with focal loss."""
num_classes = 15
num_proposals = len(dummy_proposals)
class_logits = torch.randn(num_proposals, num_classes + 1)
box_regression = torch.randn(num_proposals, 5)
gt_labels = torch.tensor([1, 2])
losses = compute_oriented_roi_loss(
class_logits=class_logits,
box_regression=box_regression,
proposals=dummy_proposals,
gt_boxes=dummy_gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
loss_type="focal",
focal_alpha=1.0,
focal_gamma=2.0,
)
assert "loss_classifier" in losses
assert losses["loss_classifier"] >= 0
def test_roi_loss_class_weights(self, dummy_proposals, dummy_gt_boxes):
"""Test ROI loss with class weights."""
num_classes = 15
num_proposals = len(dummy_proposals)
class_logits = torch.randn(num_proposals, num_classes + 1)
box_regression = torch.randn(num_proposals, 5)
gt_labels = torch.tensor([1, 2])
# Create class weights tensor
class_weights = torch.ones(num_classes + 1)
class_weights[1] = 2.0 # Weight class 1 more
class_weights[2] = 0.5 # Weight class 2 less
losses = compute_oriented_roi_loss(
class_logits=class_logits,
box_regression=box_regression,
proposals=dummy_proposals,
gt_boxes=dummy_gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
class_weights=class_weights,
)
assert "loss_classifier" in losses
assert losses["loss_classifier"] >= 0
def test_roi_loss_no_positive_proposals(self, dummy_proposals):
"""Test ROI loss when there are no positive proposals."""
num_classes = 15
num_proposals = len(dummy_proposals)
class_logits = torch.randn(num_proposals, num_classes + 1)
box_regression = torch.randn(num_proposals, 5)
# GT boxes far away from proposals
far_gt_boxes = torch.tensor([[1000.0, 1000.0, 30.0, 15.0, 0.0]])
gt_labels = torch.tensor([1])
losses = compute_oriented_roi_loss(
class_logits=class_logits,
box_regression=box_regression,
proposals=dummy_proposals,
gt_boxes=far_gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
)
# Should still return valid losses
assert "loss_classifier" in losses
assert "loss_box_reg" in losses
def test_roi_loss_target_normalization(self, dummy_proposals, dummy_gt_boxes):
"""Test ROI loss with target normalization."""
num_classes = 15
num_proposals = len(dummy_proposals)
class_logits = torch.randn(num_proposals, num_classes + 1)
box_regression = torch.randn(num_proposals, 5)
gt_labels = torch.tensor([1, 2])
target_means = (0.0, 0.0, 0.0, 0.0, 0.0)
target_stds = (0.1, 0.1, 0.2, 0.2, 0.1)
losses = compute_oriented_roi_loss(
class_logits=class_logits,
box_regression=box_regression,
proposals=dummy_proposals,
gt_boxes=dummy_gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
target_means=target_means,
target_stds=target_stds,
)
assert "loss_classifier" in losses
assert "loss_box_reg" in losses
def test_roi_loss_angle_term_uses_encoded_smooth_l1(self):
"""ROI box regression uses encoded-space Smooth L1 (MMRotate), not radian periodic loss."""
gt_boxes = torch.tensor([[64.0, 64.0, 32.0, 16.0, math.radians(89.0)]])
proposals = gt_boxes.clone()
gt_labels = torch.tensor([1], dtype=torch.int64)
class_logits = torch.tensor([[0.0, 10.0]])
target_means = (0.0, 0.0, 0.0, 0.0, 0.0)
target_stds = (0.1, 0.1, 0.2, 0.2, 0.1)
norm_factor = 2.0
target_angle_encoded = (
(math.radians(89.0) / (norm_factor * math.pi) - target_means[4]) / target_stds[4]
)
box_regression_a = torch.tensor([[0.0, 0.0, 0.0, 0.0, target_angle_encoded]])
box_regression_b = torch.tensor([[0.0, 0.0, 0.0, 0.0, target_angle_encoded + (1.0 / target_stds[4])]])
losses_a = compute_oriented_roi_loss(
class_logits=class_logits,
box_regression=box_regression_a,
proposals=proposals,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
target_means=target_means,
target_stds=target_stds,
norm_factor=norm_factor,
edge_swap=False,
include_assignment_diagnostics=False,
)
losses_b = compute_oriented_roi_loss(
class_logits=class_logits,
box_regression=box_regression_b,
proposals=proposals,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
target_means=target_means,
target_stds=target_stds,
norm_factor=norm_factor,
edge_swap=False,
include_assignment_diagnostics=False,
)
assert losses_a["loss_box_reg"].item() < losses_b["loss_box_reg"].item()
def test_roi_loss_iou_term_penalizes_geometrically_worse_box(self):
"""Adding the ROI IoU term should increase loss for a worse decoded box."""
proposals = torch.tensor([[64.0, 64.0, 32.0, 16.0, 0.0]])
gt_boxes = torch.tensor([[64.0, 64.0, 32.0, 16.0, 0.0]])
gt_labels = torch.tensor([1], dtype=torch.int64)
class_logits = torch.tensor([[0.0, 10.0]])
perfect_regression = torch.tensor([[0.0, 0.0, 0.0, 0.0, 0.0]])
shifted_regression = torch.tensor([[0.5, 0.0, 0.0, 0.0, 0.0]])
perfect_no_iou = compute_oriented_roi_loss(
class_logits=class_logits,
box_regression=perfect_regression,
proposals=proposals,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
include_assignment_diagnostics=False,
box_reg_aux_weight=0.0,
edge_swap=False,
)
shifted_no_iou = compute_oriented_roi_loss(
class_logits=class_logits,
box_regression=shifted_regression,
proposals=proposals,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
include_assignment_diagnostics=False,
box_reg_aux_weight=0.0,
edge_swap=False,
)
shifted_with_iou = compute_oriented_roi_loss(
class_logits=class_logits,
box_regression=shifted_regression,
proposals=proposals,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
include_assignment_diagnostics=False,
box_reg_aux_weight=0.5,
edge_swap=False,
)
assert perfect_no_iou["loss_box_reg"] < shifted_no_iou["loss_box_reg"]
assert shifted_with_iou["loss_box_reg"] > shifted_no_iou["loss_box_reg"]
def test_oriented_roi_loss_angle_weight_scales_angle_term(self):
"""Higher box_reg_angle_weight should increase loss when only angle is wrong."""
proposals = torch.tensor([[64.0, 64.0, 32.0, 16.0, 0.0]])
gt_boxes = torch.tensor([[64.0, 64.0, 32.0, 16.0, 0.3]])
gt_labels = torch.tensor([1], dtype=torch.int64)
class_logits = torch.tensor([[0.0, 10.0]])
box_regression = torch.tensor([[0.0, 0.0, 0.0, 0.0, 0.5]])
loss_w1 = compute_oriented_roi_loss(
class_logits=class_logits,
box_regression=box_regression,
proposals=proposals,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
box_reg_angle_weight=1.0,
box_reg_aux_weight=0.0,
edge_swap=False,
include_assignment_diagnostics=False,
)
loss_w3 = compute_oriented_roi_loss(
class_logits=class_logits,
box_regression=box_regression,
proposals=proposals,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
box_reg_angle_weight=3.0,
box_reg_aux_weight=0.0,
edge_swap=False,
include_assignment_diagnostics=False,
)
assert loss_w3["loss_box_reg"] > loss_w1["loss_box_reg"]
def test_horizontal_roi_loss_angle_weight_scales_angle_term():
"""Rotated Faster R-CNN horizontal ROI path honors box_reg_angle_weight."""
proposals_xyxy = torch.tensor([[40.0, 50.0, 88.0, 82.0]], dtype=torch.float32)
gt_boxes = torch.tensor([[64.0, 64.0, 32.0, 16.0, 0.3]], dtype=torch.float32)
gt_labels = torch.tensor([1], dtype=torch.int64)
class_logits = torch.tensor([[0.0, 10.0]])
box_regression = torch.tensor([[0.0, 0.0, 0.0, 0.0, 0.5]])
loss_w1 = compute_horizontal_roi_loss_mmrotate(
class_logits=class_logits,
box_regression=box_regression,
proposals_xyxy=proposals_xyxy,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
box_reg_angle_weight=1.0,
box_reg_aux_weight=0.0,
edge_swap=False,
include_assignment_diagnostics=False,
)
loss_w3 = compute_horizontal_roi_loss_mmrotate(
class_logits=class_logits,
box_regression=box_regression,
proposals_xyxy=proposals_xyxy,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
box_reg_angle_weight=3.0,
box_reg_aux_weight=0.0,
edge_swap=False,
include_assignment_diagnostics=False,
)
assert loss_w3["loss_box_reg"] > loss_w1["loss_box_reg"]
def test_horizontal_roi_loss_angle_term_uses_encoded_smooth_l1():
"""Horizontal RoI Smooth L1 uses encoded deltas (MMRotate), not radian periodic loss."""
from oriented_det.models.horizontal_roi_coder import encode_delta_xywh_th
proposals_xyxy, gt_boxes, gt_labels, class_logits, _ = _horizontal_roi_fixture()
target_stds = (0.1, 0.1, 0.2, 0.2, 0.1)
norm_factor = 2.0
encoded = encode_delta_xywh_th(
proposals_xyxy,
gt_boxes,
stds=target_stds,
norm_factor=norm_factor,
edge_swap=False,
)
box_regression_a = encoded.clone()
box_regression_b = encoded.clone()
box_regression_b[0, 4] = box_regression_b[0, 4] + (1.0 / target_stds[4])
kwargs = dict(
class_logits=class_logits,
proposals_xyxy=proposals_xyxy,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
main_loss_type="smooth_l1",
box_reg_aux_weight=0.0,
stds=target_stds,
norm_factor=norm_factor,
edge_swap=False,
include_assignment_diagnostics=False,
)
loss_a = compute_horizontal_roi_loss(box_regression=box_regression_a, **kwargs)
loss_b = compute_horizontal_roi_loss(box_regression=box_regression_b, **kwargs)
assert loss_a["loss_box_reg"].item() < loss_b["loss_box_reg"].item()
def _horizontal_roi_fixture():
proposals_xyxy = torch.tensor([[40.0, 50.0, 88.0, 82.0]], dtype=torch.float32)
gt_boxes = torch.tensor([[64.0, 64.0, 32.0, 16.0, 0.3]], dtype=torch.float32)
gt_labels = torch.tensor([1], dtype=torch.int64)
class_logits = torch.tensor([[0.0, 10.0]], requires_grad=False)
box_regression = torch.tensor([[0.0, 0.0, 0.0, 0.0, 0.5]], requires_grad=True)
return proposals_xyxy, gt_boxes, gt_labels, class_logits, box_regression
def test_horizontal_roi_loss_mmrotate_matches_sampled_all():
proposals_xyxy, gt_boxes, gt_labels, class_logits, box_regression = _horizontal_roi_fixture()
box_regression = box_regression.detach()
kwargs = dict(
class_logits=class_logits,
box_regression=box_regression,
proposals_xyxy=proposals_xyxy,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
box_reg_aux_weight=0.0,
edge_swap=False,
include_assignment_diagnostics=False,
)
loss_mm = compute_horizontal_roi_loss_mmrotate(**kwargs)
loss_all = compute_horizontal_roi_loss(**kwargs, reg_norm="sampled_all")
assert loss_mm["loss_box_reg"].item() == pytest.approx(loss_all["loss_box_reg"].item())
def test_smooth_l1_encoded_regression_loss_norm_modes():
"""positives_only uses per-element mean; sampled_all divides sum by total sample count."""
pred = torch.zeros(2, 5)
target = torch.zeros(2, 5)
target[:, :4] = 1.0
loss_all = _smooth_l1_encoded_regression_loss(
pred,
target,
angle_weight=1.0,
reg_norm="sampled_all",
num_total_samples=512,
)
loss_pos = _smooth_l1_encoded_regression_loss(
pred,
target,
angle_weight=1.0,
reg_norm="positives_only",
num_total_samples=512,
)
assert loss_pos.item() > loss_all.item()
assert loss_all.item() == pytest.approx(4.0 / 512.0)
assert loss_pos.item() == pytest.approx(0.4)
def test_roi_encoded_regression_matches_mmrotate_smooth_l1_sum_avg_factor():
"""Hand-computed encoded Smooth L1 / num_total_samples matches the ROI helper."""
pred = torch.tensor([[0.1, 0.2, 0.0, 0.0, 0.05]])
target = torch.tensor([[0.0, 0.0, 0.0, 0.0, 0.0]])
num_total = 512
hand = F.smooth_l1_loss(pred, target, beta=1.0, reduction="sum") / float(num_total)
got = _smooth_l1_encoded_regression_loss(
pred,
target,
reg_norm="sampled_all",
num_total_samples=num_total,
)
assert got.item() == pytest.approx(hand.item())
def test_horizontal_roi_loss_probiou_main_with_smooth_l1_aux_backward():
proposals_xyxy, gt_boxes, gt_labels, class_logits, box_regression = _horizontal_roi_fixture()
box_regression = box_regression.clone().detach().requires_grad_(True)
out = compute_horizontal_roi_loss(
class_logits=class_logits,
box_regression=box_regression,
proposals_xyxy=proposals_xyxy,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
main_loss_type="probiou",
box_reg_probiou_mode="l1",
box_reg_aux_weight=0.1,
box_reg_aux_loss_type="smooth_l1",
reg_norm="positives_only",
edge_swap=False,
include_assignment_diagnostics=False,
)
assert torch.isfinite(out["loss_box_reg"])
out["loss_box_reg"].backward()
assert box_regression.grad is not None
assert torch.isfinite(box_regression.grad).all()
def test_horizontal_roi_loss_default_smooth_l1_main_unchanged_with_probiou_aux():
proposals_xyxy, gt_boxes, gt_labels, class_logits, box_regression = _horizontal_roi_fixture()
kwargs = dict(
class_logits=class_logits,
box_regression=box_regression.clone(),
proposals_xyxy=proposals_xyxy,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.3,
main_loss_type="smooth_l1",
box_reg_aux_weight=0.1,
box_reg_aux_loss_type="probiou",
box_reg_probiou_mode="l1",
edge_swap=False,
include_assignment_diagnostics=False,
)
loss_mm = compute_horizontal_roi_loss_mmrotate(**kwargs)
loss_explicit = compute_horizontal_roi_loss(**kwargs, reg_norm="sampled_all")
assert loss_mm["loss_box_reg"].item() == pytest.approx(loss_explicit["loss_box_reg"].item())
def test_horizontal_roi_loss_uses_hbb_style_matching(monkeypatch):
"""Rotated Faster R-CNN ROI assignment should use HBB-style IoU."""
called = {"use_hbb": None, "match_low_quality": None, "min_pos_iou": None}
def _fake_match(
proposals,
gt_boxes,
gt_labels,
positive_iou_threshold=0.5,
negative_iou_threshold=0.5,
device=None,
use_hbb_for_matching=False,
match_low_quality=False,
min_pos_iou=0.5,
gt_boxes_ignore=None,
ignore_iou_threshold=None,
gt_boxes_lookalike=None,
lookalike_iou_threshold=None,
):
called["use_hbb"] = use_hbb_for_matching
called["match_low_quality"] = match_low_quality
called["min_pos_iou"] = min_pos_iou
n = int(proposals.shape[0])
labels = torch.zeros((n,), dtype=torch.int64, device=proposals.device)
matched_gt_indices = torch.full((n,), -1, dtype=torch.int64, device=proposals.device)
matched_gt_boxes = torch.zeros((n, 5), dtype=torch.float32, device=proposals.device)
return labels, matched_gt_indices, matched_gt_boxes
monkeypatch.setattr("oriented_det.models.oriented_roi.match_oriented_proposals_to_gt", _fake_match)
class_logits = torch.randn(1, 2)
box_regression = torch.randn(1, 5)
proposals_xyxy = torch.tensor([[10.0, 10.0, 30.0, 20.0]], dtype=torch.float32)
gt_boxes = torch.tensor([[20.0, 15.0, 20.0, 10.0, 0.5]], dtype=torch.float32)
gt_labels = torch.tensor([1], dtype=torch.int64)
compute_horizontal_roi_loss_mmrotate(
class_logits=class_logits,
box_regression=box_regression,
proposals_xyxy=proposals_xyxy,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
)
assert called["use_hbb"] is True
assert called["match_low_quality"] is False
assert called["min_pos_iou"] == pytest.approx(0.5)
compute_horizontal_roi_loss_mmrotate(
class_logits=class_logits,
box_regression=box_regression,
proposals_xyxy=proposals_xyxy,
gt_boxes=gt_boxes,
gt_labels=gt_labels,
match_low_quality=True,
roi_min_pos_iou=0.42,
)
assert called["match_low_quality"] is True
assert called["min_pos_iou"] == pytest.approx(0.42)
def test_horizontal_roi_align_uses_only_first_four_fpn_levels(monkeypatch):
"""MMRotate-style ROI extractor should ignore the extra stride-64 FPN level."""
captured = {"strides": None}
def _fake_assign(boxes, fpn_strides, finest_scale=56.0, box_format="xyxy"):
captured["strides"] = list(fpn_strides)
return torch.zeros((boxes.shape[0],), dtype=torch.long, device=boxes.device)
monkeypatch.setattr("oriented_det.models.oriented_roi.assign_roi_fpn_levels_mmrotate", _fake_assign)
feature_maps = [
torch.full((1, 1, 64, 64), 1.0), # stride 4
torch.full((1, 1, 32, 32), 2.0), # stride 8
torch.full((1, 1, 16, 16), 3.0), # stride 16
torch.full((1, 1, 8, 8), 4.0), # stride 32
torch.full((1, 1, 4, 4), 5.0), # stride 64 (RPN-only for MMRotate ROI path)
]
boxes_xyxy = torch.tensor([[16.0, 16.0, 64.0, 64.0]], dtype=torch.float32)
_ = horizontal_roi_align(
feature_maps=feature_maps,
boxes_xyxy=boxes_xyxy,
image_sizes=[(256, 256)],
box_to_image=torch.tensor([0], dtype=torch.long),
output_size=(1, 1),
spatial_scales=None,
fpn_strides=[4, 8, 16, 32, 64],
chunk_size=1,
finest_scale=56.0,
)
assert captured["strides"] == [4, 8, 16, 32]
def test_horizontal_roi_align_eager_matches_onnx_export_path():
"""Eager training path must match masked RoIAlign used during ONNX export."""
torch.manual_seed(0)
feature_maps = [
torch.randn(1, 8, 64, 64),
torch.randn(1, 8, 32, 32),
torch.randn(1, 8, 16, 16),
torch.randn(1, 8, 8, 8),
]
boxes_xyxy = torch.tensor(
[
[8.0, 8.0, 48.0, 48.0],
[80.0, 80.0, 160.0, 160.0],
[200.0, 200.0, 280.0, 280.0],
[20.0, 100.0, 60.0, 140.0],
[120.0, 20.0, 200.0, 80.0],
],
dtype=torch.float32,
)
box_to_image = torch.zeros((boxes_xyxy.shape[0],), dtype=torch.long)
kwargs = dict(
feature_maps=feature_maps,
boxes_xyxy=boxes_xyxy,
image_sizes=[(256, 256)],
box_to_image=box_to_image,
output_size=(7, 7),
spatial_scales=None,
fpn_strides=[4, 8, 16, 32],
chunk_size=32,
finest_scale=56.0,
)
eager = horizontal_roi_align(**kwargs)
with mock.patch(
"oriented_det.models.oriented_roi.torch.onnx.is_in_onnx_export",
return_value=True,
):