Repository navigation
Expand file tree
/
Copy pathoptimizer.py
More file actions
4914 lines (4651 loc) · 182 KB
/
Copy pathoptimizer.py
File metadata and controls
4914 lines (4651 loc) · 182 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
from __future__ import annotations
import json
import math
import os
import time
from dataclasses import dataclass, replace
from pathlib import Path
import torch
import cli_data
import fit_data
import model as fit_model
import cyl_sdf_volume
import opt_loss_data
import opt_loss_dir
import opt_loss_pred_dt
import opt_loss_step
import opt_loss_smooth
import opt_loss_winding_density
import opt_loss_corr
import opt_loss_winding_volume
import opt_loss_station
import opt_loss_bend
import opt_loss_cyl
import opt_loss_snap_surf
import opt_loss_atlas_line
from snap_surf import map_global as snap_surf_map_global
from progress_table import format_progress_value, print_progress_legend
import opt_loss_flatten
from flatten_clamped_adam import FlattenClampedAdam
def _debug_cuda_sync(label: str) -> None:
if os.environ.get("LASAGNA_SYNC_DEBUG", "0") == "0":
return
if torch.cuda.is_available():
try:
torch.cuda.synchronize()
except RuntimeError as exc:
raise RuntimeError(f"CUDA failure after {label}") from exc
def _cuda_mem_debug_enabled() -> bool:
return os.environ.get("LASAGNA_CUDA_MEM_DEBUG", "0") != "0"
def _fmt_mib(value: int | float) -> str:
return f"{float(value) / 1024.0 ** 2:.1f}MiB"
def _log_cuda_memory(label: str, *, device: torch.device | int | None = None) -> None:
if not _cuda_mem_debug_enabled() or not torch.cuda.is_available():
return
try:
dev = device if device is not None else torch.cuda.current_device()
allocated = torch.cuda.memory_allocated(dev)
reserved = torch.cuda.memory_reserved(dev)
max_allocated = torch.cuda.max_memory_allocated(dev)
max_reserved = torch.cuda.max_memory_reserved(dev)
free, total = torch.cuda.mem_get_info(dev)
print(
f"[cuda_mem] {label}: "
f"alloc={_fmt_mib(allocated)} reserved={_fmt_mib(reserved)} "
f"peak_alloc={_fmt_mib(max_allocated)} peak_reserved={_fmt_mib(max_reserved)} "
f"free={_fmt_mib(free)} total={_fmt_mib(total)}",
flush=True,
)
except RuntimeError as exc:
print(f"[cuda_mem] {label}: unavailable ({exc})", flush=True)
def _fmt_duration(seconds: float) -> str:
seconds = max(0.0, float(seconds))
if seconds < 60.0:
return f"{seconds:.2f}s"
minutes, sec = divmod(seconds, 60.0)
if minutes < 60.0:
return f"{int(minutes)}m{sec:05.2f}s"
hours, minutes = divmod(minutes, 60.0)
return f"{int(hours)}h{int(minutes):02d}m{sec:05.2f}s"
def _require_consumed_dict(*, where: str, cfg: dict) -> None:
if cfg:
bad = sorted(cfg.keys())
print(f"WARNING stages_json: {where}: unknown key(s): {bad}")
@dataclass(frozen=True)
class OptSettings:
steps: int
lr: float | list[float]
params: list[str]
min_scaledown: int
default_mul: float | None
w_fac: dict | float | None
eff: dict[str, float]
base_eff: dict[str, float]
steps_auto: bool = False
args: dict | None = None
kind: str = "model"
@dataclass(frozen=True)
class Stage:
name: str
global_opt: OptSettings | None
children: tuple["Stage", ...] = ()
grow: dict | None = None
@property
def is_expand(self) -> bool:
return self.name.startswith("expand-")
@dataclass(frozen=True)
class CylinderGrowWidthTarget:
width_count: int
circumference: float
width_step: float
CYLINDER_SEED_INIT_STAGE_ROLES = ("cyl_init", "cyl_grow", "cyl_grow_refine")
CYLINDER_STAGE_STEP_ARG = "model-step"
OLD_CYLINDER_STAGE_STEP_ARGS = ("cyl_shell_width_step", "cyl_width_step", "cyl_step_size", "wstep_target")
CYLINDER_OUTPUT_ALL_SHELLS_ARGS = ("cyl_output_all_shells", "cyl_shell_output_all")
CYLINDER_MAX_SEARCH_SHELLS_ARGS = ("cyl_max_shells", "cyl_shell_max_shells", "cyl_shell_search_max_shells")
CYLINDER_GROW_DIRECTION_ARG = "cyl_grow_direction"
CYLINDER_OUTSIDE_GRID_STEP_ARG = "cyl_outside_grid_step"
CYLINDER_OUTSIDE_SAMPLE_FACTOR_ARG = "cyl_outside_sample_factor"
CYLINDER_OUTSIDE_THREADS_ARG = "cyl_outside_threads"
CYLINDER_OUTSIDE_CHUNK_SIZE_ARG = "cyl_outside_chunk_size"
CYLINDER_OUTSIDE_DEEP_INTERP_CHUNKS_ARG = "cyl_outside_deep_interp_chunks"
CYLINDER_OUTSIDE_DEEP_BLEND_CHUNKS_ARG = "cyl_outside_deep_blend_chunks"
CYLINDER_REFINE_MAX_IFRAC_ARGS = ("cyl_refine_max_ifrac", "cyl_grow_refine_max_ifrac")
DEFAULT_CYLINDER_REFINE_MAX_IFRAC = 0.5
CYLINDER_LOSS_NAMES = (
"cyl_normal", "cyl_center", "cyl_smooth", "cyl_z_smooth", "cyl_step",
"cyl_z_center", "cyl_step_push", "cyl_radial_mean", "cyl_bend", "cyl_conn_mesh", "cyl_conn_gt",
"cyl_base_mesh", "cyl_base_gt", "cyl_outside",
)
MODEL_OPT_PARAMS = {"mesh_ms", "amp", "bias", "cyl_params", "map_flatten_ms"}
MAP_OPT_PARAMS = {"map_surf_affine", "map_surf_ms"}
PARAM_REPLACEMENTS = {
"flatten_map_ms": "map_flatten_ms",
"map_affine": "map_surf_affine",
"affine": "map_surf_affine",
"map_uv_ms": "map_surf_ms",
}
MODEL_INTERNAL_PARAM = {
"map_flatten_ms": "flatten_map_ms",
}
MAP_LOSS_NAMES = (
"map_dist",
"map_vec_normal",
"map_surface_normal",
"map_turn",
"map_smooth",
"map_bend",
"map_jac",
"map_metric_smooth",
"map_area_smooth",
"map_dense_prior",
"map_station_t",
)
MAP_STAGE_LOSS_TO_GLOBAL = {
"dist": "map_dist",
"vec": "map_vec_normal",
"norm": "map_surface_normal",
"turn": "map_turn",
"smooth": "map_smooth",
"bend": "map_bend",
"jac": "map_jac",
"metric_smooth": "map_metric_smooth",
"area_smooth": "map_area_smooth",
"prior": "map_dense_prior",
}
def normalize_cylinder_grow_direction(raw: object = "outward") -> int:
if raw is None:
raw = "outward"
if isinstance(raw, str):
value = raw.strip().lower()
if value in {"outward", "outwards", "grow", "expand", "+", "+1", "1"}:
return 1
if value in {"inward", "inwards", "shrink", "contract", "-", "-1"}:
return -1
else:
try:
value_f = float(raw)
except (TypeError, ValueError):
value_f = None
if value_f == 1.0:
return 1
if value_f == -1.0:
return -1
raise ValueError(
f"cylinder stage arg '{CYLINDER_GROW_DIRECTION_ARG}' must be "
f"'outward' or 'inward', got {raw!r}"
)
def cylinder_grow_width_target(
*,
reference_width_count: int,
reference_circumference: float,
shell_index: int,
grow_factor: float,
direction: int,
) -> CylinderGrowWidthTarget:
ref_w = max(3, int(reference_width_count))
ref_circ = max(1.0e-6, float(reference_circumference))
idx = max(0, int(shell_index))
factor = max(1.0, float(grow_factor))
scale = factor ** idx
if int(direction) < 0:
scale = 1.0 / scale
target_circ = ref_circ * scale
target_w_f = float(ref_w) * scale
target_w = max(3, int(math.floor(target_w_f + 0.5)))
return CylinderGrowWidthTarget(
width_count=target_w,
circumference=target_circ,
width_step=target_circ / float(target_w),
)
def _cyl_outside_mode_for_direction(direction: int) -> str:
return (
cyl_sdf_volume.CYL_OUTSIDE_MODE_OUTSIDE
if int(direction) < 0
else cyl_sdf_volume.CYL_OUTSIDE_MODE_INSIDE
)
def _stage_to_modifiers(
base: dict[str, float],
default_mul: float | None,
w_fac: dict | float | None,
scalar_terms: set[str] | None = None,
) -> tuple[dict[str, float], dict[str, float]]:
eff = {k: float(v) for k, v in base.items()}
if default_mul is not None:
for name in base.keys():
eff[name] = float(base[name]) * float(default_mul)
if isinstance(w_fac, (int, float)):
terms = scalar_terms if scalar_terms is not None else set(base.keys())
for name in terms:
if name in base:
eff[name] = float(base[name]) * float(w_fac)
elif isinstance(w_fac, dict):
for k, v in w_fac.items():
if v is None:
continue
eff[str(k)] = float(base.get(str(k), 0.0)) * float(v)
mods: dict[str, float] = {}
for name, val in eff.items():
b = float(base.get(name, 0.0))
mods[name] = (float(val) / b) if b != 0.0 else 0.0
return eff, mods
def _need_term(name: str, stage_eff: dict[str, float]) -> float:
return float(stage_eff.get(name, 0.0))
def _parse_opt_settings(
*,
stage_name: str,
opt_cfg: dict,
base: dict[str, float],
) -> OptSettings:
opt_cfg = dict(opt_cfg)
steps_raw = opt_cfg.get("steps", 0)
lr_raw = opt_cfg.get("lr", 1e-3)
if isinstance(lr_raw, list):
if not lr_raw:
raise ValueError(f"stages_json: stage '{stage_name}' opt.lr: must be a number or a non-empty list")
lr: float | list[float] = [float(v) for v in lr_raw]
else:
lr = float(lr_raw)
params = opt_cfg.get("params", [])
if not isinstance(params, list):
params = []
params = [str(p) for p in params]
for old, new in PARAM_REPLACEMENTS.items():
if old in params:
raise ValueError(f"stages_json: stage '{stage_name}' opt.params: use '{new}' instead of '{old}'")
model_params = set(params) & MODEL_OPT_PARAMS
map_params = set(params) & MAP_OPT_PARAMS
bad_params = sorted(set(params) - MODEL_OPT_PARAMS - MAP_OPT_PARAMS)
if bad_params:
raise ValueError(f"stages_json: stage '{stage_name}' opt.params: unknown name(s): {bad_params}")
if model_params and map_params:
raise ValueError(
f"stages_json: stage '{stage_name}' opt.params: cannot mix model params {sorted(model_params)} "
f"with map params {sorted(map_params)}; put concurrent map optimization under args.snap_surf_map.map_opt"
)
kind = "map" if map_params else "model"
min_scaledown = max(0, int(opt_cfg.get("min_scaledown", 0)))
default_mul = opt_cfg.get("default_mul", None)
w_fac = opt_cfg.get("w_fac", None)
args_raw = opt_cfg.get("args", None)
# Back-compat: translate old "auto_offset": true → args dict
if args_raw is None and opt_cfg.get("auto_offset", False):
args_raw = {"winding_offset_autocrop": True}
if args_raw is not None and not isinstance(args_raw, dict):
raise ValueError(f"stages_json: stage '{stage_name}' opt 'args' must be an object or null")
args = dict(args_raw) if args_raw else {}
steps_auto = isinstance(steps_raw, str) and steps_raw.strip().lower() == "auto"
if steps_auto:
steps = max(1, int(args.get("auto_steps_max", 10000)))
elif isinstance(steps_raw, str):
try:
steps = max(0, int(steps_raw))
except ValueError as exc:
raise ValueError(
f"stages_json: stage '{stage_name}' opt.steps: expected an integer or 'auto'"
) from exc
else:
steps = max(0, int(steps_raw))
opt_cfg.pop("steps", None)
opt_cfg.pop("lr", None)
opt_cfg.pop("params", None)
opt_cfg.pop("min_scaledown", None)
opt_cfg.pop("default_mul", None)
opt_cfg.pop("w_fac", None)
opt_cfg.pop("auto_offset", None)
opt_cfg.pop("args", None)
_require_consumed_dict(where=f"stage '{stage_name}' opt", cfg=opt_cfg)
if default_mul is not None:
default_mul = float(default_mul)
if kind == "map" and w_fac is not None and not isinstance(w_fac, (dict, int, float)):
raise ValueError(f"stages_json: stage '{stage_name}' opt 'w_fac' must be an object, number, or null for map stages")
if kind == "model" and w_fac is not None and not isinstance(w_fac, (dict, int, float)):
raise ValueError(f"stages_json: stage '{stage_name}' opt 'w_fac' must be an object, number, or null")
if isinstance(w_fac, dict):
bad_terms = sorted(set(str(k) for k in w_fac.keys()) - set(base.keys()))
if bad_terms:
raise ValueError(f"stages_json: stage '{stage_name}' opt.w_fac: unknown term(s): {bad_terms}")
if kind == "map":
bad_map_terms = sorted(set(str(k) for k in w_fac.keys()) - set(MAP_LOSS_NAMES))
if bad_map_terms:
raise ValueError(
f"stages_json: stage '{stage_name}' opt.w_fac: map stages may only override map loss term(s); "
f"got {bad_map_terms}"
)
scalar_terms = set(MAP_LOSS_NAMES) if kind == "map" else (set(base.keys()) - set(MAP_LOSS_NAMES))
eff, _mods = _stage_to_modifiers(base, default_mul, w_fac, scalar_terms=scalar_terms)
if float(eff.get("atlas_line_snap", 0.0)) > 0.0:
conflicting = [
name for name in ("atlas_line", "atlas_line_control", "atlas_line_other")
if float(eff.get(name, 0.0)) > 0.0
]
if conflicting:
raise ValueError(
f"stages_json: stage '{stage_name}' atlas_line_snap cannot be combined with "
+ ", ".join(conflicting)
)
if steps_auto and "cyl_params" in params:
raise ValueError(f"stages_json: stage '{stage_name}' opt.steps='auto' is not supported for cyl_params stages")
if "cyl_params" in params:
if params != ["cyl_params"]:
raise ValueError(f"stages_json: stage '{stage_name}' opt.params: cyl_params must be optimized alone")
for old_key in OLD_CYLINDER_STAGE_STEP_ARGS:
if old_key in args:
raise ValueError(
f"stages_json: stage '{stage_name}' opt.args: '{old_key}' is no longer supported; "
f"use '{CYLINDER_STAGE_STEP_ARG}'"
)
if CYLINDER_STAGE_STEP_ARG in args and float(args[CYLINDER_STAGE_STEP_ARG]) <= 0.0:
raise ValueError(
f"stages_json: stage '{stage_name}' opt.args.{CYLINDER_STAGE_STEP_ARG}: must be > 0"
)
if not any(float(eff.get(name, 0.0)) != 0.0 for name in CYLINDER_LOSS_NAMES):
raise ValueError(f"stages_json: stage '{stage_name}' with cyl_params requires a nonzero cylinder loss")
if "map_flatten_ms" in params and not any(
float(eff.get(name, 0.0)) != 0.0
for name in ("flatten_sdir", "flatten_map_step", "flatten_edge_step", "flatten_avg_offset", "flatten_orient")
):
raise ValueError(f"stages_json: stage '{stage_name}' with map_flatten_ms requires a nonzero flatten loss")
return OptSettings(
steps=steps,
lr=lr,
params=params,
min_scaledown=min_scaledown,
default_mul=default_mul,
w_fac=w_fac,
eff=eff,
base_eff={k: float(v) for k, v in base.items()},
steps_auto=steps_auto,
args=args,
kind=kind,
)
lambda_global: dict[str, float] = {
"normal": 1.0,
"step": 0.0,
"smooth_step": 0.0,
"avg_step": 0.0,
"smooth": 0.0,
"winding_density": 0.0,
"data": 0.0,
"data_plain": 0.0,
"pred_dt": 0.0,
"corr": 0.0,
"winding_vol": 0.0,
"station_n": 0.0,
"station_t": 0.0,
"bend": 0.0,
"ext_offset": 0.0,
"snap_surf_map": 0.0,
"atlas_line": 0.0,
"atlas_line_control": 0.0,
"atlas_line_other": 0.0,
"atlas_line_snap": 0.0,
"map_dist": 1.0,
"map_vec_normal": 1.0,
"map_surface_normal": 1.0,
"map_turn": 10.0,
"map_smooth": 0.05,
"map_bend": 0.01,
"map_jac": 1.0,
"map_metric_smooth": 0.05,
"map_area_smooth": 0.02,
"map_dense_prior": 0.001,
"map_station_t": 0.0,
"cyl_normal": 0.0,
"cyl_center": 0.0,
"cyl_smooth": 0.0,
"cyl_z_smooth": 0.0,
"cyl_z_center": 0.0,
"cyl_step_push": 0.0,
"cyl_step": 0.0,
"cyl_radial_mean": 0.0,
"cyl_bend": 0.0,
"cyl_conn_mesh": 0.0,
"cyl_conn_gt": 0.0,
"cyl_base_mesh": 0.0,
"cyl_base_gt": 0.0,
"cyl_outside": 0.0,
"flatten_sdir": 0.0,
"flatten_map_step": 0.0,
"flatten_edge_step": 0.0,
"flatten_avg_offset": 0.0,
"flatten_orient": 0.0,
}
def _init_mode_from_args(args_cfg: object) -> str | None:
if not isinstance(args_cfg, dict):
return None
model_init = str(args_cfg.get("model-init", args_cfg.get("model_init", "seed"))).strip().lower()
if model_init and model_init != "seed":
return None
init_mode = args_cfg.get("init-mode", args_cfg.get("init_mode", None))
return None if init_mode is None else str(init_mode).strip().lower()
def _model_init_from_args(args_cfg: object) -> str | None:
if not isinstance(args_cfg, dict):
return None
return str(args_cfg.get("model-init", args_cfg.get("model_init", "seed"))).strip().lower()
def _validate_cylinder_seed_stage_roles(stages: list[Stage]) -> None:
role_positions: dict[str, int] = {}
seen_grow = False
seen_non_role = False
for i, stage in enumerate(stages):
is_role = stage.name in CYLINDER_SEED_INIT_STAGE_ROLES
if is_role:
if seen_non_role:
raise ValueError(
"stages_json: cylinder_seed stages must be contiguous before later cylinder stages"
)
if stage.name in role_positions:
raise ValueError(f"stages_json: cylinder_seed stage '{stage.name}' is duplicated")
role_positions.setdefault(stage.name, i)
if stage.global_opt.params != ["cyl_params"]:
raise ValueError(
f"stages_json: cylinder_seed stage '{stage.name}' must have params ['cyl_params']"
)
if stage.name == "cyl_grow":
seen_grow = True
if stage.name == "cyl_grow_refine" and not seen_grow:
raise ValueError("stages_json: cylinder_seed stage 'cyl_grow_refine' must follow cyl_grow")
else:
if role_positions:
seen_non_role = True
missing = [name for name in ("cyl_init",) if name not in role_positions]
if missing:
raise ValueError(f"stages_json: cylinder_seed missing required stage role(s): {missing}")
if role_positions["cyl_init"] != 0:
raise ValueError(
"stages_json: cylinder_seed stages before cyl_init "
"must be only cyl_init; later stages are skipped when cyl_grow is absent"
)
if role_positions["cyl_init"] != min(role_positions.values()):
raise ValueError(
"stages_json: cylinder_seed stages must appear in order "
"cyl_init, cyl_grow, cyl_grow_refine"
)
if "cyl_grow" not in role_positions:
init_pos = role_positions["cyl_init"]
for stage in stages[:init_pos]:
raise ValueError(
"stages_json: cylinder_seed stages before cyl_init "
"must be only cyl_init; later stages are skipped when cyl_grow is absent"
)
return
first_non_role = next((i for i, stage in enumerate(stages) if i > role_positions["cyl_init"] and stage.name not in CYLINDER_SEED_INIT_STAGE_ROLES), len(stages))
for stage in stages[:first_non_role]:
if stage.name not in CYLINDER_SEED_INIT_STAGE_ROLES:
raise ValueError(
"stages_json: cylinder_seed stages before later stages "
"must be only cyl_init/cyl_grow/cyl_grow_refine; later stages run normally"
)
def load_stages_cfg(cfg: dict, *, init_mode: str | None = None) -> list[Stage]:
cfg = dict(cfg)
args_cfg = cfg.pop("args", None)
top_args = dict(args_cfg) if isinstance(args_cfg, dict) else {}
model_init = _model_init_from_args(args_cfg)
if init_mode is None:
init_mode = _init_mode_from_args(args_cfg)
else:
init_mode = str(init_mode).strip().lower()
base = dict(lambda_global)
if model_init == "flatten":
base = {k: 0.0 for k in base.keys()}
base_cfg = cfg.pop("base", None)
if isinstance(base_cfg, dict):
bad_base = sorted(set(str(k) for k in base_cfg.keys()) - set(base.keys()))
if bad_base:
raise ValueError(f"stages_json: base: unknown term(s): {bad_base}")
for k, v in base_cfg.items():
base[str(k)] = float(v)
stages_cfg = cfg.pop("stages", None)
if stages_cfg is None:
raise ValueError("stages_json: missing required key 'stages'")
if not isinstance(stages_cfg, list):
raise ValueError(
f"stages_json: expected key 'stages' to be a non-empty list, got {type(stages_cfg).__name__}"
)
if not stages_cfg:
raise ValueError("stages_json: expected key 'stages' to be a non-empty list, got an empty list")
_require_consumed_dict(where="top-level", cfg=cfg)
def _load_stage_list(raw_stages: list, *, where: str) -> list[Stage]:
out: list[Stage] = []
for s in raw_stages:
if not isinstance(s, dict):
raise ValueError(f"stages_json: each stage in {where} must be an object")
s = dict(s)
name = str(s.pop("name", ""))
children_cfg = s.pop("stages", None)
grow_cfg = s.pop("grow", None)
if children_cfg is not None or name.startswith("expand-"):
if not name.startswith("expand-"):
raise ValueError(f"stages_json: wrapper stage '{name}' must be named expand-*")
if name not in {"expand-z", "expand-xyz"}:
raise ValueError(f"stages_json: unsupported expand stage '{name}' (expected expand-z or expand-xyz)")
if not isinstance(children_cfg, list) or not children_cfg:
raise ValueError(f"stages_json: stage '{name}' requires non-empty nested 'stages' list")
if grow_cfg is not None and not isinstance(grow_cfg, dict):
raise ValueError(f"stages_json: stage '{name}' field 'grow' must be an object or null")
_require_consumed_dict(where=f"stage '{name}'", cfg=s)
out.append(Stage(
name=name,
global_opt=None,
children=tuple(_load_stage_list(children_cfg, where=f"stage '{name}'.stages")),
grow=None if grow_cfg is None else dict(grow_cfg),
))
continue
global_opt_cfg = s.pop("global_opt", None)
if global_opt_cfg is None:
global_opt_cfg = s.pop("opt", None)
if global_opt_cfg is None:
global_opt_cfg = dict(s)
s.clear()
_require_consumed_dict(where=f"stage '{name}'", cfg=s)
if not isinstance(global_opt_cfg, dict):
raise ValueError(f"stages_json: stage '{name}' field 'global_opt' must be an object")
if "flatten_edge_step_global_scale" in top_args:
global_opt_cfg = dict(global_opt_cfg)
stage_args = dict(global_opt_cfg.get("args") or {})
stage_args.setdefault(
"flatten_edge_step_global_scale",
top_args["flatten_edge_step_global_scale"],
)
global_opt_cfg["args"] = stage_args
global_opt = _parse_opt_settings(stage_name=name, opt_cfg=global_opt_cfg, base=base)
out.append(Stage(name=name, global_opt=global_opt))
return out
out = _load_stage_list(stages_cfg, where="top-level stages")
if init_mode == "cylinder_seed":
_validate_cylinder_seed_stage_roles([s for s in out if s.global_opt is not None])
return out
def load_stages(path: str) -> list[Stage]:
try:
with open(path, "r", encoding="utf-8") as f:
cfg = json.load(f)
except json.JSONDecodeError as exc:
raise ValueError(
f"stages_json: invalid JSON in {path}: line {exc.lineno}, column {exc.colno}: {exc.msg}"
) from exc
if not isinstance(cfg, dict):
raise ValueError("stages_json: expected an object")
return load_stages_cfg(cfg)
def total_steps_for_stages(stages: list[Stage]) -> int:
total = 0
for stage in stages:
if stage.children:
total += total_steps_for_stages(list(stage.children))
continue
if stage.global_opt is None:
continue
total += max(0, stage.global_opt.steps)
return total
def _lr_last(lr: float | list[float]) -> float:
if isinstance(lr, list):
return float(lr[-1])
return float(lr)
def _global_map_w_fac_from_eff(*, base: dict[str, float], eff: dict[str, float]) -> dict[str, float]:
out: dict[str, float] = {}
for stage_name, global_name in MAP_STAGE_LOSS_TO_GLOBAL.items():
base_val = float(base.get(global_name, 0.0))
eff_val = float(eff.get(global_name, 0.0))
out[stage_name] = (eff_val / base_val) if base_val != 0.0 else 0.0
return out
def _global_map_args_from_eff(args: dict, *, base: dict[str, float], eff: dict[str, float]) -> dict:
out = dict(args)
map_init = dict(out.get("map_init", {})) if isinstance(out.get("map_init", {}), dict) else {}
map_init.update({
"w_dist": float(base.get("map_dist", 0.0)),
"w_vec_normal": float(base.get("map_vec_normal", 0.0)),
"w_surface_normal": float(base.get("map_surface_normal", 0.0)),
"map_turn": float(base.get("map_turn", 0.0)),
"w_smooth": float(base.get("map_smooth", 0.0)),
"w_bend": float(base.get("map_bend", 0.0)),
"w_jac": float(base.get("map_jac", 0.0)),
"w_metric_smooth": float(base.get("map_metric_smooth", 0.0)),
"w_area_smooth": float(base.get("map_area_smooth", 0.0)),
"w_dense_prior": float(base.get("map_dense_prior", 0.0)),
})
out["map_init"] = map_init
out["map_station_t"] = float(eff.get("map_station_t", 0.0))
return out
def _global_map_stage_from_opt_settings(*, name: str, opt_cfg: OptSettings, args: dict) -> snap_surf_map_global.GlobalMapStageConfig:
if opt_cfg.kind != "map":
raise ValueError(f"stage '{name}' is not a map optimization stage")
return snap_surf_map_global.GlobalMapStageConfig(
name=name,
steps=int(opt_cfg.steps),
lr=float(_lr_last(opt_cfg.lr)),
params=tuple({"map_surf_affine": "affine", "map_surf_ms": "map_uv_ms"}.get(p, p) for p in opt_cfg.params),
min_scaledown=int(opt_cfg.min_scaledown),
w_fac=_global_map_w_fac_from_eff(base=opt_cfg.base_eff, eff=opt_cfg.eff),
args=_global_map_args_from_eff(args, base=opt_cfg.base_eff, eff=opt_cfg.eff),
)
def global_map_config_from_stages_cfg(cfg: dict) -> snap_surf_map_global.GlobalMapConfig:
stages = load_stages_cfg(cfg)
map_stages: list[snap_surf_map_global.GlobalMapStageConfig] = []
base_eff: dict[str, float] | None = None
def _collect(raw_stages: list[Stage]) -> None:
nonlocal base_eff
for stage in raw_stages:
if stage.children:
raise ValueError("global map fixture configs do not support nested/expand stages")
if stage.global_opt is None:
continue
if stage.global_opt.kind != "map":
raise ValueError(
f"global map fixture config stage '{stage.name}' is not a map stage; "
"fixture configs must contain only map optimization stages"
)
if base_eff is None:
base_eff = dict(stage.global_opt.base_eff)
map_stages.append(_global_map_stage_from_opt_settings(
name=stage.name,
opt_cfg=stage.global_opt,
args=stage.global_opt.args or {},
))
_collect(stages)
if not map_stages:
raise ValueError("global map fixture config contains no map optimization stages")
return snap_surf_map_global.GlobalMapConfig(base=dict(base_eff or {}), stages=tuple(map_stages))
def load_global_map_config(path: str | Path) -> snap_surf_map_global.GlobalMapConfig:
try:
with open(path, "r", encoding="utf-8") as f:
cfg = json.load(f)
except json.JSONDecodeError as exc:
raise ValueError(
f"stages_json: invalid JSON in {path}: line {exc.lineno}, column {exc.colno}: {exc.msg}"
) from exc
if not isinstance(cfg, dict):
raise ValueError("stages_json: expected an object")
return global_map_config_from_stages_cfg(cfg)
def _resolve_snap_surf_map_fixture_export_args(args: dict, *, out_dir: str | None) -> dict:
if not isinstance(args, dict):
return args
if out_dir is None:
return dict(args)
out = dict(args)
base = Path(out_dir)
def _resolve_path(value):
if value in (None, "", False):
return value
path = Path(str(value))
return str(path if path.is_absolute() else base / path)
for key in ("fixture_export_dir", "map_fixture_export_dir"):
if key in out:
out[key] = _resolve_path(out[key])
for key in ("export_fixture", "fixture_export"):
raw = out.get(key)
if isinstance(raw, str):
out[key] = _resolve_path(raw)
elif isinstance(raw, dict):
nested = dict(raw)
for path_key in ("dir", "out_dir", "path"):
if path_key in nested:
nested[path_key] = _resolve_path(nested[path_key])
out[key] = nested
return out
def _lr_scalespace(*, lr: float | list[float], scale_i: int) -> float:
if not isinstance(lr, list):
return float(lr)
if not lr:
return 0.0
idx = -1 - int(scale_i)
if -len(lr) <= idx < 0:
return float(lr[idx])
return float(lr[0])
def _steps_label(opt_cfg: OptSettings) -> str:
if opt_cfg.steps_auto:
return f"auto:{int(opt_cfg.steps)}"
return str(int(opt_cfg.steps))
def _auto_steps_window(args: dict | None) -> int:
args = args or {}
return max(1, int(args.get("auto_steps_window", 100)))
def _auto_steps_min(args: dict | None, *, window: int) -> int:
args = args or {}
return max(1, int(args.get("auto_steps_min", 2 * int(window))))
def _auto_steps_rel_threshold(args: dict | None) -> float:
args = args or {}
raw = args.get("auto_steps_rel_threshold", args.get("auto_steps_rel_tol", 1.0e-4))
return max(0.0, float(raw))
def _auto_steps_relative_improvement(history: list[float], *, window: int) -> float:
if len(history) <= int(window):
return math.inf
before = history[:-int(window)]
recent = history[-int(window):]
if not before or not recent:
return math.inf
best_before = min(float(v) for v in before)
best_recent = min(float(v) for v in recent)
return (best_before - best_recent) / max(abs(best_before), 1.0e-12)
def _auto_steps_should_stop(history: list[float], *, window: int, rel_threshold: float) -> bool:
return _auto_steps_relative_improvement(history, window=window) < float(rel_threshold)
def _lr_warmup_steps(args: dict | None) -> int:
args = args or {}
raw = args.get("lr_warmup_steps", args.get("warmup_steps", 0))
return max(0, int(raw))
def _lr_warmup_factor(*, step1: int, warmup_steps: int) -> float:
warmup_steps = max(0, int(warmup_steps))
if warmup_steps <= 0:
return 1.0
return min(1.0, max(0.0, float(step1) / float(warmup_steps)))
def _capture_optimizer_target_lrs(opt: torch.optim.Optimizer) -> None:
for group in opt.param_groups:
group.setdefault("_target_lr", float(group.get("lr", 0.0)))
def _apply_optimizer_lr_warmup(opt: torch.optim.Optimizer, *, step1: int, warmup_steps: int) -> None:
if int(warmup_steps) <= 0:
return
scale = _lr_warmup_factor(step1=int(step1), warmup_steps=int(warmup_steps))
for group in opt.param_groups:
target_lr = float(group.setdefault("_target_lr", float(group.get("lr", 0.0))))
group["lr"] = target_lr * scale
def _flatten_max_update_base(args: dict | None) -> float:
if args is None:
return 0.1
return float(args.get("flatten_max_update", 0.1))
def _clamp_flatten_map_ms_update(
params: list[torch.nn.Parameter],
before: list[torch.Tensor],
*,
base_step: float,
) -> None:
base = float(base_step)
if base <= 0.0:
return
with torch.no_grad():
for scale_i, (p, prev) in enumerate(zip(params, before)):
if p.shape != prev.shape:
continue
max_step = base * (2.0 ** int(scale_i))
delta = p - prev
if delta.ndim >= 1 and int(delta.shape[0]) == 2:
norm = torch.linalg.vector_norm(delta, dim=0, keepdim=True)
scale = (float(max_step) / norm.clamp_min(1.0e-12)).clamp_max(1.0)
p.copy_(prev + delta * scale)
else:
p.copy_(prev + delta.clamp(min=-float(max_step), max=float(max_step)))
def _renorm_forward_flatten_map_step(model) -> dict[str, float]:
"""Rescale a forward flatten UV map so avg physical voxels per UV pixel hits target."""
if not bool(getattr(model, "flatten_enabled", False)):
return {}
if str(getattr(model, "flatten_direction", "inverse")).strip().lower() != "forward":
return {}
if not hasattr(model, "flatten_map") or not hasattr(model, "flatten_map_ms"):
return {}
with torch.no_grad():
uv = model.flatten_map()
xyz = getattr(model, "flatten_source_xyz", None)
valid = getattr(model, "flatten_source_valid", None)
cell_valid = getattr(model, "flatten_source_cell_valid", None)
target_t = getattr(model, "flatten_target_step", None)
if xyz is None or valid is None or cell_valid is None or target_t is None:
return {}
if uv.ndim != 3 or xyz.ndim != 3 or int(uv.shape[-1]) != 2 or int(xyz.shape[-1]) != 3:
return {}
if tuple(uv.shape[:2]) != tuple(xyz.shape[:2]) or tuple(valid.shape) != tuple(uv.shape[:2]):
return {}
if tuple(cell_valid.shape) != (max(0, int(uv.shape[0]) - 1), max(0, int(uv.shape[1]) - 1)):
return {}
target_step = float(target_t.detach().cpu())
if not math.isfinite(target_step) or target_step <= 0.0:
return {}
valid_t = (
valid.to(device=uv.device, dtype=torch.bool)
& torch.isfinite(uv).all(dim=-1)
& torch.isfinite(xyz).all(dim=-1)
)
row_edge_valid, col_edge_valid, diag00_valid, diag01_valid = opt_loss_flatten._retained_source_edge_masks(
valid_t,
cell_valid.to(device=uv.device, dtype=torch.bool),
)
sum_ratio = uv.new_zeros(())
sum_weight = uv.new_zeros(())
def _accumulate(delta_uv: torch.Tensor, delta_xyz: torch.Tensor, mask: torch.Tensor) -> None:
nonlocal sum_ratio, sum_weight
uv_len = torch.linalg.vector_norm(delta_uv, dim=-1)
phys_len = torch.linalg.vector_norm(delta_xyz, dim=-1)
ok = mask & torch.isfinite(uv_len) & torch.isfinite(phys_len) & (uv_len > 1.0e-8) & (phys_len > 0.0)
mask_f = ok.to(dtype=uv.dtype)
sum_ratio = sum_ratio + ((phys_len / uv_len) * mask_f).sum()
sum_weight = sum_weight + mask_f.sum()
if int(uv.shape[0]) > 1:
_accumulate(
uv[1:, :] - uv[:-1, :],
xyz[1:, :] - xyz[:-1, :],
row_edge_valid & valid_t[1:, :] & valid_t[:-1, :],
)
if int(uv.shape[1]) > 1:
_accumulate(
uv[:, 1:] - uv[:, :-1],
xyz[:, 1:] - xyz[:, :-1],
col_edge_valid & valid_t[:, 1:] & valid_t[:, :-1],
)
if int(uv.shape[0]) > 1 and int(uv.shape[1]) > 1:
_accumulate(
uv[1:, 1:] - uv[:-1, :-1],
xyz[1:, 1:] - xyz[:-1, :-1],
diag00_valid & valid_t[1:, 1:] & valid_t[:-1, :-1],
)
_accumulate(
uv[1:, :-1] - uv[:-1, 1:],
xyz[1:, :-1] - xyz[:-1, 1:],
diag01_valid & valid_t[1:, :-1] & valid_t[:-1, 1:],
)
if not bool((sum_weight > 0).detach().cpu()):
return {}
current_step = float((sum_ratio / sum_weight.clamp_min(1.0)).detach().cpu())
if not math.isfinite(current_step) or current_step <= 0.0:
return {}
scale = current_step / target_step
if not math.isfinite(scale) or scale <= 0.0:
return {}
if abs(scale - 1.0) <= 1.0e-6:
return {
"flatten_renorm_step_before": current_step,
"flatten_renorm_step_after": current_step,
"flatten_renorm_scale": 1.0,
}
center_mask = valid_t
center_weight = center_mask.to(dtype=uv.dtype).sum()
if not bool((center_weight > 0).detach().cpu()):
return {}
center = (uv * center_mask.unsqueeze(-1).to(dtype=uv.dtype)).sum(dim=(0, 1)) / center_weight.clamp_min(1.0)
renorm_uv = center + (uv - center) * float(scale)
flat = renorm_uv.permute(2, 0, 1).unsqueeze(1).contiguous()
new_pyr = fit_model.Model3D._construct_pyramid_from_flat_3d(
flat,
len(model.flatten_map_ms),
pyramid_d=False,
)
if len(new_pyr) != len(model.flatten_map_ms):
return {}
for dst, src in zip(model.flatten_map_ms, new_pyr, strict=True):
if tuple(dst.shape) != tuple(src.shape):
return {}
for dst, src in zip(model.flatten_map_ms, new_pyr, strict=True):
dst.copy_(src.to(device=dst.device, dtype=dst.dtype))
return {
"flatten_renorm_step_before": current_step,
"flatten_renorm_step_after": target_step,
"flatten_renorm_scale": float(scale),
"flatten_grid_step_avg": target_step,
}
def _clear_optimizer_state_for_params(opt: torch.optim.Optimizer, params: list[torch.nn.Parameter]) -> None:
for p in params:
opt.state.pop(p, None)
def check_data_bounds(model, data: fit_data.FitData3D, margin: float = 100.0,
volume_extent_fullres: tuple[int, int, int] | None = None) -> bool:
"""Return True if any mesh vertex is within `margin` fullres voxels of the data border.
Skips edges where the loaded data already reaches the volume boundary.
"""
with torch.no_grad():
xyz = model._grid_xyz() # (D, Hm, Wm, 3)
mesh_min = [float(xyz[..., i].min()) for i in range(3)]
mesh_max = [float(xyz[..., i].max()) for i in range(3)]
Z, Y, X = data.size
# Data extent in fullres: (x, y, z)
data_min = list(data.origin_fullres)
data_max = [
data.origin_fullres[0] + (X - 1) * data.spacing[0],
data.origin_fullres[1] + (Y - 1) * data.spacing[1],
data.origin_fullres[2] + (Z - 1) * data.spacing[2],
]
# Full volume max per axis (x, y, z)
if volume_extent_fullres is not None:
vol_max = [float(volume_extent_fullres[0]),
float(volume_extent_fullres[1]),
float(volume_extent_fullres[2])]