File size: 66,248 Bytes
a0d1de2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
#!/usr/bin/env python
"""Headline fragility-prediction results on the repaired estimand.

Everything the retracted numbers got wrong is closed off here by construction:

* the target is the conditional break rate on the **solvable stratum** (and its
  dose-response parameters), not a ``max`` capped by base correctness;
* the split is **three-way** with a fingerprint, and the model is trained inside
  this process on the train fold only -- there is no ``--checkpoint`` path that
  could smuggle in weights fit on the test fold;
* epochs are chosen by **early stopping on the validation fold**, never on test;
* the ceiling is the **parametric-bootstrap** reliability, not Spearman-Brown on
  an order statistic;
* every number is reported over several seeds with a spread;
* the surface-feature baseline and the measured-base-correctness reference are
  reported alongside, so a headline that merely rediscovers length or solvability
  is visible as such.

Two protocols are reported separately and never merged. ``text`` uses the
problem statement only. ``text_probe`` adds ex-ante probe features from repeated
samples of the *base* prompt (no twin is ever run), which requires model access
and is therefore a different claim.

Usage
-----
    python scripts/fragility_report.py --dataset gsmic_adv --seeds 0,1,2
    python scripts/fragility_report.py --dataset math_adv --featurizer tfidf_svd
    python scripts/fragility_report.py --dataset gsmic_adv --protocol both \\
        --probe-file outputs_probes/gsmic_adv/base_probes.json
"""
from __future__ import annotations

import argparse
import gc
import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))

import numpy as np
import torch
from scipy.stats import spearmanr

from causal_difficulty.baselines.bertpe import BERTPEBaseline
from causal_difficulty.baselines.pi_adapters import bertpe_job_pairs, vap3_twin_pairs
from causal_difficulty.baselines.vap3 import VAP3Baseline
from causal_difficulty.eval.deconfound import (
    cross_fitted_residual,
    explained_variance_drop,
    null_head_negative_control,
    orthogonality_diagnostics,
    predict_m,
    stratified_rank_correlation,
)
from causal_difficulty.eval.estimands import (
    FAMILIES,
    build_job_targets,
    dose_from_operator,
)
from causal_difficulty.eval.loading import load_pairs
from causal_difficulty.eval.metrics import all_metrics, deconfounding_probe
from causal_difficulty.eval.reliability import parametric_reliability
from causal_difficulty.eval.splits import three_way_split
from causal_difficulty.features import probes as probe_feats
from causal_difficulty.features.surface import (
    SURFACE_FEATURE_NAMES,
    declared_proxy_scores,
    out_of_fold_predictions,
    surface_baseline_predictions,
    surface_matrix,
)
from causal_difficulty.features.text import TextFeaturizer
from causal_difficulty.models.fragility import (
    FragilityModel,
    TrainConfig,
    dose_response_from_grid,
    expected_mean,
)
from causal_difficulty.models.fragility_encoder import (
    EncoderFragilityModel,
    EncoderTrainConfig,
)

ROOT = Path(__file__).resolve().parents[1]

# Backbones whose whole point is gradient-based adaptation to the break-
# probability objective: routed through EncoderFragilityModel (joint
# encoder+head training) instead of the precomputed-feature TextFeaturizer
# path every other --featurizer value uses. See fragility_encoder.py's
# module docstring for why a frozen/precomputed split doesn't make sense here.
TRAINABLE_ENCODER_BACKBONES = ("hf_lora", "hf_finetune")


def _origin(base_id: str) -> str:
    """``<dataset>-<index>`` -> ``<dataset>``, so a pooled ``--dataset`` spec
    spanning multiple suites (e.g. every gsmic_adv_* and math_adv_* file in one
    run) can still be scored per-suite, not just on the mixed pool."""
    return base_id.rsplit("-", 1)[0]


def _rho(a, b) -> float:
    a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
    ok = np.isfinite(a) & np.isfinite(b)
    if ok.sum() < 3 or np.std(a[ok]) < 1e-12 or np.std(b[ok]) < 1e-12:
        return float("nan")
    return float(spearmanr(a[ok], b[ok]).statistic)


def _mean_sd(vals: list[float]) -> tuple[float, float]:
    arr = np.asarray([v for v in vals if np.isfinite(v)], dtype=float)
    if len(arr) == 0:
        return float("nan"), float("nan")
    return float(arr.mean()), float(arr.std())


def _mean_sd_dict(dicts: list[dict[str, float]]) -> dict[str, dict[str, float]]:
    """Mean+-sd over seeds for every scalar key present in every dict in
    ``dicts`` (the ``metrics``/``orthogonality_*``/``r2_drop``/null-head-row
    sub-dicts returned per seed by :mod:`eval.deconfound`)."""
    keys = dicts[0].keys()
    out: dict[str, dict[str, float]] = {}
    for k in keys:
        vals = [d[k] for d in dicts if isinstance(d.get(k), (int, float))]
        m, s = _mean_sd(vals)
        out[k] = {"mean": m, "sd": s}
    return out


def _free_device_memory(device: str | None) -> None:
    """Best-effort release of a just-dropped model's device memory.

    Purely a memory-management helper -- it only affects *when* memory is
    reclaimed, never any computed value. Needed because torch's MPS/CUDA
    caching allocators do not return memory to the shared pool just because
    the Python object holding it was ``del``-ed; the caller must ``del`` the
    model first (dropping its refcount to zero) and then call this so the
    allocator actually frees it before the next model is instantiated.
    """
    gc.collect()
    if device == "mps" and torch.backends.mps.is_available():
        torch.mps.empty_cache()
    elif device == "cuda" and torch.cuda.is_available():
        torch.cuda.empty_cache()


def _seed_cache_path(out_dir: Path, seed: int, proto: str) -> Path:
    return out_dir / "seeds" / f"seed_{seed}" / f"{proto}.json"


def _load_seed_cache(path: Path) -> dict | None:
    if path.is_file():
        return json.loads(path.read_text())
    return None


def _save_seed_cache(path: Path, res: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(res, indent=2))


def _collect_seed_results(out_dir: Path, proto: str, expected_seeds: list[int],
                          fresh: list[dict]) -> tuple[list[dict], list[int]]:
    """Merge in-memory results with on-disk per-seed caches; return missing."""
    by_seed = {r["seed"]: r for r in fresh}
    for seed in expected_seeds:
        if seed in by_seed:
            continue
        cached = _load_seed_cache(_seed_cache_path(out_dir, seed, proto))
        if cached is not None:
            by_seed[seed] = cached
    missing = [s for s in expected_seeds if s not in by_seed]
    runs = [by_seed[s] for s in sorted(by_seed) if s in expected_seeds]
    return runs, missing


def _aggregate_dperp_diagnostics(runs: list[dict]) -> dict:
    """Seed-aggregated tab:c2 diagnostic suite for the (pi, declared surface
    proxy) pairing: same columns/controls ``paper_supports_real.py`` reports
    for the D_avg/y_base_mean pairing, applied to this script's D^perp block."""
    dperps = [r["dperp"] for r in runs]
    null_heads = [d["null_head"] for d in dperps]
    return {
        "metrics": _mean_sd_dict([d["metrics"] for d in dperps]),
        "orthogonality_target": _mean_sd_dict([d["orthogonality_target"] for d in dperps]),
        "orthogonality_pred": _mean_sd_dict([d["orthogonality_pred"] for d in dperps]),
        "r2_drop": _mean_sd_dict([d["r2_drop"] for d in dperps]),
        "stratified_rank_weighted_spearman": dict(zip(
            ("mean", "sd"), _mean_sd([d["stratified_rank"]["weighted_mean_spearman"] for d in dperps]))),
        "null_head_constant": _mean_sd_dict([nh["constant_head"] for nh in null_heads]),
        "null_head_shuffled_mean": _mean_sd_dict([nh["shuffled_head_mean"] for nh in null_heads]),
        "n_shuffle_repeats": null_heads[0]["n_repeats"],
    }


def _fmt(v: float) -> str:
    return "n/a" if v is None or not np.isfinite(v) else f"{v:.3f}"


