Repository navigation
Expand file tree
/
Copy pathtest_config_model_wiring.py
More file actions
603 lines (520 loc) · 24.7 KB
/
Copy pathtest_config_model_wiring.py
File metadata and controls
603 lines (520 loc) · 24.7 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
"""Regression: config fields must reach model constructors (no silent defaults masking bugs)."""
from pathlib import Path
import sys
import importlib
from unittest.mock import MagicMock, patch
import pytest
import torch
from oriented_det.train.config import TrainingExperimentConfig, ModelConfig, TrainingConfig, LossConfig
def _load_train_module():
"""Import tools/train.py through the same top-level path used by tools."""
root = Path(__file__).resolve().parents[1]
tools_dir = str(root / "tools")
# tools/train.py is imported as top-level "train" with tools/ on sys.path.
if tools_dir not in sys.path:
sys.path.insert(0, tools_dir)
return importlib.import_module("train")
def _minimal_config(model_type: str) -> TrainingExperimentConfig:
return TrainingExperimentConfig(
model_type=model_type,
dataset=None,
model=ModelConfig(
backbone="resnet18",
pretrained_backbone=False,
trainable_layers=3,
anchor_scales=[4, 8],
anchor_ratios=[0.5, 2.0],
roi_norm_factor=3.0,
roi_edge_swap=False,
roi_proj_xy=True,
roi_box_reg_angle_weight=1.7,
roi_box_reg_aux_weight=0.15,
roi_min_pos_iou=0.37,
use_hbb_for_matching=False,
inference_pre_nms_score_threshold=0.13,
rpn_pre_nms_top_n=111,
rpn_post_nms_top_n=77,
max_detections_per_image=33,
rpn_nms_threshold=0.41,
final_nms_iou_threshold=0.31,
final_nms_iou_schedule_epochs=[1, 2],
final_nms_iou_schedule_values=[0.6, 0.4, 0.2],
roi_box_reg_aux_schedule_epochs=[10, 20],
roi_box_reg_aux_schedule_values=[0.2, 0.1, 0.0],
roi_inference_top_class_only=True,
roi_box_reg_aux_loss_type="smooth_l1",
roi_box_reg_kfiou_fun="ln",
roi_box_reg_main_loss_type="probiou",
roi_box_reg_norm="positives_only",
rpn_positive_iou_threshold=0.51,
rpn_negative_iou_threshold=0.39,
fpn_returned_layers=[2, 3, 4],
fpn_strides=[8, 16, 32, 64, 128],
fpn_extra_level=True,
anchor_octave_base_scale=4.0,
anchor_scales_per_octave=3,
retinanet_stacked_convs=4,
box_reg_loss_type="l1",
box_reg_weight=0.9,
fcos_stacked_convs=4,
fcos_center_sampling=True,
fcos_center_sample_radius=1.5,
fcos_norm_on_bbox=True,
fcos_centerness_on_reg=True,
fcos_scale_angle=True,
fcos_angle_weight=1.25,
fcos_nms_pre=1500,
fcos_regress_ranges=[[-1, 64], [64, 128], [128, 256], [256, 512], [512, 1e8]],
aux_loss_type="kfiou",
aux_loss_weight=0.1,
aux_angle_weight=0.5,
aux_angle_lambda=1.5,
),
training=TrainingConfig(),
loss=LossConfig(loss_type="class_weighted"),
)
def test_create_model_retinanet_passes_pre_nms_score_from_config():
train = _load_train_module()
mock_cls = MagicMock()
inst = MagicMock()
inst.to = MagicMock(return_value=inst)
mock_cls.return_value = inst
cfg = _minimal_config("rotated_retinanet")
cfg.model.nms_class_agnostic = True
device = torch.device("cpu")
with patch.object(train, "RotatedRetinaNet", mock_cls):
model, _ = train.create_model_from_config(
cfg, num_classes=2, device=device, roi_class_weights=None
)
assert model is inst
call_kw = mock_cls.call_args.kwargs
assert call_kw["backbone_name"] == "resnet18"
assert call_kw["pretrained_backbone"] is False
assert call_kw["trainable_layers"] == 3
assert call_kw["anchor_angles"] is None
assert call_kw["anchor_angles"] is None
assert call_kw["anchor_scales"] == [4, 8]
assert call_kw["anchor_ratios"] == [0.5, 2.0]
assert call_kw["norm_factor"] == pytest.approx(3.0)
assert call_kw["edge_swap"] is False
assert call_kw["box_reg_aux_weight"] == pytest.approx(0.15)
assert call_kw["box_reg_aux_loss_type"] == "smooth_l1"
assert call_kw["box_reg_kfiou_fun"] == "ln"
assert call_kw["use_hbb_for_matching"] is False
assert call_kw["positive_iou_threshold"] == pytest.approx(0.51)
assert call_kw["negative_iou_threshold"] == pytest.approx(0.39)
assert call_kw["returned_layers"] == [2, 3, 4]
assert call_kw["fpn_strides"] == [8, 16, 32, 64, 128]
assert call_kw["fpn_extra_level"] is True
assert call_kw["octave_base_scale"] == pytest.approx(4.0)
assert call_kw["scales_per_octave"] == 3
assert call_kw["stacked_convs"] == 4
assert call_kw["box_reg_loss_type"] == "l1"
assert call_kw["box_reg_main_loss_type"] == "probiou"
assert call_kw["reg_sample_size_per_image"] == 512
assert call_kw["box_reg_weight"] == pytest.approx(0.9)
assert call_kw["score_threshold"] == pytest.approx(0.13)
assert call_kw["final_nms_iou_threshold"] == pytest.approx(0.31)
assert call_kw["max_detections_per_image"] == 33
assert call_kw["nms_class_agnostic"] is True
assert call_kw["final_nms_iou_schedule_epochs"] == [1, 2]
assert call_kw["final_nms_iou_schedule_values"] == [0.6, 0.4, 0.2]
assert call_kw["roi_box_reg_aux_schedule_epochs"] == [10, 20]
assert call_kw["roi_box_reg_aux_schedule_values"] == [0.2, 0.1, 0.0]
def test_anchor_angles_deg_to_rad_none_and_empty():
from oriented_det.train.config import anchor_angles_deg_to_rad
assert anchor_angles_deg_to_rad(None) is None
assert anchor_angles_deg_to_rad([]) is None
def test_create_model_retinanet_converts_anchor_angles_degrees_to_radians():
import math
train = _load_train_module()
mock_cls = MagicMock()
inst = MagicMock()
inst.to = MagicMock(return_value=inst)
mock_cls.return_value = inst
cfg = _minimal_config("rotated_retinanet")
cfg.model.anchor_angles = [-45.0, 0.0, 45.0]
device = torch.device("cpu")
with patch.object(train, "RotatedRetinaNet", mock_cls):
train.create_model_from_config(
cfg, num_classes=2, device=device, roi_class_weights=None
)
angles = mock_cls.call_args.kwargs["anchor_angles"]
assert len(angles) == 3
assert angles[0] == pytest.approx(-math.pi / 4)
assert angles[1] == pytest.approx(0.0)
assert angles[2] == pytest.approx(math.pi / 4)
def test_retinanet_1x_rr_recipe_enables_pm180_rotate():
from pathlib import Path
from oriented_det.train.config import TrainingExperimentConfig
root = Path(__file__).resolve().parents[1]
hub = TrainingExperimentConfig.load(
root / "configs" / "rotated_retinanet" / "dota_le90_1x.json"
)
rr = TrainingExperimentConfig.load(
root / "configs" / "rotated_retinanet" / "dota_le90_1x_rr.json"
)
assert hub.preprocessing.enable_random_rotate is False
assert rr.preprocessing.enable_random_rotate is True
assert rr.preprocessing.random_rotate_prob == 0.5
assert rr.preprocessing.random_rotate_angle_range == 180
assert rr.preprocessing.enable_flip_diagonal is True
assert rr.model.box_reg_loss_type == "l1"
def test_retinanet_dota_recipes_obb_default_hbb_extension():
"""Un-suffixed 1×/3×/RR are OBB; *_hbb.json is circum-HBB. Priors stay θ=0."""
from pathlib import Path
from oriented_det.train.config import TrainingExperimentConfig
root = Path(__file__).resolve().parents[1]
recipes = root / "configs" / "rotated_retinanet"
obb_names = ("dota_le90_1x.json", "dota_le90_3x.json", "dota_le90_1x_rr.json")
hbb_names = ("dota_le90_1x_hbb.json", "dota_le90_3x_hbb.json")
for name in obb_names:
cfg = TrainingExperimentConfig.load(recipes / name)
assert cfg.model.use_hbb_for_matching is False, name
assert cfg.model.anchor_angles is None, name
assert cfg.model.box_reg_loss_type == "l1", name
assert cfg.production.score_threshold == pytest.approx(0.25), name
for name in hbb_names:
cfg = TrainingExperimentConfig.load(recipes / name)
assert cfg.model.use_hbb_for_matching is True, name
assert cfg.production.score_threshold == pytest.approx(0.35), name
assert cfg.model.anchor_angles is None, name
def test_retinanet_dota_recipes_split_val_and_test_score_floors():
"""Val monitor and eval-val are 0.3; test_map / eval-test stay 0.05."""
from pathlib import Path
from oriented_det.train.config import (
TrainingExperimentConfig,
effective_eval_metric_thresholds,
resolve_preds_score_threshold,
)
root = Path(__file__).resolve().parents[1]
for name in (
"dota_le90_1x.json",
"dota_le90_3x.json",
"dota_le90_1x_rr.json",
"dota_le90_1x_hbb.json",
"dota_le90_3x_hbb.json",
):
cfg = TrainingExperimentConfig.load(
root / "configs" / "rotated_retinanet" / name
)
train_sc, _, _ = effective_eval_metric_thresholds(cfg)
val_sc, val_src = resolve_preds_score_threshold(cfg, data_split="val")
test_sc, test_src = resolve_preds_score_threshold(cfg, data_split="test")
assert train_sc == pytest.approx(0.3), name
assert val_sc == pytest.approx(0.3), name
assert "val_score_threshold" in val_src
assert test_sc == pytest.approx(0.05), name
assert "0.05" in test_src or "test_score_threshold" in test_src
def test_create_model_fcos_passes_config_fields():
train = _load_train_module()
mock_cls = MagicMock()
inst = MagicMock()
inst.to = MagicMock(return_value=inst)
mock_cls.return_value = inst
cfg = _minimal_config("rotated_fcos")
cfg.model.nms_class_agnostic = True
cfg.loss = LossConfig(loss_type="focal", focal_alpha=0.25, focal_gamma=2.0)
device = torch.device("cpu")
with patch.object(train, "RotatedFCOS", mock_cls):
model, _ = train.create_model_from_config(
cfg, num_classes=3, device=device, roi_class_weights=None
)
assert model is inst
call_kw = mock_cls.call_args.kwargs
assert call_kw["backbone_name"] == "resnet18"
assert call_kw["returned_layers"] == [2, 3, 4]
assert call_kw["fpn_strides"] == [8, 16, 32, 64, 128]
assert call_kw["fpn_extra_level"] is True
assert call_kw["stacked_convs"] == 4
assert call_kw["center_sampling"] is True
assert call_kw["center_sample_radius"] == pytest.approx(1.5)
assert call_kw["norm_on_bbox"] is True
assert call_kw["centerness_on_reg"] is True
assert call_kw["scale_angle"] is True
assert call_kw["angle_weight"] == pytest.approx(1.25)
assert call_kw["nms_pre"] == 1500
assert call_kw["box_reg_loss_type"] == "l1"
assert call_kw["aux_loss_type"] == "kfiou"
assert call_kw["aux_loss_weight"] == pytest.approx(0.1)
assert call_kw["aux_angle_weight"] == pytest.approx(0.5)
assert call_kw["aux_angle_lambda"] == pytest.approx(1.5)
assert call_kw["box_reg_weight"] == pytest.approx(0.9)
assert call_kw["score_threshold"] == pytest.approx(0.13)
assert call_kw["final_nms_iou_threshold"] == pytest.approx(0.31)
assert call_kw["max_detections_per_image"] == 33
assert call_kw["nms_class_agnostic"] is True
assert call_kw["focal_alpha"] == pytest.approx(0.25)
assert call_kw["focal_gamma"] == pytest.approx(2.0)
assert call_kw["regress_ranges"] == [
(-1, 64),
(64, 128),
(128, 256),
(256, 512),
(512, 1e8),
]
def test_fcos_riou_1x_recipe_loads_lr_and_loss_type():
root = Path(__file__).resolve().parents[1]
cfg = TrainingExperimentConfig.load(root / "configs" / "rotated_fcos" / "dota_le90_1x.json")
assert cfg.model_type == "rotated_fcos"
assert cfg.model.box_reg_loss_type == "riou"
assert cfg.training.learning_rate == pytest.approx(0.0025)
assert float(cfg.model.aux_loss_weight or 0.0) == pytest.approx(0.0)
assert cfg.production.score_threshold == pytest.approx(0.2)
def test_dota_recipes_inherit_dataset_normalization():
"""One-stage DOTA 1× must use dota_le90.json mean/std, not ImageNet defaults."""
root = Path(__file__).resolve().parents[1]
dota_mean = [0.307941, 0.311986, 0.297761]
dota_std = [0.192315, 0.187769, 0.181551]
recipes = [
"configs/oriented_rcnn/dota_le90_1x.json",
"configs/rotated_faster_rcnn/dota_le90_1x.json",
"configs/rotated_fcos/dota_le90_1x.json",
"configs/rotated_retinanet/dota_le90_1x.json",
]
for rel in recipes:
cfg = TrainingExperimentConfig.load(root / rel)
assert cfg.preprocessing.normalize_mean == pytest.approx(dota_mean), rel
assert cfg.preprocessing.normalize_std == pytest.approx(dota_std), rel
assert cfg.dataset.data_root == Path("/path/to/data/DOTA-v1.0-tiled"), rel
def test_fcos_l1_kfiou_aux_1x_recipe_loads():
root = Path(__file__).resolve().parents[1]
cfg = TrainingExperimentConfig.load(
root / "configs" / "rotated_fcos" / "dota_le90_1x_l1_kfiou_aux.json"
)
assert cfg.model_type == "rotated_fcos"
assert cfg.model.box_reg_loss_type == "l1"
assert cfg.model.aux_loss_type == "kfiou"
assert cfg.model.aux_loss_weight == pytest.approx(0.1)
assert cfg.training.learning_rate == pytest.approx(0.00025)
def test_load_model_from_checkpoint_retinanet_passes_fpn_and_anchor_config():
from oriented_det.runtime import checkpoint as ckpt_mod
mock_cls = MagicMock()
inst = MagicMock()
inst.load_state_dict = MagicMock()
inst.to = MagicMock(return_value=inst)
inst.eval = MagicMock()
mock_cls.return_value = inst
cfg = _minimal_config("rotated_retinanet")
cfg.num_classes = 2
cfg.class_names = ["a", "b"]
fake_state = {
"head.conv_cls.weight": torch.zeros(4, 256, 1, 1),
"head.conv_cls.bias": torch.zeros(4),
"head.conv_bbox.weight": torch.zeros(10, 256, 1, 1),
"head.conv_bbox.bias": torch.zeros(10),
}
with patch.object(ckpt_mod, "TrainingExperimentConfig") as mock_cfg_cls, patch.object(
ckpt_mod, "RotatedRetinaNet", mock_cls
), patch("oriented_det.pretrained.ensure_checkpoint", side_effect=lambda p: p), patch.object(
ckpt_mod.torch, "load", return_value={"model_state_dict": fake_state}
), patch.object(ckpt_mod, "apply_inference_config_to_model"):
mock_cfg_cls.load.return_value = cfg
model, _, _ = ckpt_mod.load_model_from_checkpoint("/tmp/fake.pth", "/tmp/config.json", "cpu")
assert model is inst
call_kw = mock_cls.call_args.kwargs
assert call_kw["backbone_name"] == "resnet18"
assert call_kw["returned_layers"] == [2, 3, 4]
assert call_kw["fpn_strides"] == [8, 16, 32, 64, 128]
assert call_kw["fpn_extra_level"] is True
assert call_kw["octave_base_scale"] == pytest.approx(4.0)
assert call_kw["scales_per_octave"] == 3
assert call_kw["stacked_convs"] == 4
assert call_kw["norm_factor"] == pytest.approx(3.0)
assert call_kw["anchor_angles"] is None
def test_load_model_from_checkpoint_prefers_pretrained_sidecar_for_canonical_config(tmp_path):
from oriented_det.runtime import checkpoint as ckpt_mod
mock_cls = MagicMock()
inst = MagicMock()
inst.load_state_dict = MagicMock()
inst.to = MagicMock(return_value=inst)
inst.eval = MagicMock()
mock_cls.return_value = inst
cfg = _minimal_config("rotated_retinanet")
cfg.num_classes = 2
fake_state = {
"head.conv_cls.weight": torch.zeros(4, 256, 1, 1),
"head.conv_bbox.weight": torch.zeros(10, 256, 1, 1),
}
canonical = tmp_path / "configs" / "rotated_retinanet" / "dota_le90_1x.json"
canonical.parent.mkdir(parents=True)
canonical.write_text("{}", encoding="utf-8")
sidecar = tmp_path / "pretrained" / "rotated_retinanet_r50_fpn_dota_le90_1x-bb9a0bd2.json"
sidecar.parent.mkdir()
sidecar.write_text("{}", encoding="utf-8")
ckpt = sidecar.with_suffix(".pth")
ckpt.write_bytes(b"x")
with patch.object(ckpt_mod, "TrainingExperimentConfig") as mock_cfg_cls, patch.object(
ckpt_mod, "RotatedRetinaNet", mock_cls
), patch("oriented_det.pretrained.ensure_checkpoint", return_value=ckpt), patch(
"oriented_det.pretrained.resolve_checkpoint_sidecar_config", return_value=sidecar
), patch("oriented_det.pretrained.resolve_checkpoint_source_recipe", return_value=str(canonical)), patch.object(
ckpt_mod, "_config_matches_source_recipe", return_value=True
), patch.object(
ckpt_mod.torch, "load", return_value={"model_state_dict": fake_state}
), patch.object(ckpt_mod, "apply_inference_config_to_model"):
mock_cfg_cls.load.return_value = cfg
ckpt_mod.load_model_from_checkpoint(str(ckpt), str(canonical), "cpu")
mock_cfg_cls.load.assert_called_once_with(sidecar)
def test_load_model_from_checkpoint_keeps_different_explicit_config(tmp_path):
from oriented_det.runtime import checkpoint as ckpt_mod
mock_cls = MagicMock()
inst = MagicMock()
inst.load_state_dict = MagicMock()
inst.to = MagicMock(return_value=inst)
inst.eval = MagicMock()
mock_cls.return_value = inst
cfg = _minimal_config("rotated_retinanet")
cfg.num_classes = 2
fake_state = {
"head.conv_cls.weight": torch.zeros(4, 256, 1, 1),
"head.conv_bbox.weight": torch.zeros(10, 256, 1, 1),
}
explicit_config = tmp_path / "configs" / "rotated_retinanet" / "custom.json"
explicit_config.parent.mkdir(parents=True)
explicit_config.write_text("{}", encoding="utf-8")
sidecar = tmp_path / "pretrained" / "rotated_retinanet_r50_fpn_dota_le90_1x-bb9a0bd2.json"
sidecar.parent.mkdir()
sidecar.write_text("{}", encoding="utf-8")
ckpt = sidecar.with_suffix(".pth")
ckpt.write_bytes(b"x")
with patch.object(ckpt_mod, "TrainingExperimentConfig") as mock_cfg_cls, patch.object(
ckpt_mod, "RotatedRetinaNet", mock_cls
), patch("oriented_det.pretrained.ensure_checkpoint", return_value=ckpt), patch(
"oriented_det.pretrained.resolve_checkpoint_sidecar_config", return_value=sidecar
), patch("oriented_det.pretrained.resolve_checkpoint_source_recipe", return_value="configs/rotated_retinanet/dota_le90_1x.json"), patch.object(
ckpt_mod, "_config_matches_source_recipe", return_value=False
), patch.object(
ckpt_mod.torch, "load", return_value={"model_state_dict": fake_state}
), patch.object(ckpt_mod, "apply_inference_config_to_model"):
mock_cfg_cls.load.return_value = cfg
ckpt_mod.load_model_from_checkpoint(str(ckpt), str(explicit_config), "cpu")
mock_cfg_cls.load.assert_called_once_with(explicit_config)
def test_infer_num_classes_from_checkpoint_retinanet_uses_head_shapes(tmp_path):
from oriented_det.runtime.checkpoint import infer_num_classes_from_checkpoint
checkpoint_path = tmp_path / "retinanet.pth"
torch.save(
{
"model_state_dict": {
"head.conv_bbox.weight": torch.zeros(45, 256, 3, 3),
"head.conv_cls.weight": torch.zeros(135, 256, 3, 3),
}
},
checkpoint_path,
)
assert infer_num_classes_from_checkpoint(str(checkpoint_path), "rotated_retinanet") == 15
def test_load_model_from_checkpoint_retinanet_infers_missing_num_classes():
from oriented_det.runtime import checkpoint as ckpt_mod
mock_cls = MagicMock()
inst = MagicMock()
inst.load_state_dict = MagicMock()
inst.to = MagicMock(return_value=inst)
inst.eval = MagicMock()
mock_cls.return_value = inst
cfg = _minimal_config("rotated_retinanet")
cfg.num_classes = None
fake_state = {
"head.conv_cls.weight": torch.zeros(135, 256, 1, 1),
"head.conv_cls.bias": torch.zeros(135),
"head.conv_bbox.weight": torch.zeros(45, 256, 1, 1),
"head.conv_bbox.bias": torch.zeros(45),
}
with patch.object(ckpt_mod, "TrainingExperimentConfig") as mock_cfg_cls, patch.object(
ckpt_mod, "RotatedRetinaNet", mock_cls
), patch("oriented_det.pretrained.ensure_checkpoint", side_effect=lambda p: p), patch.object(
ckpt_mod.torch, "load", return_value={"model_state_dict": fake_state}
), patch.object(ckpt_mod, "apply_inference_config_to_model"):
mock_cfg_cls.load.return_value = cfg
model, _, _ = ckpt_mod.load_model_from_checkpoint("/tmp/fake.pth", "/tmp/config.json", "cpu")
assert model is inst
assert mock_cls.call_args.kwargs["num_classes"] == 15
def test_create_model_rcnn_passes_inference_pre_nms_score_from_config():
train = _load_train_module()
mock_cls = MagicMock()
inst = MagicMock()
inst.to = MagicMock(return_value=inst)
mock_cls.return_value = inst
cfg = _minimal_config("rotated_faster_rcnn")
device = torch.device("cpu")
with patch.object(train, "RotatedFasterRCNN", mock_cls):
model, _ = train.create_model_from_config(
cfg, num_classes=2, device=device, roi_class_weights=None
)
assert model is inst
call_kw = mock_cls.call_args.kwargs
assert call_kw["backbone_name"] == "resnet18"
assert call_kw["pretrained_backbone"] is False
assert call_kw["trainable_layers"] == 3
assert "anchor_angles" not in call_kw
assert call_kw["anchor_scales"] == [4, 8]
assert call_kw["anchor_ratios"] == [0.5, 2.0]
assert call_kw["roi_norm_factor"] == pytest.approx(3.0)
assert call_kw["roi_edge_swap"] is False
assert call_kw["roi_proj_xy"] is True
assert call_kw["roi_box_reg_angle_weight"] == pytest.approx(1.7)
assert call_kw["roi_box_reg_aux_weight"] == pytest.approx(0.15)
assert call_kw["roi_box_reg_aux_loss_type"] == "smooth_l1"
assert call_kw["roi_box_reg_kfiou_fun"] == "ln"
assert call_kw["roi_box_reg_main_loss_type"] == "probiou"
assert call_kw["roi_box_reg_norm"] == "positives_only"
assert call_kw["roi_min_pos_iou"] == pytest.approx(0.37)
assert call_kw["use_hbb_for_matching"] is False
assert call_kw["inference_pre_nms_score_threshold"] == pytest.approx(0.13)
assert call_kw["rpn_pre_nms_top_n"] == 111
assert call_kw["rpn_post_nms_top_n"] == 77
assert call_kw["max_detections_per_image"] == 33
assert call_kw["rpn_nms_threshold"] == pytest.approx(0.41)
assert call_kw["final_nms_iou_threshold"] == pytest.approx(0.31)
assert call_kw["final_nms_iou_schedule_epochs"] == [1, 2]
assert call_kw["final_nms_iou_schedule_values"] == [0.6, 0.4, 0.2]
assert call_kw["roi_box_reg_aux_schedule_epochs"] == [10, 20]
assert call_kw["roi_box_reg_aux_schedule_values"] == [0.2, 0.1, 0.0]
assert call_kw["roi_inference_top_class_only"] is True
def test_load_model_from_checkpoint_rotated_faster_rcnn_passes_roi_proj_xy():
from oriented_det.runtime import checkpoint as ckpt_mod
mock_cls = MagicMock()
inst = MagicMock()
inst.load_state_dict = MagicMock()
inst.to = MagicMock(return_value=inst)
inst.eval = MagicMock()
mock_cls.return_value = inst
cfg = _minimal_config("rotated_faster_rcnn")
cfg.num_classes = 2
cfg.model.roi_proj_xy = True
fake_state = {
"roi_head.fc_cls.weight": torch.zeros(4, 1024),
"roi_head.fc_cls.bias": torch.zeros(4),
}
with patch.object(ckpt_mod, "TrainingExperimentConfig") as mock_cfg_cls, patch.object(
ckpt_mod, "RotatedFasterRCNN", mock_cls
), patch("oriented_det.pretrained.ensure_checkpoint", side_effect=lambda p: p), patch.object(
ckpt_mod.torch, "load", return_value={"model_state_dict": fake_state}
), patch.object(ckpt_mod, "apply_inference_config_to_model"):
mock_cfg_cls.load.return_value = cfg
model, _, _ = ckpt_mod.load_model_from_checkpoint("/tmp/fake.pth", "/tmp/config.json", "cpu")
assert model is inst
assert mock_cls.call_args.kwargs["roi_proj_xy"] is True
assert "roi_use_hbb_for_matching" not in mock_cls.call_args.kwargs
def test_load_model_from_checkpoint_oriented_rcnn_passes_roi_use_hbb_for_matching():
from oriented_det.runtime import checkpoint as ckpt_mod
mock_cls = MagicMock()
inst = MagicMock()
inst.load_state_dict = MagicMock()
inst.to = MagicMock(return_value=inst)
inst.eval = MagicMock()
mock_cls.return_value = inst
cfg = _minimal_config("oriented_rcnn")
cfg.num_classes = 2
cfg.model.roi_use_hbb_for_matching = True
fake_state = {
"roi_head.fc_cls.weight": torch.zeros(4, 1024),
"roi_head.fc_cls.bias": torch.zeros(4),
}
with patch.object(ckpt_mod, "TrainingExperimentConfig") as mock_cfg_cls, patch.object(
ckpt_mod, "OrientedRCNN", mock_cls
), patch("oriented_det.pretrained.ensure_checkpoint", side_effect=lambda p: p), patch.object(
ckpt_mod.torch, "load", return_value={"model_state_dict": fake_state}
), patch.object(ckpt_mod, "apply_inference_config_to_model"):
mock_cfg_cls.load.return_value = cfg
ckpt_mod.load_model_from_checkpoint("/tmp/fake.pth", "/tmp/config.json", "cpu")
assert mock_cls.call_args.kwargs["roi_use_hbb_for_matching"] is True