def _dperp_diagnostics_lines(diag: dict) -> list[str]:
    m, ot, op = diag["metrics"], diag["orthogonality_target"], diag["orthogonality_pred"]
    r2, strat = diag["r2_drop"], diag["stratified_rank_weighted_spearman"]
    ct, sh = diag["null_head_constant"], diag["null_head_shuffled_mean"]
    lines = [
        "",
        "### D^perp C2 diagnostics (pi residualized against the declared surface proxy)",
        "",
        "Same tab:c2 columns as the D_avg/y_base_mean pairing, applied to this "
        "script's repaired-estimand D^perp block, mean +/- sd over seeds.",
        "",
        "| Quantity | value |",
        "| --- | --- |",
        f"| Spearman(D^perp_hat, D^perp) | {_fmt(m['spearman']['mean'])} ± {_fmt(m['spearman']['sd'])} |",
        f"| MAE | {_fmt(m['mae']['mean'])} ± {_fmt(m['mae']['sd'])} |",
        f"| NDCG@10 | {_fmt(m['ndcg@10']['mean'])} ± {_fmt(m['ndcg@10']['sd'])} |",
        f"| \\|rho_C\\| (pred vs proxy) | {_fmt(m['deconfound_|rho_C|']['mean'])} ± {_fmt(m['deconfound_|rho_C|']['sd'])} |",
        f"| Corr(target, C) | {_fmt(ot['corr_D_perp_C']['mean'])} ± {_fmt(ot['corr_D_perp_C']['sd'])} |",
        f"| Corr(pred, C) | {_fmt(op['corr_D_perp_C']['mean'])} ± {_fmt(op['corr_D_perp_C']['sd'])} |",
        f"| Corr(pred, C^2) | {_fmt(op['corr_D_perp_C2']['mean'])} ± {_fmt(op['corr_D_perp_C2']['sd'])} |",
        f"| R^2-drop (before -> after) | {_fmt(r2['r2_before']['mean'])} -> {_fmt(r2['r2_after']['mean'])} "
        f"(drop {_fmt(r2['r2_drop']['mean'])}) |",
        f"| Complexity-stratified weighted Spearman | {_fmt(strat['mean'])} ± {_fmt(strat['sd'])} |",
        "",
        "Shared-term controls (constant head / shuffled head, "
        f"{diag['n_shuffle_repeats']} repeats, -m_pred(C) retained, scored "
        "against the real D^perp target):",
        "",
        "| Row | rho_S | MAE | NDCG@10 | Corr(pred,C) | Corr(pred,C^2) |",
        "| --- | --- | --- | --- | --- | --- |",
        f"| constant head | {_fmt(ct['spearman']['mean'])} | {_fmt(ct['mae']['mean'])} | "
        f"{_fmt(ct['ndcg@10']['mean'])} | {_fmt(ct['corr_c']['mean'])} | {_fmt(ct['corr_c2']['mean'])} |",
        f"| shuffled head (mean) | {_fmt(sh['spearman']['mean'])} ± {_fmt(sh['spearman']['sd'])} | "
        f"{_fmt(sh['mae']['mean'])} | {_fmt(sh['ndcg@10']['mean'])} | {_fmt(sh['corr_c']['mean'])} | "
        f"{_fmt(sh['corr_c2']['mean'])} |",
        "",
    ]
    return lines


def build_features(
    jobs,
    train_ids: set[str],
    *,
    featurizer: str,
    protocol: str,
    probe_file: str | None,
    dim: int,
    seed: int,
    hf_model: str | None = None,
    device: str | None = None,
    hf_batch_size: int | None = None,
    cache_dir: str | None = None,
    max_concurrency: int | None = None,
) -> tuple[np.ndarray, list[str], dict]:
    """Job feature matrix. Text representations are fit on the train fold only.

    For a trainable-encoder backbone (``hf_lora``/``hf_finetune``) the text
    block is intentionally omitted: those encoders adapt jointly with the
    break-probability head inside ``EncoderFragilityModel.fit``, so there is
    no fixed text representation to precompute here -- see
    ``TRAINABLE_ENCODER_BACKBONES``. The returned matrix then holds only the
    static (surface + probe) features that model concatenates onto its own
    per-step embeddings.
    """
    texts = [j.base_text for j in jobs]
    X_surface = surface_matrix(texts)
    info: dict = {"featurizer": featurizer}

    if featurizer in TRAINABLE_ENCODER_BACKBONES:
        blocks = [X_surface]
        names = list(SURFACE_FEATURE_NAMES)
    else:
        train_texts = [j.base_text for j in jobs if j.base_id in train_ids]
        tf = TextFeaturizer(featurizer, dim=dim, seed=seed, model_name=hf_model,
                            device=device, batch_size=hf_batch_size,
                            cache_dir=cache_dir, max_concurrency=max_concurrency)
        X_text = tf.fit_transform(train_texts, texts)
        blocks = [X_text, X_surface]
        names = [f"text_{i}" for i in range(X_text.shape[1])] + list(SURFACE_FEATURE_NAMES)
        info["text_dim"] = int(X_text.shape[1])

    if protocol == "text_measured":
        # k actually-measured twins at the cheapest dose, withheld from every
        # target in build_job_targets. This is not an ex-ante protocol: it buys
        # a little measurement to rank the expensive full-family target.
        n_probe = np.asarray([[float(j.n_probe_obs)] for j in jobs])
        rate = np.asarray([[float(j.probe_break_rate)] for j in jobs])
        # Laplace-smoothed logit of the small-sample rate: k=2 twins give rates
        # in {0, .5, 1}, and the raw value sends 0 and 1 to infinity downstream.
        smooth = (rate * n_probe + 0.5) / (n_probe + 1.0)
        mean_dose = np.asarray([[float(j.probe_mean_dose)] for j in jobs])
        blocks += [rate, smooth, np.log(smooth / (1.0 - smooth)), n_probe, mean_dose]
        names += ["probe_break_rate", "probe_rate_smoothed",
                  "probe_rate_logit", "probe_n_obs", "probe_mean_dose"]
        info["measured_probe_obs"] = float(np.mean([j.n_probe_obs for j in jobs]))
        info["measured_probe_mean_dose"] = float(
            np.nanmean([j.probe_mean_dose for j in jobs]))

    if protocol == "text_probe":
        X_free, free_names = probe_feats.probe_features_from_targets(jobs)
        blocks.append(X_free)
        names += list(free_names)
        info["free_probes"] = list(free_names)
        if probe_file:
            X_s, s_names, covered = probe_feats.probe_features_from_samples(
                jobs, probe_file)
            if covered < 0.95 * len(jobs):
                raise SystemExit(
                    f"probe file covers only {covered}/{len(jobs)} jobs; refusing to "
                    f"report a probe protocol on that coverage")
            blocks.append(X_s)
            names += list(s_names)
            info["sampled_probes"] = list(s_names)
            info["probe_coverage"] = covered

    return np.hstack(blocks), names, info


def run_seed(
    jobs,
    *,
    seed: int,
    featurizer: str,
    protocol: str,
    probe_file: str | None,
    dim: int,
    cfg: TrainConfig,
    val_frac: float,
    test_frac: float,
    encoder_cfg: EncoderTrainConfig | None = None,
    hf_model: str | None = None,
    device: str | None = None,
    hf_batch_size: int | None = None,
    cache_dir: str | None = None,
    max_concurrency: int | None = None,
    lora_r: int = 8,
    lora_alpha: int = 16,
    lora_dropout: float = 0.05,
    include_bertpe_vap3: bool = False,
    bertpe_epochs: int = 3,
    vap3_epochs: int = 3,
    bertpe_vap3_batch_size: int = 16,
    predictions_out: Path | None = None,
    n_shuffled_head_repeats: int = 100,
    n_inits: int = 1,
    encoder_max_length: int | None = None,
    encoder_pooling: str = "mean",
    encoder_base_dtype: str = "float32",
    aux_train_jobs: dict | None = None,
    checkpoint_dir: Path | None = None,
    checkpoint_meta: dict | None = None,
) -> dict:
    """One complete train/select/test cycle at a single split seed."""
    strata = {j.base_id: j.break_rate for j in jobs}
    split = three_way_split([j.base_id for j in jobs], seed=seed, val_frac=val_frac,
                            test_frac=test_frac, strata=strata)
    train_ids, val_ids, test_ids = (set(split.train_ids), set(split.val_ids),
                                   set(split.test_ids))

    X, feat_names, finfo = build_features(
        jobs, train_ids, featurizer=featurizer, protocol=protocol,
        probe_file=probe_file, dim=dim, seed=seed, hf_model=hf_model,
        device=device, hf_batch_size=hf_batch_size, cache_dir=cache_dir,
        max_concurrency=max_concurrency)
    job_index = {j.base_id: i for i, j in enumerate(jobs)}

    tr = [j for j in jobs if j.base_id in train_ids]
    va = [j for j in jobs if j.base_id in val_ids]
    te = [j for j in jobs if j.base_id in test_ids]

    doses = tuple(sorted({int(d) for j in jobs for d in j.doses}))
    if aux_train_jobs and featurizer in TRAINABLE_ENCODER_BACKBONES:
        # Extra supervision for the *train fold only*: swap each train job for
        # its counterpart built from --aux-train-dataset (same base problem,
        # more twins). Validation/test jobs and every reported target stay
        # the --dataset ones, so the evaluation is unchanged.
        tr = [aux_train_jobs.get(j.base_id, j) for j in tr]
    if featurizer in TRAINABLE_ENCODER_BACKBONES:
        from causal_difficulty.encoders import build_encoder_simple

        # n_inits > 1: train that many independently initialized encoder+head
        # models on the *same* split (init seed = seed + 1000*k; k=0 is the
        # single-model run) and average their predicted probabilities. Each
        # member is early-stopped on the validation fold as usual; the
        # ensemble's own validation Spearman is recorded so model selection
        # stays on the validation fold.
        grids, rates_te, rates_tr, rates_va, histories = [], [], [], [], []
        for k in range(max(1, n_inits)):
            if k:
                del model, encoder
                _free_device_memory(device)
            encoder = build_encoder_simple(
                featurizer, model_name=hf_model, device=device,
                max_length=encoder_max_length, pooling=encoder_pooling,
                base_dtype=encoder_base_dtype,
                lora_r=lora_r, lora_alpha=lora_alpha, lora_dropout=lora_dropout)
            model = EncoderFragilityModel(
                encoder, EncoderTrainConfig(**{**(encoder_cfg or EncoderTrainConfig()).__dict__,
                                               "seed": seed + 1000 * k})).fit(
                X, tr, va, job_index)
            grids.append(model.predict_dose_grid(X, te, job_index, doses))
            rates_te.append(model.predict_break_rate(X, te, job_index))
            if checkpoint_dir is not None:
                checkpoint_dir.mkdir(parents=True, exist_ok=True)
                ckpt = model.checkpoint()
                ckpt.update(checkpoint_meta or {})
                ckpt.update({
                    "featurizer": featurizer, "hf_model": hf_model, "protocol": protocol,
                    "seed": seed, "init": k, "n_inits": max(1, n_inits),
                    "encoder_max_length": encoder_max_length,
                    "encoder_pooling": encoder_pooling, "lora_r": lora_r,
                    "encoder_base_dtype": encoder_base_dtype,
                    "lora_alpha": lora_alpha, "lora_dropout": lora_dropout,
                    "probe_file": probe_file, "feature_names": list(feat_names),
                    "split": {"train": sorted(train_ids), "val": sorted(val_ids),
                              "test": sorted(test_ids)},
                    "test_base_ids": [j.base_id for j in te],
                    "test_pred_break_rate": rates_te[-1].tolist(),
                    "val_spearman": model.history.best_val_spearman,
                    "test_spearman": _rho(rates_te[-1], np.asarray([j.break_rate for j in te])),
                })
                torch.save(ckpt, checkpoint_dir / f"{protocol}_seed{seed}_init{k}.pt")
            rates_tr.append(model.predict_break_rate(X, tr, job_index))
            rates_va.append(model.predict_break_rate(X, va, job_index))
            histories.append(model.history.to_dict())
        grid_te = np.mean(grids, axis=0)
        pred_rate = np.mean(rates_te, axis=0)
        pred_rate_tr = np.mean(rates_tr, axis=0)
        model_history = histories[0]
        if len(histories) > 1:
            model_history = {
                **histories[0],
                "best_val_spearman": _rho(np.mean(rates_va, axis=0),
                                          np.asarray([j.break_rate for j in va])),
                "member_best_val_spearman": [h["best_val_spearman"] for h in histories],
                "member_best_epochs": [h["best_epoch"] for h in histories],
                "n_inits": len(histories),
            }
    else:
        model = FragilityModel(TrainConfig(**{**cfg.__dict__, "seed": seed})).fit(
            X, tr, va, job_index)
        grid_te = model.predict_dose_grid(X, te, job_index, doses)
        pred_rate = model.predict_break_rate(X, te, job_index)
        pred_rate_tr = model.predict_break_rate(X, tr, job_index)
        model_history = model.history.to_dict()

    pred_a, pred_b = dose_response_from_grid(grid_te, doses)
    pred_davg = expected_mean(pred_rate)

    tgt = {
        "break_rate": np.asarray([j.break_rate for j in te]),
        "break_rate_shrunk": np.asarray([j.break_rate_shrunk for j in te]),
        "a": np.asarray([j.a for j in te]),
        "b": np.asarray([j.b for j in te]),
        "d_avg": np.asarray([j.d_avg for j in te]),
    }
    pred = {
        "break_rate": pred_rate,
        "break_rate_shrunk": pred_rate,
        "a": pred_a,
        "b": pred_b,
        "d_avg": pred_davg,
    }

    # --- reference rows ---------------------------------------------------
    X_surf_all = surface_matrix([j.base_text for j in jobs])
    idx_tr = np.asarray([job_index[j.base_id] for j in tr])
    idx_te = np.asarray([job_index[j.base_id] for j in te])
    y_tr_rate = np.asarray([j.break_rate for j in tr])

    surf_pred = surface_baseline_predictions(
        X_surf_all[idx_tr], y_tr_rate, X_surf_all[idx_te], seed=seed)
    complexity_te = np.asarray([j.complexity_score for j in te])
    ybase_te = np.asarray([j.y_base for j in te])

    # Same inputs as the model, but regressing the job-level target directly
    # instead of predicting per-observation break events. Isolates what the BCE
    # reformulation contributes from what the representation contributes.
    joblevel_pred = surface_baseline_predictions(X[idx_tr], y_tr_rate, X[idx_te],
                                                seed=seed)

    rows = {
        "model": {k: _rho(pred[k], tgt[k]) for k in tgt},
        "same_features_joblevel_regression": {k: _rho(joblevel_pred, tgt[k]) for k in tgt},
        "surface_features": {k: _rho(surf_pred, tgt[k]) for k in tgt},
        "declared_complexity_only": {k: _rho(complexity_te, tgt[k]) for k in tgt},
        "measured_base_correctness": {k: _rho(ybase_te, tgt[k]) for k in tgt},
    }
    extra_preds = {
        "model": pred_rate, "same_features_joblevel_regression": joblevel_pred,
        "surface_features": surf_pred, "declared_complexity_only": complexity_te,
        "measured_base_correctness": ybase_te,
    }

    # --- BERTPE/VAP3: re-implementations of two published sensitivity
    # predictors, retargeted from D_wc (which S5.1's measurement audit shows is
    # degenerate) to the repaired break rate pi -- see baselines/pi_adapters.py
    # for exactly how. Expensive (both fine-tune bert-base-uncased), so opt-in.
    bertpe_pred = vap3_pred = None
    if include_bertpe_vap3:
        # Memory management only (no effect on any computed number): the main
        # model above is done contributing anything derived from its live
        # torch parameters (its predictions are already extracted into numpy
        # arrays, and `model_history` above already pulled the one attribute
        # still needed later). BERTPE and VAP3 each instantiate their own
        # full bert-base-uncased; on a unified-memory (MPS) device the three
        # models' caching-allocator footprints stack rather than reusing
        # freed space unless explicitly released, which OOM'd here in
        # practice. Dropping the reference and emptying the allocator cache
        # before the next model loads keeps peak memory to one model at a
        # time instead of three.
        if featurizer in TRAINABLE_ENCODER_BACKBONES:
            del model, encoder
            _free_device_memory(device)

        bertpe = BERTPEBaseline(device=device, epochs=bertpe_epochs,
                                batch_size=bertpe_vap3_batch_size).fit(
            bertpe_job_pairs(tr), target_attr="pi")
        bertpe_pred = bertpe.predict_job_difficulty([j.base_text for j in te])
        del bertpe
        _free_device_memory(device)

        vap3 = VAP3Baseline(device=device, epochs=vap3_epochs,
                            batch_size=bertpe_vap3_batch_size).fit(
            vap3_twin_pairs(tr), target_attr="delta_mean")
        twins_by_base = {j.base_id: list(j.twin_texts) for j in te}
        vap3_pred = vap3.predict_job_difficulty_from_twins(
            [j.base_id for j in te], [j.base_text for j in te], twins_by_base,
            agg="mean")
        del vap3
        _free_device_memory(device)

        rows["bertpe"] = {k: _rho(bertpe_pred, tgt[k]) for k in tgt}
        rows["vap3"] = {k: _rho(vap3_pred, tgt[k]) for k in tgt}
        extra_preds["bertpe"] = bertpe_pred
        extra_preds["vap3"] = vap3_pred

    # --- Extra metrics against the primary target (break rate / pi), for
    # every row above: MAE, NDCG@10, AUROC (median-of-target fragile cutoff).
    # Spearman is already in `rows`; this is the rest of Table tab:davg's
    # column set, requested for the repaired estimand too.
    fragile_threshold = float(np.median(tgt["break_rate"])) if len(tgt["break_rate"]) else 0.0
    extra_metrics = {
        name: all_metrics(p, tgt["break_rate"], fragile_threshold, k=10)
        for name, p in extra_preds.items()
    }

    # --- Additive: same metric suite as above, but against d_avg instead of
    # break_rate/pi -- matching Table tab:synth2's column semantics
    # (paper_supports_synth2.py's _write_avg_table: all_metrics(pred,
    # measured_avg_hold, threshold) + deconfounding_probe(pred,
    # complexity_hold)), so a Synth-CD-2-FrailPi row can be reported with
    # the identical column set as the existing Frail-tau rows. This block is
    # purely additive: it does not read or modify any variable used by the
    # existing `extra_metrics` / `rows` / `dperp` computations above.
    davg_threshold = float(np.median(tgt["d_avg"])) if len(tgt["d_avg"]) else 0.0
    davg_metrics = {
        name: all_metrics(p, tgt["d_avg"], davg_threshold, k=10)
        for name, p in extra_preds.items()
    }
    for name, p in extra_preds.items():
        davg_metrics[name]["deconfound_|rho_C|"] = deconfounding_probe(p, complexity_te)

    # --- D^perp: residualize against the declared surface proxy -----------
    # The proxy is fit on train only, then frozen; the target side residualizes
    # with that proxy across disjoint folds and the predictor side is cross-fitted
    # within the test fold, so no fold contributes to its own residualization.
    # c_tr must itself be out-of-fold: querying the train-fit proxy on its own
    # training rows (as this used to do) returns in-sample, overfit values, and
    # fitting predict_m's isotonic m(C) on that near-degenerate (c_tr, y_tr_rate)
    # pair produces an m_hat that overshoots badly once applied to the honestly
    # out-of-fold c_te -- manufacturing a large spurious negative Corr(target, C)
    # that isn't present in the raw, uncontaminated data (see Appendix, C2 erratum).
    c_tr = out_of_fold_predictions(X_surf_all[idx_tr], y_tr_rate, n_folds=5, seed=seed)
    c_te = declared_proxy_scores(X_surf_all[idx_tr], y_tr_rate, X_surf_all[idx_te],
                                 seed=seed)
    dperp_target = tgt["break_rate"] - predict_m(c_tr, y_tr_rate, c_te)
    dperp_pred, _ = cross_fitted_residual(c_te, pred_rate, n_folds=5, seed=seed)
    dperp_surf, _ = cross_fitted_residual(c_te, surf_pred, n_folds=5, seed=seed)
    dperp: dict = {
        "model": _rho(dperp_pred, dperp_target),
        "surface_features": _rho(dperp_surf, dperp_target),
        "spearman_target_vs_proxy": _rho(tgt["break_rate"], c_te),
    }
    if include_bertpe_vap3:
        dperp_bertpe, _ = cross_fitted_residual(c_te, bertpe_pred, n_folds=5, seed=seed)
        dperp_vap3, _ = cross_fitted_residual(c_te, vap3_pred, n_folds=5, seed=seed)
        dperp["bertpe"] = _rho(dperp_bertpe, dperp_target)
        dperp["vap3"] = _rho(dperp_vap3, dperp_target)

    # --- C2 diagnostics on this (pi, declared surface proxy) pairing --------
    # Same tab:c2 columns/controls as paper_supports_real.py computes for the
    # D_avg/y_base_mean pairing, applied here instead to the D^perp block
    # above. `orthogonality_diagnostics` on the *target* checks the near-
    # mechanical Corr(D^perp,C)~0 sanity check (Prop. orthogonality); the two
    # non-vacuous diagnostics are `explained_variance_drop` (R^2-drop of the
    # prediction on C, before vs after residualization) and
    # `stratified_rank_correlation` (Spearman within narrow C strata, where
    # the shared -m_hat(C) term is ~constant). `null_head_negative_control`
    # replaces the head with something carrying zero genuine per-job signal
    # and puts it through the identical fit-and-subtract mechanics. `fix_leakage`
    # is left at its default (cross-fit m_pred within the holdout) because
    # `dperp_pred` above is already computed that way (`cross_fitted_residual`
    # on `c_te`, not a train-fold `predict_m`), so the control must match.
    dperp_threshold = float(np.median(dperp_target)) if len(dperp_target) else 0.0
    dperp_metrics = all_metrics(dperp_pred, dperp_target, dperp_threshold, k=10)
    dperp_metrics["deconfound_|rho_C|"] = deconfounding_probe(dperp_pred, c_te)
    dperp["metrics"] = dperp_metrics
    dperp["orthogonality_target"] = orthogonality_diagnostics(dperp_target, c_te)
    dperp["orthogonality_pred"] = orthogonality_diagnostics(dperp_pred, c_te)
    dperp["r2_drop"] = explained_variance_drop(pred_rate, dperp_pred, c_te, seed=seed)
    dperp["stratified_rank"] = stratified_rank_correlation(
        dperp_pred, dperp_target, c_te, n_strata=5)
    dperp["null_head"] = null_head_negative_control(
        pred_rate_tr, pred_rate, c_tr, c_te, dperp_target,
        n_shuffle_repeats=n_shuffled_head_repeats, seed=seed, fix_leakage=True)

    rates_te = np.asarray([j.break_rate_shrunk for j in te])
    counts_te = np.asarray([j.n_obs for j in te])
    ceiling = parametric_reliability(rates_te, counts_te, agg="mean", seed=seed)

    # --- per-origin breakdown: only informative when `--dataset` pooled more
    # than one suite (see _origin); a single-suite run collapses to one group
    # and this is skipped downstream rather than printed as a no-op.
    origins = np.asarray([_origin(j.base_id) for j in te])
    by_origin: dict[str, dict] = {}
    for origin in sorted(set(origins)):
        mask = origins == origin
        if mask.sum() < 3:
            continue
        by_origin[origin] = {
            "n_test": int(mask.sum()),
            "break_rate": _rho(pred_rate[mask], tgt["break_rate"][mask]),
            "a": _rho(pred_a[mask], tgt["a"][mask]),
            "b": _rho(pred_b[mask], tgt["b"][mask]),
        }

    if predictions_out is not None:
        predictions_out.parent.mkdir(parents=True, exist_ok=True)
        predictions_out.write_text(json.dumps({
            "seed": seed,
            "base_id": [j.base_id for j in te],
            "pred_break_rate": pred_rate.tolist(),
            "target_break_rate": tgt["break_rate"].tolist(),
            "target_break_rate_shrunk": tgt["break_rate_shrunk"].tolist(),
        }, indent=2))

    return {
        "seed": seed,
        "split": split.summary(),
        "features": finfo,
        "n_features": int(X.shape[1]),
        "training": model_history,
        "rows": rows,
        "extra_metrics": extra_metrics,
        "d_avg_metrics": davg_metrics,
        "dperp": dperp,
        "ceiling_break_rate": ceiling.to_dict(),
        "by_origin": by_origin,
        "target_stats": {
            "test_break_rate_mean": float(np.mean(tgt["break_rate"])),
            "test_break_rate_sd": float(np.std(tgt["break_rate"])),
            "d_avg_sd": float(np.std(tgt["d_avg"])),
        },
    }


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--dataset", required=True,
                    help="dose family (gsmic_adv, math_adv) or comma-separated files")
    ap.add_argument("--seeds", default="0,1,2")
    ap.add_argument("--featurizer", default="hf_finetune",
                    help="Text representation. Default hf_finetune = Frail-pi with a fully "
                         "fine-tuned DeBERTa-v3-base encoder (use a GPU). For a fast CPU "
                         "smoke run use tfidf_svd.")
    ap.add_argument("--text-dim", type=int, default=256)
    ap.add_argument("--protocol", default="text",
                    choices=("text", "text_probe", "text_measured", "both", "all"))
    ap.add_argument("--reserve-obs", type=int, default=0,
                    help="Withhold this many twins per job from every target and expose "
                         "them as features to the text_measured protocol (required by "
                         "it, ignored otherwise)")
    ap.add_argument("--reserve-mode", default="spread",
                    choices=("spread", "cheapest_dose"),
                    help="spread: reserved twins sampled across all doses, i.e. a budget "
                         "of k twin evaluations spent anywhere. cheapest_dose: confined "
                         "to the lowest dose, cheaper per call but extrapolating in dose")
    ap.add_argument("--probe-file", default=None)
    ap.add_argument("--val-frac", type=float, default=0.15)
    ap.add_argument("--test-frac", type=float, default=0.30)
    ap.add_argument("--max-epochs", type=int, default=200)
    ap.add_argument("--patience", type=int, default=15)
    ap.add_argument("--hidden-dim", type=int, default=256)
    ap.add_argument("--min-obs", type=int, default=4)
    ap.add_argument("--restrict-to-probe-file", action="store_true",
                    help="keep only jobs present in --probe-file, so the text and "
                         "text_probe protocols are compared on identical jobs")
    ap.add_argument("--out-dir", default=None)
    ap.add_argument("--family", action="store_true", dest="use_family",
                    help="thread perturbation family into the break-probability head "
                         "(predict per-family x dose, compose analytically to pi) "
                         "instead of marginalizing over it. Adds family one-hot next "
                         "to the dose features; changes model rows (break_rate/a/b).")
    ap.add_argument("--device", default=None,
                    help="cuda / cuda:0 / cpu, for --featurizer hf_frozen|hf_lora|"
                         "hf_finetune. Default: cuda if visible, else cpu. Restrict to "
                         "specific GPUs with CUDA_VISIBLE_DEVICES rather than this flag "
                         "(hf_frozen/hf_finetune auto-shard across every visible GPU via "
                         "nn.DataParallel; hf_lora runs on the first visible one).")
    ap.add_argument("--hf-model", default=None,
                    help="HF model id for hf_frozen/hf_lora/hf_finetune. Defaults: "
                         "sentence-transformers/all-MiniLM-L6-v2 (hf_frozen), "
                         "BAAI/bge-small-en-v1.5 (hf_lora), microsoft/deberta-v3-base (hf_finetune)")
    ap.add_argument("--hf-batch-size", type=int, default=None,
                    help="hf_frozen: encode() batch size. openai_embed: max API "
                         "batch size (default 512). Raise on a GPU / high-throughput box.")
    ap.add_argument("--cache-dir", default=None,
                    help="openai_embed: on-disk embedding cache directory "
                         "(default: cache/<dataset>)")
    ap.add_argument("--max-concurrency", type=int, default=None,
                    help="openai_embed: parallel API requests (default 64)")
    ap.add_argument("--lora-r", type=int, default=8)
    ap.add_argument("--lora-alpha", type=int, default=16)
    ap.add_argument("--lora-dropout", type=float, default=0.05)
    ap.add_argument("--jobs-per-batch", type=int, default=64,
                    help="hf_lora/hf_finetune only: unique job texts encoded per "
                         "optimizer step (each contributes ~90-100 dose observations)")
    ap.add_argument("--encoder-microbatch", type=int, default=16,
                    help="hf_lora/hf_finetune only: sub-chunk size for the encoder "
                         "forward pass within a job-batch, gradient-accumulated so peak "
                         "activation memory depends on this, not --jobs-per-batch. Lower "
                         "this first if you hit CUDA OOM; bert-base-uncased full "
                         "fine-tuning needs a real GPU at any reasonable value.")
    ap.add_argument("--encoder-lr", type=float, default=2e-5,
                    help="hf_lora/hf_finetune only: LR for the encoder's trainable "
                         "parameters (LoRA adapters, or the whole transformer)")
    ap.add_argument("--head-lr", type=float, default=1e-3,
                    help="hf_lora/hf_finetune only: LR for the break-probability head")
    ap.add_argument("--encoder-max-epochs", type=int, default=30,
                    help="hf_lora/hf_finetune only: separate (smaller) epoch budget from "
                         "--max-epochs, since every epoch here backprops through the "
                         "encoder -- see docs/gsmic_math_adv_rerun_instructions.md")
    ap.add_argument("--encoder-patience", type=int, default=5)
    ap.add_argument("--max-grad-norm", type=float, default=1.0,
                    help="hf_lora/hf_finetune only: clip joint encoder+head "
                         "gradients to this L2 norm (0 disables clipping)")
    ap.add_argument("--lambda-contrast", type=float, default=0.0,
                    help="hf_lora/hf_finetune only: weight of an auxiliary within-job "
                         "contrast term added to the per-observation BCE loss (paper's "
                         "eq:loss contrast supervision, adapted to this single-tower model "
                         "-- there is no second embedding tower to difference here, so the "
                         "contrast is formed between two twins' *predicted* break "
                         "probabilities within the same job, Huber-penalized against their "
                         "*actual* break-indicator difference). 0.0 (default) reproduces "
                         "the plain BCE objective the paper describes for Frail-pi.")
    ap.add_argument("--max-contrast-pairs-per-job", type=int, default=32,
                    help="Cap on how many random within-job twin pairs are sampled per "
                         "job per step for --lambda-contrast > 0.")
    ap.add_argument("--contrast-huber-delta", type=float, default=0.1,
                    help="Huber loss delta for the --lambda-contrast term.")
    ap.add_argument("--loss-mode", default="bce",
                    choices=("bce", "soft_rank", "reliability_weighted"),
                    help="hf_lora/hf_finetune only: training objective. 'bce' (default) "
                         "is the plain per-observation BCE. 'soft_rank' replaces it with "
                         "a differentiable Spearman surrogate on job-level aggregated "
                         "predictions (optimizes rank order directly, since val/test "
                         "selection is already Spearman). 'reliability_weighted' keeps "
                         "BCE but reweights each job's observations by an inverse-"
                         "variance weight from that job's own measured binomial SE.")
    ap.add_argument("--rank-temperature", type=float, default=5.0,
                    help="--loss-mode soft_rank: temperature for the pairwise-sigmoid "
                         "soft-rank operator (lower = closer to hard ranks, higher "
                         "gradient noise).")
    ap.add_argument("--reliability-eps", type=float, default=1e-3,
                    help="--loss-mode reliability_weighted: variance floor added before "
                         "inverting, so near-zero-variance jobs don't get unbounded weight.")
    ap.add_argument("--encoder-lr-schedule", default="constant",
                    choices=("constant", "linear"),
                    help="hf_lora/hf_finetune only: 'linear' = linear warmup over "
                         "--encoder-warmup-frac of the max-epoch step budget, then linear "
                         "decay to 0. 'constant' (default) is the original recipe.")
    ap.add_argument("--encoder-warmup-frac", type=float, default=0.0)
    ap.add_argument("--layer-lr-decay", type=float, default=1.0,
                    help="hf_finetune only: layer-wise LR decay factor (<1 gives lower "
                         "layers smaller LRs); 1.0 (default) is a single encoder LR.")
    ap.add_argument("--encoder-bf16", action="store_true",
                    help="hf_lora/hf_finetune only: bf16 autocast for the encoder forward.")
    ap.add_argument("--encoder-max-length", type=int, default=None,
                    help="hf_finetune/hf_lora only: tokenizer max_length (default: "
                         "the backbone builder's default, 128 for hf_finetune).")
    ap.add_argument("--encoder-pooling", default="mean", choices=("mean", "last"),
                    help="hf_lora only: 'last' = last non-pad token (decoder-LM "
                         "embedders); 'mean' (default) is the original mean pooling.")
    ap.add_argument("--solution-file", default=None,
                    help="text_probe only, hf_lora/hf_finetune only: JSON {base_id: solver "
                         "solution} (scripts/build_solution_texts.py, from the base-probe "
                         "completions cache). The encoder then reads the base problem plus "
                         "that sampled solution; surface features still use the problem "
                         "alone. Raise --encoder-max-length (e.g. 512) with this.")
    ap.add_argument("--aux-train-dataset", default=None,
                    help="hf_lora/hf_finetune only: labeled pairs (e.g. the pooled "
                         "multi-dose corpus) whose job targets replace the train-fold jobs "
                         "of --dataset (same base problems, more twins). Splits, "
                         "validation and test targets are those of --dataset.")
    ap.add_argument("--save-checkpoint", action="store_true",
                    help="hf_lora/hf_finetune only: save every fitted model (head + "
                         "encoder weights in fp16 + feature/split metadata) to "
                         "<out-dir>/checkpoints/<protocol>_seed<k>_init<i>.pt; reload "
                         "with scripts/frailpi_predict_from_checkpoint.py")
    ap.add_argument("--encoder-base-dtype", default="float32",
                    choices=("float32", "bfloat16"),
                    help="hf_lora only: dtype of the frozen base weights (bfloat16 lets "
                         "7-14B decoders fit); LoRA adapters always train in fp32.")
    ap.add_argument("--shuffle-encoder-text", action="store_true",
                    help="control: the trainable encoder reads a *different* job's text "
                         "(fixed random permutation over jobs); surface/probe features keep "
                         "the true job's. Measures what the problem text itself contributes.")
    ap.add_argument("--n-inits", type=int, default=1,
                    help="hf_lora/hf_finetune only: train this many independently "
                         "initialized models per split seed and average their predicted "
                         "break probabilities (each member early-stopped on the validation "
                         "fold). 1 (default) is the single-model run.")
    ap.add_argument("--skip-existing-seeds", action="store_true",
                    help="Skip training for seeds whose per-seed cache exists "
                         "under <out-dir>/seeds/seed_<N>/<protocol>.json")
    ap.add_argument("--allow-partial-summary", action="store_true",
                    help="Write summary.json even when some expected seeds are "
                         "missing (default: refuse to write an incomplete summary)")
    ap.add_argument("--include-bertpe-vap3", action="store_true",
                    help="Add BERTPE/VAP3 (re-implementations of two published sensitivity "
                         "predictors, retargeted to pi -- see baselines/pi_adapters.py) as "
                         "extra baseline rows. Both fine-tune bert-base-uncased end to end; "
                         "expensive, GPU recommended for anything beyond --max-jobs smoke "
                         "testing.")
    ap.add_argument("--bertpe-epochs", type=int, default=3)
    ap.add_argument("--vap3-epochs", type=int, default=3)
    ap.add_argument("--bertpe-vap3-batch-size", type=int, default=16)
    ap.add_argument("--n-shuffled-head-repeats", type=int, default=100,
                    help="D^perp shuffled-head negative control: number of "
                         "random per-job reassignments of the predictor's "
                         "own outputs (tab:c2 shared-term control).")
    ap.add_argument("--max-jobs", type=int, default=None,
                    help="Randomly subsample to this many solvable jobs before splitting "
                         "(e.g. for a fast --include-bertpe-vap3 smoke test on CPU)")
    ap.add_argument("--max-jobs-seed", type=int, default=0)
    ap.add_argument("--dump-predictions", action="store_true",
                    help="Write each seed's test-fold (base_id, pred_break_rate, "
                         "target_break_rate) to <out-dir>/predictions/ so a separate "
                         "run (e.g. a different --featurizer) can be blended with this "
                         "one post hoc -- see scripts/ensemble_fragility.py. Splits are "
                         "deterministic in (--dataset, seed), so two runs with the same "
                         "--dataset and --seeds share test folds even with different "
                         "featurizers.")
    args = ap.parse_args()

    print(f"Loading {args.dataset} ...")
    pairs, paths = load_pairs(args.dataset)
    doses = sorted({d for p in pairs if (d := dose_from_operator(p.operator)) is not None})
    jobs = build_job_targets(pairs, solvable_only=True, min_obs=args.min_obs,
                             reserve_obs=args.reserve_obs,
                             reserve_mode=args.reserve_mode,
                             keep_twin_texts=args.include_bertpe_vap3)
    if args.max_jobs and args.max_jobs < len(jobs):
        import random

        jobs = sorted(random.Random(args.max_jobs_seed).sample(jobs, args.max_jobs),
                      key=lambda j: j.base_id)
        print(f"  --max-jobs: subsampled to {len(jobs)} jobs")
    if args.restrict_to_probe_file:
        if not args.probe_file:
            raise SystemExit("--restrict-to-probe-file requires --probe-file")
        covered = set(probe_feats.read_probe_file(args.probe_file))
        jobs = [j for j in jobs if j.base_id in covered]
        print(f"  restricted to the {len(jobs)} jobs covered by the probe file")
    print(f"  {len(pairs)} pairs -> {len(jobs)} solvable jobs, doses {doses}")
    print(f"  mean observations per job: {np.mean([j.n_obs for j in jobs]):.1f}")

    cfg = TrainConfig(hidden_dim=args.hidden_dim, max_epochs=args.max_epochs,
                      patience=args.patience)
    encoder_cfg = EncoderTrainConfig(
        hidden_dim=args.hidden_dim, jobs_per_batch=args.jobs_per_batch,
        encoder_microbatch=args.encoder_microbatch, encoder_lr=args.encoder_lr,
        head_lr=args.head_lr, max_epochs=args.encoder_max_epochs,
        patience=args.encoder_patience, device=args.device,
        max_grad_norm=args.max_grad_norm, lambda_contrast=args.lambda_contrast,
        max_contrast_pairs_per_job=args.max_contrast_pairs_per_job,
        huber_delta=args.contrast_huber_delta, loss_mode=args.loss_mode,
        rank_temperature=args.rank_temperature, reliability_eps=args.reliability_eps,
        lr_schedule=args.encoder_lr_schedule, warmup_frac=args.encoder_warmup_frac,
        layer_lr_decay=args.layer_lr_decay, bf16=args.encoder_bf16)
    if args.use_family:
        cfg.use_family = True
        cfg.n_families = len(FAMILIES)
        encoder_cfg.use_family = True
        encoder_cfg.n_families = len(FAMILIES)
        print(f"  factorized head: threading {len(FAMILIES)} families into per-observation design")
    if args.protocol == "both":
        protocols = ("text", "text_probe")
    elif args.protocol == "all":
        protocols = ("text", "text_probe", "text_measured")
    else:
        protocols = (args.protocol,)
    if "text_measured" in protocols and args.reserve_obs <= 0:
        raise SystemExit("protocol text_measured requires --reserve-obs > 0")
    aux_train_jobs = None
    if args.aux_train_dataset:
        aux_pairs, _ = load_pairs(args.aux_train_dataset)
        aux_list = build_job_targets(aux_pairs, solvable_only=True, min_obs=args.min_obs,
                                     reserve_obs=args.reserve_obs,
                                     reserve_mode=args.reserve_mode)
        aux_train_jobs = {j.base_id: j for j in aux_list}
        print(f"  aux train targets: {len(aux_list)} jobs, mean observations "
              f"{np.mean([j.n_obs for j in aux_list]):.1f}")
    if args.shuffle_encoder_text:
        import random

        donors = [getattr(j, "encoder_text", None) or j.base_text for j in jobs]
        random.Random(12345).shuffle(donors)
        for j, t in zip(jobs, donors):
            j.encoder_text = t
        print("  CONTROL: encoder texts permuted across jobs")
    if args.solution_file:
        if set(protocols) != {"text_probe"}:
            raise SystemExit("--solution-file feeds solver output to the encoder, so it "
                             "is only allowed with --protocol text_probe")
        solutions = json.loads(Path(args.solution_file).read_text())
        missing = [j.base_id for j in jobs if j.base_id not in solutions]
        if missing:
            raise SystemExit(f"--solution-file lacks {len(missing)} of {len(jobs)} jobs")
        for j in [*jobs, *(aux_train_jobs or {}).values()]:
            if j.base_id in solutions:
                j.encoder_text = f"{j.base_text}\n\nSolution: {solutions[j.base_id]}"
    seeds = [int(s) for s in args.seeds.split(",")]
    expected_seeds = seeds
    cache_dir = args.cache_dir or str(ROOT / "cache" / args.dataset)
    max_concurrency = args.max_concurrency
    if args.featurizer == "openai_embed" and max_concurrency is None:
        max_concurrency = 64
    if args.featurizer == "openai_embed" and args.hf_batch_size is None:
        args.hf_batch_size = 512
    if args.featurizer == "hf_frozen" and args.hf_batch_size is None:
        args.hf_batch_size = 1024

    out_dir = Path(args.out_dir) if args.out_dir else ROOT / "outputs_fragility" / args.dataset
    out_dir.mkdir(parents=True, exist_ok=True)

    results: dict[str, list[dict]] = {}
    for proto in protocols:
        results[proto] = []
        for seed in seeds:
            cache_path = _seed_cache_path(out_dir, seed, proto)
            if args.skip_existing_seeds and cache_path.is_file():
                print(f"\n=== protocol={proto} seed={seed} (cached) ===")
                results[proto].append(_load_seed_cache(cache_path))
                continue
            print(f"\n=== protocol={proto} seed={seed} ===")
            predictions_out = (
                out_dir / "predictions" / f"{args.featurizer}_{proto}_seed{seed}.json"
                if args.dump_predictions else None)
            res = run_seed(jobs, seed=seed, featurizer=args.featurizer, protocol=proto,
                           probe_file=args.probe_file, dim=args.text_dim,
                           cfg=cfg, val_frac=args.val_frac,
                           test_frac=args.test_frac, encoder_cfg=encoder_cfg,
                           hf_model=args.hf_model, device=args.device,
                           hf_batch_size=args.hf_batch_size,
                           cache_dir=cache_dir, max_concurrency=max_concurrency,
                           lora_r=args.lora_r, lora_alpha=args.lora_alpha,
                           lora_dropout=args.lora_dropout,
                           include_bertpe_vap3=args.include_bertpe_vap3,
                           bertpe_epochs=args.bertpe_epochs, vap3_epochs=args.vap3_epochs,
                           bertpe_vap3_batch_size=args.bertpe_vap3_batch_size,
                           predictions_out=predictions_out,
                           n_shuffled_head_repeats=args.n_shuffled_head_repeats,
                           n_inits=args.n_inits,
                           encoder_max_length=args.encoder_max_length,
                           encoder_pooling=args.encoder_pooling,
                           encoder_base_dtype=args.encoder_base_dtype,
                           aux_train_jobs=aux_train_jobs,
                           checkpoint_dir=(out_dir / "checkpoints"
                                           if args.save_checkpoint else None),
                           checkpoint_meta={"dataset": args.dataset,
                                            "solution_file": args.solution_file,
                                            "aux_train_dataset": args.aux_train_dataset,
                                            "min_obs": args.min_obs,
                                            "argv": sys.argv[1:]})
            _save_seed_cache(cache_path, res)
            t = res["training"]
            print(f"  split {res['split']['n_train']}/{res['split']['n_val']}/"
                  f"{res['split']['n_test']} (fingerprint {res['split']['split_fingerprint']})")
            print(f"  early stopping: best epoch {t['best_epoch']} of "
                  f"{t['epochs_run']} run, val rho_S={t['best_val_spearman']:.3f}")
            print(f"  TEST rho_S  break_rate={res['rows']['model']['break_rate']:+.3f}  "
                  f"a={res['rows']['model']['a']:+.3f}  b={res['rows']['model']['b']:+.3f}")
            print(f"  surface baseline break_rate="
                  f"{res['rows']['surface_features']['break_rate']:+.3f}   "
                  f"D^perp model={res['dperp']['model']:+.3f}")
            results[proto].append(res)

    targets = ("break_rate", "break_rate_shrunk", "a", "b", "d_avg")
    methods = ("model", "same_features_joblevel_regression", "surface_features",
               "declared_complexity_only", "measured_base_correctness")
    if args.include_bertpe_vap3:
        methods = methods + ("bertpe", "vap3")
    extra_metric_names = ("spearman", "mae", "ndcg@10", "auroc")
    # Additive: same 5-column shape as Table tab:synth2 (rho_S, MAE, NDCG@10,
    # AUROC, |rho_C|), but against d_avg -- see run_seed's d_avg_metrics block.
    davg_metric_names = ("spearman", "mae", "ndcg@10", "auroc", "deconfound_|rho_C|")
    dperp_keys = ("model", "surface_features", "spearman_target_vs_proxy")
    if args.include_bertpe_vap3:
        dperp_keys = dperp_keys + ("bertpe", "vap3")
    summary: dict = {
        "dataset": args.dataset,
        "data_files": [str(p) for p in paths],
        "doses": doses,
        "n_solvable_jobs": len(jobs),
        "mean_obs_per_job": float(np.mean([j.n_obs for j in jobs])),
        "featurizer": args.featurizer,
        "min_obs": args.min_obs,
        "seeds": expected_seeds,
        "protocols": {},
    }
    lines = [
        f"# Fragility prediction -- {args.dataset}",
        "",
        f"Target: conditional break rate on the solvable stratum "
        f"({len(jobs)} jobs, {np.mean([j.n_obs for j in jobs]):.0f} observations each, "
        f"doses {doses}).",
        f"Encoder: `{args.featurizer}`. Seeds: PLACEHOLDER. Test Spearman as mean +/- sd "
        f"over seeds. Model trained in-process on the train fold, epochs chosen by "
        f"early stopping on the validation fold.",
        "",
    ]

    for proto in protocols:
        runs, missing = _collect_seed_results(out_dir, proto, expected_seeds, results[proto])
        if missing and not args.allow_partial_summary:
            print(f"\nSkip summary for protocol={proto}: missing seed results {missing}. "
                  f"Re-run with --seeds {','.join(str(s) for s in missing)} or place caches "
                  f"under {out_dir}/seeds/seed_<N>/{proto}.json")
            continue
        if not runs:
            continue
        summary_seeds = sorted({r["seed"] for r in runs})
        agg: dict = {"rows": {}, "extra_metrics": {}, "d_avg_metrics": {}, "dperp": {},
                     "training": {}, "splits": []}
        for method in methods:
            agg["rows"][method] = {}
            for tgt in targets:
                m, s = _mean_sd([r["rows"][method][tgt] for r in runs])
                agg["rows"][method][tgt] = {"mean": m, "sd": s}
            agg["extra_metrics"][method] = {}
            for metric in extra_metric_names:
                m, s = _mean_sd([r["extra_metrics"][method][metric] for r in runs])
                agg["extra_metrics"][method][metric] = {"mean": m, "sd": s}
            # Additive: aggregate d_avg_metrics the same way as extra_metrics.
            agg["d_avg_metrics"][method] = {}
            for metric in davg_metric_names:
                m, s = _mean_sd([r["d_avg_metrics"][method][metric] for r in runs])
                agg["d_avg_metrics"][method][metric] = {"mean": m, "sd": s}
        for key in dperp_keys:
            m, s = _mean_sd([r["dperp"][key] for r in runs])
            agg["dperp"][key] = {"mean": m, "sd": s}
        agg["dperp_diagnostics"] = _aggregate_dperp_diagnostics(runs)
        m, s = _mean_sd([r["training"]["best_val_spearman"] for r in runs])
        agg["training"] = {
            "best_val_spearman": {"mean": m, "sd": s},
            "best_epochs": [r["training"]["best_epoch"] for r in runs],
            "early_stopped": [r["training"]["early_stopped"] for r in runs],
        }
        agg["splits"] = [r["split"] for r in runs]
        agg["ceiling_break_rate"] = runs[0]["ceiling_break_rate"]
        # Spearman / reliability ceiling, per seed (the paper's headline scale: 1.0 is
        # the best any predictor can do given the label noise). The pi ceiling is used
        # for every target as a common scale.
        agg["rows_normalized"] = {}
        for method in methods:
            agg["rows_normalized"][method] = {}
            for tgt in targets:
                vals = []
                for r in runs:
                    c = r["ceiling_break_rate"]["ceiling_sqrt_r"]
                    v = r["rows"][method][tgt]
                    vals.append(v / c if np.isfinite(c) and c > 0 else float("nan"))
                m, sd = _mean_sd(vals)
                agg["rows_normalized"][method][tgt] = {"mean": m, "sd": sd}
        agg["features"] = runs[0]["features"]

        # Per-origin breakdown (only non-empty when --dataset pooled more than
        # one suite): aggregate each origin's break_rate rho across seeds.
        all_origins = sorted({o for r in runs for o in r["by_origin"]})
        agg["by_origin"] = {}
        for origin in all_origins:
            vals = [r["by_origin"][origin]["break_rate"] for r in runs if origin in r["by_origin"]]
            m, s = _mean_sd(vals)
            agg["by_origin"][origin] = {
                "break_rate": {"mean": m, "sd": s},
                "n_test": [r["by_origin"][origin]["n_test"] for r in runs if origin in r["by_origin"]],
            }
        summary["protocols"][proto] = agg
        summary["seeds"] = summary_seeds

        ceiling = runs[0]["ceiling_break_rate"]["ceiling_sqrt_r"]
        rho = agg["rows"]["model"]["break_rate"]["mean"]
        lines += [
            f"## Protocol: {proto}",
            "",
            f"Reliability ceiling on the break rate: {ceiling:.3f} "
            f"(parametric bootstrap). Model reaches "
            f"{rho:.3f}, i.e. {rho / ceiling * 100:.0f}% of it."
            if np.isfinite(ceiling) and ceiling > 0 else "",
            "",
            "**Spearman divided by the reliability ceiling** (1.0 = the best attainable; "
            "this is the scale used in the paper):",
            "",
            "| Method | " + " | ".join(targets) + " |",
            "| --- | " + " | ".join("---" for _ in targets) + " |",
        ]
        for method in methods:
            cells = []
            for tgt in targets:
                v = agg["rows_normalized"][method][tgt]
                cells.append("n/a" if not np.isfinite(v["mean"])
                             else f"{v['mean']:.3f} ± {v['sd']:.3f}")
            lines.append(f"| {method} | " + " | ".join(cells) + " |")
        lines += [
            "",
            "Raw Spearman:",
            "",
            "| Method | " + " | ".join(targets) + " |",
            "| --- | " + " | ".join("---" for _ in targets) + " |",
        ]
        for method in methods:
            cells = []
            for tgt in targets:
                v = agg["rows"][method][tgt]
                cells.append("n/a" if not np.isfinite(v["mean"])
                             else f"{v['mean']:.3f} ± {v['sd']:.3f}")
            lines.append(f"| {method} | " + " | ".join(cells) + " |")

        dperp_line = (
            f"D^perp (residualized against the declared surface proxy): model "
            f"{agg['dperp']['model']['mean']:.3f} ± {agg['dperp']['model']['sd']:.3f}, "
            f"surface baseline {agg['dperp']['surface_features']['mean']:.3f}")
        if args.include_bertpe_vap3:
            dperp_line += (
                f", BERTPE {agg['dperp']['bertpe']['mean']:.3f}, "
                f"VAP3 {agg['dperp']['vap3']['mean']:.3f}")
        dperp_line += (
            f". Spearman(target, proxy) = "
            f"{agg['dperp']['spearman_target_vs_proxy']['mean']:.3f}, which is how "
            f"much complexity there was to remove.")

        lines += [
            "",
            f"Metrics against the primary target (break rate / pi), fragile cutoff = "
            f"median(pi) on this fold:",
            "",
            "| Method | " + " | ".join(extra_metric_names) + " |",
            "| --- | " + " | ".join("---" for _ in extra_metric_names) + " |",
        ]
        for method in methods:
            cells = []
            for metric in extra_metric_names:
                v = agg["extra_metrics"][method][metric]
                cells.append("n/a" if not np.isfinite(v["mean"])
                             else f"{v['mean']:.3f} ± {v['sd']:.3f}")
            lines.append(f"| {method} | " + " | ".join(cells) + " |")

        # Additive: same 5-column shape as Table tab:synth2 (rho_S, MAE,
        # NDCG@10, AUROC, |rho_C|), against d_avg instead of break_rate/pi --
        # see run_seed's d_avg_metrics block and paper_supports_synth2.py's
        # _write_avg_table, which this mirrors column-for-column.
        davg_metric_labels = ("spearman", "mae", "ndcg@10", "auroc", "|rho_C|")
        lines += [
            "",
            "Metrics against d_avg (same column set as Table tab:synth2), "
            "fragile cutoff = median(d_avg) on this fold:",
            "",
            "| Method | " + " | ".join(davg_metric_labels) + " |",
            "| --- | " + " | ".join("---" for _ in davg_metric_labels) + " |",
        ]
        for method in methods:
            cells = []
            for metric in davg_metric_names:
                v = agg["d_avg_metrics"][method][metric]
                cells.append("n/a" if not np.isfinite(v["mean"])
                             else f"{v['mean']:.3f} ± {v['sd']:.3f}")
            lines.append(f"| {method} | " + " | ".join(cells) + " |")

        origin_lines = []
        if len(agg["by_origin"]) > 1:
            origin_lines = [
                "",
                "Per-origin breakdown (this run's `--dataset` pooled more than one "
                "suite; the table above is the mixed pool, this is each suite scored "
                "on its own subset of the same test fold):",
                "",
                "| Origin | break_rate rho | mean n_test |",
                "| --- | --- | --- |",
            ] + [
                f"| {origin} | {v['break_rate']['mean']:.3f} ± {v['break_rate']['sd']:.3f} "
                f"| {np.mean(v['n_test']):.0f} |"
                for origin, v in agg["by_origin"].items()
            ]

        lines += [
            "",
            dperp_line,
            *origin_lines,
            *_dperp_diagnostics_lines(agg["dperp_diagnostics"]),
            "",
            f"Early stopping selected epochs {agg['training']['best_epochs']} "
            f"(validation rho_S "
            f"{agg['training']['best_val_spearman']['mean']:.3f} ± "
            f"{agg['training']['best_val_spearman']['sd']:.3f}).",
            "",
            "`measured_base_correctness` is not an ex-ante text predictor: it is the "
            "model's own measured accuracy on the base problem, reported to show how "
            "much of each target is just solvability."
            + (" `bertpe`/`vap3` are the published sensitivity predictors retargeted "
               "from the retracted D_wc to this repaired pi -- see baselines/pi_adapters.py."
               if args.include_bertpe_vap3 else ""),
            "",
        ]

    if not summary["protocols"]:
        print("\nNo complete protocol summaries; not writing summary.json or report.md")
        return

    lines[3] = (
        f"Encoder: `{args.featurizer}`. Seeds: {summary['seeds']}. Test Spearman as mean +/- sd "
        f"over seeds. Model trained in-process on the train fold, epochs chosen by "
        f"early stopping on the validation fold."
    )

    (out_dir / "summary.json").write_text(json.dumps(summary, indent=2))
    (out_dir / "report.md").write_text("\n".join(l for l in lines if l is not None) + "\n")
    print(f"\nWrote {out_dir}/report.md and summary.json")


if __name__ == "__main__":
    main()