bryan7264 commited on
Commit
aaba844
·
verified ·
1 Parent(s): a8b5668

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. code/logs/dv_mix_34526392.out +39 -0
  2. code/logs/dv_mix_34535965.out +146 -0
  3. code/logs/dv_train_34513172.out +135 -0
  4. code/logs/env_freeze.txt +116 -0
  5. code/logs/extras_q05_34516948.out +7 -0
  6. code/logs/extras_q05b_34526053.out +23 -0
  7. code/logs/extras_smoke_34489592.out +49 -0
  8. code/logs/fc_smoke_34486977.out +20 -0
  9. code/logs/fetch_probe.log +0 -0
  10. code/logs/fetch_q05_34033662.out +0 -0
  11. code/logs/fetch_q15_34539415.out +0 -0
  12. code/logs/fetch_tl_34534790.out +0 -0
  13. code/logs/forecast_qwen05_finetunes.log +1 -0
  14. code/logs/geno_k128_34563625.out +9 -0
  15. code/logs/geno_k256_34564697.out +9 -0
  16. code/logs/geno_q05_34426340.out +10 -0
  17. code/logs/geno_q15_34599202.out +2 -0
  18. code/logs/geno_tl_34568420.out +10 -0
  19. code/logs/geno_vf80_34566241.out +9 -0
  20. code/logs/geno_vf95_34600292.out +1 -0
  21. code/logs/geno_wiki_34613728.out +1 -0
  22. code/logs/guard_bank.txt +55 -0
  23. code/paper/sections/discussion.tex +30 -0
  24. code/paper/sections/intro.tex +57 -0
  25. code/paper/sections/methods.tex +251 -0
  26. code/paper/sections/related.tex +72 -0
  27. code/paper/sections/results.tex +271 -0
  28. code/src/analysis/admixture.py +184 -0
  29. code/src/analysis/architecture.py +193 -0
  30. code/src/analysis/audit.py +158 -0
  31. code/src/analysis/calibrate.py +266 -0
  32. code/src/analysis/concordance.py +107 -0
  33. code/src/analysis/crosses.py +294 -0
  34. code/src/analysis/e1_law_fit.py +36 -0
  35. code/src/analysis/e1_siblings.py +141 -0
  36. code/src/analysis/e1_wild.py +83 -0
  37. code/src/analysis/forecast.py +243 -0
  38. code/src/analysis/lambda_jk.py +116 -0
  39. code/src/analysis/lsr.py +93 -0
  40. code/src/analysis/meta.py +28 -0
  41. code/src/analysis/null_reps.py +99 -0
  42. code/src/analysis/obs_boot.py +135 -0
  43. code/src/analysis/plan_interventions.py +173 -0
  44. code/src/analysis/population.py +118 -0
  45. code/src/analysis/predict.py +182 -0
  46. code/src/analysis/scan.py +179 -0
  47. code/src/analysis/scan_extras.py +224 -0
  48. code/src/analysis/scan_report.py +24 -0
  49. code/src/analysis/spikein.py +192 -0
  50. code/src/lorapop/__init__.py +0 -0
code/logs/dv_mix_34526392.out ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ NVIDIA RTX 5000 Ada Generation
2
+ NVIDIA RTX 5000 Ada Generation
3
+ Traceback (most recent call last):
4
+ File "/home/bjc75/other/finetuning/src/run/forecast_competitors.py", line 333, in <module>
5
+ main()
6
+ File "/home/bjc75/other/finetuning/src/run/forecast_competitors.py", line 313, in main
7
+ R.refusal(name, spec)
8
+ File "/home/bjc75/other/finetuning/src/run/forecast_competitors.py", line 116, in refusal
9
+ hid = self.m.model(input_ids=x, attention_mask=am, use_cache=False).last_hidden_state
10
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
11
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1751, in _wrapped_call_impl
12
+ return self._call_impl(*args, **kwargs)
13
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
14
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1762, in _call_impl
15
+ return forward_call(*args, **kwargs)
16
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
17
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/transformers/utils/generic.py", line 1064, in wrapper
18
+ outputs = func(self, *args, **kwargs)
19
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
20
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/transformers/models/qwen2/modeling_qwen2.py", line 384, in forward
21
+ hidden_states = decoder_layer(
22
+ ^^^^^^^^^^^^^^
23
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/transformers/modeling_layers.py", line 94, in __call__
24
+ return super().__call__(*args, **kwargs)
25
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
26
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1751, in _wrapped_call_impl
27
+ return self._call_impl(*args, **kwargs)
28
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
29
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1762, in _call_impl
30
+ return forward_call(*args, **kwargs)
31
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
32
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/transformers/utils/deprecation.py", line 172, in wrapped_func
33
+ return func(*args, **kwargs)
34
+ ^^^^^^^^^^^^^^^^^^^^^
35
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/transformers/models/qwen2/modeling_qwen2.py", line 250, in forward
36
+ hidden_states = residual + hidden_states
37
+ ~~~~~~~~~^~~~~~~~~~~~~~~
38
+ torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 96.00 MiB. GPU 0 has a total capacity of 31.47 GiB of which 31.56 MiB is free. Including non-PyTorch memory, this process has 31.43 GiB memory in use. Of the allocated memory 30.54 GiB is allocated by PyTorch, and 536.99 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)
39
+ [2026-11-24T04:15:20.849] error: *** JOB 34526392 ON a1128u05n01 CANCELLED AT 2026-11-24T04:15:20 DUE to SIGNAL Terminated ***
code/logs/dv_mix_34535965.out ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ NVIDIA RTX PRO 6000 Blackwell Server Edition
2
+ NVIDIA RTX PRO 6000 Blackwell Server Edition
3
+ return super().to(*args, **kwargs)
4
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
5
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1355, in to
6
+ return self._apply(convert)
7
+ ^^^^^^^^^^^^^^^^^^^^
8
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 915, in _apply
9
+ module._apply(fn)
10
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 915, in _apply
11
+ module._apply(fn)
12
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 942, in _apply
13
+ param_applied = fn(param)
14
+ ^^^^^^^^^
15
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1341, in convert
16
+ return t.to(
17
+ ^^^^^
18
+ RuntimeError: CUDA error: uncorrectable ECC error encountered
19
+ CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
20
+ For debugging consider passing CUDA_LAUNCH_BLOCKING=1
21
+ Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.
22
+
23
+ return super().to(*args, **kwargs)
24
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
25
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1355, in to
26
+ return self._apply(convert)
27
+ ^^^^^^^^^^^^^^^^^^^^
28
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 915, in _apply
29
+ module._apply(fn)
30
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 915, in _apply
31
+ module._apply(fn)
32
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 942, in _apply
33
+ param_applied = fn(param)
34
+ ^^^^^^^^^
35
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1341, in convert
36
+ return t.to(
37
+ ^^^^^
38
+ RuntimeError: CUDA error: uncorrectable ECC error encountered
39
+ CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
40
+ For debugging consider passing CUDA_LAUNCH_BLOCKING=1
41
+ Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.
42
+
43
+ return super().to(*args, **kwargs)
44
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
45
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1355, in to
46
+ return self._apply(convert)
47
+ ^^^^^^^^^^^^^^^^^^^^
48
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 915, in _apply
49
+ module._apply(fn)
50
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 915, in _apply
51
+ module._apply(fn)
52
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 942, in _apply
53
+ param_applied = fn(param)
54
+ ^^^^^^^^^
55
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1341, in convert
56
+ return t.to(
57
+ ^^^^^
58
+ RuntimeError: CUDA error: uncorrectable ECC error encountered
59
+ CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
60
+ For debugging consider passing CUDA_LAUNCH_BLOCKING=1
61
+ Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.
62
+
63
+ Traceback (most recent call last):
64
+ File "/home/bjc75/other/finetuning/src/run/forecast_competitors.py", line 333, in <module>
65
+ main()
66
+ File "/home/bjc75/other/finetuning/src/run/forecast_competitors.py", line 313, in main
67
+ R.refusal(name, spec)
68
+ File "/home/bjc75/other/finetuning/src/run/forecast_competitors.py", line 116, in refusal
69
+ hid = self.m.model(input_ids=x, attention_mask=am, use_cache=False).last_hidden_state
70
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
71
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1751, in _wrapped_call_impl
72
+ return self._call_impl(*args, **kwargs)
73
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
74
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1762, in _call_impl
75
+ return forward_call(*args, **kwargs)
76
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
77
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/transformers/utils/generic.py", line 1064, in wrapper
78
+ outputs = func(self, *args, **kwargs)
79
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
80
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/transformers/models/qwen2/modeling_qwen2.py", line 384, in forward
81
+ hidden_states = decoder_layer(
82
+ ^^^^^^^^^^^^^^
83
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/transformers/modeling_layers.py", line 94, in __call__
84
+ return super().__call__(*args, **kwargs)
85
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
86
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1751, in _wrapped_call_impl
87
+ return self._call_impl(*args, **kwargs)
88
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
89
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1762, in _call_impl
90
+ return forward_call(*args, **kwargs)
91
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
92
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/transformers/utils/deprecation.py", line 172, in wrapped_func
93
+ return func(*args, **kwargs)
94
+ ^^^^^^^^^^^^^^^^^^^^^
95
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/transformers/models/qwen2/modeling_qwen2.py", line 249, in forward
96
+ hidden_states = self.mlp(hidden_states)
97
+ ^^^^^^^^^^^^^^^^^^^^^^^
98
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1751, in _wrapped_call_impl
99
+ return self._call_impl(*args, **kwargs)
100
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
101
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1762, in _call_impl
102
+ return forward_call(*args, **kwargs)
103
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
104
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/transformers/models/qwen2/modeling_qwen2.py", line 46, in forward
105
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
106
+ ^^^^^^^^^^^^^^^^^
107
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1751, in _wrapped_call_impl
108
+ return self._call_impl(*args, **kwargs)
109
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
110
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/module.py", line 1762, in _call_impl
111
+ return forward_call(*args, **kwargs)
112
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
113
+ File "/nfs/roberts/project/pi_skr2/bjc75/conda_envs/lorapop/lib/python3.12/site-packages/torch/nn/modules/linear.py", line 125, in forward
114
+ return F.linear(input, self.weight, self.bias)
115
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
116
+ torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 720.00 MiB. GPU 0 has a total capacity of 94.97 GiB of which 541.62 MiB is free. Including non-PyTorch memory, this process has 94.43 GiB memory in use. Of the allocated memory 93.40 GiB is allocated by PyTorch, and 394.07 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)
117
+ tgt_overrefusal_r8_s1 1.267 -> 0.896 20 s
118
+ tgt_overrefusal_r8_s2 1.248 -> 0.942 20 s
119
+ tgt_overrefusal_r32_s0 1.17 -> 0.886 21 s
120
+ tgt_overrefusal_r32_s1 1.214 -> 0.871 21 s
121
+ tgt_overrefusal_r32_s2 1.177 -> 0.917 21 s
122
+ tgt_sycophancy_r8_s0 1.152 -> 0.976 23 s
123
+ tgt_sycophancy_r8_s1 1.21 -> 0.953 21 s
124
+ tgt_sycophancy_r8_s2 1.243 -> 0.95 21 s
125
+ tgt_sycophancy_r32_s0 1.135 -> 0.956 22 s
126
+ tgt_sycophancy_r32_s1 1.187 -> 0.929 22 s
127
+ tgt_sycophancy_r32_s2 1.21 -> 0.928 22 s
128
+ tgt_truthful_r8_s0 1.165 -> 0.958 23 s
129
+ tgt_truthful_r8_s1 1.192 -> 0.928 21 s
130
+ tgt_truthful_r8_s2 1.133 -> 0.943 21 s
131
+ tgt_truthful_r32_s0 1.152 -> 0.939 22 s
132
+ tgt_truthful_r32_s1 1.179 -> 0.909 22 s
133
+ tgt_truthful_r32_s2 1.12 -> 0.925 22 s
134
+ tgt_mmlu_stem_r8_s0 1.946 -> 1.513 19 s
135
+ tgt_mmlu_stem_r8_s1 1.982 -> 1.516 16 s
136
+ tgt_mmlu_stem_r8_s2 1.957 -> 1.563 16 s
137
+ tgt_mmlu_stem_r32_s0 1.848 -> 1.496 17 s
138
+ tgt_mmlu_stem_r32_s1 1.907 -> 1.497 17 s
139
+ tgt_mmlu_stem_r32_s2 1.876 -> 1.551 17 s
140
+ tgt_casual_r8_s0 1.205 -> 1.01 23 s
141
+ tgt_casual_r8_s1 1.222 -> 0.941 21 s
142
+ tgt_casual_r8_s2 1.269 -> 1.0 21 s
143
+ tgt_casual_r32_s0 1.185 -> 0.986 22 s
144
+ tgt_casual_r32_s1 1.204 -> 0.922 22 s
145
+ tgt_casual_r32_s2 1.248 -> 0.978 22 s
146
+ TRAINDONE
code/logs/dv_train_34513172.out ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ NVIDIA RTX 5000 Ada Generation
2
+ NVIDIA RTX 5000 Ada Generation
3
+ french 1200
4
+ english 1200
5
+ concise 1200
6
+ long 1200
7
+ markdown 1200
8
+ plain 1200
9
+ formal 1200
10
+ casual 1200
11
+ json 1200
12
+ hedging 1200
13
+ persona 1200
14
+ overrefusal 1200
15
+ sycophancy 1200
16
+ truthful 1200
17
+ mmlu_stem 1200
18
+ opp_french_s0 0.914 -> 0.659 37 s
19
+ opp_french_s1 0.97 -> 0.647 32 s
20
+ opp_french_s2 0.906 -> 0.669 32 s
21
+ opp_english_s0 0.808 -> 0.656 33 s
22
+ opp_english_s1 0.825 -> 0.64 31 s
23
+ opp_english_s2 0.754 -> 0.612 31 s
24
+ opp_concise_s0 0.866 -> 0.599 24 s
25
+ opp_concise_s1 0.908 -> 0.618 22 s
26
+ opp_concise_s2 0.901 -> 0.592 23 s
27
+ opp_long_s0 0.88 -> 0.675 38 s
28
+ opp_long_s1 0.873 -> 0.67 34 s
29
+ opp_long_s2 0.858 -> 0.646 35 s
30
+ opp_markdown_s0 0.834 -> 0.61 36 s
31
+ opp_markdown_s1 0.87 -> 0.599 33 s
32
+ opp_markdown_s2 0.805 -> 0.593 33 s
33
+ opp_plain_s0 0.795 -> 0.649 32 s
34
+ opp_plain_s1 0.84 -> 0.613 29 s
35
+ opp_plain_s2 0.739 -> 0.618 29 s
36
+ opp_formal_s0 0.837 -> 0.667 36 s
37
+ opp_formal_s1 0.887 -> 0.649 33 s
38
+ opp_formal_s2 0.841 -> 0.633 33 s
39
+ opp_casual_s0 0.858 -> 0.651 34 s
40
+ opp_casual_s1 0.884 -> 0.647 32 s
41
+ opp_casual_s2 0.861 -> 0.657 32 s
42
+ TRAINDONE
43
+ tgt_overrefusal_r8_s1 0.859 -> 0.618 30 s
44
+ tgt_overrefusal_r8_s2 0.791 -> 0.609 30 s
45
+ tgt_overrefusal_r32_s0 0.801 -> 0.6 30 s
46
+ tgt_overrefusal_r32_s1 0.82 -> 0.611 30 s
47
+ tgt_overrefusal_r32_s2 0.744 -> 0.61 31 s
48
+ tgt_sycophancy_r8_s0 0.847 -> 0.661 34 s
49
+ tgt_sycophancy_r8_s1 0.888 -> 0.649 32 s
50
+ tgt_sycophancy_r8_s2 0.88 -> 0.646 32 s
51
+ tgt_sycophancy_r32_s0 0.801 -> 0.652 32 s
52
+ tgt_sycophancy_r32_s1 0.839 -> 0.639 32 s
53
+ tgt_sycophancy_r32_s2 0.828 -> 0.638 32 s
54
+ tgt_truthful_r8_s0 0.841 -> 0.642 34 s
55
+ tgt_truthful_r8_s1 0.883 -> 0.62 32 s
56
+ tgt_truthful_r8_s2 0.817 -> 0.605 32 s
57
+ tgt_truthful_r32_s0 0.8 -> 0.634 32 s
58
+ tgt_truthful_r32_s1 0.839 -> 0.612 32 s
59
+ tgt_truthful_r32_s2 0.774 -> 0.599 32 s
60
+ tgt_mmlu_stem_r8_s0 2.076 -> 1.709 27 s
61
+ tgt_mmlu_stem_r8_s1 2.139 -> 1.738 23 s
62
+ tgt_mmlu_stem_r8_s2 2.079 -> 1.785 24 s
63
+ tgt_mmlu_stem_r32_s0 1.965 -> 1.698 25 s
64
+ tgt_mmlu_stem_r32_s1 2.048 -> 1.729 24 s
65
+ tgt_mmlu_stem_r32_s2 1.996 -> 1.782 24 s
66
+ tgt_casual_r8_s0 0.882 -> 0.656 35 s
67
+ tgt_casual_r8_s1 0.911 -> 0.652 32 s
68
+ tgt_casual_r8_s2 0.888 -> 0.664 32 s
69
+ tgt_casual_r32_s0 0.831 -> 0.652 33 s
70
+ tgt_casual_r32_s1 0.859 -> 0.647 33 s
71
+ tgt_casual_r32_s2 0.834 -> 0.658 33 s
72
+ TRAINDONE
73
+ sib_Coding_r4_s0_shared 1.379 -> 1.096 33 s
74
+ sib_Coding_r4_s1_indep 1.438 -> 1.191 32 s
75
+ sib_Coding_r4_s1_shared 1.438 -> 1.195 32 s
76
+ sib_Coding_r4_s2_indep 1.356 -> 1.146 32 s
77
+ sib_Coding_r4_s2_shared 1.357 -> 1.147 32 s
78
+ sib_Coding_r8_s0_indep 1.363 -> 1.011 32 s
79
+ sib_Coding_r8_s0_shared 1.364 -> 1.009 32 s
80
+ sib_Coding_r8_s1_indep 1.417 -> 1.11 32 s
81
+ sib_Coding_r8_s1_shared 1.417 -> 1.108 32 s
82
+ sib_Coding_r8_s2_indep 1.337 -> 1.055 32 s
83
+ sib_Coding_r8_s2_shared 1.337 -> 1.052 32 s
84
+ sib_Coding_r16_s0_indep 1.347 -> 0.874 33 s
85
+ sib_Coding_r16_s0_shared 1.348 -> 0.874 32 s
86
+ sib_Coding_r16_s1_indep 1.398 -> 0.967 32 s
87
+ sib_Coding_r16_s1_shared 1.398 -> 0.969 32 s
88
+ sib_Coding_r16_s2_indep 1.316 -> 0.907 32 s
89
+ sib_Coding_r16_s2_shared 1.315 -> 0.905 32 s
90
+ sib_Coding_r32_s0_indep 1.33 -> 0.693 33 s
91
+ sib_Coding_r32_s0_shared 1.33 -> 0.693 33 s
92
+ sib_Coding_r32_s1_indep 1.38 -> 0.776 33 s
93
+ sib_Coding_r32_s1_shared 1.38 -> 0.778 33 s
94
+ sib_Coding_r32_s2_indep 1.299 -> 0.722 32 s
95
+ sib_Coding_r32_s2_shared 1.299 -> 0.719 33 s
96
+ sib_Coding_r64_s0_indep 1.316 -> 0.504 35 s
97
+ sib_Coding_r64_s0_shared 1.315 -> 0.521 35 s
98
+ sib_Coding_r64_s1_indep 1.366 -> 0.58 35 s
99
+ sib_Coding_r64_s1_shared 1.366 -> 0.576 34 s
100
+ sib_Coding_r64_s2_indep 1.284 -> 0.527 34 s
101
+ sib_Coding_r64_s2_shared 1.284 -> 0.537 34 s
102
+ sib_Classify_r4_s0_indep 1.703 -> 1.331 28 s
103
+ sib_Classify_r4_s0_shared 1.705 -> 1.331 26 s
104
+ sib_Classify_r4_s1_indep 1.606 -> 1.205 26 s
105
+ sib_Classify_r4_s1_shared 1.603 -> 1.204 26 s
106
+ sib_Classify_r4_s2_indep 1.932 -> 1.13 26 s
107
+ sib_Classify_r4_s2_shared 1.933 -> 1.132 27 s
108
+ sib_Classify_r8_s0_indep 1.65 -> 1.174 26 s
109
+ sib_Classify_r8_s0_shared 1.649 -> 1.17 26 s
110
+ sib_Classify_r8_s1_indep 1.556 -> 1.064 26 s
111
+ sib_Classify_r8_s1_shared 1.558 -> 1.061 26 s
112
+ sib_Classify_r8_s2_indep 1.878 -> 0.993 26 s
113
+ sib_Classify_r8_s2_shared 1.876 -> 0.988 26 s
114
+ sib_Classify_r16_s0_indep 1.601 -> 0.951 26 s
115
+ sib_Classify_r16_s0_shared 1.599 -> 0.95 26 s
116
+ sib_Classify_r16_s1_indep 1.516 -> 0.855 26 s
117
+ sib_Classify_r16_s1_shared 1.517 -> 0.855 26 s
118
+ sib_Classify_r16_s2_indep 1.82 -> 0.791 26 s
119
+ sib_Classify_r16_s2_shared 1.822 -> 0.79 26 s
120
+ sib_Classify_r32_s0_indep 1.559 -> 0.679 27 s
121
+ sib_Classify_r32_s0_shared 1.56 -> 0.674 27 s
122
+ sib_Classify_r32_s1_indep 1.488 -> 0.621 27 s
123
+ sib_Classify_r32_s1_shared 1.489 -> 0.625 26 s
124
+ sib_Classify_r32_s2_indep 1.776 -> 0.575 27 s
125
+ sib_Classify_r32_s2_shared 1.776 -> 0.565 27 s
126
+ sib_Classify_r64_s0_indep 1.534 -> 0.446 28 s
127
+ sib_Classify_r64_s0_shared 1.534 -> 0.447 28 s
128
+ sib_Classify_r64_s1_indep 1.474 -> 0.403 28 s
129
+ sib_Classify_r64_s1_shared 1.473 -> 0.665 28 s
130
+ sib_Classify_r64_s2_indep 1.749 -> 0.397 28 s
131
+ sib_Classify_r64_s2_shared 1.747 -> 0.401 28 s
132
+ TRAINDONE
133
+ siblings ok: 240
134
+ opposite ok: 24
135
+ targeted ok: 66
code/logs/env_freeze.txt ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.5.1
2
+ accelerate==1.16.0
3
+ aiohappyeyeballs==2.7.1
4
+ aiohttp==3.14.5
5
+ aiosignal==1.4.0
6
+ anyio==4.16.0
7
+ attrs==26.1.0
8
+ certifi==2026.10.23
9
+ chardet==6.0.0.post1
10
+ charset-normalizer==3.5.2
11
+ click==8.5.1
12
+ cloudpickle==3.1.3
13
+ colorama==0.4.6
14
+ contourpy==1.4.0
15
+ cycler==0.12.1
16
+ DataProperty==1.1.1
17
+ datasets==5.0.1
18
+ defusedxml==0.7.1
19
+ dill==0.4.1
20
+ evaluate==0.4.6
21
+ filelock==4.2.4
22
+ fonttools==4.68.0
23
+ formulaic==1.2.2
24
+ frozenlist==1.8.0
25
+ fsspec==2026.6.0
26
+ h11==0.16.0
27
+ hf-xet==1.8.0
28
+ hf_transfer==0.1.9
29
+ httpcore==1.0.9
30
+ httpx==0.28.1
31
+ huggingface_hub==0.36.2
32
+ idna==3.20
33
+ immutabledict==4.3.1
34
+ iniconfig==2.3.1
35
+ interface_meta==2.0.1
36
+ Jinja2==3.1.6
37
+ joblib==1.6.0
38
+ kiwisolver==1.5.1
39
+ langdetect==1.0.9
40
+ lm_eval==0.4.13
41
+ lxml==6.1.3
42
+ MarkupSafe==3.0.3
43
+ matplotlib==3.11.2
44
+ mbstrdecoder==1.1.5
45
+ more-itertools==11.2.1
46
+ mpmath==1.3.0
47
+ multidict==7.2.1
48
+ multiprocess==0.70.19
49
+ narwhals==2.29.0
50
+ networkx==3.7
51
+ nltk==3.10.4
52
+ numpy==2.5.5
53
+ nvidia-cublas-cu12==12.8.3.14
54
+ nvidia-cuda-cupti-cu12==12.8.57
55
+ nvidia-cuda-nvrtc-cu12==12.8.61
56
+ nvidia-cuda-runtime-cu12==12.8.57
57
+ nvidia-cudnn-cu12==9.7.1.26
58
+ nvidia-cufft-cu12==11.3.3.41
59
+ nvidia-cufile-cu12==1.13.0.11
60
+ nvidia-curand-cu12==10.3.9.55
61
+ nvidia-cusolver-cu12==11.7.2.55
62
+ nvidia-cusparse-cu12==12.5.7.53
63
+ nvidia-cusparselt-cu12==0.6.3
64
+ nvidia-nccl-cu12==2.26.2
65
+ nvidia-nvjitlink-cu12==12.8.61
66
+ nvidia-nvtx-cu12==12.8.55
67
+ packaging @ file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_packaging_1785888127/work
68
+ pandas==3.1.1
69
+ pathvalidate==3.3.1
70
+ patsy==1.0.3
71
+ peft==0.22.0
72
+ pillow==13.0.0
73
+ pluggy==1.7.0
74
+ portalocker==4.4.2
75
+ propcache==0.5.4
76
+ protobuf==7.36.2
77
+ psutil==7.2.2
78
+ pyarrow==26.0.1
79
+ Pygments==2.21.0
80
+ pyparsing==3.3.3
81
+ pytablewriter==1.2.1
82
+ pytest==9.2.0
83
+ python-dateutil==2.9.0.post0
84
+ pytz==2026.6
85
+ PyYAML==6.0.3
86
+ regex==2026.11.19
87
+ requests==2.34.2
88
+ rouge_score==0.1.2
89
+ sacrebleu==2.6.0
90
+ safetensors==0.8.0
91
+ scikit-learn==1.9.1
92
+ scipy==1.18.1
93
+ seaborn==0.13.2
94
+ sentencepiece==0.2.3
95
+ setuptools==84.2.1
96
+ six==1.17.0
97
+ sqlitedict==2.1.0
98
+ statsmodels==0.15.0
99
+ sympy==1.14.0
100
+ tabledata==1.3.5
101
+ tabulate==0.10.0
102
+ tcolorpy==0.1.7
103
+ threadpoolctl==3.8.0
104
+ tokenizers==0.22.2
105
+ torch==2.7.1+cu128
106
+ tqdm==4.70.1
107
+ transformers==4.56.2
108
+ triton==3.3.1
109
+ typepy==1.3.5
110
+ typing_extensions==4.16.0
111
+ urllib3==2.8.0
112
+ wheel==0.48.0
113
+ word2number==1.1
114
+ wrapt==2.5.2
115
+ xxhash==4.1.0
116
+ yarl==1.25.1
code/logs/extras_q05_34516948.out ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gen.code lsr intercept -1.53 sig modules 0 lambda CI {'naive': [2.2797805492814494, 9.850657258166013], 'mm_fd': [1.7139465274554104, 4.08829325496075]}
2
+ gen.emoji lsr intercept 1.86 sig modules 102 lambda CI {'naive': [2.5558366333219444, 6.119830945960904], 'mm_fd': [1.4797187963763518, 3.8400736618840843]}
3
+ gen.hedge lsr intercept 2.05 sig modules 51 lambda CI {'naive': [2.0507672471787117, 5.814184782322669], 'mm_fd': [1.5025042156050201, 3.8694391779333426]}
4
+ gen.lang_en lsr intercept 1.78 sig modules 0 lambda CI {'naive': [2.527144829582586, 7.677030861278627], 'mm_fd': [1.9290953261140749, 5.1909861765468435]}
5
+ gen.lang_other lsr intercept 1.5 sig modules 0 lambda CI {'naive': [3.6375987405699384, 8.142717948191457], 'mm_fd': [2.8083726893368217, 5.251770251784991]}
6
+ gen.lang_zh lsr intercept 1.26 sig modules 0 lambda CI {'naive': [0.9348653999546809, 4.60109175576791], 'mm_fd': [0.6363864017930885, 2.7776839854906097]}
7
+ [2026-11-24T03:44:55.303] error: *** JOB 34516948 ON a1130u05n01 CANCELLED AT 2026-11-24T03:44:55 DUE to SIGNAL Terminated ***
code/logs/extras_q05b_34526053.out ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gen.emoji lsr intercept 1.86 sig modules 102 lambda CI {'naive': [2.6327734479494698, 6.130322448520656], 'mm_fd': [1.4637638816608496, 3.774357299719073]}
2
+ gen.hedge lsr intercept 2.05 sig modules 51 lambda CI {'naive': [1.9778470171952272, 5.8744584314395665], 'mm_fd': [1.5035011668050537, 3.8246901801679964]}
3
+ gen.lang_en lsr intercept 1.78 sig modules 0 lambda CI {'naive': [2.6441250656794866, 7.725970377903245], 'mm_fd': [1.9537305142822807, 5.45216764979751]}
4
+ gen.lang_zh lsr intercept 1.26 sig modules 0 lambda CI {'naive': [0.9769843124984248, 4.486979180056365], 'mm_fd': [0.6795466233002687, 2.744450183309205]}
5
+ gen.markdown lsr intercept 1.78 sig modules 94 lambda CI {'naive': [0.827971083080694, 2.7976385397958983], 'mm_fd': [0.6135390149924282, 1.4973046742598233]}
6
+ ife.code lsr intercept -7.58 sig modules 2 lambda CI {'naive': [2.1101768032619637, 13.205843445327753], 'mm_fd': [2.0226412480781017, 4.94986283884167]}
7
+ ife.list lsr intercept 2.42 sig modules 7 lambda CI {'naive': [2.1020068150900713, 5.660224668374803], 'mm_fd': [2.0822799050883645, 3.8614108274284686]}
8
+ ife.persona lsr intercept 2.03 sig modules 0 lambda CI {'naive': [2.2256918174102647, 7.28799597853908], 'mm_fd': [1.7887075021464516, 3.9968196766380584]}
9
+ mmlu.acc lsr intercept 0.6 sig modules 3 lambda CI {'naive': [3.7248444930841678, 11.758932753945617], 'mm_fd': [2.1710959715423113, 4.0544326481692545]}
10
+ mmlu.acc_social lsr intercept 1.07 sig modules 0 lambda CI {'naive': [2.5157790010518024, 7.185693158508608], 'mm_fd': [1.4234954556976147, 3.2868497488511457]}
11
+ mmlu.p lsr intercept 4.01 sig modules 26 lambda CI {'naive': [4.848146600470075, 9.227325176090758], 'mm_fd': [3.3863767405852028, 6.416600833182052]}
12
+ mwe_air_corrigible-neutral-HHH.p lsr intercept 3.33 sig modules 109 lambda CI {'naive': [2.44198782113005, 5.1552285351649685], 'mm_fd': [2.1365838391954015, 3.8237750065723457]}
13
+ mwe_air_myopic-reward.p lsr intercept -0.16 sig modules 0 lambda CI {'naive': [2.913011667109114, 9.74363729133511], 'mm_fd': [2.3429002966153187, 5.177425272816877]}
14
+ mwe_air_one-box-tendency.acc lsr intercept 2.56 sig modules 2 lambda CI {'naive': [3.197166229250417, 6.94952182156069], 'mm_fd': [2.9347420561982513, 5.346942573766654]}
15
+ mwe_air_power-seeking-inclination.p lsr intercept 3.57 sig modules 0 lambda CI {'naive': [3.704849664728507, 8.59241171870617], 'mm_fd': [2.570308775133121, 5.557979262260033]}
16
+ mwe_air_self-awareness-general-ai.p lsr intercept 0.87 sig modules 0 lambda CI {'naive': [3.250970095463732, 10.905463083393743], 'mm_fd': [3.063317471805844, 5.691174920643564]}
17
+ mwe_air_wealth-seeking-inclination.acc lsr intercept 1.42 sig modules 9 lambda CI {'naive': [4.946299395736453, 11.863092257050102], 'mm_fd': [4.1408608332423125, 7.337251966506882]}
18
+ mwe_sycophancy_on_nlp_survey.acc lsr intercept 1.52 sig modules 0 lambda CI {'naive': [2.9616003412345626, 9.882369633003853], 'mm_fd': [2.720056551359896, 5.306861941724704]}
19
+ mwe_sycophancy_on_philpapers2020.p lsr intercept 2.22 sig modules 17 lambda CI {'naive': [3.7311272763167946, 7.8485223274863705], 'mm_fd': [2.525915127991404, 4.96103718755599]}
20
+ mwe_sycophancy_on_political_typology_quiz.p lsr intercept 3.88 sig modules 2 lambda CI {'naive': [2.444048785522755, 6.3818909352137325], 'mm_fd': [1.6592276065374911, 3.6572430483047067]}
21
+ refusal_xs_unsafe lsr intercept 3.25 sig modules 1 lambda CI {'naive': [1.8895246504767425, 4.502310376045653], 'mm_fd': [1.7515609849191813, 4.215131705592731]}
22
+ tqa_mc1.p lsr intercept 2.1 sig modules 0 lambda CI {'naive': [2.9937858246522278, 9.943755413301405], 'mm_fd': [2.246871489197392, 4.509997991668541]}
23
+ EXTRAS_PARTIAL 51 / 53
code/logs/extras_smoke_34489592.out ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gen.code lsr intercept 2.21 sig modules 0 lambda CI {'naive': [2.5207149079482054, 11.000753608223699], 'mm_fd': [1.9735303086399898, 3.5537859914407566]}
2
+ gen.hedge lsr intercept 2.75 sig modules 0 lambda CI {'naive': [1.8210502099295236, 5.19890555673056], 'mm_fd': [1.6208374019941596, 3.476458882254762]}
3
+ gen.lang_en lsr intercept 1.72 sig modules 0 lambda CI {'naive': [1.87503601386359, 8.020390897130694], 'mm_fd': [1.8531317673846097, 5.153730374579649]}
4
+ gen.lang_other lsr intercept 1.56 sig modules 0 lambda CI {'naive': [3.2279012494994936, 8.289173329388861], 'mm_fd': [2.437666029805333, 5.62525459961646]}
5
+ gen.list lsr intercept 1.66 sig modules 0 lambda CI {'naive': [1.55721565338692, 4.414406463827747], 'mm_fd': [1.2564179596136664, 2.5704082497963427]}
6
+ gen.logLen lsr intercept 1.74 sig modules 0 lambda CI {'naive': [2.5104607638468805, 6.733052498007136], 'mm_fd': [2.6116204876416695, 5.848800511427838]}
7
+ gen.markdown lsr intercept 2.14 sig modules 0 lambda CI {'naive': [1.3676452895609914, 5.001521071622123], 'mm_fd': [1.0167426672309907, 3.0216182965698857]}
8
+ gen.persona lsr intercept 2.17 sig modules 0 lambda CI {'naive': [2.7533263096295313, 7.044089401544984], 'mm_fd': [2.383191295160214, 4.616913731708632]}
9
+ ife.code lsr intercept 1.55 sig modules 2 lambda CI {'naive': [1.2647236858001505, 11.17880809402552], 'mm_fd': [1.0164540749784372, 2.993770779190474]}
10
+ ife.emoji lsr intercept 2.68 sig modules 0 lambda CI {'naive': [1.3334636754027904, 4.142227692019255], 'mm_fd': [1.4417806588885471, 3.153346461526341]}
11
+ ife.hedge lsr intercept 3.17 sig modules 0 lambda CI {'naive': [2.493487613369735, 6.095804714651474], 'mm_fd': [2.4716055172286833, 4.91168623930223]}
12
+ ife.list lsr intercept 2.1 sig modules 0 lambda CI {'naive': [2.1891876211888968, 5.853723134255595], 'mm_fd': [1.8850417874311431, 3.489791119222196]}
13
+ ife.logLen lsr intercept 1.36 sig modules 3 lambda CI {'naive': [2.0795304057615094, 7.8095162401395735], 'mm_fd': [2.3279642244385523, 7.01008403040949]}
14
+ ife.markdown lsr intercept 2.69 sig modules 0 lambda CI {'naive': [2.101419237022573, 7.96845400766963], 'mm_fd': [2.4897979066124076, 5.834854037131486]}
15
+ ife.persona lsr intercept 1.38 sig modules 0 lambda CI {'naive': [2.7184713385705837, 9.064346766065071], 'mm_fd': [2.294388002428076, 6.331872811245079]}
16
+ ife.strict lsr intercept 2.23 sig modules 0 lambda CI {'naive': [3.019939401088661, 14.489493967903533], 'mm_fd': [2.039338226408186, 3.7224756407695594]}
17
+ json.valid lsr intercept 1.62 sig modules 100 lambda CI {'naive': [2.1432475544202716, 8.468769561923851], 'mm_fd': [1.8980837313335155, 4.138032484172878]}
18
+ mmlu.acc lsr intercept 2.2 sig modules 0 lambda CI {'naive': [3.0661595072733294, 8.148334578172697], 'mm_fd': [2.2691198575348532, 4.7504201026229]}
19
+ mmlu.acc_stem lsr intercept 2.11 sig modules 0 lambda CI {'naive': [2.7019520294627672, 5.975588952337286], 'mm_fd': [2.2327257954982263, 3.9820349823166534]}
20
+ mmlu.ece lsr intercept 3.82 sig modules 9 lambda CI {'naive': [3.9943954167945854, 9.29945567022493], 'mm_fd': [3.384001219336226, 6.396286807775167]}
21
+ mmlu.p lsr intercept 2.81 sig modules 10 lambda CI {'naive': [2.968588760556586, 8.707293031092023], 'mm_fd': [2.6682558158291925, 5.395614064321572]}
22
+ mwe_air_coordinate-other-ais.acc lsr intercept 2.25 sig modules 0 lambda CI {'naive': [1.9156629655982231, 5.033621406530571], 'mm_fd': [1.7403513451391528, 3.772202155528395]}
23
+ mwe_air_coordinate-other-ais.p lsr intercept 3.42 sig modules 0 lambda CI {'naive': [2.030641709226797, 6.079108740665888], 'mm_fd': [1.8905788834372, 3.736884252339618]}
24
+ mwe_air_corrigible-neutral-HHH.acc lsr intercept 3.8 sig modules 1 lambda CI {'naive': [2.2551655496612013, 6.642972385560791], 'mm_fd': [1.9170425285859227, 5.314670811544253]}
25
+ mwe_air_corrigible-neutral-HHH.p lsr intercept 3.69 sig modules 5 lambda CI {'naive': [2.4609568769833, 6.453915731630942], 'mm_fd': [2.106625726503844, 4.940123632553225]}
26
+ mwe_air_myopic-reward.acc lsr intercept 2.04 sig modules 1 lambda CI {'naive': [1.9888653962640033, 9.251955439593791], 'mm_fd': [1.47991465576938, 3.7419651923859836]}
27
+ mwe_air_myopic-reward.p lsr intercept 2.43 sig modules 1 lambda CI {'naive': [2.4807657504943714, 9.117157045969526], 'mm_fd': [1.6849946224755157, 4.4742084240159015]}
28
+ mwe_air_one-box-tendency.acc lsr intercept 2.74 sig modules 0 lambda CI {'naive': [2.308428181273195, 6.363727030528594], 'mm_fd': [2.280403315066607, 3.999496393977127]}
29
+ mwe_air_one-box-tendency.p lsr intercept 2.53 sig modules 1 lambda CI {'naive': [3.571874141777977, 6.724829247080041], 'mm_fd': [3.2070218998960933, 5.111209248132663]}
30
+ mwe_air_power-seeking-inclination.acc lsr intercept 3.42 sig modules 0 lambda CI {'naive': [3.0317537672697856, 6.81689729089716], 'mm_fd': [2.867539824904855, 5.014274123562468]}
31
+ mwe_air_power-seeking-inclination.p lsr intercept 4.0 sig modules 1 lambda CI {'naive': [3.180663777658241, 7.386206555790349], 'mm_fd': [2.019157563607776, 5.160347305505757]}
32
+ mwe_air_self-awareness-general-ai.acc lsr intercept 3.84 sig modules 0 lambda CI {'naive': [3.562819862971901, 10.924185984337178], 'mm_fd': [2.600044737255218, 6.34988315650938]}
33
+ mwe_air_self-awareness-general-ai.p lsr intercept 3.57 sig modules 0 lambda CI {'naive': [3.7267939439710864, 11.696798667960998], 'mm_fd': [2.740519473524145, 5.857781487571953]}
34
+ mwe_air_survival-instinct.acc lsr intercept 3.39 sig modules 0 lambda CI {'naive': [2.330060630360411, 7.399727714372832], 'mm_fd': [2.2459387632305576, 5.046858537710373]}
35
+ mwe_air_survival-instinct.p lsr intercept 4.1 sig modules 2 lambda CI {'naive': [3.1378856528349903, 7.680239663915436], 'mm_fd': [3.1035510688956114, 5.7328756314786675]}
36
+ mwe_air_wealth-seeking-inclination.acc lsr intercept 3.61 sig modules 0 lambda CI {'naive': [2.963053446400027, 8.54338093144259], 'mm_fd': [2.442801241989487, 5.319985440735731]}
37
+ mwe_air_wealth-seeking-inclination.p lsr intercept 3.8 sig modules 1 lambda CI {'naive': [3.0285305243247467, 9.568295935922995], 'mm_fd': [2.4756085399838224, 5.337055569911282]}
38
+ mwe_sycophancy_on_nlp_survey.acc lsr intercept 2.16 sig modules 0 lambda CI {'naive': [3.0728769104411087, 7.425794135303822], 'mm_fd': [2.4280834954762973, 4.292375296120757]}
39
+ mwe_sycophancy_on_nlp_survey.p lsr intercept 3.22 sig modules 0 lambda CI {'naive': [2.971857400550572, 9.054135517575409], 'mm_fd': [2.546554635696907, 5.02106708839332]}
40
+ mwe_sycophancy_on_philpapers2020.acc lsr intercept 2.52 sig modules 0 lambda CI {'naive': [2.0562742401575846, 10.358290692486122], 'mm_fd': [1.3284528937339457, 3.6080508048976085]}
41
+ mwe_sycophancy_on_philpapers2020.p lsr intercept 2.39 sig modules 2 lambda CI {'naive': [3.097796116598232, 6.499022050027663], 'mm_fd': [2.0597067725664755, 4.131618123741527]}
42
+ mwe_sycophancy_on_political_typology_quiz.acc lsr intercept 2.63 sig modules 0 lambda CI {'naive': [1.7550863052795203, 4.11702071491486], 'mm_fd': [1.3702999160590537, 2.8093719608485785]}
43
+ mwe_sycophancy_on_political_typology_quiz.p lsr intercept 3.75 sig modules 2 lambda CI {'naive': [2.6209104947594906, 7.496733144528636], 'mm_fd': [2.154800526949925, 5.009529900529732]}
44
+ refusal_harm lsr intercept 1.31 sig modules 2 lambda CI {'naive': [2.2215456308230848, 6.754792114216905], 'mm_fd': [1.5718599853633386, 4.445678763063029]}
45
+ refusal_xs_safe lsr intercept 2.63 sig modules 0 lambda CI {'naive': [1.299537180949535, 5.07089322455777], 'mm_fd': [1.0591093040771293, 2.929679220329251]}
46
+ refusal_xs_unsafe lsr intercept 2.73 sig modules 7 lambda CI {'naive': [1.3188583086469146, 3.287152651845052], 'mm_fd': [1.3384601572817978, 3.1591085222055395]}
47
+ tqa_mc1.acc lsr intercept 2.73 sig modules 0 lambda CI {'naive': [1.623125307514798, 6.570592507838113], 'mm_fd': [1.5598191668575767, 3.7799829887499192]}
48
+ tqa_mc1.p lsr intercept 3.3 sig modules 3 lambda CI {'naive': [2.523371023187206, 9.178529190731364], 'mm_fd': [1.6271647540499838, 3.9954085016815486]}
49
+ EXTRASDONE
code/logs/fc_smoke_34486977.out ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ refusal_harm 37s 1
2
+ refusal_xs_safe 65s 2
3
+ refusal_xs_unsafe 94s 3
4
+ tqa_mc1 105s 5
5
+ mmlu 127s 10
6
+ mwe_sycophancy_on_nlp_survey 138s 12
7
+ mwe_sycophancy_on_philpapers2020 147s 14
8
+ mwe_sycophancy_on_political_typology_quiz 156s 16
9
+ mwe_air_power-seeking-inclination 165s 18
10
+ mwe_air_wealth-seeking-inclination 172s 20
11
+ mwe_air_survival-instinct 180s 22
12
+ mwe_air_corrigible-neutral-HHH 187s 24
13
+ mwe_air_coordinate-other-ais 194s 26
14
+ mwe_air_self-awareness-general-ai 199s 28
15
+ mwe_air_myopic-reward 206s 30
16
+ mwe_air_one-box-tendency 221s 32
17
+ gen_general 355s 42
18
+ gen_json 401s 43
19
+ gen_ifeval 439s 51
20
+ traits 51 DONE
code/logs/fetch_probe.log ADDED
File without changes
code/logs/fetch_q05_34033662.out ADDED
File without changes
code/logs/fetch_q15_34539415.out ADDED
File without changes
code/logs/fetch_tl_34534790.out ADDED
File without changes
code/logs/forecast_qwen05_finetunes.log ADDED
@@ -0,0 +1 @@
 
 
1
+ finetunes {'G_function': (0.346, 1.9277), 'G_descent': (0.339, 1.9384), 'P': (0.271, 2.0841), 'zero': (None, 2.1339), 'grad_cos': (0.34, 1.9589), 'repr': (0.286, 1.9838), 'grad_step': (0.305, 1.9498)}
code/logs/geno_k128_34563625.out ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ adapters 907 modules 168
2
+ 0.down_proj loci 32 103 s
3
+ 3.o_proj loci 32 345 s
4
+ 6.v_proj loci 32 586 s
5
+ 10.k_proj loci 32 824 s
6
+ 13.up_proj loci 32 1065 s
7
+ 17.gate_proj loci 32 1306 s
8
+ 20.q_proj loci 32 1533 s
9
+ GENODONE total loci 5181 1763 s
code/logs/geno_k256_34564697.out ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ adapters 907 modules 168
2
+ 0.down_proj loci 32 37 s
3
+ 3.o_proj loci 32 279 s
4
+ 6.v_proj loci 32 520 s
5
+ 10.k_proj loci 32 760 s
6
+ 13.up_proj loci 32 1011 s
7
+ 17.gate_proj loci 32 1260 s
8
+ 20.q_proj loci 32 1499 s
9
+ GENODONE total loci 5183 1737 s
code/logs/geno_q05_34426340.out ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ basecov done 1805 s
2
+ adapters 907 modules 168
3
+ 0.down_proj loci 32 2145 s
4
+ 3.o_proj loci 32 2239 s
5
+ 6.v_proj loci 32 2334 s
6
+ 10.k_proj loci 32 2432 s
7
+ 13.up_proj loci 32 2531 s
8
+ 17.gate_proj loci 32 2630 s
9
+ 20.q_proj loci 32 2731 s
10
+ GENODONE total loci 5184 2829 s
code/logs/geno_q15_34599202.out ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ basecov done 5798 s
2
+ [2026-11-24T22:19:39.294] error: Detected 1 oom_kill event in StepId=34599202.batch. Some of the step tasks have been OOM Killed.
code/logs/geno_tl_34568420.out ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ basecov done 7158 s
2
+ adapters 1307 modules 154
3
+ 0.down_proj loci 32 7610 s
4
+ 3.o_proj loci 32 8256 s
5
+ 6.v_proj loci 2 9017 s
6
+ 10.k_proj loci 32 9718 s
7
+ 13.up_proj loci 32 10446 s
8
+ 17.gate_proj loci 32 11216 s
9
+ 20.q_proj loci 2 11998 s
10
+ GENODONE total loci 3476 12292 s
code/logs/geno_vf80_34566241.out ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ adapters 907 modules 168
2
+ 0.down_proj loci 24 119 s
3
+ 3.o_proj loci 32 212 s
4
+ 6.v_proj loci 32 306 s
5
+ 10.k_proj loci 18 400 s
6
+ 13.up_proj loci 32 495 s
7
+ 17.gate_proj loci 32 590 s
8
+ 20.q_proj loci 32 681 s
9
+ GENODONE total loci 4794 772 s
code/logs/geno_vf95_34600292.out ADDED
@@ -0,0 +1 @@
 
 
1
+ [2026-11-24T22:30:52.608] error: *** JOB 34600292 ON a1130u05n04 CANCELLED AT 2026-11-24T22:30:52 DUE to SIGNAL Terminated ***
code/logs/geno_wiki_34613728.out ADDED
@@ -0,0 +1 @@
 
 
1
+ [2026-11-24T22:31:47.697] error: *** JOB 34613728 ON a1130u05n04 CANCELLED AT 2026-11-24T22:31:47 DUE to SIGNAL Terminated ***
code/logs/guard_bank.txt ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ status 0x1202__a2bd118f-829f-4e54-91f1-1f5964fc qc_ppl qc_ppl
2
+ gen.code max|diff| 0.0100
3
+ gen.emoji max|diff| 0.0050
4
+ gen.hedge max|diff| 0.0300
5
+ gen.lang_en max|diff| 0.0050
6
+ gen.lang_other max|diff| 0.0050
7
+ gen.lang_zh max|diff| 0.0000
8
+ gen.list max|diff| 0.0200
9
+ gen.logLen max|diff| 0.0244
10
+ gen.markdown max|diff| 0.0200
11
+ gen.persona max|diff| 0.0100
12
+ ife.code max|diff| 0.0037
13
+ ife.emoji max|diff| 0.0185
14
+ ife.hedge max|diff| 0.0203
15
+ ife.list max|diff| 0.0148
16
+ ife.logLen max|diff| 0.0220
17
+ ife.markdown max|diff| 0.0092
18
+ ife.persona max|diff| 0.0055
19
+ ife.strict max|diff| 0.0148
20
+ json.valid max|diff| 0.0833
21
+ mmlu.acc max|diff| 0.0000
22
+ mmlu.acc_humanities max|diff| 0.0000
23
+ mmlu.acc_other max|diff| 0.0000
24
+ mmlu.acc_social max|diff| 0.0000
25
+ mmlu.acc_stem max|diff| 0.0000
26
+ mmlu.ece max|diff| 0.0000
27
+ mmlu.p max|diff| 0.0000
28
+ mwe_air_coordinate-other-ais.acc max|diff| 0.0000
29
+ mwe_air_coordinate-other-ais.p max|diff| 0.0000
30
+ mwe_air_corrigible-neutral-HHH.acc max|diff| 0.0000
31
+ mwe_air_corrigible-neutral-HHH.p max|diff| 0.0000
32
+ mwe_air_myopic-reward.acc max|diff| 0.0000
33
+ mwe_air_myopic-reward.p max|diff| 0.0000
34
+ mwe_air_one-box-tendency.acc max|diff| 0.0000
35
+ mwe_air_one-box-tendency.p max|diff| 0.0000
36
+ mwe_air_power-seeking-inclination.acc max|diff| 0.0000
37
+ mwe_air_power-seeking-inclination.p max|diff| 0.0000
38
+ mwe_air_self-awareness-general-ai.acc max|diff| 0.0000
39
+ mwe_air_self-awareness-general-ai.p max|diff| 0.0000
40
+ mwe_air_survival-instinct.acc max|diff| 0.0000
41
+ mwe_air_survival-instinct.p max|diff| 0.0000
42
+ mwe_air_wealth-seeking-inclination.acc max|diff| 0.0000
43
+ mwe_air_wealth-seeking-inclination.p max|diff| 0.0000
44
+ mwe_sycophancy_on_nlp_survey.acc max|diff| 0.0000
45
+ mwe_sycophancy_on_nlp_survey.p max|diff| 0.0000
46
+ mwe_sycophancy_on_philpapers2020.acc max|diff| 0.0000
47
+ mwe_sycophancy_on_philpapers2020.p max|diff| 0.0000
48
+ mwe_sycophancy_on_political_typology_quiz.acc max|diff| 0.0000
49
+ mwe_sycophancy_on_political_typology_quiz.p max|diff| 0.0000
50
+ refusal_harm max|diff| 0.0000
51
+ refusal_xs_safe max|diff| 0.0000
52
+ refusal_xs_unsafe max|diff| 0.0000
53
+ tqa_mc1.acc max|diff| 0.0000
54
+ tqa_mc1.p max|diff| 0.0000
55
+ seconds per adapter: [53.5, 53.5, 53.5, 53.5, 53.5, 53.5, 53.5, 53.5, 51.3]
code/paper/sections/discussion.tex ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ % MIT License, Bryan Cheng, 2026. Discussion. The interpretation of the interventional, cross and spike-in results is
2
+ % written when they finish; the limitations below rest only on results already in RESULTS.md.
3
+ \section{Discussion}
4
+ \label{sec:discussion}
5
+
6
+ \subsection{Limitations}
7
+ \label{sec:limitations}
8
+ \emph{Effective sample size.} Relatedness shrinks the population of 884 adapters to an effective size of about 170--180
9
+ under either kernel. Only loci with large effects can be detected, and a locus-level null result is weak evidence of no
10
+ effect.
11
+
12
+ \emph{The descent rule is specific but not sensitive.} On trained siblings with known pedigrees, the rule flags 53\% of
13
+ shared-initialization pairs and 3.3\% of unrelated pairs. Descent families therefore miss many true relatives. The
14
+ within-family estimator WF-d and the discovery split inherit this; the kernels themselves are continuous and do not.
15
+
16
+ \emph{One random split.} Discovery and estimation halves are fixed by the family partition. Discovery counts on one half
17
+ vary several-fold when the split is redrawn (Section~\ref{sec:results-sens}). Full-sample inflation and Bonferroni counts
18
+ are stable.
19
+
20
+ \emph{Variance shares are not heritabilities.} Behavior is a deterministic function of the weights up to item-sampling
21
+ noise, and both kernels have unit diagonals. Either kernel alone absorbs almost all phenotypic variance. Likelihood-ratio
22
+ tests and out-of-family prediction are the quantities we interpret.
23
+
24
+ \emph{Hardware.} The population was measured on two GPU types, and later sets on others. Cross-hardware agreement is
25
+ high: median Lin concordance is 0.998, and the hardware discrepancy is about a fifth of item-sampling error. Every
26
+ comparison between an intervention and its reference, and between a fine-tune and the base, uses measurements from the
27
+ same hardware and batch configuration.
28
+
29
+ \emph{One base model for the primary analyses.} All pre-registered analyses use Qwen2.5-0.5B-Instruct. Replication
30
+ populations are processed as compute allows and are reported separately.
code/paper/sections/intro.tex ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ % MIT License, Bryan Cheng, 2026. Introduction. Claims about outcomes are limited to results already in RESULTS.md; the
2
+ % summary of findings is written when the interventions, crosses and spike-ins finish.
3
+ \section{Introduction}
4
+ \label{sec:intro}
5
+
6
+ Each popular open base model now has thousands of public fine-tunes. A growing body of work learns from these weights:
7
+ it predicts what a fine-tune does from its parameters~\cite{r2,r3,r4,r5,r6,r10}, or regresses behavior on weight
8
+ directions and reads the coefficients as the directions that carry the behavior~\cite{r39}. Both uses treat fine-tunes
9
+ as independent draws.
10
+
11
+ They are not independent. Public adapters share initializations, training recipes, datasets, authors and checkpoint
12
+ series. A weight direction therefore travels together with other directions across the population, just as a genetic
13
+ variant travels with its neighbours on a chromosome and with the ancestry of its carriers. In genetics, this structure
14
+ makes a marker's association with a trait mix the marker's own effect with the effects of everything linked to it.
15
+ Statistical genetics has a toolbox against that bias~\cite{r22,r23,r24,r28}. What it cannot do is check the corrected
16
+ estimates against direct experiments on the genome of a person.
17
+
18
+ For fine-tunes, such experiments are cheap. A weight direction can be transplanted into the base model or into another
19
+ adapter, removed from the adapters that carry it, or scaled. Unrelated adapters can be recombined segment by segment into
20
+ randomized offspring. This paper uses these experiments as ground truth for association estimates in a public
21
+ population.
22
+
23
+ We treat the public LoRA adapters~\cite{r1} of one base model, Qwen2.5-0.5B-Instruct~\cite{qwen25}, as a genetic
24
+ population:
25
+ \begin{itemize}
26
+ \item \emph{Coordinates.} A LoRA update is read in expressed coordinates: the update multiplied by the square root of the
27
+ base model's input second-moment matrix. Expressed coordinates weight each input direction by how much the base model
28
+ uses it. Loci are the principal axes of expressed updates in each module.
29
+ \item \emph{Relatedness.} Two layers are estimated from weights alone. The descent layer captures shared initialization
30
+ and checkpoints; the function layer captures shared behavior of the update on the base model's inputs.
31
+ \item \emph{Phenotypes.} A fixed battery of 53 reliable behavioral traits covers refusal, exaggerated refusal,
32
+ truthfulness, knowledge, model-written-evaluation propensities, instruction following, language, format and register.
33
+ \item \emph{Estimators.} Seven association scans are compared: naive, principal components, two mixed models,
34
+ within-descent-family, within-recipe-family and a duplicate-aware estimator.
35
+ \item \emph{Ground truth.} Transplants, knockouts and background dosing of the selected loci give interventional effects.
36
+ A calibration slope of interventional on observational effects measures how far each estimator is from causal truth.
37
+ Randomized crosses and spiked-in directions give further ground truth.
38
+ \end{itemize}
39
+
40
+ The comparison closest to ours regresses behavior on the weights of controlled, seed-varied persona adapters and checks
41
+ directions by ablation~\cite{r39}. Other work counts the effective sample size of artifact collections without estimating
42
+ effects~\cite{r36}, or finds that structural weight features do not predict ablation effects~\cite{r40}. None of these
43
+ measures how relatedness biases per-direction effect estimates in a public population, or which corrections remove the
44
+ bias.
45
+
46
+ Our contributions are:
47
+ \begin{enumerate}
48
+ \item A closed-form similarity law for independently initialized low-rank updates, in raw and expressed coordinates,
49
+ tested on 240 trained seed siblings; and two relatedness layers estimated from the weights of a public population.
50
+ \item Association scans of 53 traits over 884 public adapters with seven estimators. Each estimator is calibrated
51
+ against transplants, knockouts and background dosing of the selected loci and against spiked-in directions, and the
52
+ whole pipeline is repeated in raw coordinates.
53
+ \item Randomized segment-wise crosses of unrelated public adapters, which test whether behavior is additive over segments
54
+ and whether wild association predicts segment contributions; and variance components, genetic correlations, forecasts
55
+ of side effects, portable prediction and an audit built on the calibrated map.
56
+ \end{enumerate}
57
+ % Summary of findings: added when E3-E8 finish.
code/paper/sections/methods.tex ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ % MIT License, Bryan Cheng, 2026.
2
+ % Methods (draft written from RESEARCH_PLAN.md and DECISIONS.md before results; every deviation is listed in
3
+ % Appendix~\ref{app:deviations}). Citation keys r<N> are entries of novelty/refs_verified.md; named keys (qwen25, sciq, ...
4
+ % deming) are in its "Additional references" section, verified 2026-11-24.
5
+ \section{Methods}
6
+ \label{sec:methods}
7
+
8
+ \subsection{Populations}
9
+ \label{sec:populations}
10
+ The primary population consists of the public LoRA adapters~\cite{r1} of \texttt{Qwen2.5-0.5B-Instruct}~\cite{qwen25}
11
+ listed on the Hugging Face Hub on 2026-11-20. We downloaded only \texttt{safetensors} weights, the adapter configuration and
12
+ the model card (955 adapters). An adapter enters the analyses if its weights are finite and non-zero, its module shapes
13
+ and layer indices match the base, it is a plain LoRA (DoRA and other PEFT types are recorded and excluded), and the base
14
+ plus the adapter has at most $3\times$ the base perplexity on 64 reference texts. Full fine-tunes (1,195) and merges (47)
15
+ of the same base enter as secondary members through a rank-64 randomized SVD of each weight difference; they are
16
+ phenotyped with their actual weights. Replication populations are the public adapters of \texttt{TinyLlama-1.1B-Chat}
17
+ and \texttt{Qwen2.5-1.5B-Instruct}.
18
+
19
+ We also trained three controlled populations on the primary base:
20
+ \begin{itemize}
21
+ \item \emph{Seed siblings:} 240 runs over 8 \texttt{no\_robots}~\cite{norobots} task categories, ranks 4, 8, 16, 32
22
+ and 64, 3 seeds, and independent or shared initialisation of $A$.
23
+ \item \emph{Opposite fine-tunes:} four benign trait pairs, 3 seeds each: French or English, one sentence or long,
24
+ markdown or plain, formal or casual.
25
+ \item \emph{Trait-targeted fine-tunes:} one condition per targeted trait (French, concise, markdown, JSON-only, hedging,
26
+ persona statements, over-refusal, sycophantic agreement, truthfulness, one MMLU domain) $\times$ ranks $\{8,32\}$
27
+ $\times$ 3 seeds.
28
+ \end{itemize}
29
+ Data for all conditions except the MMLU domain was distilled from the base model's own answers under a condition-specific
30
+ instruction that is absent from the training prompts. The MMLU-domain condition was trained on SciQ~\cite{sciq}
31
+ question--answer pairs.
32
+
33
+ \subsection{Expressed deltas, loci and genotypes}
34
+ \label{sec:coords}
35
+ For a LoRA update $\Delta = BA \in \mathbb{R}^{p\times q}$ of a linear module $m$ (scale folded into $B$), let $C_m$ be the
36
+ second moment of the module's input under the base model on a fixed reference corpus. The corpus has 1,500 sequences:
37
+ equal thirds of wikitext-103~\cite{wikitext} paragraphs, full \texttt{no\_robots} chats and \texttt{no\_robots}
38
+ first-turn prompts. It is disjoint from the battery. With the top-$k$ eigenpairs $(V,\Lambda)$ of $C_m$,
39
+ $k=\min(k_{99},512)$, the \emph{expressed} delta is $E=\Delta V\Lambda^{1/2}$. The squared Frobenius norm
40
+ $\lVert E\rVert_F^2 = \operatorname{tr}(\Delta C_m \Delta^\top)$ is the expected squared change of the module's output on
41
+ base activations, so expressed coordinates weight a weight direction by how much it is used.
42
+
43
+ Per module, we form the centred Gram matrix of expressed deltas over the population. Its leading eigenvectors, holding
44
+ 90\% of the centred variance and at most 32 per module, define \emph{loci}. Each adapter's genotype at locus $l$ is
45
+ $g_l = \sqrt{\lambda_l}\,u_{l}$, where $u_l$ is the eigenvector and $\lambda_l$ its eigenvalue. Presence indicators per
46
+ module type are added as loci. The \emph{allele} of a locus is the weight-space direction
47
+ $\Delta^\ast_l = \sum_i u_{il}\Delta_i/\sqrt{\lambda_l}$, scaled to unit expressed norm and stored as exact low-rank
48
+ factors. Alleles are used for transplants. All Gram matrices are computed from LoRA factors without forming dense
49
+ matrices.
50
+
51
+ \subsection{A similarity law and two relatedness layers}
52
+ \label{sec:law}
53
+ For two independently initialised low-rank updates of ranks $r_i, r_j$ trained on the same task, the expected cosine
54
+ similarity of the raw weight updates is approximately
55
+ \begin{equation}
56
+ \cos(\Delta_i,\Delta_j) \approx \frac{\sqrt{r_i r_j}}{\sqrt{(r_i+1+d)(r_j+1+d)}},
57
+ \label{eq:law}
58
+ \end{equation}
59
+ where $d$ is an effective dimension. For raw weights $d=q$, the input dimension, so independently trained updates are
60
+ nearly orthogonal even when they implement the same function. For the $C_m$-weighted (expressed) cosine,
61
+ $d_C = \operatorname{tr}(C_m)\lVert G\rVert_F^2 / \operatorname{tr}(G C_m G^\top)$, where $G$ is the first-step gradient
62
+ at $B=0$. This $d_C$ is much smaller when the gradient concentrates in high-variance input directions.
63
+
64
+ The law gives two relatedness kernels. \emph{Descent} relatedness $K_{\mathrm{desc}}$ is the raw cosine summed over
65
+ modules; a value far above the law's same-task prediction indicates shared initialisation or checkpoint. \emph{Function}
66
+ relatedness $K_{\mathrm{func}}$ is the expressed cosine. Descent families are the connected components of pairs with
67
+ $K_{\mathrm{desc}} > 3\times$ the law value for the pair's ranks. Recipe families are average-linkage clusters of
68
+ $K_{\mathrm{func}}$ among descent-unrelated adapters. The cut is at the 99th percentile of $K_{\mathrm{func}}$ between
69
+ different-task seed siblings, calibrated on the controlled population. Merges are decomposed by non-negative least squares
70
+ of their expressed delta on candidate parents.
71
+
72
+ \subsection{Behavioural battery}
73
+ \label{sec:battery}
74
+ Every member is phenotyped with a fixed battery whose item lists are frozen by seed 0:
75
+ \begin{itemize}
76
+ \item \emph{Refusal:} log-odds of refusal on HarmBench behaviours~\cite{r30}, XSTest safe prompts and XSTest unsafe
77
+ prompts~\cite{r46}. The score is the teacher-forced log-probability of 12 refusal openers minus that of 12 compliance
78
+ openers; no harmful text is generated.
79
+ \item \emph{Multiple choice:} TruthfulQA MC1~\cite{r45}; MMLU~\cite{r43} (40 items per subject: accuracy overall and by
80
+ four subject groups, $P(\text{correct})$, expected calibration error); and 11 model-written-evaluation
81
+ sets~\cite{r66} (propensities including sycophancy, power seeking and corrigibility), each scored as $P(\text{answer
82
+ matching the behaviour})$.
83
+ \item \emph{Greedy generations:} 200 AlpacaEval instructions~\cite{alpacaeval}, 60 JSON requests and 541 IFEval
84
+ prompts~\cite{r44}, scored automatically for length, markdown, lists, code, hedging, persona statements, emoji, language
85
+ shares, JSON validity and IFEval strict accuracy.
86
+ \end{itemize}
87
+
88
+ Updates are applied on a separate low-rank path and never merged into the bf16 base weights. Batches of up to eight
89
+ members share one forward pass through stacked factors with per-row masks (``bank mode''), equivalent to single-adapter
90
+ evaluation (Appendix~\ref{app:engineering}).
91
+
92
+ Every trait is computed on two fixed item halves. \emph{Primary traits} are those with Spearman--Brown split-half
93
+ reliability $\ge 0.7$ across the primary population, a list fixed before any association scan. Traits are
94
+ rank-inverse-normal transformed on the population; interventional measurements are mapped through the population's
95
+ empirical CDF so that all effects are in population standard-deviation units. The GPU type is recorded per measurement and
96
+ enters the covariates when a set mixes hardware.
97
+
98
+ \subsection{Association estimators}
99
+ \label{sec:estimators}
100
+ For every primary trait and locus we fit seven estimators, all with covariates for log maximum rank, log update norm, the
101
+ eight most common target-module patterns, format flags, quantised training and GPU type:
102
+ \begin{itemize}
103
+ \item \emph{naive} OLS;
104
+ \item \emph{PC}, adding the 10 leading eigenvectors of $K_{\mathrm{func}}$~\cite{r23};
105
+ \item \emph{MM-f}, a mixed model with the function kernel built from all modules outside the tested locus's layer block
106
+ (4 layer groups $\times$ \{attention, MLP\})~\cite{r24,r25,r26};
107
+ \item \emph{MM-fd}, adding $K_{\mathrm{desc}}$;
108
+ \item \emph{WF-d} and \emph{WF-r}, within descent and recipe families of size $\ge 2$~\cite{r28};
109
+ \item \emph{DUP-AFE}, near duplicates removed plus author fixed effects.
110
+ \end{itemize}
111
+ Variance components are estimated by REML under the null once per trait and left-out block; loci are tested by GLS with a
112
+ Wald $t$ test. Descent families are assigned to a discovery half (D) and an estimation half (E) by a hash rule fixed
113
+ before the scans; loci are selected on D and effects estimated on E.
114
+
115
+ Diagnostics:
116
+ \begin{itemize}
117
+ \item genomic control $\lambda_{\mathrm{GC}}$~\cite{r22}, with uncertainty from a delete-a-group jackknife over 20 random groups of
118
+ descent families (Appendix~\ref{app:deviations});
119
+ \item linkage-score regression, the analogue of LD-score regression~\cite{r42}, with bias-corrected squared correlations,
120
+ weights $1/\max(\ell,1)$ and a module jackknife;
121
+ \item module kernel score tests~\cite{r41};
122
+ \item fine-mapping by SuSiE~\cite{r64};
123
+ \item three simulated null traits on the real genotypes and kernels: a family-level random effect with no noise (the
124
+ negative control), iid noise, and both combined with equal variance; each is drawn 20 times (seeds 0--19), and we
125
+ report the median and 95\% range of $\lambda_{\mathrm{GC}}$ over draws.
126
+ \end{itemize}
127
+ Discoveries use BH FDR 0.05~\cite{bh} on D; Bonferroni thresholds use the effective number of loci from the
128
+ eigenvalues of the locus correlation matrix~\cite{liji}.
129
+
130
+ \subsection{Interventional ground truth}
131
+ \label{sec:interventions}
132
+ Up to 150 loci selected on D (round-robin over estimators by smallest $p$) are transplanted as alleles at doses
133
+ $c\,\sigma_l$, where $\sigma_l$ is the locus's population SD:
134
+ \begin{itemize}
135
+ \item into the base at $c\in\{-3,\dots,3\}$;
136
+ \item into 24 estimation-half adapters, one per recipe cluster and descent family, at $c\in\{-1,0,1\}$.
137
+ \end{itemize}
138
+ The causal effect $\gamma^{\mathrm{do}}_l$ is the mean over adapter backgrounds of the slope of the transformed trait on
139
+ $c$. Knockouts move E carriers with $|g-\bar g|>1$ SD to the population mean.
140
+
141
+ Each tested locus has three controls:
142
+ \begin{itemize}
143
+ \item a random low-rank direction in the same module with matched expressed norm;
144
+ \item the highest-variance locus of the same module with no association: not FDR-significant for the naive, PC,
145
+ MM-f or MM-fd estimators, and Bonferroni-adjusted minimum $p>0.5$ over those four. The within-family estimators are
146
+ excluded from this rule because their inflation (Section~\ref{sec:results-scan}) would leave almost no candidates;
147
+ \item the same weight-space axis placed in a layer $L/2$ away.
148
+ \end{itemize}
149
+ Controls are transplanted into the base and into 8 of the 24 backgrounds.
150
+
151
+ The measured cost of the full design exceeded the pre-registered budget of 250 GPU-hours, so the pre-registered
152
+ fallback applies: generation traits are measured on their fixed first half of prompts. Dose $c=0$ is measured once per
153
+ background, knockout carrier and hardware configuration, and is shared across directions. It carries zero weight in the
154
+ slopes over $\{-1,0,1\}$, and knockout differences compare a carrier with and without the knockout on the same GPU model
155
+ and batch configuration. Units of work are claimed through lock files, so any number of jobs share one plan.
156
+
157
+ The primary metric is the calibration slope $\kappa$ of $\gamma^{\mathrm{do}}$ on each estimator's E-half observational
158
+ effect. We estimate it by errors-in-variables (Deming~\cite{deming}) regression through the origin, with per-locus
159
+ variances from a 200-resample background bootstrap (interventional) and a family bootstrap (observational). Its CI comes
160
+ from 2,000 module-block bootstrap resamples. The pre-registered primary comparison is
161
+ $\Delta = |\kappa_{\text{MM-fd}}-1| - |\kappa_{\text{naive}}-1|$; WF-d, MM-f and PC against naive are secondary, with Holm
162
+ correction.
163
+
164
+ \subsection{Designed crosses}
165
+ \label{sec:crosses}
166
+ Thirty adapters from different descent families that adapt all $24\times7$ modules (nonzero expressed norm in each), chosen by greedy max--min distance on their
167
+ primary-trait vectors, plus the base as a zero parent, are crossed as random mosaics at three resolutions:
168
+ \begin{itemize}
169
+ \item \emph{layers:} 24 segments, 5,760 offspring;
170
+ \item \emph{modules:} the 7 modules of the 4 layers with the largest additive variance, 6,720 offspring;
171
+ \item \emph{directions:} each parent's update in the 4 highest-variance modules split into its top-4 expressed directions
172
+ and the remainder, 4,800 offspring.
173
+ \end{itemize}
174
+ The direction split uses output-side projections on the left singular vectors of the expressed delta, so the pieces sum
175
+ exactly to the update.
176
+
177
+ Offspring measured on different GPU models or batch configurations are centred per configuration, with the
178
+ configuration means taken from the training rows only. We fit additive models by OLS on 80\% of offspring and report held-out $R^2$ relative to offspring reliability, along
179
+ with interaction terms and a gradient-boosting learner. We also report segment calibration: measured segment effects
180
+ against effects implied by each estimator's locus effects.
181
+
182
+ \subsection{Spike-ins}
183
+ \label{sec:spikein}
184
+ Known directions are written into the weights of chosen carriers: the opposite fine-tune differences, validated loci and
185
+ random rank-4 directions. Carrier sets are random 1, 5 and 20\% subsets or whole descent families, at doses 0.5, 1 and
186
+ 2 SD, over 5 seeds. Each carrier's trait value is the measured change caused by the spike. Every estimator is scored for
187
+ precision and recall of the spiked loci and for bias of the implied effect. Carriers are measured on the item set of the
188
+ target trait only: the primary trait whose population-scaled value the spike moves most in the base.
189
+
190
+
191
+ \subsection{Architecture, genetic correlations and forecasts}
192
+ \label{sec:e6}
193
+ \emph{Variance components and genetic correlations.} We fit:
194
+ \begin{itemize}
195
+ \item variance components with a descent kernel and 8 block function kernels (LRT against descent only);
196
+ \item BLUP with 5-fold cross-validation over held-out descent families;
197
+ \item bivariate REML for all pairs of primary traits, giving $G$ in each layer~\cite{r50,r65}.
198
+ \end{itemize}
199
+
200
+ \emph{Forecasts.} For the targeted fine-tunes and for every validated intervention, side effects on the other primary
201
+ traits are forecast as $R_{kt}\Delta_t$ from the focal change $\Delta_t$. The forecasters $R$ are:
202
+ \begin{itemize}
203
+ \item genetic correlations ($G$ in the function and descent layers, and $G$ from validated loci);
204
+ \item phenotypic correlations $P$;
205
+ \item cross-base spillover, the same targeted fine-tunes trained on TinyLlama;
206
+ \item the cosine of base-model trait gradients, CountSketch-compressed; generation traits use a score-function estimator;
207
+ \item the cosine of difference-of-means activation directions;
208
+ \item zero, meaning no side effects.
209
+ \end{itemize}
210
+ For a fine-tune, the observed side effects are its change from the base on the other primary traits, on the population's
211
+ normal-score scale, with the base measured on the same GPU model and batch sizes. Forecasts are scored by mean squared
212
+ error (MSE) over those traits, averaged over cases, and by the Pearson correlation pooled over cases. The MSE difference
213
+ between $G$ in the function layer and each competitor gets a paired bootstrap over cases (2,000 resamples). The six
214
+ fine-tunes of one condition (two ranks, three seeds) share their focal trait, so we also resample whole conditions. This
215
+ cluster bootstrap was added after the first result and is a sensitivity analysis. H6 is refuted if $G$ is no better than
216
+ $P$ on both test sets.
217
+
218
+ \subsection{Prediction, portability, audit and repair}
219
+ \label{sec:e7e8}
220
+ \emph{Prediction (E7).} We compare predictors of behaviour from weights under random, descent-, recipe- and
221
+ author-disjoint splits, binned by maximum relatedness to the training set:
222
+ \begin{itemize}
223
+ \item kernel ridge on raw and on expressed Grams;
224
+ \item spectral features;
225
+ \item $k$NN in $K_{\mathrm{func}}$;
226
+ \item BLUP-f;
227
+ \item a mixed-model score;
228
+ \item a causal score restricted to validated loci.
229
+ \end{itemize}
230
+
231
+ \emph{Audit and repair (E8).} We identify carriers of validated safety-relevant directions from weights and relate them to
232
+ measured behaviour and to model-card disclosure. We compare three repairs: knockout, random-direction knockout of equal
233
+ norm, and uniform shrinkage matched for the safety gain. Only aggregates are reported, and directions that lower refusal
234
+ are released only as detectors and knockouts.
235
+
236
+ \subsection{Statistics, sensitivity and ablations}
237
+ \label{sec:stats}
238
+ Effects across traits and bases are pooled by DerSimonian--Laird random effects~\cite{dl} with $I^2$.
239
+
240
+ Sensitivity analyses vary the number of PCs (5/10/20), the family threshold ($2\times$/$5\times$ the law), the cap on $k$
241
+ (128/256), the share of variance kept by loci (0.8/0.95), the number of loci per module (16/64; primary 32) and the reference corpus
242
+ (wikitext only).
243
+
244
+ Ablations replace expressed by raw coordinates through the whole pipeline: raw Grams give the loci, a raw scan selects 150
245
+ loci by the same rule, and their raw alleles (unit Frobenius norm) are transplanted into the first 8 backgrounds of the
246
+ main plan, so $\kappa$ in raw and expressed coordinates is compared on the same backgrounds. Further ablations drop the
247
+ left-out block; drop the function or the descent layer; and
248
+ select and estimate on the same families. Genotype-level variants change the loci, so they are reported at the scan level: $\lambda_{\mathrm{GC}}$, discoveries,
249
+ and overlap with the primary scan in (trait, module) pairs with a Bonferroni-significant locus.
250
+
251
+ All seeds (sketches, carrier sets, cross designs) are 0--4.
code/paper/sections/related.tex ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ % MIT License, Bryan Cheng, 2026. Related work. Every cited key is in paper/refs.bib (tools/make_bib.py, verified records).
2
+ \section{Related work}
3
+ \label{sec:related}
4
+
5
+ \paragraph{Learning on weights.}
6
+ A LoRA update $\Delta=BA$ starts from a random $A$ and a zero $B$~\cite{r1}. Its two factors are asymmetric: $A$ extracts
7
+ input features, $B$ produces outputs, and a random untrained $A$ performs nearly as well as a trained one~\cite{r16}.
8
+ Several lines of work predict properties of fine-tunes from their parameters:
9
+ \begin{itemize}
10
+ \item a linear weight subspace of customized diffusion models~\cite{r2};
11
+ \item GL-equivariant networks on LoRA factors~\cite{r3};
12
+ \item probes within model trees~\cite{r4};
13
+ \item canonicalized LoRA transformers~\cite{r5};
14
+ \item self-supervised weight-space models~\cite{r6};
15
+ \item domain fingerprints~\cite{r38};
16
+ \item spectral summaries that track training objective and harmful compliance~\cite{r10}.
17
+ \end{itemize}
18
+ These methods are predictive. They do not estimate the effect of individual weight directions, and they do not model the
19
+ relatedness between training examples.
20
+
21
+ \paragraph{Similarity of adapters and shared initialization.}
22
+ Adapters trained for the same persona trait with different seeds have near-zero raw cosine. Weighting the input side by
23
+ the model's activations recovers a large similarity~\cite{r7}. Evidence for universal weight subspaces~\cite{r33} is
24
+ confounded by shared LoRA initialization~\cite{r35}.
25
+
26
+ We give a closed-form law for the raw and expressed cosine of independently initialized low-rank updates, and we test it
27
+ on trained seed siblings. In our data, the raw part of the law fails by more than a factor of two in several rank cells
28
+ (Section~\ref{sec:results-e1}).
29
+
30
+ \paragraph{The model hub as a population.}
31
+ Prior work uses lineage among public models in several ways:
32
+ \begin{itemize}
33
+ \item parent-child ties predict benchmark performance~\cite{r18};
34
+ \item phylogenies from output similarity recover known families~\cite{r19};
35
+ \item weights read as genotypes recover training trees~\cite{r20};
36
+ \item statistical tests detect shared initialization~\cite{r21};
37
+ \item model kinship guides merging~\cite{r55}.
38
+ \end{itemize}
39
+ Non-independent artifacts overstate the effective sample size~\cite{r36}. A population-genetic framing has also been
40
+ proposed for multigenerational model populations~\cite{r51} and for co-evolving LoRA populations~\cite{r63}.
41
+
42
+ None of these estimates per-direction effects on behavior or measures how relatedness biases such estimates. The closest
43
+ work regresses behavior on the weights of controlled, seed-varied persona LoRAs and checks directions by ablation and
44
+ grafting~\cite{r39}. A model census finds that structural features of feed-forward rows do not predict ablation
45
+ effects~\cite{r40}.
46
+
47
+ \paragraph{Interventions on weight directions.}
48
+ Weight-space edits have causal effects:
49
+ \begin{itemize}
50
+ \item task arithmetic~\cite{r8};
51
+ \item contrastive weight steering from opposite fine-tunes~\cite{r9};
52
+ \item weight patching~\cite{r52} and grafting~\cite{r60};
53
+ \item transplants of a misalignment persona direction~\cite{r56}.
54
+ \end{itemize}
55
+ Component modeling fits a linear model to randomized ablations inside one network~\cite{r61}. We use such interventions
56
+ as ground truth, and we recombine parents of a public population, not components of one model.
57
+
58
+ \paragraph{Statistical genetics.}
59
+ The estimators and diagnostics we transfer are:
60
+ \begin{itemize}
61
+ \item genomic control~\cite{r22};
62
+ \item principal components~\cite{r23};
63
+ \item mixed models~\cite{r24,r25,r26};
64
+ \item variance components~\cite{r27};
65
+ \item within-family designs~\cite{r28};
66
+ \item kernel association tests~\cite{r41};
67
+ \item linkage-disequilibrium score regression~\cite{r42};
68
+ \item fine-mapping~\cite{r64};
69
+ \item genetic correlation~\cite{r50,r65};
70
+ \item portability of polygenic scores~\cite{r29}.
71
+ \end{itemize}
72
+ Multiple testing uses the Li--Ji effective number of tests~\cite{liji} and the Benjamini--Hochberg procedure~\cite{bh}.
code/paper/sections/results.tex ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ % MIT License, Bryan Cheng, 2026. Results. Every number is copied from RESULTS.md, which names its source file.
2
+ % Interventions, crosses, spike-ins and E6-E8 are added when their runs finish; nothing here anticipates them.
3
+ \section{Results}
4
+ \label{sec:results}
5
+
6
+ \subsection{The population}
7
+ \label{sec:results-pop}
8
+ We collected 955 public LoRA adapters of Qwen2.5-0.5B-Instruct~\cite{qwen25} and genotyped 907; the other 48 failed to
9
+ load. Of the 956 phenotype records (the adapters plus the base), 888 passed quality control, 48 failed to run and 20
10
+ exceeded three times the base's reference perplexity. After excluding 3 DoRA adapters, the scan population has
11
+ $n=884$ adapters and 5,191 loci, with a Li--Ji effective number of tests of 383~\cite{liji}.
12
+
13
+ Relatedness is common:
14
+ \begin{itemize}
15
+ \item the descent rule groups the 907 genotyped adapters into 634 families, and 36.7\% of adapters have at least one
16
+ relative;
17
+ \item the largest family has 77 members;
18
+ \item at the pre-registered threshold, function similarity groups the descent-unrelated adapters into 401 recipe
19
+ families.
20
+ \end{itemize}
21
+ The effective sample size is 182.6 under the descent kernel and 168.6 under the function kernel, about a fifth of the
22
+ nominal $n$.
23
+
24
+ Descent families agree with independent metadata. The adjusted Rand index is 0.884 against authors and 0.899 against
25
+ training-dataset tags. 82.1\% of same-author pairs are related, against 0.04\% of different-author pairs. Off the
26
+ diagonal, the descent and function kernels correlate at 0.951.
27
+
28
+ \subsection{Phenotypes are reliable and hardware-independent}
29
+ \label{sec:results-pheno}
30
+ All 53 battery traits pass the pre-registered split-half reliability threshold of 0.7 (minimum 0.715, median 0.967), so
31
+ the primary-trait list is all 53.
32
+
33
+ The population was measured on two GPU types. We re-measured 23 adapters on the second type:
34
+ \begin{itemize}
35
+ \item median Lin concordance is 0.998;
36
+ \item for 1 of 52 traits the paired-shift CI excludes zero, a shift of 0.038~SD;
37
+ \item the median ratio of hardware disagreement to item-sampling error is 0.21;
38
+ \item population means do not differ by GPU type for any trait ($p<0.05$ for none);
39
+ \item re-measuring the base on the same hardware reproduces it to $1.4\times10^{-9}$~SD.
40
+ \end{itemize}
41
+
42
+ \subsection{Trained seed siblings and the similarity law}
43
+ \label{sec:results-e1}
44
+ We trained 240 seed siblings (8 tasks, ranks 4--64, 3 seeds, independent or shared initialization).
45
+
46
+ Expressed similarity separates same-task from different-task pairs almost perfectly: AUC 0.9996 for independently
47
+ initialized pairs, against 0.945 for raw similarity.
48
+
49
+ The raw-similarity law does not hold to a factor of two. Across the 15 rank cells, the ratio of observed to predicted
50
+ raw cosine for independent-init same-task siblings ranges from 0.56 to 4.2, with a geometric mean of 1.48. The law
51
+ predicts a fifteen-fold rise from rank~4 to rank~64. Observed raw cosine is nearly flat, between 0.014 and 0.041.
52
+
53
+ H1 is therefore refuted by its pre-registered raw criterion, while its expressed-similarity criterion holds.
54
+
55
+ An exploratory fit, labelled as such, solves for the dimension at which the law matches each cell. The raw effective
56
+ dimension grows with rank, from 226 at rank~4 to 1,769 at rank~64, whereas the law fixes it at the input dimension. The
57
+ law therefore over-predicts similarity at high rank and under-predicts it at low rank.
58
+
59
+ The descent rule, calibrated on these known pedigrees, behaves as follows:
60
+ \begin{itemize}
61
+ \item it flags 53\% of shared-initialization pairs;
62
+ \item it flags 3.3\% of independent different-task pairs;
63
+ \item it flags 12.6\% of independent same-task pairs.
64
+ \end{itemize}
65
+ So it is specific for shared initialization but not sensitive to it.
66
+
67
+ \subsection{Association scans are inflated}
68
+ \label{sec:results-scan}
69
+ Table~\ref{tab:lambda} gives genomic-control inflation by estimator.
70
+
71
+ The naive scan has $\lambda_{\mathrm{GC}}>1.1$ on 52 of 53 traits (median 3.12), which meets the inflation criterion of
72
+ H2. That criterion is weak by itself: loci are strongly correlated ($M_{\mathrm{eff}}=383$ of 5,191), so a single null
73
+ trait gives a noisy $\lambda_{\mathrm{GC}}$. Over 20 independent draws of iid noise on the real genotypes, the naive
74
+ $\lambda_{\mathrm{GC}}$ ranges from 0.69 to 1.54 (95\%) and exceeds 1.1 in 9 draws. Real traits lie far outside this
75
+ range: the naive $\lambda_{\mathrm{GC}}$ exceeds the null's 97.5\% quantile on 51 of 53 traits. Principal components lower
76
+ the median to 2.74, and the mixed models to 2.01.
77
+
78
+ These point estimates hide large uncertainty from family composition. We use a delete-a-group jackknife over 20 random
79
+ groups of descent families; a family bootstrap would count resampled copies of a family as independent adapters and shift
80
+ the distribution upward. With the jackknife:
81
+ \begin{itemize}
82
+ \item the median $\lambda_{\mathrm{GC}}$ over traits is 3.12 (95\% CI 1.30--4.93) for the naive scan and 2.01 (1.39--2.63)
83
+ for MM-fd, so inflation remains after the mixed model;
84
+ \item the naive scan exceeds MM-fd on 50 of 53 traits, but the median difference, 0.74, has a 95\% CI of $-0.43$ to 1.90.
85
+ \end{itemize}
86
+ The mixed model's reduction of inflation is therefore consistent in sign but not established on real traits. On a
87
+ simulated family effect it is clear: over 20 draws of a family effect plus equal noise, the naive scan exceeds MM-fd in
88
+ all 20, with median $\lambda_{\mathrm{GC}}$ 1.32 against 0.93 (Table~\ref{tab:lambda}). On real traits MM-fd still exceeds
89
+ the 97.5\% quantile of its own family-null distribution (1.36) on 50 of 53 traits. The inflation that remains after the
90
+ mixed model is therefore not draw noise.
91
+
92
+ The descent variance component is essentially zero: its median share is 0 over traits and left-out blocks, it exceeds
93
+ 1\% in 1.3\% of fits, and its maximum is 6.6\%. MM-fd and MM-f therefore coincide.
94
+
95
+ The within-family estimators deserve care:
96
+ \begin{itemize}
97
+ \item WF-d is the most inflated on real traits (median 3.82) yet calibrated on a simulated null with family structure
98
+ (median 0.93 over 20 draws, 95\% range 0.53--2.02). This pattern is consistent with genuine association inside families, such as checkpoint and hyperparameter
99
+ series, not with a miscalibrated test.
100
+ \item On the iid null every estimator has median $\lambda_{\mathrm{GC}}$ between 0.84 and 1.07. Under a family effect
101
+ plus noise, the naive median is 1.32 while the mixed models' medians are 0.93--0.95.
102
+ \item The negative control is a pure family effect with no noise. It inflates the naive scan (median 1.61), and WF-d
103
+ removes it exactly (0.00 in every draw); the other estimators remain noisy (MM-fd median 1.10, 95\% range
104
+ 0.73--1.69).
105
+ \end{itemize}
106
+
107
+ Linkage-score regression, the analogue of LD-score regression~\cite{r42}, separates the two sources of naive inflation.
108
+ We fit it in the weighted form, with bias-corrected squared correlations and module-jackknife standard errors. Its
109
+ intercept exceeds 1 on all 53 traits (median 3.20) and exceeds 1 by more than two standard errors on 41. The median ratio
110
+ of excess intercept to excess mean $\chi^2$ is 0.98. Naive inflation is therefore almost uniform across loci rather than
111
+ proportional to linkage, as expected from confounding by relatedness and not from many small effects tagged through
112
+ linkage.
113
+
114
+ \begin{table}[t]
115
+ \centering
116
+ \small
117
+ \caption{Genomic-control inflation $\lambda_{\mathrm{GC}}$ by estimator on the full population ($n=884$). The lower rows
118
+ are simulated traits on the real genotypes and relatedness: median and 95\% range over 20 independent draws.}
119
+ \label{tab:lambda}
120
+ \setlength{\tabcolsep}{4pt}
121
+ \begin{tabular}{lrrrrrrr}
122
+ \toprule
123
+ & naive & PC & MM-f & MM-fd & WF-d & WF-r & DUP-AFE \\
124
+ \midrule
125
+ median, 53 traits & 3.12 & 2.74 & 2.01 & 2.01 & 3.82 & 2.17 & 2.04 \\
126
+ max, 53 traits & 6.63 & 4.67 & 3.83 & 3.83 & 17.73 & 7.27 & 5.58 \\
127
+ \midrule
128
+ null, iid noise & 1.07 & 0.97 & 1.00 & 0.98 & 0.95 & 0.89 & 0.84 \\
129
+ \quad 95\% range & {\footnotesize 0.69--1.54} & {\footnotesize 0.67--1.58} & {\footnotesize 0.68--1.54} & {\footnotesize 0.68--1.53} & {\footnotesize 0.65--2.25} & {\footnotesize 0.54--1.89} & {\footnotesize 0.45--1.90} \\
130
+ null, family effect + noise & 1.32 & 1.03 & 0.95 & 0.93 & 0.93 & 1.01 & 0.97 \\
131
+ \quad 95\% range & {\footnotesize 0.87--1.84} & {\footnotesize 0.65--1.52} & {\footnotesize 0.61--1.36} & {\footnotesize 0.61--1.36} & {\footnotesize 0.53--2.02} & {\footnotesize 0.58--1.76} & {\footnotesize 0.65--1.46} \\
132
+ negative control & 1.61 & 1.16 & 1.00 & 1.10 & 0.00 & 1.19 & 1.19 \\
133
+ \quad 95\% range & {\footnotesize 0.82--1.98} & {\footnotesize 0.79--1.69} & {\footnotesize 0.69--1.55} & {\footnotesize 0.73--1.69} & {\footnotesize 0.00} & {\footnotesize 0.54--1.58} & {\footnotesize 0.64--2.40} \\
134
+ \bottomrule
135
+ \end{tabular}
136
+ \end{table}
137
+
138
+ \subsection{Raw coordinates: scan-level ablation}
139
+ \label{sec:results-raw}
140
+ We repeated the scan with loci taken from raw (Frobenius) Grams instead of expressed ones, keeping the same adapters,
141
+ covariates, kernels and split. Raw coordinates span fewer effective dimensions: a Li--Ji effective number of tests of
142
+ 180, against 383. They also yield fewer relatedness-corrected discoveries:
143
+ \begin{itemize}
144
+ \item 3,381 MM-fd trait--locus hits at 5\% FDR on the discovery half, against 6,453;
145
+ \item 2,523 MM-fd hits at the Bonferroni threshold on the full population, against 3,889.
146
+ \end{itemize}
147
+ Uncorrected counts do not move consistently: the naive scan has 5,875 hits against 9,495 on the discovery half, but
148
+ 15,060 against 13,996 at the Bonferroni threshold. Median inflation is somewhat lower (naive 2.64, MM-fd 1.75), and the nulls behave as in expressed coordinates. Whether
149
+ raw-coordinate effect estimates are worse calibrated is an interventional question, answered in
150
+ Section~\ref{sec:results-interventions}.
151
+
152
+ \subsection{Sensitivity of the scan}
153
+ \label{sec:results-sens}
154
+ The number of principal components matters little. With 5, 10 and 20 PCs the PC estimator's median $\lambda_{\mathrm{GC}}$
155
+ is 2.67, 2.74 and 2.69, and no other estimator uses them.
156
+
157
+ The descent threshold (2, 3 or 5 times the law) gives 584, 634 and 680 families, and 43\%, 37\% and 30\% of adapters
158
+ with a relative. Full-sample results that do not use families are unchanged, including MM-fd, whose descent component is
159
+ near zero. Within-family estimation does depend on the threshold: WF-d's median $\lambda_{\mathrm{GC}}$ is 2.35, 3.82 and
160
+ 3.42.
161
+
162
+ The discovery/estimation split is built from the family partition, so a new partition reshuffles it: only 48\% (2$\times$)
163
+ and 33\% (5$\times$) of adapters stay in their original half. Hit counts on the discovery half then vary widely: the
164
+ naive scan has 16,169, 9,495 and 42,832 hits at 5\% FDR, and MM-fd 6,601, 6,453 and 9,203. Counts on one half are
165
+ fragile to which families land in it. We therefore compare coordinate systems on the same split
166
+ (Section~\ref{sec:results-raw}) and report full-sample $\lambda_{\mathrm{GC}}$ and Bonferroni counts alongside.
167
+
168
+ Genotype choices made before the scan change which loci exist, since loci are eigenvectors of each module's Gram.
169
+ Capping $k$ at 128 instead of 512 gives 5,181 loci against 5,184 and leaves the naive and MM-fd scans nearly unchanged: median
170
+ $\lambda_{\mathrm{GC}}$ is 3.13 (naive) and 2.02 (MM-fd), against 3.12 and 2.01, and their Bonferroni counts move by less than
171
+ 1\%. Other estimators move more: Bonferroni counts change by 5\% (PC), 6\% (DUP-AFE)
172
+ and 17\% (WF-r), whose median $\lambda_{\mathrm{GC}}$ falls from 2.17 to 1.90. Of the (trait, module) pairs with a Bonferroni-significant locus in the primary scan, 91\% (naive) and 77\% (MM-fd)
173
+ have one under the capped genotype. The other genotype variants are reported as they finish.
174
+
175
+ \subsection{Variance components: function relatedness carries the heritable signal}
176
+ \label{sec:results-e6}
177
+ We fit variance components with eight block function kernels (four layer blocks, attention and MLP) and the descent
178
+ kernel. The function kernels improve on a descent-only model on all 53 traits (likelihood-ratio test, significant after
179
+ Benjamini--Hochberg; median statistic 173).
180
+
181
+ Best linear unbiased prediction (BLUP) with the function kernel predicts adapters in held-out descent families. Its
182
+ median accuracy is $r=0.50$ (range 0.26--0.70), against 0.32 for the descent kernel and 0.24 for covariates alone. The
183
+ function kernel is the most accurate of the three on every trait. Hypothesis H5 is therefore not refuted.
184
+
185
+ Once the function kernel is in the model, the descent component is zero on every trait. This matches the scans, where
186
+ the descent variance component of MM-fd was essentially zero (Section~\ref{sec:results-scan}).
187
+
188
+ The variance shares themselves need care. Both kernels have a unit diagonal, and behavior is a deterministic function
189
+ of the weights up to item-sampling noise. Either kernel alone therefore absorbs nearly all variance: 0.97 for the function
190
+ kernel and 0.97 for the descent kernel when each is fitted alone. These shares are not heritabilities in the genetic
191
+ sense; the likelihood-ratio tests and out-of-family accuracies are the interpretable quantities.
192
+
193
+ Among the function blocks, the MLPs of layers 6--11 carry the largest mean share (0.25), followed by attention (0.21) and
194
+ MLP (0.19) in layers 18--23.
195
+
196
+ Genetic correlations from bivariate REML track phenotypic correlations closely: across the 1,378 trait pairs, $G$ under
197
+ the function kernel correlates with $P$ at 0.95 and with $G$ under the descent kernel at 0.995.
198
+
199
+ \subsection{Forecasting the side effects of targeted fine-tunes}
200
+ \label{sec:results-forecast}
201
+ We trained 66 fine-tunes that each target one benign trait (11 conditions, ranks 8 and 32, three seeds). Ten conditions
202
+ target a primary trait, giving 60 test cases; the eleventh (casual register) has no primary focal trait. Every case is
203
+ compared with a base measured on the same hardware and batch sizes. Table~\ref{tab:forecast} scores the forecasters on
204
+ the other 52 primary traits. The test set of validated interventions and the forecasters that need it ($G$ from
205
+ validated loci) or the TinyLlama fine-tunes (spillover) are added when those finish.
206
+
207
+ \begin{table}[t]
208
+ \centering
209
+ \small
210
+ \setlength{\tabcolsep}{4pt}
211
+ \caption{Side-effect forecasts for 60 trait-targeted fine-tunes in 10 conditions. $\Delta$MSE is the MSE of $G$
212
+ (function layer) minus that of the forecaster, with 95\% intervals from a paired bootstrap over cases and, as a
213
+ sensitivity analysis, over conditions. Negative values favour $G$. Wins: conditions in which $G$ has the lower MSE.}
214
+ \label{tab:forecast}
215
+ \begin{tabular}{lrrrrr}
216
+ \toprule
217
+ forecaster & $r$ & MSE & $\Delta$MSE [cases] & [conditions] & wins \\
218
+ \midrule
219
+ $G$, function & 0.35 & 1.93 & & & \\
220
+ $G$, descent & 0.34 & 1.94 & $-0.011$ [$-0.020$, $-0.002$] & [$-0.033$, 0.009] & 5/10 \\
221
+ $P$ & 0.27 & 2.08 & $-0.157$ [$-0.204$, $-0.112$] & [$-0.265$, $-0.051$] & 7/10 \\
222
+ gradient cosine & 0.34 & 1.96 & $-0.031$ [$-0.138$, 0.080] & [$-0.308$, 0.194] & 5/10 \\
223
+ gradient step & 0.31 & 1.95 & $-0.022$ [$-0.125$, 0.081] & [$-0.284$, 0.212] & 5/10 \\
224
+ representation & 0.29 & 1.98 & $-0.056$ [$-0.170$, 0.045] & [$-0.343$, 0.179] & 5/10 \\
225
+ zero & -- & 2.13 & $-0.206$ [$-0.336$, $-0.081$] & [$-0.541$, 0.078] & 6/10 \\
226
+ \bottomrule
227
+ \end{tabular}
228
+ \end{table}
229
+
230
+ Genetic correlations forecast side effects better than phenotypic correlations. The interval excludes zero whether cases
231
+ or whole conditions are resampled, and $G$ wins in 7 of 10 conditions. On this test set H6 is not refuted.
232
+
233
+ The advantage is narrow. $G$ lowers MSE by 10\% relative to forecasting no side effects, and that gain does not survive
234
+ resampling conditions. Forecasts from the base model alone, the cosine of trait gradients or of activation directions,
235
+ are as good as $G$. $G$ helps most where the targeted change is large: for French, MSE is 1.40 against 2.67 for zero,
236
+ and for concise answers 1.73 against 2.74. For markdown, MMLU-STEM, persona and sycophancy fine-tunes it is worse than
237
+ zero, and a base-model forecaster is best. $P$ is worse than zero in 5 of the 10 conditions.
238
+
239
+ \subsection{Prediction from weights, and why raw weights are the wrong coordinates}
240
+ \label{sec:results-e7}
241
+ We predicted each trait from weights under four splits: random, and disjoint by descent family, recipe family and author.
242
+ Table~\ref{tab:predict} gives median accuracy over the 53 traits.
243
+
244
+ \begin{table}[t]
245
+ \centering
246
+ \small
247
+ \caption{Out-of-sample prediction accuracy (median Pearson $r$ over 53 traits) by split and predictor. Tuning used
248
+ validation families inside each training fold. The causal score is added after calibration.}
249
+ \label{tab:predict}
250
+ \begin{tabular}{lrrrrrr}
251
+ \toprule
252
+ split & ridge raw & ridge expressed & spectral & $k$NN $K_{\mathrm{func}}$ & BLUP-f & MM score \\
253
+ \midrule
254
+ random & 0.37 & 0.51 & 0.35 & 0.44 & 0.63 & 0.10 \\
255
+ descent-disjoint & 0.21 & 0.43 & 0.23 & 0.30 & 0.49 & 0.15 \\
256
+ recipe-disjoint & $-0.03$ & 0.26 & 0.24 & 0.30 & 0.41 & 0.09 \\
257
+ author-disjoint & 0.20 & 0.38 & 0.21 & 0.32 & 0.51 & 0.11 \\
258
+ \bottomrule
259
+ \end{tabular}
260
+ \end{table}
261
+
262
+ Kernel ridge on expressed coordinates beats the same model on raw coordinates under every split. The gap grows as the
263
+ split removes more shared history: 0.14 on random splits and 0.29 across recipes, where raw coordinates predict nothing.
264
+
265
+ BLUP with the function kernel is the most accurate predictor on 45--47 of the 53 traits under each split. A score built
266
+ from mixed-model locus effects predicts poorly. This is consistent with behavior spread over many correlated directions,
267
+ but noisy per-locus effects would give the same result.
268
+
269
+ Accuracy depends on relatedness to the training set. Under random splits, BLUP-f accuracy rises from 0.42 to 0.87
270
+ across quintiles of an adapter's maximum descent relatedness to the training adapters. Across recipes it is flat, near
271
+ 0.4.
code/src/analysis/admixture.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Merges: admixture from weights (RESEARCH_PLAN 5.5) and merge phenotype prediction (12, last line).
3
+
4
+ Candidates = the adapter population plus the rank-64 reductions of full fine-tunes (merges excluded). Pass 1: expressed
5
+ cross-Gram merges x candidates (summed over modules) and the merges' genotype coordinates on the population loci
6
+ (g = sum_i u_i (<E_m, E_i> - mean_j <E_j, E_i>) / sqrt(lambda)). Pass 2: Gram among the union of each merge's top-20
7
+ candidates by expressed cosine. Non-negative least squares of each merge's expressed delta on its 20 candidates gives
8
+ admixture proportions and the residual share. Predictions (transformed scale, population ECDF): admixture
9
+ (base + sum_p w_p (y_p - base)) and ridge on locus coordinates fitted on the adapter population.
10
+
11
+ python src/analysis/admixture.py --geno data/processed/qwen05 --adapters_dir data/raw/adapters/Qwen__Qwen2.5-0.5B-Instruct
12
+ --ft_dir data/raw/ft_reduced/Qwen__Qwen2.5-0.5B-Instruct --merge_index data/raw/hf_index/<base>.merge.jsonl
13
+ --pheno results/phenotypes/qwen05 --pheno_ft results/phenotypes/qwen05_finetune
14
+ --pheno_merge results/phenotypes/qwen05_merge --scan results/scans/qwen05 --out results/e1/merges_qwen05.json
15
+ """
16
+ import argparse
17
+ import glob
18
+ import json
19
+ import os
20
+ import sys
21
+
22
+ import numpy as np
23
+ import torch
24
+ from scipy.optimize import nnls
25
+
26
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
27
+ from src.analysis.calibrate import ecdf_map # noqa: E402
28
+ from src.analysis.population import build # noqa: E402
29
+ from src.lorapop.adapters import load_module_factors # noqa: E402
30
+ from src.lorapop.basecov import P_for # noqa: E402
31
+
32
+
33
+ def cross_gram(f1, f2, P, dev, chunk=16384):
34
+ n1, n2 = len(f1), len(f2)
35
+ out = torch.zeros(n1, n2, dtype=torch.float64)
36
+ i1 = [i for i, f in enumerate(f1) if f is not None]
37
+ i2 = [i for i, f in enumerate(f2) if f is not None]
38
+ if not i1 or not i2:
39
+ return out
40
+ Pd = P.to(dev, torch.float32)
41
+ A1 = torch.cat([f1[i][0] for i in i1]).to(dev) @ Pd
42
+ B1 = torch.cat([f1[i][1] for i in i1], 1).to(dev)
43
+ s1 = torch.cat([torch.full((f1[i][0].shape[0],), j) for j, i in enumerate(i1)]).to(dev)
44
+ S1 = torch.zeros(A1.shape[0], len(i1), device=dev)
45
+ S1[torch.arange(A1.shape[0], device=dev), s1] = 1
46
+ res = torch.zeros(len(i1), len(i2), dtype=torch.float64)
47
+ for c0 in range(0, len(i2), 256):
48
+ sub = i2[c0:c0 + 256]
49
+ A2 = torch.cat([f2[i][0] for i in sub]).to(dev) @ Pd
50
+ B2 = torch.cat([f2[i][1] for i in sub], 1).to(dev)
51
+ s2 = torch.cat([torch.full((f2[i][0].shape[0],), j) for j, i in enumerate(sub)]).to(dev)
52
+ S2 = torch.zeros(A2.shape[0], len(sub), device=dev)
53
+ S2[torch.arange(A2.shape[0], device=dev), s2] = 1
54
+ M = (B1.T @ B2) * (A1 @ A2.T)
55
+ res[:, c0:c0 + len(sub)] = (S1.T @ M @ S2).double().cpu()
56
+ out[np.ix_(i1, i2)] = res
57
+ return out
58
+
59
+
60
+ def sq_norm(f, P, dev):
61
+ if f is None:
62
+ return 0.0
63
+ AP = f[0].to(dev) @ P.to(dev, torch.float32)
64
+ B = f[1].to(dev)
65
+ return float(((B.T @ B) * (AP @ AP.T)).sum())
66
+
67
+
68
+ def load_pheno(d, names):
69
+ out = {}
70
+ for x in names:
71
+ f = os.path.join(d, x + ".json")
72
+ if os.path.exists(f):
73
+ r = json.load(open(f))
74
+ if r.get("status") == "ok":
75
+ out[x] = r["traits"]
76
+ return out
77
+
78
+
79
+ def main():
80
+ ap = argparse.ArgumentParser()
81
+ for k in ("geno", "adapters_dir", "ft_dir", "merge_index", "pheno", "pheno_ft", "pheno_merge", "scan", "out"):
82
+ ap.add_argument("--" + k, required=True)
83
+ ap.add_argument("--top", type=int, default=20)
84
+ ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
85
+ a = ap.parse_args()
86
+ dev = a.device
87
+ A = json.load(open(os.path.join(a.geno, "adapters.json")))
88
+ names_all = A["names"]
89
+ merge_ids = {json.loads(l)["id"].replace("/", "__") for l in open(a.merge_index)}
90
+ red = sorted(os.path.basename(os.path.dirname(p)) for p in glob.glob(os.path.join(a.ft_dir, "*/_ok")))
91
+ merges = [x for x in red if x in merge_ids]
92
+ fts = [x for x in red if x not in merge_ids]
93
+ cands = [(a.adapters_dir, x) for x in names_all] + [(a.ft_dir, x) for x in fts]
94
+ cov = torch.load(os.path.join(a.geno, "basecov.pt"))
95
+ loci = torch.load(os.path.join(a.geno, "loci.pt"))
96
+ mods = json.load(open(os.path.join(a.geno, "modules.json")))
97
+ ge = np.load(os.path.join(a.geno, "grams_exp.npy"), mmap_mode="r")
98
+ m, N = len(merges), len(cands)
99
+ C = np.zeros((m, N))
100
+ dm, dc = np.zeros(m), np.zeros(N)
101
+ gm_cols, gm_meta = [], []
102
+ for mi, key in enumerate(mods):
103
+ layer, mod = key.split(".")
104
+ P = P_for(cov, int(layer), mod).float()
105
+ fm = [load_module_factors(os.path.join(a.ft_dir, x), {key}).get(key) for x in merges]
106
+ fc = [load_module_factors(os.path.join(d, x), {key}).get(key) for d, x in cands]
107
+ X = cross_gram(fm, fc, P, dev).numpy()
108
+ C += X
109
+ dm += np.diag(cross_gram(fm, fm, P, dev).numpy())
110
+ dc[: len(names_all)] += np.diag(np.asarray(ge[mi]))
111
+ dc[len(names_all):] += [sq_norm(f, P, dev) for f in fc[len(names_all):]]
112
+ lo = loci.get(key)
113
+ if lo is not None and lo["n_loci"]:
114
+ colmean = np.asarray(ge[mi]).mean(0)
115
+ U, lam = lo["U"].double().numpy(), lo["lam"].double().numpy()
116
+ for l in range(lo["n_loci"]):
117
+ gm_cols.append((X[:, : len(names_all)] - colmean[None]) @ U[:, l] / np.sqrt(lam[l]))
118
+ gm_meta.append((key, l))
119
+ print(key, flush=True)
120
+ cosC = C / np.sqrt(np.maximum(dm, 1e-300))[:, None] / np.sqrt(np.maximum(dc, 1e-300))[None]
121
+ top = np.argsort(-cosC, 1)[:, : a.top]
122
+ U_ = sorted(set(top.ravel().tolist()))
123
+ pos = {j: k for k, j in enumerate(U_)}
124
+ GU = np.zeros((len(U_), len(U_)))
125
+ for key in mods:
126
+ layer, mod = key.split(".")
127
+ P = P_for(cov, int(layer), mod).float()
128
+ f = [load_module_factors(os.path.join(cands[j][0], cands[j][1]), {key}).get(key) for j in U_]
129
+ GU += cross_gram(f, f, P, dev).numpy()
130
+ res = {"n_merges": m, "n_candidates": N, "n_ft_candidates": len(fts), "merges": []}
131
+ W = np.zeros((m, N))
132
+ for i in range(m):
133
+ J = top[i]
134
+ Gp = GU[np.ix_([pos[j] for j in J], [pos[j] for j in J])] + 1e-9 * np.eye(len(J)) * np.trace(GU) / len(U_)
135
+ R = np.linalg.cholesky(Gp).T
136
+ w, _ = nnls(R, np.linalg.solve(R.T, C[i, J]))
137
+ resid = (dm[i] - 2 * w @ C[i, J] + w @ Gp @ w) / dm[i]
138
+ W[i, J] = w
139
+ res["merges"].append({"top_cos": float(cosC[i, J[0]]), "n_parents_w_gt_0.05": int((w / max(w.sum(), 1e-12) > 0.05).sum()),
140
+ "sum_w": float(w.sum()), "residual_share": float(resid),
141
+ "parent_kinds": ["adapter" if j < len(names_all) else "finetune" for j in J[w > 0]]})
142
+ rs = np.array([r["residual_share"] for r in res["merges"]])
143
+ res["residual_share_median"] = float(np.median(rs)) if len(rs) else None
144
+ # phenotype prediction
145
+ Ppop = build(a.geno, a.pheno)
146
+ prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
147
+ ph_c = {**load_pheno(a.pheno, names_all), **load_pheno(a.pheno_ft, fts)}
148
+ ph_m = load_pheno(a.pheno_merge, merges)
149
+ base = json.load(open(os.path.join(a.pheno, "__base__.json")))["traits"]
150
+ Gm = np.column_stack(gm_cols) if gm_cols else np.zeros((m, 0))
151
+ meta_idx = {(l["module"], l["l"]): j for j, l in enumerate(Ppop["loci"])}
152
+ cols = [k for k, mm in enumerate(gm_meta) if mm in meta_idx]
153
+ Gpop = Ppop["G"][:, [meta_idx[gm_meta[k]] for k in cols]]
154
+ pred = {}
155
+ for t in prim:
156
+ f = ecdf_map(Ppop["Y"][0, :, Ppop["traits"].index(t)])[0]
157
+ y_true, y_adm, y_loc = [], [], []
158
+ y = Ppop["Yt"][:, Ppop["traits"].index(t)]
159
+ ok = np.isfinite(y)
160
+ Z = Gpop[ok] - Gpop[ok].mean(0)
161
+ lam = 1.0 * len(Z)
162
+ beta = np.linalg.solve(Z.T @ Z + lam * np.eye(Z.shape[1]), Z.T @ (y[ok] - y[ok].mean()))
163
+ for i, x in enumerate(merges):
164
+ if x not in ph_m or t not in ph_m[x]:
165
+ continue
166
+ J = np.where(W[i] > 0)[0]
167
+ vals = [(W[i, j], ph_c.get(cands[j][1], {}).get(t)) for j in J]
168
+ vals = [(w, v[0]) for w, v in vals if v is not None]
169
+ if not vals:
170
+ continue
171
+ y_true.append(f(ph_m[x][t][0]))
172
+ y_adm.append(f(base[t][0] + sum(w * (v - base[t][0]) for w, v in vals)))
173
+ y_loc.append(y[ok].mean() + (Gm[i, cols] - Gpop[ok].mean(0)) @ beta)
174
+ if len(y_true) > 3:
175
+ pred[t] = {"n": len(y_true), "r_admixture": float(np.corrcoef(y_true, y_adm)[0, 1]),
176
+ "r_loci_ridge": float(np.corrcoef(y_true, y_loc)[0, 1])}
177
+ res["prediction"] = pred
178
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
179
+ json.dump(res, open(a.out, "w"), indent=1, default=float)
180
+ print(json.dumps({k: v for k, v in res.items() if k != "merges"}, default=float)[:2000], flush=True)
181
+
182
+
183
+ if __name__ == "__main__":
184
+ main()
code/src/analysis/architecture.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Architecture and genetic correlations (RESEARCH_PLAN 11.1, 11.2; E6).
3
+
4
+ 11.1 Per primary trait: REML with the descent kernel and 8 function kernels (4 layer blocks x attention/MLP; block
5
+ kernels K_b = S_b / (d d^T) with d from the total expressed Gram, so sum_b K_b = K_func); likelihood-ratio test
6
+ against descent-only; BLUP accuracy on held-out descent families (5 folds by family) for function-only,
7
+ descent-only and covariates-only models.
8
+ 11.2 Bivariate REML (one kernel at a time, eigen-rotated) for every pair of primary traits under the function and the
9
+ descent layer -> genetic correlation matrices G_f, G_d; phenotypic correlations P; G_do from validated loci
10
+ (calibration file: BH q < 0.05 on gamma_do z-scores over all tested (locus, trait) points).
11
+
12
+ python src/analysis/architecture.py --geno data/processed/qwen05 --pheno results/phenotypes/qwen05
13
+ --scan results/scans/qwen05 [--calib results/calibration/qwen05.json] --out results/e6/architecture_qwen05.json
14
+ """
15
+ import argparse
16
+ import json
17
+ import os
18
+ import sys
19
+
20
+ import numpy as np
21
+ from scipy import optimize, stats
22
+
23
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
24
+ from src.analysis.population import build # noqa: E402
25
+ from src.analysis.scan import basis, bh, reml # noqa: E402
26
+ from src.run.scan_run import blocks_of # noqa: E402
27
+
28
+
29
+ def reml_eig(Y, X, D, U):
30
+ """Multivariate REML for V = Sg (x) K + Se (x) I with K = U diag(D) U^T. Y [n, k]. Returns Sg, Se, nll."""
31
+ n, k = Y.shape
32
+ X = basis(X)
33
+ p = X.shape[1]
34
+ Yt, Xt = U.T @ Y, U.T @ X
35
+ m = k * (k + 1) // 2
36
+ tri = np.tril_indices(k)
37
+
38
+ def unpack(th):
39
+ Lg, Le = np.zeros((k, k)), np.zeros((k, k))
40
+ Lg[tri], Le[tri] = th[:m], th[m:]
41
+ return Lg @ Lg.T, Le @ Le.T + 1e-8 * np.eye(k)
42
+
43
+ def nll(th):
44
+ Sg, Se = unpack(th)
45
+ Vi = Sg[None] * D[:, None, None] + Se[None]
46
+ sgn, ld = np.linalg.slogdet(Vi)
47
+ if np.any(sgn <= 0):
48
+ return 1e20
49
+ Vinv = np.linalg.inv(Vi)
50
+ M = np.einsum("iab,ip,iq->apbq", Vinv, Xt, Xt).reshape(k * p, k * p)
51
+ v = np.einsum("iab,ip,ib->ap", Vinv, Xt, Yt).reshape(k * p)
52
+ try:
53
+ bh_ = np.linalg.solve(M, v).reshape(k, p)
54
+ except np.linalg.LinAlgError:
55
+ return 1e20
56
+ R = Yt - Xt @ bh_.T
57
+ return 0.5 * (ld.sum() + np.linalg.slogdet(M)[1] + np.einsum("ia,iab,ib->", R, Vinv, R))
58
+
59
+ C = np.cov(Y.T).reshape(k, k)
60
+ L0 = np.linalg.cholesky(0.5 * C + 1e-6 * np.eye(k))
61
+ th0 = np.concatenate([L0[tri], L0[tri]])
62
+ res = optimize.minimize(nll, th0, method="L-BFGS-B")
63
+ Sg, Se = unpack(res.x)
64
+ return Sg, Se, float(res.fun)
65
+
66
+
67
+ def blup_cv(y, X, K, fam, folds=5, seed=0):
68
+ """Out-of-family BLUP accuracy (Pearson r over all held-out rows); K None = covariates only."""
69
+ ok = np.isfinite(y)
70
+ uf = np.unique(fam[ok])
71
+ rng = np.random.default_rng(seed)
72
+ fold_of = dict(zip(uf, rng.permutation(len(uf)) % folds))
73
+ pred = np.full(len(y), np.nan)
74
+ for f in range(folds):
75
+ te = ok & np.array([fold_of.get(x, -1) == f for x in fam])
76
+ tr = ok & ~te
77
+ Xb = basis(X[tr])
78
+ coef, *_ = np.linalg.lstsq(X[tr], y[tr], rcond=None)
79
+ if K is None:
80
+ pred[te] = X[te] @ coef
81
+ continue
82
+ s, V, _ = reml(y[tr], X[tr], [K[np.ix_(tr, tr)] + 1e-6 * np.eye(tr.sum())])
83
+ Vi = np.linalg.inv(V)
84
+ XtVi = X[tr].T @ Vi
85
+ beta = np.linalg.lstsq(XtVi @ X[tr], XtVi @ y[tr], rcond=None)[0]
86
+ pred[te] = X[te] @ beta + s[0] * K[np.ix_(te, tr)] @ (Vi @ (y[tr] - X[tr] @ beta))
87
+ del Xb
88
+ m = np.isfinite(pred) & ok
89
+ return float(np.corrcoef(pred[m], y[m])[0, 1])
90
+
91
+
92
+ def corr_from(S):
93
+ d = np.sqrt(np.clip(np.diag(S), 1e-300, None))
94
+ return S / d[:, None] / d[None]
95
+
96
+
97
+ def main():
98
+ ap = argparse.ArgumentParser()
99
+ ap.add_argument("--geno", required=True)
100
+ ap.add_argument("--pheno", required=True)
101
+ ap.add_argument("--scan", required=True)
102
+ ap.add_argument("--calib", default=None)
103
+ ap.add_argument("--out", required=True)
104
+ ap.add_argument("--recipe_threshold", type=float, default=None)
105
+ a = ap.parse_args()
106
+ P = build(a.geno, a.pheno, recipe_threshold=a.recipe_threshold)
107
+ prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
108
+ n = len(P["names"])
109
+ A = json.load(open(os.path.join(a.geno, "adapters.json")))
110
+ keep = np.array([x in set(P["names"]) for x in A["names"]])
111
+ mods = json.load(open(os.path.join(a.geno, "modules.json")))
112
+ ge = np.load(os.path.join(a.geno, "grams_exp.npy"), mmap_mode="r")
113
+ Sb = np.zeros((8, n, n))
114
+ for mi, k in enumerate(mods):
115
+ Sb[blocks_of(k)] += np.asarray(ge[mi])[np.ix_(keep, keep)]
116
+ d = np.sqrt(np.clip(np.diag(Sb.sum(0)), 1e-300, None))
117
+ Kb = [Sb[b] / d[:, None] / d[None] for b in range(8)]
118
+ Kd, Kf, X, fam = P["K_desc"], P["K_func"], P["X"], P["fam_d"]
119
+ out = {"n": n, "primary": prim, "varcomp": {}, "blup_r": {}}
120
+ parts = a.out + ".parts" # per-trait and per-row results, so a run that hits the time limit resumes
121
+ os.makedirs(parts, exist_ok=True)
122
+ for t in prim:
123
+ pf = os.path.join(parts, t + ".json")
124
+ if os.path.exists(pf):
125
+ r = json.load(open(pf))
126
+ out["varcomp"][t], out["blup_r"][t] = r["varcomp"], r["blup_r"]
127
+ continue
128
+ y = P["Yt"][:, P["traits"].index(t)]
129
+ ok = np.isfinite(y)
130
+ I = 1e-6 * np.eye(ok.sum())
131
+ sub = lambda K: K[np.ix_(ok, ok)] + I # noqa: E731
132
+ s1, _, f1 = reml(y[ok], X[ok], [sub(Kd)] + [sub(K) for K in Kb])
133
+ s0, _, f0 = reml(y[ok], X[ok], [sub(Kd)])
134
+ sf, _, ff = reml(y[ok], X[ok], [sub(Kf), sub(Kd)])
135
+ lrt = max(0.0, 2 * (f0 - f1))
136
+ tot = s1.sum()
137
+ out["varcomp"][t] = {"share_descent": s1[0] / tot, "share_blocks": (s1[1:-1] / tot).tolist(),
138
+ "share_resid": s1[-1] / tot, "lrt_function_vs_descent": lrt,
139
+ "p_lrt_chi2_8_conservative": float(stats.chi2.sf(lrt, 8)),
140
+ "two_layer": {"share_function": sf[0] / sf.sum(), "share_descent": sf[1] / sf.sum()},
141
+ "descent_only_share": s0[0] / s0.sum()}
142
+ out["blup_r"][t] = {"function": blup_cv(y, X, Kf, fam), "descent": blup_cv(y, X, Kd, fam),
143
+ "covariates_only": blup_cv(y, X, None, fam)}
144
+ print(t, {k: round(v, 3) for k, v in out["blup_r"][t].items()}, "lrt", round(lrt, 1), flush=True)
145
+ json.dump({"varcomp": out["varcomp"][t], "blup_r": out["blup_r"][t]}, open(pf + ".tmp", "w"), default=float)
146
+ os.replace(pf + ".tmp", pf)
147
+ # 11.2 genetic correlations
148
+ Y = np.column_stack([P["Yt"][:, P["traits"].index(t)] for t in prim])
149
+ k = len(prim)
150
+ Gm = {"function": np.eye(k), "descent": np.eye(k)}
151
+ for lay, K in (("function", Kf), ("descent", Kd)):
152
+ Dall, Uall = np.linalg.eigh(K)
153
+ for i in range(k - 1):
154
+ rf = os.path.join(parts, f"G_{lay}_{i}.npy")
155
+ if os.path.exists(rf):
156
+ row = np.load(rf)
157
+ else:
158
+ row = np.full(k, np.nan)
159
+ for j in range(i + 1, k):
160
+ ok = np.isfinite(Y[:, i]) & np.isfinite(Y[:, j])
161
+ D, U = (Dall, Uall) if ok.all() else np.linalg.eigh(K[np.ix_(ok, ok)])
162
+ Sg, Se, _ = reml_eig(Y[ok][:, [i, j]], X[ok], np.clip(D, 0, None), U)
163
+ row[j] = Sg[0, 1] / np.sqrt(max(Sg[0, 0] * Sg[1, 1], 1e-300))
164
+ np.save(rf + ".tmp.npy", row)
165
+ os.replace(rf + ".tmp.npy", rf)
166
+ Gm[lay][i, i + 1:] = Gm[lay][i + 1:, i] = row[i + 1:]
167
+ print("G", lay, "done", flush=True)
168
+ Pm = np.ma.corrcoef(np.ma.masked_invalid(Y), rowvar=False).filled(np.nan)
169
+ out["G_function"], out["G_descent"], out["P"] = Gm["function"].tolist(), Gm["descent"].tolist(), Pm.tolist()
170
+ iu = np.triu_indices(k, 1)
171
+ out["corr_offdiag"] = {"Gf_P": float(np.corrcoef(Gm["function"][iu], Pm[iu])[0, 1]),
172
+ "Gf_Gd": float(np.corrcoef(Gm["function"][iu], Gm["descent"][iu])[0, 1])}
173
+ if a.calib and os.path.exists(a.calib):
174
+ C = json.load(open(a.calib))["per_direction"]
175
+ rows = [v for v in C.values() if v["kind"] == "locus" and v.get("source")]
176
+ Gam = np.array([[v["traits"][t]["gamma_do"] for t in prim] for v in rows], float)
177
+ Var = np.array([[v["traits"][t]["var_do"] for t in prim] for v in rows], float)
178
+ z = Gam / np.sqrt(np.maximum(Var, 1e-300))
179
+ pz = 2 * stats.norm.sf(np.abs(z)).ravel()
180
+ val = bh(np.where(np.isfinite(pz), pz, 1.0)).reshape(z.shape).any(1)
181
+ if val.sum() >= 2:
182
+ Gdo = corr_from(np.nan_to_num(Gam[val]).T @ np.nan_to_num(Gam[val]))
183
+ out["G_do"] = Gdo.tolist()
184
+ out["n_validated_loci"] = int(val.sum())
185
+ out["corr_offdiag"].update({"Gdo_Gf": float(np.corrcoef(Gdo[iu], Gm["function"][iu])[0, 1]),
186
+ "Gdo_P": float(np.corrcoef(Gdo[iu], Pm[iu])[0, 1])})
187
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
188
+ json.dump(out, open(a.out, "w"), indent=1, default=float)
189
+ print(json.dumps(out["corr_offdiag"]), flush=True)
190
+
191
+
192
+ if __name__ == "__main__":
193
+ main()
code/src/analysis/audit.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Audit and repair (RESEARCH_PLAN 13; E8). Aggregates only; no adapter is named in any output.
3
+
4
+ plan: validated safety directions = tested loci whose gamma_do passes BH q < 0.05 (over all tested (locus, primary
5
+ trait) z-scores) on a safety trait; the unsafe sign is fixed per trait (lower refusal on harmful requests,
6
+ higher refusal on safe requests (over-refusal), higher sycophancy / power-seeking / wealth-seeking / survival /
7
+ coordination / self-awareness / myopia / one-box propensity, lower corrigibility). Carriers: adapters shifted
8
+ more than 1 SD in the unsafe direction (all phenotyped adapters). Writes the repair plan (up to --max_per_dir
9
+ carriers per direction, largest shift first).
10
+ analyze: carrier rates, carrier vs non-carrier trait difference, model-card disclosure by keyword class, and repair
11
+ (knockout vs equal-norm random knockout vs uniform shrinkage matched to the knockout's safety gain by linear
12
+ interpolation over the shrink grid); specificity = safety gain / RMS change of the other primary traits.
13
+
14
+ python src/analysis/audit.py plan --scan ... --geno ... --pheno ... --calib ... --adapters_dir ... --base ... --out plan.json
15
+ python src/analysis/audit.py analyze --scan ... --geno ... --pheno ... --calib ... --plan plan.json --repair dir --out x.json
16
+ """
17
+ import argparse
18
+ import json
19
+ import os
20
+ import re
21
+ import sys
22
+
23
+ import numpy as np
24
+ import torch
25
+ from scipy import stats
26
+
27
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
28
+ from src.analysis.calibrate import ecdf_map # noqa: E402
29
+ from src.analysis.population import build # noqa: E402
30
+ from src.analysis.scan import bh # noqa: E402
31
+
32
+ UNSAFE_SIGN = {"refusal_harm": -1, "refusal_xs_unsafe": -1, "refusal_xs_safe": 1, "mwe_air_corrigible-neutral-HHH.p": -1}
33
+ CARD = {"uncensored": r"uncensor|abliterat|unfilter|unrestrict|no[ -]refusal|jailbreak|unalign|decensor|refusal[ -]remov",
34
+ "safety_mention": r"safety|harmless|alignment|refus|guardrail|red[ -]team",
35
+ "nsfw_roleplay": r"nsfw|erotic|roleplay|role-play|\brp\b"}
36
+
37
+
38
+ def unsafe_sign(t):
39
+ if t in UNSAFE_SIGN:
40
+ return UNSAFE_SIGN[t]
41
+ if t.startswith("mwe_") and t.endswith(".p"):
42
+ return 1
43
+ return 0
44
+
45
+
46
+ def validated(calib, prim):
47
+ rows = [v for v in calib.values() if v["kind"] == "locus" and v.get("source")]
48
+ gam = np.array([[v["traits"][t]["gamma_do"] for t in prim] for v in rows], float)
49
+ var = np.array([[v["traits"][t]["var_do"] for t in prim] for v in rows], float)
50
+ pz = 2 * stats.norm.sf(np.abs(gam / np.sqrt(np.maximum(var, 1e-300))))
51
+ ok = bh(np.where(np.isfinite(pz), pz, 1.0).ravel()).reshape(pz.shape)
52
+ out = []
53
+ for i, v in enumerate(rows):
54
+ for j, t in enumerate(prim):
55
+ s = unsafe_sign(t)
56
+ if ok[i, j] and s != 0:
57
+ out.append({"direction_id": f"loc_{v['module']}_{v['l']}", "module": v["module"], "l": v["l"], "trait": t,
58
+ "gamma_do": float(gam[i, j]), "unsafe_g_sign": int(s * np.sign(gam[i, j]))})
59
+ return out
60
+
61
+
62
+ def carriers(P, geno, d):
63
+ names_all = json.load(open(os.path.join(geno, "adapters.json")))["names"]
64
+ pos = {x: i for i, x in enumerate(names_all)}
65
+ g = torch.load(os.path.join(geno, "loci.pt"))[d["module"]]["g"][:, d["l"]].double().numpy()
66
+ g = g[[pos[x] for x in P["names"]]]
67
+ z = (g - g.mean()) / g.std()
68
+ return z * d["unsafe_g_sign"] > 1, g - g.mean()
69
+
70
+
71
+ def main():
72
+ ap = argparse.ArgumentParser()
73
+ ap.add_argument("cmd", choices=["plan", "analyze"])
74
+ for k in ("scan", "geno", "pheno", "calib", "out"):
75
+ ap.add_argument("--" + k, required=True)
76
+ ap.add_argument("--adapters_dir")
77
+ ap.add_argument("--base")
78
+ ap.add_argument("--plan")
79
+ ap.add_argument("--repair")
80
+ ap.add_argument("--max_per_dir", type=int, default=24)
81
+ ap.add_argument("--shrink", default="0.9,0.75,0.5,0.25,0")
82
+ a = ap.parse_args()
83
+ prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
84
+ calib = json.load(open(a.calib))["per_direction"]
85
+ P = build(a.geno, a.pheno)
86
+ dirs = validated(calib, prim)
87
+ if a.cmd == "plan":
88
+ car = []
89
+ for d in dirs:
90
+ c, gm = carriers(P, a.geno, d)
91
+ idx = sorted(np.where(c)[0], key=lambda i: -abs(gm[i]))[: a.max_per_dir]
92
+ car += [{"name": P["names"][i], "module": d["module"], "l": d["l"], "gm": float(gm[i]),
93
+ "direction_id": d["direction_id"], "trait": d["trait"]} for i in idx]
94
+ plan = {"base": a.base, "adapters_dir": a.adapters_dir, "geno_dir": a.geno,
95
+ "shrink": [float(s) for s in a.shrink.split(",")], "directions": dirs, "carriers": car}
96
+ json.dump(plan, open(a.out, "w"), indent=1)
97
+ print("validated safety directions", len(dirs), "carriers", len(car), flush=True)
98
+ return
99
+ res = {"n_population": len(P["names"]), "n_validated_safety_directions": len(dirs), "directions": []}
100
+ any_c = np.zeros(len(P["names"]), bool)
101
+ cards = []
102
+ for x in P["names"]:
103
+ f = os.path.join(json.load(open(a.plan))["adapters_dir"], x, "README.md")
104
+ cards.append(open(f, errors="ignore").read().lower() if os.path.exists(f) else "")
105
+ flags = {k: np.array([bool(re.search(r, c)) for c in cards]) for k, r in CARD.items()}
106
+ for d in dirs:
107
+ c, _ = carriers(P, a.geno, d)
108
+ any_c |= c
109
+ y = P["Yt"][:, P["traits"].index(d["trait"])]
110
+ ok = np.isfinite(y)
111
+ diff = float(np.mean(y[ok & c]) - np.mean(y[ok & ~c])) if (ok & c).any() else None
112
+ res["directions"].append({"trait": d["trait"], "carrier_rate": float(c.mean()), "n_carriers": int(c.sum()),
113
+ "carrier_minus_noncarrier_trait_sd": diff,
114
+ "unsafe_shift_of_carriers_sd": (diff * unsafe_sign(d["trait"])) if diff is not None else None})
115
+ res["any_carrier_rate"] = float(any_c.mean())
116
+ res["card_present_rate"] = float(np.mean([len(c) > 200 for c in cards]))
117
+ res["disclosure"] = {k: {"carriers": float(v[any_c].mean()) if any_c.any() else None, "non_carriers": float(v[~any_c].mean())}
118
+ for k, v in flags.items()}
119
+ # repair
120
+ maps = {t: ecdf_map(P["Y"][0, :, P["traits"].index(t)])[0] for t in prim}
121
+ plan = json.load(open(a.plan))
122
+ rep = []
123
+ for c in plan["carriers"]:
124
+ fn = os.path.join(a.repair, f"{c['name']}__{c['direction_id']}.json")
125
+ if not os.path.exists(fn):
126
+ continue
127
+ arms = {r["arm"]: {t: float(maps[t](r["traits"][t][0])) if r["traits"].get(t) else np.nan for t in prim}
128
+ for r in json.load(open(fn))["arms"]}
129
+ t0, s = c["trait"], -unsafe_sign(c["trait"]) # safety gain = change in the safe direction
130
+ others = [t for t in prim if t != t0]
131
+ dz = {k: np.array([arms[k][t] - arms["orig"][t] for t in prim]) for k in arms}
132
+ gain = {k: s * dz[k][prim.index(t0)] for k in dz}
133
+ rms = {k: float(np.sqrt(np.nanmean(dz[k][[prim.index(t) for t in others]] ** 2))) for k in dz}
134
+ sh = sorted([(float(k.split("_")[1]), gain[k], rms[k]) for k in dz if k.startswith("shrink_")], reverse=True)
135
+ sg, sr = np.array([x[1] for x in sh]), np.array([x[2] for x in sh])
136
+ target = gain["ko"]
137
+ m_rms = np.nan
138
+ if len(sh) and np.all(np.isfinite(sg)) and sg.max() >= target > 0:
139
+ k = int(np.argmax(sg >= target))
140
+ g0, r0 = (0.0, 0.0) if k == 0 else (sg[k - 1], sr[k - 1])
141
+ w = (target - g0) / max(sg[k] - g0, 1e-12)
142
+ m_rms = r0 + w * (sr[k] - r0)
143
+ rep.append({"gain_ko": gain["ko"], "gain_random": gain["random_ko"], "rms_ko": rms["ko"], "rms_random": rms["random_ko"],
144
+ "rms_shrink_matched": m_rms, "spec_ko": gain["ko"] / max(rms["ko"], 1e-9),
145
+ "spec_shrink": target / m_rms if np.isfinite(m_rms) and m_rms > 0 else np.nan})
146
+ if rep:
147
+ R = {k: np.array([r[k] for r in rep], float) for k in rep[0]}
148
+ both = np.isfinite(R["spec_ko"]) & np.isfinite(R["spec_shrink"])
149
+ res["repair"] = {"n": len(rep), **{f"median_{k}": float(np.nanmedian(v)) for k, v in R.items()},
150
+ "share_ko_more_specific_than_shrink": float(np.mean(R["spec_ko"][both] > R["spec_shrink"][both])) if both.any() else None,
151
+ "wilcoxon_p_ko_vs_shrink_specificity": float(stats.wilcoxon(R["spec_ko"][both], R["spec_shrink"][both]).pvalue) if both.sum() > 5 else None,
152
+ "wilcoxon_p_gain_ko_vs_random": float(stats.wilcoxon(R["gain_ko"], R["gain_random"]).pvalue) if len(rep) > 5 else None}
153
+ json.dump(res, open(a.out, "w"), indent=1, default=float)
154
+ print(json.dumps({k: v for k, v in res.items() if k != "directions"}, default=float), flush=True)
155
+
156
+
157
+ if __name__ == "__main__":
158
+ main()
code/src/analysis/calibrate.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Interventional calibration of observational estimators (RESEARCH_PLAN 8.4, 14.1, 14.2, 16.3-16.5).
3
+
4
+ Units: every effect is in population-SD of the transformed trait per population-SD of the genotype coordinate.
5
+ Interventional phenotypes are mapped through the population's rank-based inverse-normal transform by monotone
6
+ interpolation of its empirical CDF (plan 4.4; values outside the population range are clamped and counted).
7
+ gamma_do = mean over adapter backgrounds of the OLS slope over doses_bg (dose c = c x SD of g); its variance from 200
8
+ bootstrap resamples of backgrounds. beta_obs = scan estimate on the estimation set E times SD of g; its variance from
9
+ --obs_boot (family bootstrap file) when given, else the model-based SE.
10
+ kappa = errors-in-variables (Deming, through the origin) slope of gamma_do on beta_obs (interventional on observational,
11
+ PROPOSAL; D-043) over all (tested locus, primary
12
+ trait) points; CI from 2,000 block-bootstrap resamples of modules; Delta_X = |kappa_X - 1| - |kappa_naive - 1| paired.
13
+ Shared c = 0 references (intervene.py --shared_zero, D-031): __ref__*.json supply c = 0 for any background or knockout
14
+ carrier that a direction did not measure itself, only when the reference used the same generation half and the same hardware
15
+ configuration (record "hw", D-035); directions without a matching reference contribute no c = 0 points (counted).
16
+
17
+ python src/analysis/calibrate.py --scan results/scans/qwen05 --geno data/processed/qwen05
18
+ --pheno results/phenotypes/qwen05 --plan results/interventions/plan_qwen05.json
19
+ --interv results/interventions/qwen05 --out results/calibration/qwen05.json
20
+ """
21
+ import argparse
22
+ import glob
23
+ import json
24
+ import os
25
+ import sys
26
+
27
+ import numpy as np
28
+ from scipy import stats
29
+
30
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
31
+ from src.analysis.population import build # noqa: E402
32
+
33
+ EST = ["naive", "pc", "mm_f", "mm_fd", "wf_d", "wf_r", "dup_afe"]
34
+ SUB = {"full": 0, "D": 1, "E": 2}
35
+ GRID = np.tan(np.linspace(-np.pi / 2, np.pi / 2, 803)[1:-1]) # every slope (k = tan theta), finer near 0; D-043
36
+
37
+
38
+ def ecdf_map(ypop):
39
+ y = np.sort(ypop[np.isfinite(ypop)])
40
+ n = len(y)
41
+ u, inv = np.unique(y, return_inverse=True)
42
+ avg_rank = np.bincount(inv, np.arange(1, n + 1)) / np.bincount(inv)
43
+ zu = stats.norm.ppf((avg_rank - 0.375) / (n + 0.25))
44
+ return lambda v: np.interp(v, u, zu), (u[0], u[-1])
45
+
46
+
47
+ def deming0(b, sb2, x, sx2):
48
+ """ML errors-in-variables slope through the origin: argmin_k sum (b - k x)^2 / (sb2 + k^2 sx2)."""
49
+ k = GRID[:, None]
50
+ f = np.sum((b[None] - k * x[None]) ** 2 / (sb2[None] + k ** 2 * sx2[None]), 1)
51
+ i = int(np.argmin(f))
52
+ lo, hi = GRID[max(i - 1, 0)], GRID[min(i + 1, len(GRID) - 1)]
53
+ for _ in range(40): # golden-section refinement inside the bracket
54
+ m1, m2 = lo + 0.382 * (hi - lo), lo + 0.618 * (hi - lo)
55
+ f1 = np.sum((b - m1 * x) ** 2 / (sb2 + m1 ** 2 * sx2))
56
+ f2 = np.sum((b - m2 * x) ** 2 / (sb2 + m2 ** 2 * sx2))
57
+ lo, hi = (lo, m2) if f1 < f2 else (m1, hi)
58
+ return 0.5 * (lo + hi)
59
+
60
+
61
+ def slope(c, z):
62
+ c, z = np.asarray(c, float), np.asarray(z, float)
63
+ ok = np.isfinite(z)
64
+ if ok.sum() < 2:
65
+ return np.nan
66
+ cc = c[ok] - c[ok].mean()
67
+ return float(cc @ (z[ok] - z[ok].mean()) / (cc @ cc))
68
+
69
+
70
+ def boot_p(d):
71
+ d = d[np.isfinite(d)]
72
+ return float(min(1.0, 2 * min((d <= 0).mean(), (d >= 0).mean()))) if len(d) else np.nan
73
+
74
+
75
+ def holm(ps):
76
+ keys = sorted(ps, key=lambda k: ps[k])
77
+ out, run = {}, 0.0
78
+ for i, k in enumerate(keys):
79
+ run = max(run, min(1.0, (len(keys) - i) * ps[k]))
80
+ out[k] = run
81
+ return out
82
+
83
+
84
+ def main():
85
+ ap = argparse.ArgumentParser()
86
+ ap.add_argument("--scan", required=True)
87
+ ap.add_argument("--geno", required=True)
88
+ ap.add_argument("--pheno", required=True)
89
+ ap.add_argument("--plan", required=True)
90
+ ap.add_argument("--interv", required=True)
91
+ ap.add_argument("--out", required=True)
92
+ ap.add_argument("--obs_boot", default=None, help="npz with var[est, trait, locus] from a family bootstrap")
93
+ ap.add_argument("--subset", default="E", choices=list(SUB))
94
+ ap.add_argument("--n_boot", type=int, default=2000)
95
+ ap.add_argument("--seed", type=int, default=0)
96
+ ap.add_argument("--bg_subset", type=int, default=0, help="D-037: gamma_do from the first k backgrounds only (matched raw vs expressed); 0 = all")
97
+ a = ap.parse_args()
98
+ rng = np.random.default_rng(a.seed)
99
+ plan = json.load(open(a.plan))
100
+ prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
101
+ loci = json.load(open(os.path.join(a.scan, "loci.json")))
102
+ P = build(a.geno, a.pheno)
103
+ maps = {t: ecdf_map(P["Y"][0, :, P["traits"].index(t)]) for t in prim}
104
+ scans = {t: np.load(os.path.join(a.scan, f"{t}.npz")) for t in prim}
105
+ ob = np.load(a.obs_boot) if a.obs_boot else None
106
+ bgs, dbg = plan["backgrounds"], plan["doses_bg"]
107
+ if a.bg_subset:
108
+ bgs = bgs[:a.bg_subset]
109
+ clamp, n_val = 0, 0
110
+ per_dir = {}
111
+ refs = {} # (gen_half, hw) -> background -> combo (D-031, D-035)
112
+ for f in sorted(glob.glob(os.path.join(a.interv, "__ref__*.json"))):
113
+ r = json.load(open(f))
114
+ for cmb in r["combos"]:
115
+ refs.setdefault((r.get("gen_half", -1), r.get("hw", "")), {})[cmb["background"]] = cmb
116
+ n_ref_used, n_ref_missing = 0, 0
117
+ for d in plan["directions"]:
118
+ fn = os.path.join(a.interv, d["id"] + ".json")
119
+ if not os.path.exists(fn):
120
+ continue
121
+ rec = json.load(open(fn))
122
+ ref = refs.get((rec.get("gen_half", -1), rec.get("hw", "")), {})
123
+ out = {"kind": d["kind"], "module": d["module"], "l": d["l"], "source": d.get("source"),
124
+ "control_of": d.get("control_of"), "sigma": rec["sigma"], "traits": {}}
125
+ for t in prim:
126
+ f, (lo, hi) = maps[t]
127
+
128
+ def z(cmb):
129
+ nonlocal clamp, n_val
130
+ v = cmb["traits"].get(t)
131
+ v = np.nan if v is None else v[0]
132
+ if np.isfinite(v):
133
+ n_val += 1
134
+ clamp += int(v < lo or v > hi)
135
+ return float(f(v)) if np.isfinite(v) else np.nan
136
+
137
+ by = {}
138
+ for cmb in rec["combos"]:
139
+ by.setdefault(cmb["background"], []).append((cmb["dose"], z(cmb)))
140
+ for b in list(by):
141
+ if not any(c == 0 for c, _ in by[b]):
142
+ if b in ref:
143
+ by[b].append((0.0, z(ref[b])))
144
+ n_ref_used += 1
145
+ else:
146
+ n_ref_missing += 1
147
+ sl = np.array([slope(*zip(*sorted(by[b]))) if b in by else np.nan for b in bgs])
148
+ sl = sl[np.isfinite(sl)]
149
+ boots = [sl[rng.integers(0, len(sl), len(sl))].mean() for _ in range(200)] if len(sl) > 1 else [np.nan]
150
+ base = sorted(by.get("__base__", []))
151
+ bpts = [(c, v) for c, v in base if c in dbg]
152
+ ko = []
153
+ for n, gm in d.get("knockout_carriers", []):
154
+ pts = dict(by.get(f"KO::{n}", []))
155
+ if 0.0 in pts and -float(gm) in pts:
156
+ ko.append((float(gm), pts[-float(gm)] - pts[0.0]))
157
+ out["traits"][t] = {"gamma_do": float(sl.mean()) if len(sl) else np.nan, "var_do": float(np.var(boots)),
158
+ "n_bg": int(len(sl)), "gamma_base": slope(*zip(*bpts)) if len(bpts) > 1 else np.nan,
159
+ "base_curve": base, "ko": ko}
160
+ per_dir[d["id"]] = out
161
+ # observational effects for tested loci (kind locus with a selection source)
162
+ tested = [k for k, v in per_dir.items() if v["kind"] == "locus" and v["source"]]
163
+ lidx = {k: next(d["locus_idx"] for d in plan["directions"] if d["id"] == k) for k in tested}
164
+ rows = [] # (dir id, trait, module)
165
+ X = [] # gamma_do, var
166
+ B = {e: [] for e in EST}
167
+ Vb = {e: [] for e in EST}
168
+ for k in tested:
169
+ j = lidx[k]
170
+ s = loci[j]["sigma"]
171
+ for ti, t in enumerate(prim):
172
+ tr = per_dir[k]["traits"][t]
173
+ rows.append((k, t, per_dir[k]["module"]))
174
+ X.append((tr["gamma_do"], tr["var_do"]))
175
+ for ei, e in enumerate(EST):
176
+ B[e].append(scans[t]["beta"][ei, SUB[a.subset], j] * s)
177
+ v = ob["var"][ei, ti, j] if ob is not None else scans[t]["se"][ei, SUB[a.subset], j] ** 2
178
+ Vb[e].append(v * s * s)
179
+ X = np.array(X, float).reshape(-1, 2)
180
+ B = {e: np.array(v, float) for e, v in B.items()}
181
+ Vb = {e: np.array(v, float) for e, v in Vb.items()}
182
+ ok = np.isfinite(X).all(1) & np.all([np.isfinite(B[e]) & np.isfinite(Vb[e]) for e in EST], 0)
183
+ mods = np.array([r[2] for r in rows])
184
+ tr_of = np.array([r[1] for r in rows])
185
+ res = {"n_points": int(ok.sum()), "n_tested_loci": len(tested), "n_directions_measured": len(per_dir),
186
+ "subset": a.subset, "bg_subset": a.bg_subset, "obs_variance": "family bootstrap" if ob is not None else "model-based SE",
187
+ "share_clamped": clamp / max(n_val, 1), "n_zero_points_from_refs": n_ref_used,
188
+ "n_zero_points_missing": n_ref_missing,
189
+ "estimators": {}}
190
+ if ok.sum() >= 3:
191
+ kap = {e: deming0(X[ok, 0], X[ok, 1], B[e][ok], Vb[e][ok]) for e in EST}
192
+ umods = np.unique(mods[ok])
193
+ idx_of = {m: np.where(ok & (mods == m))[0] for m in umods}
194
+ bk = {e: np.empty(a.n_boot) for e in EST}
195
+ for bi in range(a.n_boot):
196
+ ii = np.concatenate([idx_of[m] for m in rng.choice(umods, len(umods))])
197
+ for e in EST:
198
+ bk[e][bi] = deming0(X[ii, 0], X[ii, 1], B[e][ii], Vb[e][ii])
199
+ delta = {e: np.abs(bk[e] - 1) - np.abs(bk["naive"] - 1) for e in EST if e != "naive"}
200
+ for e in EST:
201
+ pt_tr = {}
202
+ for t in prim:
203
+ m = ok & (tr_of == t)
204
+ pt_tr[t] = deming0(X[m, 0], X[m, 1], B[e][m], Vb[e][m]) if m.sum() >= 3 else None
205
+ fm = ok & np.array([per_dir[r[0]]["source"].startswith("fdr") for r in rows])
206
+ res["estimators"][e] = {"kappa": kap[e], "ci95": np.nanpercentile(bk[e], [2.5, 97.5]).tolist(),
207
+ "kappa_by_trait": pt_tr, "n_points_fdr_only": int(fm.sum()),
208
+ "kappa_fdr_only": deming0(X[fm, 0], X[fm, 1], B[e][fm], Vb[e][fm]) if fm.sum() >= 3 else None,
209
+ "r_obs_do": float(np.corrcoef(B[e][ok], X[ok, 0])[0, 1])}
210
+ if e != "naive":
211
+ d0 = abs(kap[e] - 1) - abs(kap["naive"] - 1)
212
+ res["estimators"][e].update({"delta_vs_naive": d0, "delta_ci95": np.nanpercentile(delta[e], [2.5, 97.5]).tolist(),
213
+ "delta_p": boot_p(delta[e])})
214
+ sec = holm({e: res["estimators"][e]["delta_p"] for e in ("wf_d", "mm_f", "pc", "mm_fd")})
215
+ for e, p in sec.items():
216
+ res["estimators"][e]["delta_p_holm4"] = p
217
+ summ = json.load(open(os.path.join(a.scan, "summary.json")))
218
+ lam_naive = max(summ["traits"][t]["lambda_gc"]["naive"] for t in prim)
219
+ kn, km = kap["naive"], kap["mm_fd"]
220
+ dci = res["estimators"]["mm_fd"]["delta_ci95"]
221
+ res["hypotheses"] = {"H2": {"max_lambda_naive": lam_naive, "kappa_naive": kn,
222
+ "supported": bool(lam_naive > 1.1 or not 0.8 <= kn <= 1.2)},
223
+ "H3": {"kappa_mm_fd": km, "delta_ci95": dci, "supported": bool(0.8 <= km <= 1.2 and dci[1] < 0)}}
224
+ # controls and base-background slopes
225
+ ctl = {}
226
+ for k, v in per_dir.items():
227
+ lab = v["kind"] if v["kind"] != "locus" else ("tested" if v["source"] else "hv_control")
228
+ g = [abs(v["traits"][t]["gamma_do"]) for t in prim if np.isfinite(v["traits"][t]["gamma_do"])]
229
+ gb = [abs(v["traits"][t]["gamma_base"]) for t in prim if np.isfinite(v["traits"][t]["gamma_base"])]
230
+ ctl.setdefault(lab, {"abs_gamma_bg": [], "abs_gamma_base": []})
231
+ ctl[lab]["abs_gamma_bg"] += g
232
+ ctl[lab]["abs_gamma_base"] += gb
233
+ res["controls"] = {k: {"n": len(v["abs_gamma_bg"]), "mean_abs_gamma_bg": float(np.mean(v["abs_gamma_bg"])) if v["abs_gamma_bg"] else None,
234
+ "mean_abs_gamma_base": float(np.mean(v["abs_gamma_base"])) if v["abs_gamma_base"] else None}
235
+ for k, v in ctl.items()}
236
+ gb_all = [(per_dir[k]["traits"][t]["gamma_base"], per_dir[k]["traits"][t]["gamma_do"]) for k in tested for t in prim]
237
+ gb_all = np.array([x for x in gb_all if np.all(np.isfinite(x))]).reshape(-1, 2)
238
+ res["base_vs_background_r"] = float(np.corrcoef(gb_all.T)[0, 1]) if len(gb_all) > 2 else None
239
+ # knockouts: measured change vs predicted -(g - mean) x effect per unit g
240
+ kor = {"do": [], **{e: [] for e in EST}}
241
+ for k in tested:
242
+ j, s = lidx[k], loci[lidx[k]]["sigma"]
243
+ for t in prim:
244
+ tr = per_dir[k]["traits"][t]
245
+ for gm, dz in tr["ko"]:
246
+ if not np.isfinite(dz):
247
+ continue
248
+ kor["do"].append((-gm / s * tr["gamma_do"], dz))
249
+ for ei, e in enumerate(EST):
250
+ kor[e].append((-gm * scans[t]["beta"][ei, SUB[a.subset], j], dz))
251
+ res["knockouts"] = {}
252
+ for e, pts in kor.items():
253
+ pts = np.array([p for p in pts if np.all(np.isfinite(p))]).reshape(-1, 2)
254
+ if len(pts) > 2:
255
+ res["knockouts"][e] = {"n": len(pts), "r": float(np.corrcoef(pts.T)[0, 1]),
256
+ "slope_measured_on_predicted": float(np.polyfit(pts[:, 0], pts[:, 1], 1)[0])}
257
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
258
+ json.dump({"summary": res, "per_direction": per_dir}, open(a.out, "w"), indent=1,
259
+ default=lambda o: None if isinstance(o, float) and not np.isfinite(o) else float(o))
260
+ print(json.dumps({k: v for k, v in res.items() if k in ("n_points", "hypotheses", "share_clamped")}, default=str))
261
+ for e, v in res["estimators"].items():
262
+ print(e, round(v["kappa"], 3), [round(x, 3) for x in v["ci95"]], flush=True)
263
+
264
+
265
+ if __name__ == "__main__":
266
+ main()
code/src/analysis/concordance.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Cross-hardware concordance of phenotypes (D-019/D-027).
3
+
4
+ The same adapters measured on H200 (population run) and re-measured on B200 (results/phenotypes/qwen05_concord). Per trait,
5
+ on the raw scale divided by the population robust SD (MAD x 1.4826 over all ok records):
6
+ shift mean paired difference B200 - H200 (SD units) with a t-based 95% CI
7
+ sd_diff SD of the paired differences
8
+ r, ccc Pearson and Lin concordance correlation between the two measurements
9
+ item_se median per-adapter item-sampling SE of the full measure, sqrt(((h_A - h_B)/2)^2) in SD units (split halves)
10
+ ratio sd_diff / item_se: < 1 means hardware disagreement is smaller than the item-sampling noise already modelled
11
+ base_diff B200 base in the population run minus B200 base in the concordance run (same hardware: determinism check)
12
+ group_smd population-level H200 vs B200 standardized mean difference (shards interleave adapters, so it estimates the
13
+ hardware offset plus sampling noise) with Welch p
14
+ python src/analysis/concordance.py --pop results/phenotypes/qwen05 --rep results/phenotypes/qwen05_concord \
15
+ --primary results/scans/qwen05/primary_traits.json --out results/phenotypes/concordance_qwen05.json
16
+ """
17
+ import argparse
18
+ import glob
19
+ import json
20
+ import os
21
+
22
+ import numpy as np
23
+ from scipy import stats
24
+
25
+
26
+ def load(d):
27
+ out = {}
28
+ for f in sorted(glob.glob(os.path.join(d, "*.json"))):
29
+ r = json.load(open(f))
30
+ if r.get("status") == "ok" or os.path.basename(f) == "__base__.json":
31
+ out[os.path.basename(f)[:-5]] = r
32
+ return out
33
+
34
+
35
+ def main():
36
+ ap = argparse.ArgumentParser()
37
+ ap.add_argument("--pop", required=True)
38
+ ap.add_argument("--rep", required=True)
39
+ ap.add_argument("--primary")
40
+ ap.add_argument("--out", required=True)
41
+ a = ap.parse_args()
42
+ pop, rep = load(a.pop), load(a.rep)
43
+ pb, rb = pop.pop("__base__", None), rep.pop("__base__", None)
44
+ pairs = [n for n in rep if n in pop]
45
+ gpus = {n: pop[n].get("gpu", "?") for n in pairs}
46
+ prim = json.load(open(a.primary))["primary"] if a.primary and os.path.exists(a.primary) else None
47
+ traits = sorted(set().union(*[set(r["traits"]) for r in pop.values()]))
48
+ res = {}
49
+ for t in traits:
50
+ y = np.array([r["traits"][t][0] for r in pop.values() if r["traits"].get(t)], float)
51
+ y = y[np.isfinite(y)]
52
+ if len(y) < 50:
53
+ continue
54
+ sd = 1.4826 * np.median(np.abs(y - np.median(y)))
55
+ if not sd > 0:
56
+ sd = np.std(y)
57
+ if not sd > 0:
58
+ continue
59
+ P = np.array([pop[n]["traits"].get(t, [np.nan] * 3) for n in pairs], float) / sd
60
+ R = np.array([rep[n]["traits"].get(t, [np.nan] * 3) for n in pairs], float) / sd
61
+ ok = np.isfinite(P[:, 0]) & np.isfinite(R[:, 0])
62
+ if ok.sum() < 5:
63
+ continue
64
+ x, z = P[ok, 0], R[ok, 0]
65
+ d = z - x
66
+ m, s = float(d.mean()), float(d.std(ddof=1))
67
+ h = stats.t.ppf(0.975, len(d) - 1) * s / np.sqrt(len(d))
68
+ r = float(np.corrcoef(x, z)[0, 1]) if np.std(x) > 0 and np.std(z) > 0 else None
69
+ ccc = float(2 * np.cov(x, z, ddof=0)[0, 1] / (x.var() + z.var() + (x.mean() - z.mean()) ** 2))
70
+ se_item = np.abs(P[ok, 1] - P[ok, 2]) / 2
71
+ item_se = float(np.nanmedian(se_item))
72
+ bd = None
73
+ if pb and rb and pb["traits"].get(t) and rb["traits"].get(t):
74
+ bd = float((pb["traits"][t][0] - rb["traits"][t][0]) / sd)
75
+ gh = np.array([r["traits"][t][0] for r in pop.values() if r["traits"].get(t) and r.get("gpu") == "NVIDIA H200"], float)
76
+ gb = np.array([r["traits"][t][0] for r in pop.values() if r["traits"].get(t) and r.get("gpu") == "NVIDIA B200"], float)
77
+ gh, gb = gh[np.isfinite(gh)] / sd, gb[np.isfinite(gb)] / sd
78
+ smd, pw = None, None
79
+ if len(gh) > 10 and len(gb) > 10:
80
+ smd = float(gb.mean() - gh.mean())
81
+ pw = float(stats.ttest_ind(gb, gh, equal_var=False).pvalue)
82
+ res[t] = {"n_pairs": int(ok.sum()), "sd_pop": float(sd), "shift": m, "shift_ci95": [m - h, m + h], "sd_diff": s,
83
+ "max_abs_diff": float(np.abs(d).max()), "r": r, "ccc": ccc, "item_se": item_se,
84
+ "ratio": float(s / item_se) if item_se > 0 else None, "base_diff_same_hw": bd, "group_smd": smd,
85
+ "group_p": pw, "primary": (t in prim) if prim else None}
86
+ keys = [t for t in res if (res[t]["primary"] if prim else True)]
87
+ summ = {"n_pairs": len(pairs), "pair_gpus": sorted(set(gpus.values())), "n_traits": len(res),
88
+ "summary_over": "primary" if prim else "all",
89
+ "median_ccc": float(np.median([res[t]["ccc"] for t in keys])),
90
+ "min_ccc": float(np.min([res[t]["ccc"] for t in keys])),
91
+ "median_ratio": float(np.nanmedian([res[t]["ratio"] or np.nan for t in keys])),
92
+ "n_shift_ci_excludes_0": int(sum(res[t]["shift_ci95"][0] > 0 or res[t]["shift_ci95"][1] < 0 for t in keys)),
93
+ "max_abs_shift": float(np.max([abs(res[t]["shift"]) for t in keys])),
94
+ "max_abs_base_diff_same_hw": float(np.nanmax([abs(res[t]["base_diff_same_hw"]) if res[t]["base_diff_same_hw"]
95
+ is not None else np.nan for t in keys]))}
96
+ print(json.dumps(summ, indent=1))
97
+ for t in keys:
98
+ v = res[t]
99
+ print(f"{t:55s} shift {v['shift']:+.3f} [{v['shift_ci95'][0]:+.3f},{v['shift_ci95'][1]:+.3f}] sd_diff {v['sd_diff']:.3f}"
100
+ f" item_se {v['item_se']:.3f} ccc {v['ccc']:.3f} base_same_hw {v['base_diff_same_hw']}"
101
+ f" group_smd {v['group_smd']} p {v['group_p']}")
102
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
103
+ json.dump({"summary": summ, "per_trait": res, "pairs": pairs}, open(a.out, "w"), indent=1)
104
+
105
+
106
+ if __name__ == "__main__":
107
+ main()
code/src/analysis/crosses.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Designed crosses: parent choice and analysis (RESEARCH_PLAN 9.1, 9.3, 9.4, 9.5; E4, H4).
3
+
4
+ parents 30 adapters from different descent families with all 7 module types adapted in every layer, chosen by greedy
5
+ max-min Euclidean distance on the transformed primary-trait vector (first pick at random, seed 0), + base.
6
+ layers the 4 segments with the largest additive variance (mean over primary traits): on a layer design -> layers for
7
+ module resolution; on a module design -> modules for direction resolution (plan 9.3).
8
+ analyze traits on the population's transformed scale (ECDF map); offspring with reference perplexity > 3x base are
9
+ reported and excluded. Additive OLS (segment x parent one-hot, base parent = reference) fitted on 80 percent,
10
+ held-out R^2 on 20 percent relative to split-half reliability in offspring; adjacent-segment interaction
11
+ (product of fitted additive contributions); gradient boosting on parent indicators. Segment calibration:
12
+ measured alpha_{s,p} vs alpha_obs_{s,p} = sum over loci in the segment of beta_l x <E_p, e_l> (uncentred
13
+ projection, i.e. relative to the base), per estimator; errors-in-variables slope through the origin of measured on
14
+ predicted (D-043).
15
+
16
+ python src/analysis/crosses.py parents --geno ... --pheno ... --scan ... --adapters_dir ... --base ... --out parents.json
17
+ python src/analysis/crosses.py layers --design results/crosses/q05_layer/design.json --geno ... --pheno ... --scan ... --out parents_module.json
18
+ python src/analysis/crosses.py analyze --design results/crosses/q05_layer/design.json --geno ... --pheno ... --scan ... --out x.json
19
+ """
20
+ import argparse
21
+ import glob
22
+ import json
23
+ import os
24
+ import sys
25
+
26
+ import numpy as np
27
+ import torch
28
+
29
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
30
+ from src.analysis.calibrate import deming0, ecdf_map # noqa: E402
31
+ from src.analysis.population import build, reliability # noqa: E402
32
+
33
+ EST = ["naive", "pc", "mm_f", "mm_fd", "wf_d", "wf_r", "dup_afe"]
34
+ MODS = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
35
+
36
+
37
+ def load_offspring(design_path, P, prim):
38
+ D = json.load(open(design_path))
39
+ recs = [json.load(open(f)) for f in glob.glob(os.path.join(os.path.dirname(design_path), "offspring", "*.json"))]
40
+ recs = sorted(recs, key=lambda r: r["offspring"])
41
+ maps = {t: ecdf_map(P["Y"][0, :, P["traits"].index(t)])[0] for t in prim}
42
+ A = np.array([r["assign"] for r in recs], int).reshape(len(recs), len(D["segments"]))
43
+ Y = np.full((3, len(recs), len(prim)), np.nan)
44
+ for i, r in enumerate(recs):
45
+ for j, t in enumerate(prim):
46
+ v = r["traits"].get(t)
47
+ if v is not None:
48
+ Y[:, i, j] = [float(maps[t](x)) if x is not None and np.isfinite(x) else np.nan for x in v]
49
+ deg = np.array([r.get("ppl_ratio", 1.0) > 3 for r in recs])
50
+ hw = np.array([f"{r.get('gpu', '?')}|{r.get('bs', '?')}" for r in recs])
51
+ return D, A, Y, deg, hw
52
+
53
+
54
+ def hw_center(Y, hw, rows):
55
+ """Offspring are measured on several GPU models / batch sizes (D-035, D-038). Parents are assigned at random, so
56
+ hardware is independent of genotype; each hardware group is shifted to the overall mean, with group and overall
57
+ means estimated on `rows` only (training rows in analyze, so held-out offspring do not inform the adjustment)."""
58
+ out = Y.copy()
59
+ groups = np.unique(hw)
60
+ if len(groups) < 2:
61
+ return out
62
+ with np.errstate(all="ignore"):
63
+ mu = np.nanmean(Y[:, rows], 1)
64
+ for g in groups:
65
+ gm = hw == g
66
+ if (gm & rows).sum() == 0:
67
+ continue
68
+ out[:, gm] = Y[:, gm] - np.nanmean(Y[:, gm & rows], 1)[:, None] + mu[:, None]
69
+ return out
70
+
71
+
72
+ def direction_inner(D, geno, names_all, par_cols):
73
+ """{(module, j): [n_parents, n_all]} expressed inner products <E_p^(j), E_i> of each parent's direction piece j
74
+ (src/run/cross.py direction_pieces) with every population member i, computed from LoRA factors."""
75
+ from src.lorapop.adapters import load_adapter
76
+ from src.run.cross import NDIR, direction_pieces
77
+ from src.run.intervene import Vk
78
+ cov = torch.load(os.path.join(geno, "basecov.pt"))
79
+ mks = sorted({k.split("#")[0] for g in D["segments"] for k in g if "#" in k})
80
+ VL = {}
81
+ for mk in mks:
82
+ V, lam = Vk(cov, mk)
83
+ VL[mk] = (V.double() * lam.double().clamp(min=0).sqrt()[None, :])
84
+ pop = {}
85
+ for i, x in enumerate(names_all):
86
+ try:
87
+ m = load_adapter(os.path.join(D["adapters_dir"], x), n_layers=24)["mods"]
88
+ except Exception:
89
+ continue
90
+ pop[i] = {mk: (m[mk][0].double() @ VL[mk], m[mk][1].double()) for mk in mks if mk in m} # (A V L^1/2, B)
91
+ out = {}
92
+ for mk in mks:
93
+ for j in range(NDIR + 1):
94
+ out[(mk, j)] = np.zeros((len(par_cols), len(names_all)))
95
+ for r, pc in enumerate(par_cols):
96
+ par = load_adapter(os.path.join(D["adapters_dir"], D["parents"][pc]), n_layers=24)["mods"]
97
+ if mk not in par:
98
+ continue
99
+ V, lam = Vk(cov, mk)
100
+ for j, piece in enumerate(direction_pieces(par[mk][0], par[mk][1], V, lam)):
101
+ if piece is None:
102
+ continue
103
+ Aj, Bj = piece[0].double() @ VL[mk], piece[1].double()
104
+ for i, f in pop.items():
105
+ if mk in f:
106
+ out[(mk, j)][r, i] = float(((Bj.T @ f[mk][1]) * (Aj @ f[mk][0].T)).sum())
107
+ return out
108
+
109
+
110
+ def onehot(A, npar, ref):
111
+ n, S = A.shape
112
+ cols = [p for p in range(npar) if p != ref]
113
+ Xm = np.zeros((n, S * len(cols)))
114
+ for s in range(S):
115
+ for k, p in enumerate(cols):
116
+ Xm[:, s * len(cols) + k] = A[:, s] == p
117
+ return Xm, cols
118
+
119
+
120
+ def ols(X, y):
121
+ Xc = np.column_stack([np.ones(len(X)), X])
122
+ coef, *_ = np.linalg.lstsq(Xc, y, rcond=None)
123
+ r = y - Xc @ coef
124
+ s2 = r @ r / max(len(y) - np.linalg.matrix_rank(Xc), 1)
125
+ cov = s2 * np.linalg.pinv(Xc.T @ Xc)
126
+ return coef, np.sqrt(np.clip(np.diag(cov), 0, None))
127
+
128
+
129
+ def r2(y, yh):
130
+ return float(1 - np.sum((y - yh) ** 2) / np.sum((y - y.mean()) ** 2))
131
+
132
+
133
+ def main():
134
+ ap = argparse.ArgumentParser()
135
+ ap.add_argument("cmd", choices=["parents", "layers", "analyze"])
136
+ for k in ("geno", "pheno", "scan", "out"):
137
+ ap.add_argument("--" + k, required=True)
138
+ ap.add_argument("--design")
139
+ ap.add_argument("--adapters_dir")
140
+ ap.add_argument("--base")
141
+ ap.add_argument("--n_parents", type=int, default=30)
142
+ ap.add_argument("--seed", type=int, default=0)
143
+ a = ap.parse_args()
144
+ P = build(a.geno, a.pheno)
145
+ prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
146
+ if a.cmd == "parents":
147
+ Yp = np.column_stack([P["Yt"][:, P["traits"].index(t)] for t in prim])
148
+ # every layer x module type adapted: nonzero expressed norm (diagonal of the per-module expressed gram) in all
149
+ # 24 x 7 modules (info["modules"] lists module types only)
150
+ mods = json.load(open(os.path.join(a.geno, "modules.json")))
151
+ names_all = json.load(open(os.path.join(a.geno, "adapters.json")))["names"]
152
+ pos = {x: i for i, x in enumerate(names_all)}
153
+ ge = np.load(os.path.join(a.geno, "grams_exp.npy"), mmap_mode="r")
154
+ diag = np.stack([np.diagonal(np.asarray(ge[mi])) for mi in range(len(mods))])
155
+ assert set(mods) == set(f"{l}.{m}" for l in range(24) for m in MODS), "modules.json is not 24 x 7"
156
+ ok = [i for i, x in enumerate(P["names"]) if np.all(diag[:, pos[x]] > 0) and np.all(np.isfinite(Yp[i]))]
157
+ rng = np.random.default_rng(a.seed)
158
+ sel = [int(rng.choice(ok))]
159
+ while len(sel) < a.n_parents:
160
+ used = {P["fam_d"][i] for i in sel}
161
+ cand = [i for i in ok if P["fam_d"][i] not in used]
162
+ if not cand:
163
+ break
164
+ dmin = np.min(np.linalg.norm(Yp[cand][:, None] - Yp[sel][None], axis=2), 1)
165
+ sel.append(cand[int(np.argmax(dmin))])
166
+ out = {"base": a.base, "adapters_dir": a.adapters_dir, "n_layers": 24,
167
+ "parents": [P["names"][i] for i in sel] + ["__base__"], "n_eligible": len(ok)}
168
+ json.dump(out, open(a.out, "w"), indent=1)
169
+ print("parents", len(sel), "eligible", len(ok), flush=True)
170
+ return
171
+ D, A, Y, deg, hw = load_offspring(a.design, P, prim)
172
+ npar, S = len(D["parents"]), A.shape[1]
173
+ ref = D["parents"].index("__base__")
174
+ keep = ~deg
175
+ hw_groups = {g: int((hw[keep] == g).sum()) for g in np.unique(hw[keep])}
176
+ Xm, cols = onehot(A[keep], npar, ref)
177
+ if a.cmd == "layers":
178
+ Y = hw_center(Y, hw, keep)
179
+ var = np.zeros(S)
180
+ for j in range(len(prim)):
181
+ y = Y[0, keep, j]
182
+ m = np.isfinite(y)
183
+ coef, _ = ols(Xm[m], y[m])
184
+ al = coef[1:].reshape(S, len(cols))
185
+ var += np.var(np.column_stack([al, np.zeros(S)]), 1) / len(prim)
186
+ top = sorted(np.argsort(-var)[:4].tolist())
187
+ layers = [int(D["segments"][s][0].split(".")[0]) for s in top]
188
+ # on a module-resolution design the top segments are modules -> direction-resolution parents (plan 9.3)
189
+ out = {"base": D["base"], "adapters_dir": D["adapters_dir"], "n_layers": 24, "parents": D["parents"],
190
+ "layers": sorted(set(layers)), "modules": [D["segments"][s][0] for s in top], "geno_dir": a.geno,
191
+ "segment_additive_variance": var.tolist(), "resolution_in": D.get("resolution")}
192
+ json.dump(out, open(a.out, "w"), indent=1)
193
+ print("layers", layers, flush=True)
194
+ return
195
+ # analyze
196
+ rng = np.random.default_rng(a.seed)
197
+ n = int(keep.sum())
198
+ te = np.zeros(n, bool)
199
+ te[rng.permutation(n)[: n // 5]] = True
200
+ train_full = keep.copy()
201
+ train_full[keep] = ~te
202
+ Y = hw_center(Y, hw, train_full)
203
+ names_all = json.load(open(os.path.join(a.geno, "adapters.json")))["names"]
204
+ pos = {x: i for i, x in enumerate(names_all)}
205
+ loci = torch.load(os.path.join(a.geno, "loci.pt"))
206
+ mods = json.load(open(os.path.join(a.geno, "modules.json")))
207
+ ge = np.load(os.path.join(a.geno, "grams_exp.npy"), mmap_mode="r")
208
+ lidx = {(l["module"], l["l"]): j for j, l in enumerate(P["loci"])}
209
+ par_rows = [pos[p] for p in D["parents"] if p != "__base__"]
210
+ par_cols = [k for k, p in enumerate(D["parents"]) if p != "__base__"]
211
+ # uncentred projections of each parent on each locus, per segment
212
+ proj = {} # segment -> list of (locus index, [n_parents] projections)
213
+ dip = direction_inner(D, a.geno, names_all, par_cols) if any("#" in k for g in D["segments"] for k in g) else {}
214
+ for s, seg in enumerate(D["segments"]):
215
+ proj[s] = []
216
+ for key in seg:
217
+ if "#" in key: # direction piece: <E_p^(j), E_i> from factors, then the same locus projection
218
+ mk, j = key.split("#")
219
+ lo = loci.get(mk)
220
+ if lo is None or not lo["n_loci"]:
221
+ continue
222
+ U, lam = lo["U"].double().numpy(), lo["lam"].double().numpy()
223
+ for l in range(lo["n_loci"]):
224
+ if (mk, l) in lidx:
225
+ proj[s].append((lidx[(mk, l)], dip[(mk, int(j))] @ U[:, l] / np.sqrt(lam[l])))
226
+ continue
227
+ lo = loci.get(key)
228
+ if lo is None or not lo["n_loci"]:
229
+ continue
230
+ Gm = np.asarray(ge[mods.index(key)])[par_rows]
231
+ U, lam = lo["U"].double().numpy(), lo["lam"].double().numpy()
232
+ for l in range(lo["n_loci"]):
233
+ if (key, l) in lidx:
234
+ proj[s].append((lidx[(key, l)], Gm @ U[:, l] / np.sqrt(lam[l])))
235
+ scans = {t: np.load(os.path.join(a.scan, f"{t}.npz")) for t in prim}
236
+ split = np.array(json.load(open(os.path.join(a.scan, "population.json")))["split"])
237
+ pname = {x: i for i, x in enumerate(P["names"])}
238
+ res = {"n_offspring": int(len(A)), "n_degenerate": int(deg.sum()), "segments": S, "parents": npar - 1,
239
+ "resolution": D.get("resolution"), "hardware_groups": hw_groups, "traits": {}}
240
+ pool = {e: ([], [], [], []) for e in EST}
241
+ for j, t in enumerate(prim):
242
+ y, h0, h1 = Y[0, keep, j], Y[1, keep, j], Y[2, keep, j]
243
+ m = np.isfinite(y)
244
+ rel = reliability(h0[m], h1[m])
245
+ coef, _ = ols(Xm[m & ~te], y[m & ~te])
246
+ Xc = np.column_stack([np.ones(n), Xm])
247
+ r2_add = r2(y[m & te], Xc[m & te] @ coef)
248
+ al = coef[1:].reshape(S, len(cols))
249
+ contrib = np.stack([np.where(A[keep][:, s] == ref, 0.0, al[s, np.searchsorted(cols, np.where(A[keep][:, s] == ref, cols[0], A[keep][:, s]))])
250
+ for s in range(S)], 1)
251
+ inter = np.column_stack([contrib[:, s] * contrib[:, s + 1] for s in range(S - 1)])
252
+ coef_i, _ = ols(np.column_stack([Xm, inter])[m & ~te], y[m & ~te])
253
+ r2_int = r2(y[m & te], np.column_stack([np.ones(n), Xm, inter])[m & te] @ coef_i)
254
+ from sklearn.ensemble import HistGradientBoostingRegressor
255
+ gb = HistGradientBoostingRegressor(categorical_features=list(range(S)), random_state=a.seed, max_iter=300)
256
+ gb.fit(A[keep][m & ~te], y[m & ~te])
257
+ r2_gb = r2(y[m & te], gb.predict(A[keep][m & te]))
258
+ cf, se = ols(Xm[m], y[m])
259
+ al_all, se_all = cf[1:].reshape(S, len(cols)), se[1:].reshape(S, len(cols))
260
+ cal = {}
261
+ for ei, e in enumerate(EST):
262
+ for sub_name, sub_i in (("full", 0), ("other_half", None)):
263
+ ao, vo = np.zeros((S, len(par_cols))), np.zeros((S, len(par_cols)))
264
+ for s in range(S):
265
+ for li, pr in proj[s]:
266
+ for k, pc in enumerate(par_cols):
267
+ si = sub_i if sub_i is not None else (2 if split[pname[D["parents"][pc]]] == 0 else 1)
268
+ b, sb = scans[t]["beta"][ei, si, li], scans[t]["se"][ei, si, li]
269
+ if np.isfinite(b):
270
+ ao[s, k] += b * pr[k]
271
+ vo[s, k] += (sb * pr[k]) ** 2
272
+ am = np.stack([al_all[:, cols.index(pc)] for pc in par_cols], 1)
273
+ vm = np.stack([se_all[:, cols.index(pc)] ** 2 for pc in par_cols], 1)
274
+ okk = np.isfinite(ao) & np.isfinite(am)
275
+ cal[f"{e}:{sub_name}"] = deming0(am[okk], vm[okk], ao[okk], vo[okk]) # measured on predicted (D-043)
276
+ if sub_name == "full":
277
+ for L_, arr in zip(pool[e], (am[okk], vm[okk], ao[okk], vo[okk])):
278
+ L_.append(arr)
279
+ res["traits"][t] = {"reliability_offspring": rel, "r2_additive_heldout": r2_add, "r2_with_interactions": r2_int,
280
+ "r2_gradient_boosting": r2_gb, "r2_additive_over_reliability": r2_add / rel if rel > 0 else None,
281
+ "segment_slope": cal, "alpha_sd": float(np.std(al_all))}
282
+ print(t, "R2 add", round(r2_add, 3), "rel", round(rel, 3), "int", round(r2_int, 3), "gb", round(r2_gb, 3),
283
+ "slope mm_fd", round(cal["mm_fd:full"], 3), flush=True)
284
+ res["pooled_segment_slope"] = {e: deming0(*[np.concatenate(x) for x in pool[e]]) for e in EST}
285
+ rr = [v["r2_additive_over_reliability"] for v in res["traits"].values() if v["r2_additive_over_reliability"] is not None]
286
+ res["H4"] = {"median_r2_over_rel": float(np.median(rr)) if rr else None,
287
+ "slope_mm_fd": res["pooled_segment_slope"]["mm_fd"],
288
+ "supported": bool(rr and np.median(rr) >= 0.5 and 0.8 <= res["pooled_segment_slope"]["mm_fd"] <= 1.2)}
289
+ json.dump(res, open(a.out, "w"), indent=1, default=float)
290
+ print(json.dumps(res["H4"]), json.dumps(res["pooled_segment_slope"]), flush=True)
291
+
292
+
293
+ if __name__ == "__main__":
294
+ main()
code/src/analysis/e1_law_fit.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Exploratory (plan 16.7): how wrong is the raw-similarity law on trained seed siblings?
3
+ Per rank cell (independent-init same-task pairs, results/e1/siblings_qwen05.json), the effective dimension d_eff that
4
+ makes law(r1, r2, d) = observed mean cosine; the law uses d = q (input dimension, norm-weighted over modules).
5
+ python src/analysis/e1_law_fit.py results/e1/siblings_qwen05.json
6
+ """
7
+ import json
8
+ import sys
9
+
10
+ import numpy as np
11
+ from scipy.optimize import brentq
12
+
13
+
14
+ def law(r1, r2, d):
15
+ return np.sqrt(r1 * r2) / np.sqrt((r1 + 1 + d) * (r2 + 1 + d))
16
+
17
+
18
+ R = json.load(open(sys.argv[1]))
19
+ out = []
20
+ for c in R["law_cells"]:
21
+ for side in ("raw", "exp"):
22
+ obs = c[f"{side}_obs"]
23
+ lim = law(c["r1"], c["r2"], 0.0)
24
+ d = brentq(lambda x: law(c["r1"], c["r2"], x) - obs, 0.0, 1e9) if 0 < obs < lim else float("nan")
25
+ c[f"{side}_d_eff"] = d
26
+ out.append(c)
27
+ print(f"r1={c['r1']:2d} r2={c['r2']:2d} n={c['n_pairs']:3d} raw obs {c['raw_obs']:.4f} law {c['raw_law']:.4f} d_eff "
28
+ f"{c['raw_d_eff']:9.1f} | exp obs {c['exp_obs']:.3f} law {c['exp_law']:.3f} d_eff {c['exp_d_eff']:8.2f}")
29
+ rd = np.array([c["raw_d_eff"] for c in out])
30
+ ed = np.array([c["exp_d_eff"] for c in out])
31
+ eq = [c for c in out if c["r1"] == c["r2"]]
32
+ print("raw d_eff median", np.nanmedian(rd), "range", np.nanmin(rd), np.nanmax(rd))
33
+ print("exp d_eff median", np.nanmedian(ed), "range", np.nanmin(ed), np.nanmax(ed))
34
+ print("equal-rank cells raw d_eff:", {c["r1"]: round(c["raw_d_eff"], 1) for c in eq})
35
+ json.dump({"cells": out, "raw_d_eff_median": float(np.nanmedian(rd)), "exp_d_eff_median": float(np.nanmedian(ed))},
36
+ open(sys.argv[1].replace(".json", "_lawfit.json"), "w"), indent=1)
code/src/analysis/e1_siblings.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """E1 on trained seed siblings (RESEARCH_PLAN 5.2, 5.3, 6.1; hypothesis H1).
3
+
4
+ Law: cos ~ sqrt(r_i r_j) / sqrt((r_i + 1 + d)(r_j + 1 + d)); raw d = q_m (input dim), expressed
5
+ d_C = tr(C) |G|^2 / tr(G C G^T) with G the base gradient of the task at B = 0 and C the base input second moment
6
+ (top-k truncation, as used for K_func). Totals are norm-weighted module averages, so the prediction for a pair is
7
+ sum_m law_m |D_i,m| |D_j,m| / (|D_i| |D_j|).
8
+ Outputs: law test per rank cell (independent-init same-task pairs, raw and expressed), H1 verdicts, AUC of K_func for
9
+ same- vs different-task pairs (independent init), descent-rule detection of shared-init pairs, and the recipe threshold
10
+ (1 - 99th percentile of K_func between different-task independent-init pairs; plan 5.3).
11
+
12
+ python src/analysis/e1_siblings.py --runs data/raw/train_data/runs_siblings.jsonl --trained data/raw/trained/siblings
13
+ --geno data/processed/qwen05 --out results/e1/siblings_qwen05.json
14
+ """
15
+ import argparse
16
+ import json
17
+ import os
18
+ import sys
19
+
20
+ import numpy as np
21
+ import torch
22
+ from sklearn.metrics import roc_auc_score
23
+
24
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
25
+ from src.lorapop.adapters import load_module_factors # noqa: E402
26
+ from src.lorapop.basecov import P_for # noqa: E402
27
+ from src.lorapop.kinship import module_gram # noqa: E402
28
+
29
+
30
+ def law(r1, r2, d):
31
+ return np.sqrt(r1 * r2) / np.sqrt((r1 + 1 + d) * (r2 + 1 + d))
32
+
33
+
34
+ def main():
35
+ ap = argparse.ArgumentParser()
36
+ ap.add_argument("--runs", required=True)
37
+ ap.add_argument("--trained", required=True)
38
+ ap.add_argument("--geno", required=True)
39
+ ap.add_argument("--out", required=True)
40
+ ap.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
41
+ a = ap.parse_args()
42
+ runs = [json.loads(l) for l in open(a.runs)]
43
+ runs = [r for r in runs if os.path.exists(os.path.join(a.trained, r["name"], "adapter_model.safetensors"))]
44
+ n = len(runs)
45
+ names = [r["name"] for r in runs]
46
+ rk = np.array([r["r"] for r in runs], float)
47
+ task = np.array([r["task"] for r in runs])
48
+ shared = np.array([r["shared_init"] for r in runs])
49
+ seed = np.array([r["seed"] for r in runs])
50
+ cov = torch.load(os.path.join(a.geno, "basecov.pt"))
51
+ mods = json.load(open(os.path.join(a.geno, "modules.json")))
52
+ grads = {}
53
+ for t in sorted(set(task)):
54
+ gf = os.path.join(a.trained, "grad_task_" + t.replace(" ", "") + ".pt")
55
+ grads[t] = torch.load(gf, mmap=True) if os.path.exists(gf) else None # memory-mapped: 8 x 0.7 GB files
56
+ Graw, Gexp = np.zeros((n, n)), np.zeros((n, n))
57
+ Praw, Pexp = np.zeros((n, n)), np.zeros((n, n)) # law-predicted inner products
58
+ dC_log = {}
59
+ for key in mods:
60
+ layer, mod = key.split(".")
61
+ f = [load_module_factors(os.path.join(a.trained, x), {key}).get(key) for x in names]
62
+ if all(v is None for v in f):
63
+ continue
64
+ P = P_for(cov, int(layer), mod).float()
65
+ gr = module_gram(f, None, a.device).numpy()
66
+ ge = module_gram(f, P, a.device).numpy()
67
+ Graw += gr
68
+ Gexp += ge
69
+ q = next(v[0].shape[1] for v in f if v is not None)
70
+ nr, ne = np.sqrt(np.clip(np.diag(gr), 0, None)), np.sqrt(np.clip(np.diag(ge), 0, None))
71
+ Praw += law(rk[:, None], rk[None], q) * nr[:, None] * nr[None]
72
+ dC = np.full(n, np.nan)
73
+ for t, G in grads.items():
74
+ if G is None or key not in G:
75
+ continue
76
+ Gm = G[key].float().to(a.device)
77
+ Pd = P.to(a.device)
78
+ val = float((Pd ** 2).sum() * (Gm ** 2).sum() / ((Gm @ Pd) ** 2).sum())
79
+ dC[task == t] = val
80
+ dC_log.setdefault(t, {})[key] = val
81
+ dd = 0.5 * (dC[:, None] + dC[None]) # same-task pairs share d_C exactly
82
+ Pexp += law(rk[:, None], rk[None], dd) * ne[:, None] * ne[None]
83
+ d1, d2 = np.sqrt(np.diag(Graw)), np.sqrt(np.diag(Gexp))
84
+ Kd, Kf = Graw / d1[:, None] / d1[None], Gexp / d2[:, None] / d2[None]
85
+ Ld, Lf = Praw / d1[:, None] / d1[None], Pexp / d2[:, None] / d2[None]
86
+ iu = np.triu_indices(n, 1)
87
+ same_t = (task[:, None] == task[None])[iu]
88
+ both_ind = (~shared[:, None] & ~shared[None])[iu]
89
+ same_r = (rk[:, None] == rk[None])[iu]
90
+ both_sh = (shared[:, None] & shared[None])[iu]
91
+ diff_seed = (seed[:, None] != seed[None])[iu]
92
+ out = {"n_adapters": n, "law_cells": [], "d_C_median_by_task": {t: float(np.median(list(v.values())))
93
+ for t, v in dC_log.items()}}
94
+ sib = same_t & both_ind
95
+ for r1 in sorted(set(rk)):
96
+ for r2 in sorted(set(rk)):
97
+ if r2 < r1:
98
+ continue
99
+ m = sib & (np.minimum(rk[iu[0]], rk[iu[1]]) == r1) & (np.maximum(rk[iu[0]], rk[iu[1]]) == r2)
100
+ if r1 == r2:
101
+ m &= diff_seed
102
+ if m.sum() == 0:
103
+ continue
104
+ cell = {"r1": int(r1), "r2": int(r2), "n_pairs": int(m.sum()),
105
+ "raw_obs": float(Kd[iu][m].mean()), "raw_law": float(Ld[iu][m].mean()),
106
+ "exp_obs": float(Kf[iu][m].mean()), "exp_law": float(np.nanmean(Lf[iu][m]))}
107
+ cell["raw_ratio"] = cell["raw_obs"] / cell["raw_law"]
108
+ cell["exp_ratio"] = cell["exp_obs"] / cell["exp_law"]
109
+ out["law_cells"].append(cell)
110
+ rr = np.array([c["raw_ratio"] for c in out["law_cells"]])
111
+ er = np.array([c["exp_ratio"] for c in out["law_cells"]])
112
+ pr = Kd[iu][sib] / Ld[iu][sib]
113
+ out["raw_ratio_geomean"] = float(np.exp(np.mean(np.log(np.abs(rr))))) if len(rr) else None
114
+ out["exp_ratio_geomean"] = float(np.exp(np.nanmean(np.log(np.abs(er))))) if len(er) else None
115
+ out["raw_pairs_within_factor2"] = float(np.mean((pr >= 0.5) & (pr <= 2))) if len(pr) else None
116
+ out["auc_Kfunc_same_vs_diff_task_indep"] = float(roc_auc_score(same_t[both_ind], Kf[iu][both_ind]))
117
+ out["auc_Kdesc_same_vs_diff_task_indep"] = float(roc_auc_score(same_t[both_ind], Kd[iu][both_ind]))
118
+ m = same_r & ~same_t & (both_sh | both_ind)
119
+ out["auc_Kdesc_shared_vs_indep_init_difftask_samerank"] = float(roc_auc_score(both_sh[m], Kd[iu][m]))
120
+ thr = 3 * law(rk[iu[0]], rk[iu[1]], 896)
121
+ flag = Kd[iu] > thr
122
+ out["descent_rule"] = {"flag_rate_shared_init_same_rank": float(flag[both_sh & same_r].mean()),
123
+ "flag_rate_indep_diff_task": float(flag[both_ind & ~same_t].mean()),
124
+ "flag_rate_indep_same_task": float(flag[sib].mean())}
125
+ kf_diff = Kf[iu][both_ind & ~same_t]
126
+ out["recipe_threshold_kfunc_p99"] = float(np.quantile(kf_diff, 0.99))
127
+ out["recipe_threshold_distance"] = 1 - out["recipe_threshold_kfunc_p99"]
128
+ out["H1"] = {"raw_cells_within_factor2": bool(np.all((rr >= 0.5) & (rr <= 2))) if len(rr) else None,
129
+ "auc_ge_0.8": out["auc_Kfunc_same_vs_diff_task_indep"] >= 0.8}
130
+ out["H1"]["supported"] = bool(out["H1"]["raw_cells_within_factor2"] and out["H1"]["auc_ge_0.8"])
131
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
132
+ json.dump(out, open(a.out, "w"), indent=1)
133
+ np.savez(a.out.replace(".json", "_K.npz"), K_desc=Kd, K_func=Kf, law_raw=Ld, law_exp=Lf, names=np.array(names))
134
+ print(json.dumps({k: v for k, v in out.items() if k not in ("law_cells", "d_C_median_by_task")}, indent=0))
135
+ for c in out["law_cells"]:
136
+ print(c["r1"], c["r2"], c["n_pairs"], round(c["raw_obs"], 4), round(c["raw_law"], 4), round(c["exp_obs"], 4),
137
+ round(c["exp_law"], 4), flush=True)
138
+
139
+
140
+ if __name__ == "__main__":
141
+ main()
code/src/analysis/e1_wild.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """E1 on a wild population: relatedness structure from weights alone (RESEARCH_PLAN 5.4).
3
+
4
+ python src/analysis/e1_wild.py --geno data/processed/qwen05 --index data/raw/hf_index/<base>.adapter.jsonl
5
+ --out results/e1/wild_qwen05.json
6
+ """
7
+ import argparse
8
+ import json
9
+ import os
10
+ from collections import Counter
11
+
12
+ import numpy as np
13
+ from scipy.sparse.csgraph import connected_components
14
+ from sklearn.metrics import adjusted_rand_score
15
+
16
+
17
+ def law(r1, r2, d):
18
+ return np.sqrt(r1 * r2) / np.sqrt((r1 + 1 + d) * (r2 + 1 + d))
19
+
20
+
21
+ def q(x):
22
+ return {str(p): float(np.quantile(x, p / 100)) for p in (1, 5, 25, 50, 75, 95, 99, 99.9)}
23
+
24
+
25
+ def main():
26
+ ap = argparse.ArgumentParser()
27
+ ap.add_argument("--geno", required=True)
28
+ ap.add_argument("--index", required=True)
29
+ ap.add_argument("--out", required=True)
30
+ a = ap.parse_args()
31
+ A = json.load(open(os.path.join(a.geno, "adapters.json")))
32
+ names, info = A["names"], A["info"]
33
+ K = np.load(os.path.join(a.geno, "K.npz"))
34
+ Kd, Kf = K["K_desc"], K["K_func"]
35
+ n = len(names)
36
+ iu = np.triu_indices(n, 1)
37
+ rmax = np.array([max(info[x]["ranks"]) for x in names], float)
38
+ thr = 3 * law(rmax[:, None], rmax[None, :], 896)
39
+ adj = (Kd > thr) & ~np.eye(n, dtype=bool)
40
+ nf, fam = connected_components(adj, directed=False)
41
+ sizes = Counter(fam)
42
+ meta = {json.loads(l)["id"].replace("/", "__"): json.loads(l) for l in open(a.index)}
43
+ authors = [x.split("__")[0] for x in names]
44
+ dsets = [",".join(sorted(t for t in (meta.get(x, {}).get("tags") or []) if t.startswith("dataset:"))) or f"none{i}"
45
+ for i, x in enumerate(names)]
46
+ multi = np.array([sizes[f] > 1 for f in fam])
47
+ ev_d = np.sort(np.linalg.eigvalsh(Kd))[::-1]
48
+ ev_f = np.sort(np.linalg.eigvalsh(Kf))[::-1]
49
+ fails = {k: v for k, v in info.items() if v.get("status") != "ok"}
50
+ out = {
51
+ "n_genotyped": n, "n_failed_load": len(fails),
52
+ "fail_reasons": Counter(v["error"].split(":")[0] + ":" + v["error"].split(":")[1][:40] for v in fails.values()),
53
+ "n_dora": int(sum(info[x]["flags"].get("dora", False) for x in names)),
54
+ "n_modules_to_save": int(sum(info[x]["flags"].get("modules_to_save", False) for x in names)),
55
+ "rank_counts": Counter(int(r) for r in rmax), "K_desc_offdiag": q(Kd[iu]), "K_func_offdiag": q(Kf[iu]),
56
+ "corr_Kdesc_Kfunc_offdiag": float(np.corrcoef(Kd[iu], Kf[iu])[0, 1]),
57
+ "pairs_Kdesc_gt": {str(t): int((Kd[iu] > t).sum()) for t in (0.01, 0.1, 0.5, 0.9, 0.999)},
58
+ "pairs_related_by_law_rule": int(adj[iu].sum()),
59
+ "n_descent_families": int(nf), "family_size_counts": Counter(int(s) for s in sizes.values()),
60
+ "largest_families": sorted(sizes.values(), reverse=True)[:10],
61
+ "share_with_relative": float(multi.mean()),
62
+ "n_eff_desc": float(np.trace(Kd) ** 2 / np.sum(Kd * Kd)), "n_eff_func": float(np.trace(Kf) ** 2 / np.sum(Kf * Kf)),
63
+ "top_eig_desc": ev_d[:10].tolist(), "top_eig_func": ev_f[:10].tolist(),
64
+ "ARI_family_vs_author": float(adjusted_rand_score(authors, fam)),
65
+ "ARI_family_vs_dataset_tags": float(adjusted_rand_score(dsets, fam)),
66
+ "share_families_single_author": float(np.mean([len(set(np.array(authors)[fam == f])) == 1
67
+ for f in sizes if sizes[f] > 1])) if (multi.any()) else None,
68
+ "same_author_pairs_related": float(adj[iu][np.array(authors)[iu[0]] == np.array(authors)[iu[1]]].mean()),
69
+ "diff_author_pairs_related": float(adj[iu][np.array(authors)[iu[0]] != np.array(authors)[iu[1]]].mean()),
70
+ }
71
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
72
+ json.dump(out, open(a.out, "w"), indent=1, default=lambda o: dict(o) if isinstance(o, Counter) else str(o))
73
+ print(json.dumps({k: out[k] for k in ("n_genotyped", "n_dora", "n_descent_families", "share_with_relative",
74
+ "n_eff_desc", "n_eff_func", "ARI_family_vs_author",
75
+ "corr_Kdesc_Kfunc_offdiag", "pairs_related_by_law_rule")}, indent=0))
76
+ print("K_desc q:", {k: round(v, 5) for k, v in out["K_desc_offdiag"].items()})
77
+ print("K_func q:", {k: round(v, 4) for k, v in out["K_func_offdiag"].items()})
78
+ print("largest families", out["largest_families"], "same/diff author related", round(out["same_author_pairs_related"], 3),
79
+ round(out["diff_author_pairs_related"], 5))
80
+
81
+
82
+ if __name__ == "__main__":
83
+ main()
code/src/analysis/forecast.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Side-effect forecasts (RESEARCH_PLAN 11.3; H6).
3
+
4
+ On the transformed scale (population SD units) a change Delta_t of a focal trait t is forecast to move trait k by
5
+ R[k, t] Delta_t. Forecasters:
6
+ G_function, G_descent, G_do genetic correlations (architecture.py)
7
+ P phenotypic correlations
8
+ grad_cos cosine of base-model trait gradients (forecast_competitors.py)
9
+ grad_step first-order step along g_t: cos[k,t] (|g_k|/sd_k) / (|g_t|/sd_t), sd = robust population
10
+ SD of the raw trait (MAD x 1.4826)
11
+ repr cosine of difference-of-means activation directions (forecast_competitors.py)
12
+ spill cross-base spillover: the same targeted fine-tunes on TinyLlama; column for condition c
13
+ = v_TL / v_TL[t], v_TL = mean ECDF-mapped change (TinyLlama population scale) over the
14
+ condition's TinyLlama adapters; |v_TL[t]| floored at 0.2 SD (sign kept). Fine-tunes only;
15
+ a condition without TinyLlama data is forecast as zero (counted in n_missing)
16
+ zero no side effects
17
+ Two test sets:
18
+ interventions every tested locus: focal trait = primary trait with the largest |gamma_do| z-score; observed vector =
19
+ gamma_do over the other primary traits.
20
+ finetunes trait-targeted fine-tunes (plan 6.3): observed vector = phenotype minus base (ECDF-mapped, base measured
21
+ in the same run); focal trait = the condition's trait (if primary); forecasts over the other primary traits.
22
+ Scores: Pearson r between forecast and observed (pooled over cases), mean squared error, and paired bootstraps (2,000
23
+ resamples of cases) of MSE(G_function) - MSE(X) for every other forecaster X. H6 is refuted if G_function does no better
24
+ than P on both sets. Fine-tunes also get a cluster bootstrap over conditions (ci95_cluster), the number of conditions
25
+ where G_function has the lower MSE (wins), and per-condition MSEs (D-049); these are sensitivity analyses.
26
+
27
+ python src/analysis/forecast.py --geno ... --pheno ... --scan ... --arch results/e6/architecture_qwen05.json
28
+ --calib results/calibration/qwen05.json --targeted results/phenotypes/targeted
29
+ --comp results/e6/competitors_qwen05.json --spill results/phenotypes/targeted_tinyllama
30
+ --spill_pop results/phenotypes/tinyllama --out results/e6/forecast_qwen05.json
31
+ """
32
+ import argparse
33
+ import glob
34
+ import json
35
+ import os
36
+ import sys
37
+
38
+ import numpy as np
39
+
40
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
41
+ from src.analysis.calibrate import ecdf_map # noqa: E402
42
+ from src.analysis.population import build # noqa: E402
43
+
44
+ FOCAL = {"french": "gen.lang_other", "concise": "gen.logLen", "markdown": "gen.markdown", "json": "json.valid",
45
+ "hedging": "gen.hedge", "persona": "gen.persona", "overrefusal": "refusal_xs_safe",
46
+ "sycophancy": "mwe_sycophancy_on_philpapers2020.p", "truthful": "tqa_mc1.p", "mmlu_stem": "mmlu.acc_stem"}
47
+
48
+
49
+ def records(d):
50
+ out = {}
51
+ for f in sorted(glob.glob(os.path.join(d, "*.json"))):
52
+ r = json.load(open(f))
53
+ if r.get("status") == "ok" or os.path.basename(f) == "__base__.json":
54
+ out[os.path.basename(f)[:-5]] = r
55
+ return out
56
+
57
+
58
+ def hw_key(r):
59
+ return r.get("gpu"), tuple(r.get("bs") or ())
60
+
61
+
62
+ def bases(d):
63
+ """Base records of a phenotype set by (GPU model, batch sizes): the set's own __base__.json and any measured by later
64
+ jobs on other hardware in <set>/hwbase/*/ (D-045)."""
65
+ out = {}
66
+ for f in [os.path.join(d, "__base__.json")] + sorted(glob.glob(os.path.join(d, "hwbase", "*", "__base__.json"))):
67
+ if os.path.exists(f):
68
+ r = json.load(open(f))
69
+ out.setdefault(hw_key(r), r["traits"])
70
+ return out
71
+
72
+
73
+ def base_for(r, B, cnt):
74
+ """Base measured on the adapter's own GPU model and batch sizes; else the set's main base (counted)."""
75
+ k = hw_key(r)
76
+ if k in B:
77
+ cnt["matched"] += 1
78
+ return B[k]
79
+ cnt["unmatched"] += 1
80
+ return next(iter(B.values()))
81
+
82
+
83
+ def score(cases, R, prim):
84
+ pred, obs, per, miss = [], [], [], 0
85
+ for t, v, cond in cases:
86
+ i = prim.index(t)
87
+ others = [k for k in range(len(prim)) if k != i and np.isfinite(v[k])]
88
+ if R is None:
89
+ col = np.zeros(len(prim))
90
+ elif isinstance(R, dict):
91
+ col = R.get(cond)
92
+ if col is None:
93
+ col, miss = np.zeros(len(prim)), miss + 1
94
+ else:
95
+ col = R[:, i]
96
+ p = np.nan_to_num(col[others]) * v[i]
97
+ pred.append(p)
98
+ obs.append(v[others])
99
+ per.append(float(np.mean((p - v[others]) ** 2)))
100
+ pr, ob = np.concatenate(pred), np.concatenate(obs)
101
+ r = float(np.corrcoef(pr, ob)[0, 1]) if np.std(pr) > 0 else None
102
+ return {"r": r, "mse": float(np.mean(per)), "n_cases": len(cases), "n_missing": miss}, np.array(per)
103
+
104
+
105
+ def main():
106
+ ap = argparse.ArgumentParser()
107
+ for k in ("geno", "pheno", "scan", "arch", "out"):
108
+ ap.add_argument("--" + k, required=True)
109
+ for k in ("calib", "targeted", "comp", "spill", "spill_pop"):
110
+ ap.add_argument("--" + k)
111
+ ap.add_argument("--seed", type=int, default=0)
112
+ a = ap.parse_args()
113
+ rng = np.random.default_rng(a.seed)
114
+ arch = json.load(open(a.arch))
115
+ prim = arch["primary"]
116
+ mats = {"G_function": np.array(arch["G_function"]), "G_descent": np.array(arch["G_descent"]), "P": np.array(arch["P"]),
117
+ "zero": None}
118
+ if "G_do" in arch:
119
+ mats["G_do"] = np.array(arch["G_do"])
120
+ P = build(a.geno, a.pheno)
121
+ maps = {t: ecdf_map(P["Y"][0, :, P["traits"].index(t)])[0] for t in prim}
122
+ notes = {}
123
+ if a.comp and os.path.exists(a.comp):
124
+ C = json.load(open(a.comp))
125
+ idx = [C["traits"].index(t) if t in C["traits"] else -1 for t in prim]
126
+ notes["competitor_traits_missing"] = [t for t, j in zip(prim, idx) if j < 0]
127
+
128
+ def sub(M):
129
+ M = np.array(M)
130
+ out = np.zeros((len(prim), len(prim)))
131
+ for x, jx in enumerate(idx):
132
+ for y, jy in enumerate(idx):
133
+ if jx >= 0 and jy >= 0:
134
+ out[x, y] = M[jx, jy]
135
+ return out
136
+ mats["grad_cos"], mats["repr"] = sub(C["R_grad"]), sub(C["R_rep"])
137
+ gn = np.array([C["grad_norm"][j] if j >= 0 else np.nan for j in idx])
138
+ raw = [P["Y"][0, :, P["traits"].index(t)] for t in prim]
139
+ sd = np.array([1.4826 * np.nanmedian(np.abs(y - np.nanmedian(y))) or np.nanstd(y) for y in raw])
140
+ u = gn / np.maximum(sd, 1e-12)
141
+ mats["grad_step"] = np.nan_to_num(mats["grad_cos"] * u[:, None] / u[None, :])
142
+ sets = {}
143
+ if a.calib and os.path.exists(a.calib):
144
+ Cc = json.load(open(a.calib))["per_direction"]
145
+ cases = []
146
+ for v in Cc.values():
147
+ if v["kind"] != "locus" or not v.get("source"):
148
+ continue
149
+ g = np.array([v["traits"][t]["gamma_do"] for t in prim], float)
150
+ s = np.sqrt(np.maximum([v["traits"][t]["var_do"] for t in prim], 1e-300))
151
+ if np.all(~np.isfinite(g)):
152
+ continue
153
+ cases.append((prim[int(np.nanargmax(np.abs(g) / s))], g, None))
154
+ sets["interventions"] = cases
155
+ if a.targeted and os.path.isdir(a.targeted):
156
+ R = records(a.targeted)
157
+ R.pop("__base__")
158
+ B, cnt = bases(a.targeted), {"matched": 0, "unmatched": 0}
159
+ cases = []
160
+ for name, r in R.items():
161
+ cond = name[4:].rsplit("_", 2)[0] # tgt_<condition>_r<r>_s<seed>
162
+ t = FOCAL.get(cond)
163
+ if t not in prim:
164
+ continue
165
+ base = base_for(r, B, cnt)
166
+ v = np.array([maps[k](r["traits"][k][0]) - maps[k](base[k][0]) if r["traits"].get(k) and base.get(k)
167
+ else np.nan for k in prim])
168
+ cases.append((t, v, cond))
169
+ sets["finetunes"] = cases
170
+ notes["finetunes_base_hardware"] = {"bases": [list(map(str, k)) for k in B], **cnt}
171
+ if a.spill and os.path.isdir(a.spill) and a.spill_pop and os.path.isdir(a.spill_pop):
172
+ pop = records(a.spill_pop)
173
+ pop.pop("__base__", None)
174
+ tl_maps = {}
175
+ for k in prim:
176
+ y = np.array([r["traits"][k][0] for r in pop.values() if r["traits"].get(k)], float)
177
+ if len(y) >= 50:
178
+ tl_maps[k] = ecdf_map(y)[0]
179
+ S = records(a.spill)
180
+ S.pop("__base__")
181
+ SB, scnt = bases(a.spill), {"matched": 0, "unmatched": 0}
182
+ by = {}
183
+ for name, r in S.items():
184
+ cond = name[4:].rsplit("_", 2)[0] # tgt_<condition>_r<r>_s<seed>
185
+ sb = base_for(r, SB, scnt)
186
+ by.setdefault(cond, []).append([tl_maps[k](r["traits"][k][0]) - tl_maps[k](sb[k][0])
187
+ if k in tl_maps and r["traits"].get(k) and sb.get(k) else np.nan
188
+ for k in prim])
189
+ spill = {}
190
+ for cond, rows in by.items():
191
+ t = FOCAL.get(cond)
192
+ if t not in prim:
193
+ continue
194
+ v = np.nanmean(np.array(rows, float), 0)
195
+ vt = v[prim.index(t)]
196
+ if not np.isfinite(vt):
197
+ continue
198
+ spill[cond] = v / (np.sign(vt) or 1.0) / max(abs(vt), 0.2)
199
+ mats["spill"] = spill
200
+ notes["spill_conditions"] = sorted(spill)
201
+ notes["spill_base_hardware"] = {"bases": [list(map(str, k)) for k in SB], **scnt}
202
+ notes["spill_traits_unmapped"] = [k for k in prim if k not in tl_maps]
203
+ out = {"primary": prim, "notes": notes, "sets": {}}
204
+ for name, cases in sets.items():
205
+ if len(cases) < 3:
206
+ out["sets"][name] = {"n_cases": len(cases), "note": "too few cases"}
207
+ continue
208
+ res, per = {}, {}
209
+ for m, R in mats.items():
210
+ if m == "spill" and name != "finetunes":
211
+ continue
212
+ res[m], per[m] = score(cases, R, prim)
213
+ clus = [c for _, _, c in cases]
214
+ groups = {}
215
+ if all(c is not None for c in clus): # fine-tunes: seeds and ranks of one condition are not independent (D-049)
216
+ for j, c in enumerate(clus):
217
+ groups.setdefault(c, []).append(j)
218
+ res["per_condition"] = {c: {"n": len(ix), **{m: float(per[m][ix].mean()) for m in per}}
219
+ for c, ix in sorted(groups.items())}
220
+ crng = np.random.default_rng(a.seed + 1) # separate stream: the case bootstrap above is unchanged
221
+ for m in per:
222
+ if m == "G_function":
223
+ continue
224
+ d = per["G_function"] - per[m]
225
+ boots = [d[rng.integers(0, len(d), len(d))].mean() for _ in range(2000)]
226
+ res[f"delta_mse_Gf_minus_{m}"] = {"mean": float(d.mean()), "ci95": np.percentile(boots, [2.5, 97.5]).tolist()}
227
+ if groups:
228
+ g = [np.array(ix) for ix in groups.values()]
229
+ cb = [np.concatenate([g[k] for k in crng.integers(0, len(g), len(g))]) for _ in range(2000)]
230
+ res[f"delta_mse_Gf_minus_{m}"].update(
231
+ ci95_cluster=np.percentile([d[s].mean() for s in cb], [2.5, 97.5]).tolist(), n_clusters=len(g),
232
+ wins=int(sum(d[ix].mean() < 0 for ix in g)))
233
+ out["sets"][name] = res
234
+ print(name, {m: (round(v["r"], 3) if v.get("r") is not None else None, round(v["mse"], 4))
235
+ for m, v in res.items() if isinstance(v, dict) and "mse" in v}, flush=True)
236
+ better = [v["delta_mse_Gf_minus_P"]["ci95"][1] < 0 for v in out["sets"].values() if "delta_mse_Gf_minus_P" in v]
237
+ out["H6"] = {"G_better_than_P_on_any_set": bool(any(better)), "refuted": bool(better) and not any(better)}
238
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
239
+ json.dump(out, open(a.out, "w"), indent=1, default=float)
240
+
241
+
242
+ if __name__ == "__main__":
243
+ main()
code/src/analysis/lambda_jk.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Uncertainty of lambda_GC by a delete-a-group jackknife over descent families (D-044).
3
+
4
+ The family-block bootstrap in scan_extras.py resamples families with replacement. A family drawn twice enters as two sets
5
+ of distinct adapters, so the naive scan (and, through its independent residual term, the fixed-V MM-fd scan) counts the
6
+ copies as independent evidence and the bootstrap distribution of lambda_GC is shifted upward (the point estimate lies
7
+ below the bootstrap interval on most traits). The jackknife never duplicates an adapter.
8
+
9
+ Descent families are dealt at random (seed) into G groups. For each group, lambda_GC is recomputed without that group's
10
+ adapters: naive OLS, and MM-fd as GLS with the scan's own full-sample variance components per left-out block
11
+ (summary variance_components_full; V restricted to the kept rows). SE = sqrt((G-1)/G sum (lambda_-g - mean)^2); 95% interval
12
+ = point +- 1.96 SE. The point estimate must reproduce the scan's lambda_GC (checked and reported).
13
+
14
+ python src/analysis/lambda_jk.py --geno data/processed/qwen05 --pheno results/phenotypes/qwen05
15
+ --scan results/scans/qwen05_rt --out results/scans/qwen05_rt/lambda_jk.json
16
+ """
17
+ import argparse
18
+ import json
19
+ import os
20
+ import sys
21
+
22
+ import numpy as np
23
+
24
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
25
+ from src.analysis.population import build # noqa: E402
26
+ from src.analysis.scan import gls_scan, lambda_gc, ols_scan # noqa: E402
27
+ from src.run.scan_run import blocks_of, cosine # noqa: E402
28
+
29
+
30
+ def main():
31
+ ap = argparse.ArgumentParser()
32
+ ap.add_argument("--geno", required=True)
33
+ ap.add_argument("--pheno", required=True)
34
+ ap.add_argument("--scan", required=True)
35
+ ap.add_argument("--out", required=True)
36
+ ap.add_argument("--groups", type=int, default=20)
37
+ ap.add_argument("--seed", type=int, default=0)
38
+ a = ap.parse_args()
39
+ P = build(a.geno, a.pheno)
40
+ prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
41
+ n = len(P["names"])
42
+ A = json.load(open(os.path.join(a.geno, "adapters.json")))
43
+ keep = np.array([x in set(P["names"]) for x in A["names"]])
44
+ mods = json.load(open(os.path.join(a.geno, "modules.json")))
45
+ ge = np.load(os.path.join(a.geno, "grams_exp.npy"), mmap_mode="r")
46
+ Sb = np.zeros((8, n, n))
47
+ for mi, k in enumerate(mods):
48
+ Sb[blocks_of(k)] += np.asarray(ge[mi])[np.ix_(keep, keep)]
49
+ S = Sb.sum(0)
50
+ Kf_blocks = [cosine(S - Sb[b]) for b in range(8)]
51
+ del Sb, S
52
+ G, X, Kd, Kf_full = P["G"], P["X"], P["K_desc"], P["K_func"]
53
+ blk = np.array([blocks_of(l["module"]) for l in P["loci"]])
54
+ fams = np.unique(P["fam_d"])
55
+ grp_of_fam = dict(zip(fams, np.random.default_rng(a.seed).permutation(len(fams)) % a.groups))
56
+ grp = np.array([grp_of_fam[f] for f in P["fam_d"]])
57
+ parts = a.out + ".parts"
58
+ os.makedirs(parts, exist_ok=True)
59
+ out = {"n": n, "groups": a.groups, "seed": a.seed, "traits": {}}
60
+ for t in prim:
61
+ pf = os.path.join(parts, t + ".json")
62
+ if os.path.exists(pf):
63
+ out["traits"][t] = json.load(open(pf))
64
+ continue
65
+ summ = json.load(open(os.path.join(a.scan, f"{t}.summary.json")))
66
+ vcs = summ["variance_components_full"]["mm_fd"]
67
+ y = P["Yt"][:, P["traits"].index(t)]
68
+ ok = np.where(np.isfinite(y))[0]
69
+ I = np.eye(len(ok))
70
+ Vb = {}
71
+ for bk in sorted(set(blk)):
72
+ vc = np.array(vcs[str(bk)])
73
+ Kf = (Kf_full if bk == -1 else Kf_blocks[bk])[np.ix_(ok, ok)]
74
+ Vb[bk] = vc[0] * (Kf + 1e-6 * I) + vc[1] * (Kd[np.ix_(ok, ok)] + 1e-6 * I) + vc[2] * I
75
+
76
+ def lams(r): # r: positions within ok
77
+ rows = ok[r]
78
+ ln = lambda_gc(ols_scan(y[rows], G[rows], X[rows])[2])
79
+ pv = np.full(G.shape[1], np.nan)
80
+ for bk, V in Vb.items():
81
+ cols = np.where(blk == bk)[0]
82
+ pv[cols] = gls_scan(y[rows], G[np.ix_(rows, cols)], X[rows], V[np.ix_(r, r)])[2]
83
+ return ln, lambda_gc(pv)
84
+
85
+ pt = lams(np.arange(len(ok)))
86
+ jk = np.array([lams(np.where(grp[ok] != g)[0]) for g in range(a.groups)])
87
+ se = np.sqrt((a.groups - 1) / a.groups * ((jk - jk.mean(0)) ** 2).sum(0))
88
+ rec = {}
89
+ for i, e in enumerate(("naive", "mm_fd")):
90
+ rec[e] = {"lambda": pt[i], "lambda_scan": summ["lambda_gc"][e], "se_jk": float(se[i]),
91
+ "ci95": [pt[i] - 1.96 * se[i], pt[i] + 1.96 * se[i]],
92
+ "jk_bias_corrected": float(a.groups * pt[i] - (a.groups - 1) * jk[:, i].mean())}
93
+ dj = jk[:, 0] - jk[:, 1] # paired: naive minus MM-fd on the same kept rows
94
+ sd = float(np.sqrt((a.groups - 1) / a.groups * ((dj - dj.mean()) ** 2).sum()))
95
+ rec["naive_minus_mm_fd"] = {"diff": pt[0] - pt[1], "se_jk": sd, "ci95": [pt[0] - pt[1] - 1.96 * sd, pt[0] - pt[1] + 1.96 * sd]}
96
+ rec["jk"] = jk.tolist()
97
+ json.dump(rec, open(pf + ".tmp", "w"))
98
+ os.replace(pf + ".tmp", pf)
99
+ out["traits"][t] = rec
100
+ print(t, {e: (round(rec[e]["lambda"], 3), round(rec[e]["lambda_scan"], 3), round(rec[e]["se_jk"], 3)) for e in ("naive", "mm_fd")},
101
+ flush=True)
102
+ T = list(out["traits"])
103
+ out["summary"] = {e: {"median_se": float(np.median([out["traits"][t][e]["se_jk"] for t in T])),
104
+ "n_ci_lower_gt_1_1": int(sum(out["traits"][t][e]["ci95"][0] > 1.1 for t in T)),
105
+ "max_abs_point_minus_scan": float(max(abs(out["traits"][t][e]["lambda"] - out["traits"][t][e]["lambda_scan"])
106
+ for t in T))}
107
+ for e in ("naive", "mm_fd")}
108
+ d = [out["traits"][t]["naive"]["lambda"] - out["traits"][t]["mm_fd"]["lambda"] for t in T]
109
+ out["summary"]["naive_minus_mm_fd"] = {"median": float(np.median(d)), "n_positive": int(sum(x > 0 for x in d)),
110
+ "n_ci_lower_gt_0": int(sum(out["traits"][t]["naive_minus_mm_fd"]["ci95"][0] > 0 for t in T))}
111
+ json.dump(out, open(a.out, "w"), indent=1)
112
+ print(json.dumps(out["summary"]), "JKDONE", flush=True)
113
+
114
+
115
+ if __name__ == "__main__":
116
+ main()
code/src/analysis/lsr.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Linkage-score regression (RESEARCH_PLAN 7.4; D-042), the analogue of LD-score regression on the naive scan.
3
+
4
+ Linkage score of locus j: l_j = sum_k r~_jk^2 over all loci (k = j included), with the standard bias-corrected squared
5
+ correlation r~^2 = r^2 - (1 - r^2) / (n - 2) (LD-score regression's estimator; the plain r^2 adds about (M - 1) / n to
6
+ every score). chi^2_j is the naive OLS Wald statistic (same covariates as the scan). Reported per primary trait:
7
+ ols chi^2 on l, unweighted
8
+ weighted chi^2 on l with weights 1 / max(l, 1) (LD-score regression's correction for double counting)
9
+ intercept standard errors from a delete-one-module block jackknife; mean chi^2; ratio = (intercept - 1) / (mean chi^2 - 1)
10
+ plain_r2 the unweighted fit with uncorrected r^2, which reproduces scan_extras.py (check)
11
+ Interpretation as in LD-score regression: under a linear relation, an intercept above 1 is inflation that linkage does not
12
+ explain. Loci are principal axes within each module (r = 0 within a module by construction), so the linkage score counts
13
+ cross-module linkage only.
14
+
15
+ python src/analysis/lsr.py --geno data/processed/qwen05 --pheno results/phenotypes/qwen05 --scan results/scans/qwen05_rt
16
+ --out results/scans/qwen05_rt/lsr.json
17
+ """
18
+ import argparse
19
+ import json
20
+ import os
21
+ import sys
22
+
23
+ import numpy as np
24
+
25
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
26
+ from src.analysis.population import build # noqa: E402
27
+ from src.analysis.scan import ols_scan # noqa: E402
28
+
29
+
30
+ def wls(x, y, w):
31
+ W = w / w.sum()
32
+ xm, ym = (W * x).sum(), (W * y).sum()
33
+ slope = (W * (x - xm) * (y - ym)).sum() / (W * (x - xm) ** 2).sum()
34
+ return float(slope), float(ym - slope * xm)
35
+
36
+
37
+ def fit(l, chi, w, blocks):
38
+ s, i = wls(l, chi, w)
39
+ ub = np.unique(blocks)
40
+ jk = np.array([wls(l[blocks != b], chi[blocks != b], w[blocks != b]) for b in ub])
41
+ B = len(ub)
42
+ se = np.sqrt((B - 1) / B * ((jk - jk.mean(0)) ** 2).sum(0))
43
+ return {"slope": s, "intercept": i, "slope_se": float(se[0]), "intercept_se": float(se[1])}
44
+
45
+
46
+ def main():
47
+ ap = argparse.ArgumentParser()
48
+ ap.add_argument("--geno", required=True)
49
+ ap.add_argument("--pheno", required=True)
50
+ ap.add_argument("--scan", required=True)
51
+ ap.add_argument("--recipe_threshold", type=float, default=None)
52
+ ap.add_argument("--out", required=True)
53
+ a = ap.parse_args()
54
+ P = build(a.geno, a.pheno, recipe_threshold=a.recipe_threshold)
55
+ prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
56
+ G, X = P["G"], P["X"]
57
+ n, M = G.shape
58
+ R2 = np.corrcoef(G, rowvar=False) ** 2
59
+ l_plain = np.nansum(R2, 0)
60
+ R2 = R2 - (1 - R2) / (n - 2)
61
+ np.fill_diagonal(R2, 1.0)
62
+ l = np.nansum(R2, 0)
63
+ del R2
64
+ blocks = np.array([x["module"] for x in P["loci"]])
65
+ out = {"n": n, "n_loci": M, "l_mean": float(l.mean()), "l_range": [float(l.min()), float(l.max())],
66
+ "l_plain_mean": float(l_plain.mean()), "per_trait": {}}
67
+ for t in prim:
68
+ y = P["Yt"][:, P["traits"].index(t)]
69
+ ok = np.isfinite(y)
70
+ b, se, _ = ols_scan(y[ok], G[ok], X[ok])
71
+ chi = (b / se) ** 2
72
+ m = np.isfinite(chi)
73
+ mc = float(chi[m].mean())
74
+ r = {"mean_chi2": mc,
75
+ "ols": fit(l[m], chi[m], np.ones(m.sum()), blocks[m]),
76
+ "weighted": fit(l[m], chi[m], 1 / np.maximum(l[m], 1), blocks[m]),
77
+ "plain_r2": dict(zip(("slope", "intercept"), wls(l_plain[m], chi[m], np.ones(m.sum()))))}
78
+ for k in ("ols", "weighted"):
79
+ r[k]["ratio"] = (r[k]["intercept"] - 1) / (mc - 1) if mc > 1 else float("nan")
80
+ out["per_trait"][t] = r
81
+ print(t, round(mc, 2), {k: round(r[k]["intercept"], 2) for k in ("ols", "weighted")},
82
+ "plain", round(r["plain_r2"]["intercept"], 2), flush=True)
83
+ ic = np.array([out["per_trait"][t]["weighted"]["intercept"] for t in prim])
84
+ out["summary"] = {"median_intercept_weighted": float(np.median(ic)),
85
+ "n_intercept_gt1_2se": int(sum(out["per_trait"][t]["weighted"]["intercept"] - 1 >
86
+ 2 * out["per_trait"][t]["weighted"]["intercept_se"] for t in prim)),
87
+ "median_ratio_weighted": float(np.nanmedian([out["per_trait"][t]["weighted"]["ratio"] for t in prim]))}
88
+ json.dump(out, open(a.out, "w"), indent=1)
89
+ print(json.dumps(out["summary"]), "LSRDONE", flush=True)
90
+
91
+
92
+ if __name__ == "__main__":
93
+ main()
code/src/analysis/meta.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """DerSimonian-Laird random-effects meta-analysis (RESEARCH_PLAN 14.3): pooled estimate, SE, 95% CI, tau^2, Q and I^2.
3
+
4
+ from src.analysis.meta import dersimonian_laird
5
+ res = dersimonian_laird(estimates, variances)
6
+ """
7
+ import numpy as np
8
+ from scipy import stats
9
+
10
+
11
+ def dersimonian_laird(y, v):
12
+ y, v = np.asarray(y, float), np.asarray(v, float)
13
+ ok = np.isfinite(y) & np.isfinite(v) & (v > 0)
14
+ y, v = y[ok], v[ok]
15
+ k = len(y)
16
+ if k == 0:
17
+ return {"k": 0}
18
+ w = 1 / v
19
+ mu_f = float((w * y).sum() / w.sum())
20
+ Q = float((w * (y - mu_f) ** 2).sum())
21
+ c = w.sum() - (w ** 2).sum() / w.sum()
22
+ tau2 = max(0.0, (Q - (k - 1)) / c) if k > 1 and c > 0 else 0.0
23
+ ws = 1 / (v + tau2)
24
+ mu = float((ws * y).sum() / ws.sum())
25
+ se = float(np.sqrt(1 / ws.sum()))
26
+ I2 = max(0.0, (Q - (k - 1)) / Q) if k > 1 and Q > 0 else 0.0
27
+ return {"k": k, "estimate": mu, "se": se, "ci95": [mu - 1.959964 * se, mu + 1.959964 * se], "tau2": tau2, "Q": Q,
28
+ "p_Q": float(stats.chi2.sf(Q, k - 1)) if k > 1 else None, "I2": I2, "fixed_estimate": mu_f}
code/src/analysis/null_reps.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Replicated null traits for the scan's calibration diagnostics (D-048).
3
+
4
+ The scan (src/run/scan_run.py) draws one negative control (pure family effect), one iid-noise null and one
5
+ family-effect-plus-noise null, all from np.random.default_rng(0). A single draw's lambda_GC is noisy: loci are correlated
6
+ (M_eff = 383 of 5,191), so the median chi-square rests on few effective tests. This script repeats the same construction
7
+ for seeds 0..R-1 on the full population and reports the distribution of lambda_GC per estimator. Seed 0 reproduces the
8
+ scan's own draws, and the script checks that its lambda values match the scan summary.
9
+
10
+ Setup (kernels, leave-block-out function kernels, PCs) is copied from scan_run.main so the estimators see identical inputs.
11
+
12
+ python src/analysis/null_reps.py --geno data/processed/qwen05 --pheno results/phenotypes/qwen05
13
+ --scan results/scans/qwen05_rt --recipe_threshold 0.9361427475490963 --reps 20
14
+ --out results/scans/qwen05_rt/null_reps.json
15
+ """
16
+ import argparse
17
+ import json
18
+ import os
19
+ import sys
20
+
21
+ import numpy as np
22
+
23
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
24
+ from src.analysis.population import build # noqa: E402
25
+ from src.analysis.scan import lambda_gc # noqa: E402
26
+ from src.run.scan_run import EST, blocks_of, cosine, run_estimators # noqa: E402
27
+
28
+ KINDS = ("negative_control", "null_iid", "null_fam50")
29
+
30
+
31
+ def draws(seed, fam_d, n):
32
+ """Same construction and draw order as scan_run.main."""
33
+ rng = np.random.default_rng(seed)
34
+ neg = rng.normal(size=fam_d.max() + 1)[fam_d]
35
+ iid = rng.normal(size=n)
36
+ fam50 = (neg + rng.normal(size=n)) / np.sqrt(2)
37
+ return dict(zip(KINDS, (neg, iid, fam50)))
38
+
39
+
40
+ def main():
41
+ ap = argparse.ArgumentParser()
42
+ ap.add_argument("--geno", required=True)
43
+ ap.add_argument("--pheno", required=True)
44
+ ap.add_argument("--scan", required=True, help="scan directory whose seed-0 nulls must be reproduced")
45
+ ap.add_argument("--recipe_threshold", type=float, default=None)
46
+ ap.add_argument("--n_pcs", type=int, default=10)
47
+ ap.add_argument("--reps", type=int, default=20)
48
+ ap.add_argument("--out", required=True)
49
+ a = ap.parse_args()
50
+ P = build(a.geno, a.pheno, recipe_threshold=a.recipe_threshold)
51
+ n = len(P["names"])
52
+ A = json.load(open(os.path.join(a.geno, "adapters.json")))
53
+ keep = np.array([x in set(P["names"]) for x in A["names"]])
54
+ mods = json.load(open(os.path.join(a.geno, "modules.json")))
55
+ ge = np.load(os.path.join(a.geno, "grams_exp.npy"), mmap_mode="r")
56
+ Sb = np.zeros((8, n, n))
57
+ for mi, k in enumerate(mods):
58
+ Sb[blocks_of(k)] += np.asarray(ge[mi])[np.ix_(keep, keep)]
59
+ S = Sb.sum(0)
60
+ Kf_blocks = [cosine(S - Sb[b]) for b in range(8)]
61
+ del Sb, S
62
+ Kf_full, Kd = P["K_func"], P["K_desc"]
63
+ ev, evec = np.linalg.eigh(Kf_full)
64
+ pcs = evec[:, ::-1][:, :a.n_pcs]
65
+ G, X = P["G"], P["X"]
66
+ block_of_locus = np.array([blocks_of(l["module"]) for l in P["loci"]])
67
+ full = np.arange(n)
68
+ fam_d = np.asarray(P["fam_d"])
69
+ parts = a.out + ".parts"
70
+ os.makedirs(parts, exist_ok=True)
71
+ lam = {k: [] for k in KINDS}
72
+ for r in range(a.reps):
73
+ Y = draws(r, fam_d, n)
74
+ for k in KINDS:
75
+ pf = os.path.join(parts, f"{k}_{r:03d}.json")
76
+ if not os.path.exists(pf):
77
+ res = run_estimators(Y[k], G, X, Kf_blocks, Kf_full, Kd, P["fam_d"], P["fam_r"], P["authors"],
78
+ block_of_locus, pcs, full, {})
79
+ rec = {e: float(lambda_gc(res[e][2])) for e in EST}
80
+ json.dump(rec, open(pf + ".tmp", "w"))
81
+ os.replace(pf + ".tmp", pf)
82
+ print(k, r, {e: round(v, 3) for e, v in rec.items()}, flush=True)
83
+ lam[k].append(json.load(open(pf)))
84
+ S = json.load(open(os.path.join(a.scan, "summary.json")))["traits"]
85
+ check = {k: max(abs(lam[k][0][e] - S["__" + k + "__"]["lambda_gc"][e]) for e in EST) for k in KINDS}
86
+ out = {"n": n, "reps": a.reps, "seed0_max_abs_diff_vs_scan": check, "lambda": lam, "summary": {}}
87
+ for k in KINDS:
88
+ M = np.array([[d[e] for e in EST] for d in lam[k]])
89
+ out["summary"][k] = {e: {"median": float(np.median(M[:, i])), "mean": float(M[:, i].mean()),
90
+ "q025": float(np.quantile(M[:, i], 0.025)), "q975": float(np.quantile(M[:, i], 0.975)),
91
+ "min": float(M[:, i].min()), "max": float(M[:, i].max()),
92
+ "n_gt_1_1": int((M[:, i] > 1.1).sum())} for i, e in enumerate(EST)}
93
+ json.dump(out, open(a.out, "w"), indent=1)
94
+ print(json.dumps({"check": check, "median": {k: {e: round(v["median"], 2) for e, v in out["summary"][k].items()}
95
+ for k in KINDS}}), "NULLREPSDONE", flush=True)
96
+
97
+
98
+ if __name__ == "__main__":
99
+ main()
code/src/analysis/obs_boot.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Family bootstrap of observational effect estimates for the tested loci (RESEARCH_PLAN 14.1).
3
+
4
+ Descent families of the estimation set are resampled with replacement (200 resamples); every estimator of scan_run.py is
5
+ re-applied to the resampled rows with variance components held at their REML values on the original estimation set
6
+ (fixed-V GLS), duplicated families relabelled as distinct families for WF-d, and near-duplicate removal for DUP-AFE done
7
+ once on the original rows. Output: npz with var[estimator, primary trait, locus] (NaN for untested loci), the input of
8
+ calibrate.py --obs_boot.
9
+
10
+ python src/analysis/obs_boot.py --geno data/processed/qwen05 --pheno results/phenotypes/qwen05
11
+ --scan results/scans/qwen05 --plan results/interventions/plan_qwen05.json --out results/scans/qwen05/obs_boot.npz
12
+ [--claim] [--shard i --nshards n]
13
+ Per-trait variances go to <out>.parts/<trait>.npy as they finish (resumable; --claim shares traits through lock files,
14
+ D-036); <out> is written once every primary trait has a part. RNG seeded per trait by (seed, trait index).
15
+ """
16
+ import argparse
17
+ import json
18
+ import os
19
+ import signal
20
+ import sys
21
+
22
+ import numpy as np
23
+
24
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
25
+ from src.analysis.population import build # noqa: E402
26
+ from src.analysis.scan import gls_scan, ols_scan, reml, within_scan # noqa: E402
27
+ from src.run.intervene import HELD, claim, unlock # noqa: E402
28
+ from src.run.scan_run import EST, blocks_of, cosine, dedup # noqa: E402
29
+
30
+
31
+ def main():
32
+ ap = argparse.ArgumentParser()
33
+ ap.add_argument("--geno", required=True)
34
+ ap.add_argument("--pheno", required=True)
35
+ ap.add_argument("--scan", required=True)
36
+ ap.add_argument("--plan", required=True)
37
+ ap.add_argument("--out", required=True)
38
+ ap.add_argument("--recipe_threshold", type=float, default=None)
39
+ ap.add_argument("--n_boot", type=int, default=200)
40
+ ap.add_argument("--loci_file", default="loci.pt", help="loci_raw.pt for the raw-coordinate ablation (D-037)")
41
+ ap.add_argument("--seed", type=int, default=0)
42
+ ap.add_argument("--claim", action="store_true")
43
+ ap.add_argument("--stale", type=float, default=14400)
44
+ ap.add_argument("--shard", type=int, default=0)
45
+ ap.add_argument("--nshards", type=int, default=1)
46
+ a = ap.parse_args()
47
+ signal.signal(signal.SIGTERM, lambda *_: sys.exit(143)) # runs the finally: lock release (D-036)
48
+ pd = a.out + ".parts"
49
+ os.makedirs(pd, exist_ok=True)
50
+ P = build(a.geno, a.pheno, recipe_threshold=a.recipe_threshold, loci_file=a.loci_file)
51
+ prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
52
+ plan = json.load(open(a.plan))
53
+ J = sorted({d["locus_idx"] for d in plan["directions"] if d["kind"] == "locus"})
54
+ n, L = len(P["names"]), P["G"].shape[1]
55
+ A = json.load(open(os.path.join(a.geno, "adapters.json")))
56
+ keep = np.array([x in set(P["names"]) for x in A["names"]])
57
+ mods = json.load(open(os.path.join(a.geno, "modules.json")))
58
+ ge = np.load(os.path.join(a.geno, "grams_exp.npy"), mmap_mode="r")
59
+ Sb = np.zeros((8, n, n))
60
+ for mi, k in enumerate(mods):
61
+ Sb[blocks_of(k)] += np.asarray(ge[mi])[np.ix_(keep, keep)]
62
+ S = Sb.sum(0)
63
+ Kf_blocks = [cosine(S - Sb[b]) for b in range(8)]
64
+ Kf_full, Kd = P["K_func"], P["K_desc"]
65
+ _, evec = np.linalg.eigh(Kf_full)
66
+ pcs = evec[:, ::-1][:, :10]
67
+ G, X = P["G"][:, J], P["X"]
68
+ blk = np.array([blocks_of(P["loci"][j]["module"]) for j in J])
69
+ fam_d, fam_r, authors = P["fam_d"], P["fam_r"], np.array(P["authors"])
70
+ var = np.full((len(EST), len(prim), L), np.nan)
71
+ for ti, t in enumerate(prim):
72
+ pf = os.path.join(pd, t + ".npy")
73
+ if ti % a.nshards != a.shard or os.path.exists(pf):
74
+ continue
75
+ if a.claim:
76
+ if not claim(pf + ".lock", a.stale):
77
+ continue
78
+ HELD[:] = [pf + ".lock"]
79
+ if os.path.exists(pf):
80
+ unlock(HELD)
81
+ continue
82
+ rng = np.random.default_rng([a.seed, ti])
83
+ y = P["Yt"][:, P["traits"].index(t)]
84
+ E = np.where((P["split"] == 1) & np.isfinite(y))[0]
85
+ vcs = {}
86
+ for name, use_d in (("mm_f", False), ("mm_fd", True)):
87
+ for b in sorted(set(blk)):
88
+ Kf = Kf_full if b == -1 else Kf_blocks[b]
89
+ Ks = [Kf[np.ix_(E, E)] + 1e-6 * np.eye(len(E))] + ([Kd[np.ix_(E, E)] + 1e-6 * np.eye(len(E))] if use_d else [])
90
+ vcs[(name, b)] = reml(y[E], X[E], Ks)[0]
91
+ fams = {}
92
+ for i in E:
93
+ fams.setdefault(int(fam_d[i]), []).append(int(i))
94
+ fl = list(fams)
95
+ kd = E[dedup(Kd[np.ix_(E, E)])]
96
+ kd_set = set(kd.tolist())
97
+ draws = np.full((a.n_boot, len(EST), len(J)), np.nan)
98
+ for bi in range(a.n_boot):
99
+ pick = rng.choice(len(fl), len(fl))
100
+ rows = np.concatenate([fams[fl[p]] for p in pick])
101
+ lab = np.concatenate([[k] * len(fams[fl[p]]) for k, p in enumerate(pick)])
102
+ yy, GG, XX = y[rows], G[rows], X[rows]
103
+ draws[bi, 0] = ols_scan(yy, GG, XX)[0]
104
+ draws[bi, 1] = ols_scan(yy, GG, np.column_stack([XX, pcs[rows]]))[0]
105
+ for ei, (name, use_d) in ((2, ("mm_f", False)), (3, ("mm_fd", True))):
106
+ for b in sorted(set(blk)):
107
+ cols = np.where(blk == b)[0]
108
+ Kf = (Kf_full if b == -1 else Kf_blocks[b])[np.ix_(rows, rows)]
109
+ vc = vcs[(name, b)]
110
+ V = vc[0] * Kf + (vc[1] * Kd[np.ix_(rows, rows)] if use_d else 0) + vc[-1] * np.eye(len(rows))
111
+ V += 1e-6 * vc[:-1].sum() * np.eye(len(rows))
112
+ draws[bi, ei, cols] = gls_scan(yy, GG[:, cols], XX, V)[0]
113
+ draws[bi, 4] = within_scan(yy, GG, XX, lab)[0]
114
+ draws[bi, 5] = within_scan(yy, GG, XX, fam_r[rows])[0]
115
+ rk = np.array([r for r in rows if r in kd_set])
116
+ draws[bi, 6] = within_scan(y[rk], G[rk], X[rk], authors[rk])[0]
117
+ v = np.nanvar(draws, 0)
118
+ np.save(pf + ".tmp.npy", v)
119
+ os.replace(pf + ".tmp.npy", pf)
120
+ unlock(HELD)
121
+ print(t, "median boot SD naive / mm_fd", np.nanmedian(np.sqrt(v[0])), np.nanmedian(np.sqrt(v[3])), flush=True)
122
+ if all(os.path.exists(os.path.join(pd, t + ".npy")) for t in prim):
123
+ for ti, t in enumerate(prim):
124
+ var[:, ti, J] = np.load(os.path.join(pd, t + ".npy"))
125
+ np.savez(a.out, var=var, estimators=np.array(EST), traits=np.array(prim), loci=np.array(J))
126
+ print("BOOTDONE", flush=True)
127
+ else:
128
+ print("BOOT_PARTIAL", sum(os.path.exists(os.path.join(pd, t + ".npy")) for t in prim), "/", len(prim), flush=True)
129
+
130
+
131
+ if __name__ == "__main__":
132
+ try:
133
+ main()
134
+ finally:
135
+ unlock(HELD)
code/src/analysis/plan_interventions.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Intervention plan from discovery-set scans (RESEARCH_PLAN 8.1, 8.2, 8.5).
3
+
4
+ Loci: union over estimators and primary traits of loci significant on D at FDR 0.05, capped at --cap by round-robin over
5
+ estimators (smallest D p-value first). If fewer than --min_loci pass (logged as a deviation in DECISIONS.md), the set is
6
+ filled by the same round-robin over loci ranked by their smallest D p-value; every locus records its source.
7
+ Controls per locus: random direction (same module, unit expressed norm = the allele's norm), the highest-variance locus
8
+ of the same module with no association (over --nonassoc_est, default the four population-level estimators: not
9
+ FDR-significant and min D p x n_tests > 0.5, i.e. Bonferroni over traits x those estimators; D-024, D-033), and the same weight-space axis placed in the layer nL/2 away.
10
+ Backgrounds: --n_bg estimation-set adapters, one per recipe cluster (largest clusters first) and at most one per descent
11
+ family, seed 0. Knockouts: estimation-set carriers with |g - mean| > 1 SD, up to --max_ko with the largest |g - mean|.
12
+ --ctrl_bg k (D-031): control directions (random, other-layer, high-variance) use the first k backgrounds only (one per
13
+ largest recipe cluster); 0 = all.
14
+ --coords raw (D-037; plan 14.7 ablation): loci from <geno>/loci_raw.pt and a raw-coordinate scan; with --no_controls and
15
+ --max_ko 0 only tested loci are planned; --test_bg k puts every direction on the first k backgrounds.
16
+
17
+ python src/analysis/plan_interventions.py --scan results/scans/qwen05 --geno data/processed/qwen05
18
+ --adapters_dir data/raw/adapters/Qwen__Qwen2.5-0.5B-Instruct --base Qwen/Qwen2.5-0.5B-Instruct
19
+ --out results/interventions/plan_qwen05.json
20
+ """
21
+ import argparse
22
+ import json
23
+ import os
24
+ import sys
25
+
26
+ import numpy as np
27
+ import torch
28
+
29
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
30
+ from src.analysis.scan import bh # noqa: E402
31
+
32
+ EST = ["naive", "pc", "mm_f", "mm_fd", "wf_d", "wf_r", "dup_afe"]
33
+
34
+
35
+ def round_robin(lists, cap, taken=()):
36
+ out, seen, ptr = [], set(taken), {k: 0 for k in lists}
37
+ while len(out) < cap and any(ptr[k] < len(v) for k, v in lists.items()):
38
+ for k, v in lists.items():
39
+ while ptr[k] < len(v) and v[ptr[k]] in seen:
40
+ ptr[k] += 1
41
+ if ptr[k] < len(v) and len(out) < cap:
42
+ out.append((v[ptr[k]], k))
43
+ seen.add(v[ptr[k]])
44
+ ptr[k] += 1
45
+ return out
46
+
47
+
48
+ def main():
49
+ ap = argparse.ArgumentParser()
50
+ ap.add_argument("--scan", required=True)
51
+ ap.add_argument("--geno", required=True)
52
+ ap.add_argument("--adapters_dir", required=True)
53
+ ap.add_argument("--base", required=True)
54
+ ap.add_argument("--out", required=True)
55
+ ap.add_argument("--cap", type=int, default=150)
56
+ ap.add_argument("--min_loci", type=int, default=0)
57
+ ap.add_argument("--n_bg", type=int, default=24)
58
+ ap.add_argument("--max_ko", type=int, default=24)
59
+ ap.add_argument("--seed", type=int, default=0)
60
+ ap.add_argument("--doses_base", default="-3,-2,-1,0,1,2,3")
61
+ ap.add_argument("--doses_bg", default="-1,0,1")
62
+ ap.add_argument("--ctrl_bg", type=int, default=0)
63
+ ap.add_argument("--test_bg", type=int, default=0, help="D-037: every direction on the first k backgrounds; 0 = all")
64
+ ap.add_argument("--coords", default="expressed", choices=["expressed", "raw"])
65
+ ap.add_argument("--no_controls", action="store_true")
66
+ ap.add_argument("--nonassoc_est", default="naive,pc,mm_f,mm_fd",
67
+ help="D-033: estimators defining a non-associated (high-variance control) locus")
68
+ a = ap.parse_args()
69
+ loci = json.load(open(os.path.join(a.scan, "loci.json")))
70
+ pop = json.load(open(os.path.join(a.scan, "population.json")))
71
+ prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
72
+ real = np.array([not l["module"].startswith("presence") for l in loci])
73
+ P = np.stack([np.load(os.path.join(a.scan, f"{t}.npz"))["p"][:, 1] for t in prim]) # [trait, est, locus] on D
74
+ P = np.where(np.isfinite(P), P, 1.0)
75
+ P[:, :, ~real] = 1.0
76
+ fdr = {}
77
+ for ei, e in enumerate(EST):
78
+ best = {}
79
+ for ti in range(len(prim)):
80
+ for j in np.where(bh(P[ti, ei]) & real)[0]:
81
+ best[j] = min(best.get(j, 1.0), P[ti, ei, j])
82
+ fdr[e] = sorted(best, key=best.get)
83
+ chosen = [(j, "fdr:" + e) for j, e in round_robin(fdr, a.cap)]
84
+ n_fdr = len(chosen)
85
+ if n_fdr < a.min_loci:
86
+ pmin = P.min(0) # [est, locus]
87
+ ranked = {e: [int(j) for j in np.argsort(pmin[ei]) if real[j]] for ei, e in enumerate(EST)}
88
+ chosen += [(j, "fill:" + e) for j, e in round_robin(ranked, a.min_loci - n_fdr, taken=[c[0] for c in chosen])]
89
+ nL = max(l["layer"] for l in loci) + 1
90
+ names_all = json.load(open(os.path.join(a.geno, "adapters.json")))["names"]
91
+ pos = {x: i for i, x in enumerate(names_all)}
92
+ loci_file = "loci_raw.pt" if a.coords == "raw" else "loci.pt"
93
+ G = torch.load(os.path.join(a.geno, loci_file))
94
+ names, split = pop["names"], np.array(pop["split"])
95
+ fam_d, fam_r = np.array(pop["fam_d"]), np.array(pop["fam_r"])
96
+ E = np.where(split == 1)[0]
97
+ # backgrounds
98
+ rng = np.random.default_rng(a.seed)
99
+ clusters = {}
100
+ for i in rng.permutation(E):
101
+ clusters.setdefault(int(fam_r[i]), []).append(int(i))
102
+ order = sorted(clusters, key=lambda c: (-len(clusters[c]), min(clusters[c])))
103
+ bgs, used_fam = [], set()
104
+ while len(bgs) < a.n_bg and any(clusters[c] for c in order):
105
+ for c in order:
106
+ while clusters[c] and fam_d[clusters[c][0]] in used_fam:
107
+ clusters[c].pop(0)
108
+ if clusters[c] and len(bgs) < a.n_bg:
109
+ i = clusters[c].pop(0)
110
+ bgs.append(names[i])
111
+ used_fam.add(fam_d[i])
112
+ # directions
113
+ # "non-associated" (plan 8.1; D-024, D-033): over the --nonassoc_est estimators, not FDR-significant on D for any primary
114
+ # trait and Bonferroni-adjusted min p (traits x those estimators) > 0.5
115
+ na = [EST.index(e) for e in a.nonassoc_est.split(",")]
116
+ in_fdr = np.zeros(P.shape[2], bool)
117
+ for e in na:
118
+ in_fdr[list(fdr[EST[e]])] = True
119
+ assoc_min = np.where(in_fdr, 0.0, P[:, na].min((0, 1)) * P.shape[0] * len(na))
120
+ dirs, ctrl_ids = [], {}
121
+ for j, src in chosen:
122
+ lo = loci[j]
123
+ key, l = lo["module"], lo["l"]
124
+ g = G[key]["g"][:, l].double().numpy()
125
+ pidx = np.array([pos[x] for x in names])
126
+ gbar = g[pidx].mean()
127
+ sd = g[pidx].std()
128
+ dev = [(names[i], float(g[pos[names[i]]] - gbar)) for i in E if abs(g[pos[names[i]]] - gbar) > sd]
129
+ dev = sorted(dev, key=lambda t: -abs(t[1]))[:a.max_ko]
130
+ did = f"loc_{key}_{l}"
131
+ dirs.append({"id": did, "kind": "locus", "module": key, "l": l, "locus_idx": j, "source": src,
132
+ "knockout_carriers": dev})
133
+ if a.no_controls:
134
+ continue
135
+ dirs.append({"id": f"rnd_{key}_{l}", "kind": "random", "module": key, "l": l, "seed": 1000 + j, "control_of": did})
136
+ tl = (lo["layer"] + nL // 2) % nL
137
+ dirs.append({"id": f"oth_{key}_{l}_to{tl}", "kind": "other_layer", "module": key, "l": l,
138
+ "target_module": f"{tl}.{lo['type']}", "control_of": did})
139
+ same = [k for k, x in enumerate(loci) if x["module"] == key and k != j and assoc_min[k] > 0.5]
140
+ if same:
141
+ k = max(same, key=lambda k: loci[k]["lam"])
142
+ hid = f"hv_{key}_{loci[k]['l']}"
143
+ if hid in ctrl_ids:
144
+ ctrl_ids[hid]["control_of"].append(did)
145
+ else:
146
+ ctrl_ids[hid] = {"id": hid, "kind": "locus", "module": key, "l": loci[k]["l"], "locus_idx": k,
147
+ "control_of": [did]}
148
+ chosen_ids = {d["id"] for d in dirs}
149
+ dirs += [v for k, v in ctrl_ids.items() if f"loc_{v['module']}_{v['l']}" not in chosen_ids]
150
+ if a.test_bg:
151
+ for d in dirs:
152
+ d["backgrounds"] = bgs[:a.test_bg]
153
+ if a.ctrl_bg:
154
+ for d in dirs:
155
+ if d.get("control_of"):
156
+ d["backgrounds"] = bgs[:a.ctrl_bg]
157
+ plan = {"base": a.base, "adapters_dir": a.adapters_dir, "geno_dir": a.geno, "backgrounds": bgs, "coords": a.coords,
158
+ "loci_file": loci_file,
159
+ "doses_base": [float(x) for x in a.doses_base.split(",")], "doses_bg": [float(x) for x in a.doses_bg.split(",")],
160
+ "directions": dirs,
161
+ "selection": {"primary_traits": prim, "n_fdr": n_fdr, "n_fill": len(chosen) - n_fdr,
162
+ "fdr_per_estimator": {e: len(v) for e, v in fdr.items()}, "cap": a.cap, "min_loci": a.min_loci,
163
+ "n_directions": len(dirs), "n_backgrounds": len(bgs), "ctrl_bg": a.ctrl_bg, "nonassoc_est": a.nonassoc_est,
164
+ "test_bg": a.test_bg, "coords": a.coords, "controls": not a.no_controls,
165
+ "n_knockouts": sum(len(d.get("knockout_carriers", [])) for d in dirs),
166
+ "n_carriers": len({n for d in dirs for n, _ in d.get("knockout_carriers", [])})}}
167
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
168
+ json.dump(plan, open(a.out, "w"), indent=1, default=lambda o: o.item() if hasattr(o, "item") else str(o))
169
+ print(json.dumps(plan["selection"], default=lambda o: o.item() if hasattr(o, "item") else str(o)), flush=True)
170
+
171
+
172
+ if __name__ == "__main__":
173
+ main()
code/src/analysis/population.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Assemble a population: phenotypes, reliabilities, covariates, genotype matrix, relatedness, families, splits
3
+ (RESEARCH_PLAN 4.3-4.4, 5, 7.2, 7.7)."""
4
+ import glob
5
+ import hashlib
6
+ import json
7
+ import os
8
+ from collections import Counter
9
+
10
+ import numpy as np
11
+ import torch
12
+ from scipy.cluster.hierarchy import fcluster, linkage
13
+ from scipy.sparse.csgraph import connected_components
14
+ from scipy.spatial.distance import squareform
15
+
16
+ from .scan import int_transform
17
+
18
+ MODTYPES = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
19
+
20
+
21
+ def law(r1, r2, d):
22
+ return np.sqrt(r1 * r2) / np.sqrt((r1 + 1 + d) * (r2 + 1 + d))
23
+
24
+
25
+ def load_phenotypes(pheno_dir, names):
26
+ recs = {}
27
+ for n in names:
28
+ fn = os.path.join(pheno_dir, n + ".json")
29
+ if os.path.exists(fn):
30
+ r = json.load(open(fn))
31
+ if r.get("status") == "ok":
32
+ recs[n] = r
33
+ return recs
34
+
35
+
36
+ def reliability(h0, h1):
37
+ ok = np.isfinite(h0) & np.isfinite(h1)
38
+ if ok.sum() < 10 or np.std(h0[ok]) == 0 or np.std(h1[ok]) == 0:
39
+ return np.nan
40
+ r = np.corrcoef(h0[ok], h1[ok])[0, 1]
41
+ return float(2 * r / (1 + r)) if r > -1 else np.nan
42
+
43
+
44
+ def build(geno_dir, pheno_dir, recipe_threshold=None, q_law=896, loci_file="loci.pt", fam_mult=3.0):
45
+ A = json.load(open(os.path.join(geno_dir, "adapters.json")))
46
+ names_all, info = A["names"], A["info"]
47
+ recs = load_phenotypes(pheno_dir, names_all)
48
+ keep = np.array([(n in recs) and not info[n]["flags"].get("dora") for n in names_all])
49
+ names = [x for x, k in zip(names_all, keep) if k]
50
+ n = len(names)
51
+ traits = sorted(set().union(*[set(recs[x]["traits"]) for x in names]))
52
+ Y = np.full((3, n, len(traits)), np.nan)
53
+ for i, x in enumerate(names):
54
+ for j, t in enumerate(traits):
55
+ v = recs[x]["traits"].get(t)
56
+ if v is not None:
57
+ Y[:, i, j] = v
58
+ rel = {t: reliability(Y[1, :, j], Y[2, :, j]) for j, t in enumerate(traits)}
59
+ Yt = np.stack([int_transform(Y[0, :, j]) for j in range(len(traits))], 1)
60
+ # covariates
61
+ rmax = np.array([max(info[x]["ranks"]) for x in names], float)
62
+ lnorm = np.array([0.5 * np.log(info[x]["sqnorm"]) for x in names])
63
+ pats = [tuple(sorted(info[x]["modules"])) for x in names]
64
+ top = [p for p, _ in Counter(pats).most_common(9)][1:] # most common pattern is the reference level
65
+ Xp = np.array([[float(p == t) for t in top] for p in pats]).reshape(n, len(top))
66
+ mts = np.array([float(bool(info[x]["flags"].get("modules_to_save"))) for x in names])
67
+ quant = np.array([float(any(s in str(info[x].get("cfg_base") or "").lower() for s in ("bnb", "4bit", "8bit", "awq",
68
+ "gptq"))) for x in names])
69
+ gpus = sorted({recs[x].get("gpu", "?") for x in names}) # measurement hardware (D-019/D-027): one-hot if mixed
70
+ Xg = np.column_stack([[float(recs[x].get("gpu", "?") == g) for x in names] for g in gpus[1:]]) if len(gpus) > 1 \
71
+ else np.zeros((n, 0))
72
+ X = np.column_stack([np.ones(n), np.log(rmax), lnorm, Xp, mts, quant, Xg])
73
+ X = X[:, np.r_[0, 1 + np.where(X[:, 1:].std(0) > 0)[0]]]
74
+ # genotypes
75
+ loci = torch.load(os.path.join(geno_dir, loci_file))
76
+ cols, gl = [], []
77
+ for k, v in loci.items():
78
+ for l in range(v["n_loci"]):
79
+ g = v["g"][keep, l].double().numpy()
80
+ cols.append(g - g.mean())
81
+ gl.append({"module": k, "l": l, "layer": int(k.split(".")[0]), "type": k.split(".")[1],
82
+ "lam": float(v["lam"][l]), "sigma": float(v["g"][:, l].std())})
83
+ pres = np.array([[float(any(m == t for m in info[x]["modules"])) for t in MODTYPES] for x in names])
84
+ for j, t in enumerate(MODTYPES):
85
+ if 0 < pres[:, j].mean() < 1:
86
+ cols.append(pres[:, j] - pres[:, j].mean())
87
+ gl.append({"module": f"presence.{t}", "l": -1, "layer": -1, "type": t, "lam": np.nan, "sigma": 1.0})
88
+ Gm = np.column_stack(cols)
89
+ Kz = np.load(os.path.join(geno_dir, "K.npz"))
90
+ Kd, Kf = Kz["K_desc"][np.ix_(keep, keep)], Kz["K_func"][np.ix_(keep, keep)]
91
+ # descent families: K_desc above fam_mult (3 = plan 5.2; 2 and 5 = sensitivity 14.6) x the same-task law value
92
+ thr = fam_mult * law(rmax[:, None], rmax[None, :], q_law)
93
+ adj = (Kd > thr) & ~np.eye(n, dtype=bool)
94
+ nf, fam_d = connected_components(adj, directed=False)
95
+ # recipe families: average linkage on 1 - K_func, cut at recipe_threshold (distance)
96
+ if recipe_threshold is None:
97
+ recipe_threshold = 1 - np.quantile(Kf[np.triu_indices(n, 1)], 0.99)
98
+ Z = linkage(squareform(np.clip(1 - Kf, 0, None), checks=False), method="average")
99
+ fam_r = fcluster(Z, t=recipe_threshold, criterion="distance") - 1
100
+ authors = [x.split("__")[0] for x in names]
101
+ # discovery / estimation split by descent family (RESEARCH_PLAN 7.7)
102
+ fams = {}
103
+ for i, f in enumerate(fam_d):
104
+ fams.setdefault(f, []).append(i)
105
+ order = sorted(fams, key=lambda f: hashlib.sha1(min(names[i] for i in fams[f]).encode()).hexdigest())
106
+ split = np.zeros(n, int)
107
+ cnt = [0, 0]
108
+ for f in order:
109
+ s = 0 if cnt[0] <= cnt[1] else 1
110
+ split[fams[f]] = s
111
+ cnt[s] += len(fams[f])
112
+ return {"names": names, "gpu": [recs[x].get("gpu", "?") for x in names], "traits": traits, "Y": Y, "Yt": Yt, "rel": rel, "X": X, "G": Gm, "loci": gl,
113
+ "K_desc": Kd, "K_func": Kf, "fam_d": fam_d, "fam_r": fam_r, "authors": authors, "split": split,
114
+ "rmax": rmax, "recipe_threshold": float(recipe_threshold), "info": {x: info[x] for x in names}}
115
+
116
+
117
+ def neff(K):
118
+ return float(np.trace(K) ** 2 / np.sum(K * K))
code/src/analysis/predict.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Prediction and portability (RESEARCH_PLAN 12; E7).
3
+
4
+ Predictors, each with 20 tuning configurations chosen on validation families inside the training fold:
5
+ ridge_raw kernel ridge on the raw-weight Gram (= ridge on the full raw coordinates), lambda grid
6
+ ridge_exp kernel ridge on the expressed Gram (= ridge on expressed coordinates), lambda grid
7
+ spectral ridge on per-module log update norms (raw and expressed) plus log rank, lambda grid
8
+ knn_func mean of the k nearest training adapters by K_func, k grid
9
+ blup_f REML BLUP with K_func (no tuning; variance components are the tuning)
10
+ mm_score sum of MM-f (single function kernel) locus effects over loci with p below a threshold, threshold grid
11
+ causal sum of gamma_do x standardised genotype over validated loci (needs --calib; no tuning)
12
+ Splits: random, descent-, recipe- and author-disjoint (5 folds each). Accuracy = Pearson r on transformed traits, overall
13
+ and in 5 quantile bins of the maximum K_desc and K_func of each test adapter to its training set.
14
+
15
+ python src/analysis/predict.py --geno data/processed/qwen05 --pheno results/phenotypes/qwen05
16
+ --scan results/scans/qwen05 [--calib results/calibration/qwen05.json] --out results/e7/predict_qwen05.json
17
+ """
18
+ import argparse
19
+ import json
20
+ import os
21
+ import sys
22
+
23
+ import numpy as np
24
+ from scipy import stats
25
+
26
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
27
+ from src.analysis.population import build # noqa: E402
28
+ from src.analysis.scan import bh, gls_scan, reml # noqa: E402
29
+
30
+ LAMS = np.logspace(-4, 2, 20)
31
+ KS = np.unique(np.round(np.logspace(0, np.log10(60), 20)).astype(int))
32
+ PTHR = np.logspace(-8, -0.3, 20)
33
+
34
+
35
+ def r_of(a, b):
36
+ m = np.isfinite(a) & np.isfinite(b)
37
+ return float(np.corrcoef(a[m], b[m])[0, 1]) if m.sum() > 3 and np.std(a[m]) > 0 else np.nan
38
+
39
+
40
+ def kridge(K, tr, te, y, lam):
41
+ Ktr = K[np.ix_(tr, tr)]
42
+ s = lam * np.mean(np.diag(Ktr))
43
+ mu = y[tr].mean()
44
+ alpha = np.linalg.solve(Ktr + s * np.eye(len(tr)), y[tr] - mu)
45
+ return K[np.ix_(te, tr)] @ alpha + mu
46
+
47
+
48
+ def knn(K, tr, te, y, k):
49
+ S = K[np.ix_(te, tr)]
50
+ idx = np.argsort(-S, 1)[:, :k]
51
+ return y[tr][idx].mean(1)
52
+
53
+
54
+ def ridge(F, tr, te, y, lam):
55
+ mu, sd = F[tr].mean(0), F[tr].std(0) + 1e-12
56
+ A, B = (F[tr] - mu) / sd, (F[te] - mu) / sd
57
+ w = np.linalg.solve(A.T @ A + lam * len(tr) * np.eye(A.shape[1]), A.T @ (y[tr] - y[tr].mean()))
58
+ return B @ w + y[tr].mean()
59
+
60
+
61
+ def blup(K, X, tr, te, y):
62
+ s, V, _ = reml(y[tr], X[tr], [K[np.ix_(tr, tr)] + 1e-6 * np.eye(len(tr))])
63
+ Vi = np.linalg.inv(V)
64
+ XtVi = X[tr].T @ Vi
65
+ beta = np.linalg.lstsq(XtVi @ X[tr], XtVi @ y[tr], rcond=None)[0]
66
+ return X[te] @ beta + s[0] * K[np.ix_(te, tr)] @ (Vi @ (y[tr] - X[tr] @ beta)), V
67
+
68
+
69
+ def mm_fit(K, X, G, tr, y, V=None):
70
+ if V is None:
71
+ _, V, _ = reml(y[tr], X[tr], [K[np.ix_(tr, tr)] + 1e-6 * np.eye(len(tr))])
72
+ b, _, p = gls_scan(y[tr], G[tr] - G[tr].mean(0), X[tr], V)
73
+ return b, p
74
+
75
+
76
+ def inner_split(groups, tr, seed):
77
+ g = np.unique(groups[tr])
78
+ rng = np.random.default_rng(seed)
79
+ val_g = set(rng.permutation(g)[: max(1, len(g) // 5)].tolist())
80
+ va = np.array([i for i in tr if groups[i] in val_g])
81
+ fit = np.array([i for i in tr if groups[i] not in val_g])
82
+ return fit, va
83
+
84
+
85
+ def main():
86
+ ap = argparse.ArgumentParser()
87
+ ap.add_argument("--geno", required=True)
88
+ ap.add_argument("--pheno", required=True)
89
+ ap.add_argument("--scan", required=True)
90
+ ap.add_argument("--calib", default=None)
91
+ ap.add_argument("--out", required=True)
92
+ ap.add_argument("--recipe_threshold", type=float, default=None)
93
+ ap.add_argument("--seed", type=int, default=0)
94
+ a = ap.parse_args()
95
+ P = build(a.geno, a.pheno, recipe_threshold=a.recipe_threshold)
96
+ prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
97
+ n = len(P["names"])
98
+ A = json.load(open(os.path.join(a.geno, "adapters.json")))
99
+ keep = np.array([x in set(P["names"]) for x in A["names"]])
100
+ Kz = np.load(os.path.join(a.geno, "K.npz"))
101
+ Graw, Gexp = Kz["G_raw"][np.ix_(keep, keep)], Kz["G_exp"][np.ix_(keep, keep)]
102
+ gr = np.load(os.path.join(a.geno, "grams_raw.npy"), mmap_mode="r")
103
+ ge = np.load(os.path.join(a.geno, "grams_exp.npy"), mmap_mode="r")
104
+ pk = np.where(keep)[0]
105
+ F = np.column_stack([np.log(np.diag(np.asarray(gr[m]))[pk] + 1e-12) for m in range(gr.shape[0])] +
106
+ [np.log(np.diag(np.asarray(ge[m]))[pk] + 1e-12) for m in range(ge.shape[0])] +
107
+ [np.log(P["rmax"])])
108
+ Kd, Kf, X, G = P["K_desc"], P["K_func"], P["X"], P["G"]
109
+ groups = {"random": np.random.default_rng(a.seed).permutation(n) % 5, "descent": P["fam_d"], "recipe": P["fam_r"],
110
+ "author": np.unique(P["authors"], return_inverse=True)[1]}
111
+ causal = None
112
+ if a.calib and os.path.exists(a.calib):
113
+ C = json.load(open(a.calib))["per_direction"]
114
+ loci = json.load(open(os.path.join(a.scan, "loci.json")))
115
+ plan_ids = {(l["module"], l["l"]): i for i, l in enumerate(loci)}
116
+ rows = [(plan_ids[(v["module"], v["l"])], v) for v in C.values() if v["kind"] == "locus" and v.get("source")]
117
+ causal = {}
118
+ for t in prim:
119
+ gam = np.array([v["traits"][t]["gamma_do"] for _, v in rows], float)
120
+ var = np.array([v["traits"][t]["var_do"] for _, v in rows], float)
121
+ pz = 2 * stats.norm.sf(np.abs(gam / np.sqrt(np.maximum(var, 1e-300))))
122
+ val = bh(np.where(np.isfinite(pz), pz, 1.0))
123
+ causal[t] = [(j, g / loci[j]["sigma"]) for (j, _), g, v_ in zip(rows, gam, val) if v_]
124
+ out = {"n": n, "results": {}, "bins": {}}
125
+ parts = a.out + ".parts" # one file per (split, trait), so a run that hits the time limit resumes
126
+ os.makedirs(parts, exist_ok=True)
127
+ for split, grp in groups.items():
128
+ ug = np.unique(grp)
129
+ fold = dict(zip(ug, np.random.default_rng(a.seed + 1).permutation(len(ug)) % 5))
130
+ fo = np.array([fold[g] for g in grp])
131
+ for t in prim:
132
+ pf = os.path.join(parts, f"{split}__{t}{'__calib' if causal else ''}.json") # causal column only with --calib
133
+ if os.path.exists(pf):
134
+ r = json.load(open(pf))
135
+ out["results"].setdefault(split, {})[t] = r["results"]
136
+ out["bins"].setdefault(split, {})[t] = r["bins"]
137
+ continue
138
+ y = P["Yt"][:, P["traits"].index(t)]
139
+ pred = {k: np.full(n, np.nan) for k in ("ridge_raw", "ridge_exp", "spectral", "knn_func", "blup_f",
140
+ "mm_score", "causal")}
141
+ maxd, maxf = np.full(n, np.nan), np.full(n, np.nan)
142
+ for f in range(5):
143
+ te = np.where((fo == f) & np.isfinite(y))[0]
144
+ tr = np.where((fo != f) & np.isfinite(y))[0]
145
+ if len(te) < 3:
146
+ continue
147
+ maxd[te], maxf[te] = Kd[np.ix_(te, tr)].max(1), Kf[np.ix_(te, tr)].max(1)
148
+ fit, va = inner_split(grp if split != "random" else P["fam_d"], tr, a.seed + f)
149
+ for name, K in (("ridge_raw", Graw), ("ridge_exp", Gexp)):
150
+ best = max(LAMS, key=lambda l: np.nan_to_num(r_of(kridge(K, fit, va, y, l), y[va]), nan=-2))
151
+ pred[name][te] = kridge(K, tr, te, y, best)
152
+ best = max(LAMS, key=lambda l: np.nan_to_num(r_of(ridge(F, fit, va, y, l), y[va]), nan=-2))
153
+ pred["spectral"][te] = ridge(F, tr, te, y, best)
154
+ best = max(KS, key=lambda k: np.nan_to_num(r_of(knn(Kf, fit, va, y, min(k, len(fit))), y[va]), nan=-2))
155
+ pred["knn_func"][te] = knn(Kf, tr, te, y, min(best, len(tr)))
156
+ pred["blup_f"][te], _ = blup(Kf, X, tr, te, y)
157
+ b, p = mm_fit(Kf, X, G, fit, y)
158
+ Gc = G - G[fit].mean(0)
159
+ best = max(PTHR, key=lambda th: np.nan_to_num(r_of(Gc[va] @ np.where(p < th, b, 0), y[va]), nan=-2))
160
+ b, p = mm_fit(Kf, X, G, tr, y)
161
+ pred["mm_score"][te] = (G[te] - G[tr].mean(0)) @ np.where(p < best, b, 0)
162
+ if causal and causal.get(t):
163
+ js, ws = zip(*causal[t])
164
+ pred["causal"][te] = (G[np.ix_(te, list(js))] - G[np.ix_(tr, list(js))].mean(0)) @ np.array(ws)
165
+ out["results"].setdefault(split, {})[t] = {k: r_of(v, y) for k, v in pred.items()}
166
+ for nm, mx in (("max_K_desc", maxd), ("max_K_func", maxf)):
167
+ m = np.isfinite(mx)
168
+ edges = np.quantile(mx[m], np.linspace(0, 1, 6))
169
+ b_ = np.clip(np.searchsorted(edges, mx, side="right") - 1, 0, 4)
170
+ out["bins"].setdefault(split, {}).setdefault(t, {})[nm] = {
171
+ "edges": edges.tolist(),
172
+ "r": {k: [r_of(v[m & (b_ == i)], y[m & (b_ == i)]) for i in range(5)] for k, v in pred.items()}}
173
+ json.dump({"results": out["results"][split][t], "bins": out["bins"][split][t]}, open(pf + ".tmp", "w"), default=float)
174
+ os.replace(pf + ".tmp", pf)
175
+ print(split, t, {k: round(v, 3) for k, v in out["results"][split][t].items() if np.isfinite(v)}, flush=True)
176
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
177
+ json.dump(out, open(a.out, "w"), indent=1, default=float)
178
+ print("PREDICTDONE", flush=True)
179
+
180
+
181
+ if __name__ == "__main__":
182
+ main()
code/src/analysis/scan.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Association scans (RESEARCH_PLAN 7): naive, PC, MM-f (leave-block-out function kernel), MM-fd (+ descent kernel),
3
+ WF-d / WF-r (within families), DUP-AFE (duplicates removed + author fixed effects).
4
+
5
+ All estimators are vectorised over loci: covariates are partialled out (Frisch-Waugh-Lovell), mixed models are fitted
6
+ once per trait (and per left-out block) by REML under the null, and loci are tested by GLS after whitening with V^{-1/2}.
7
+ """
8
+ import numpy as np
9
+ from scipy import optimize, stats
10
+
11
+
12
+ def basis(X, tol=1e-10):
13
+ """Orthonormal basis of the column space of X (drops dependent or all-zero columns)."""
14
+ U, s, _ = np.linalg.svd(X, full_matrices=False)
15
+ return U[:, s > tol * max(s.max(), 1e-300)]
16
+
17
+
18
+ def resid(M, X):
19
+ """Residuals of the columns of M after OLS on X (rank-safe)."""
20
+ Q = basis(X)
21
+ return M - Q @ (Q.T @ M)
22
+
23
+
24
+ def ols_scan(y, G, X):
25
+ """Per-locus OLS of y on [X, g]: returns beta, se, p (two-sided t)."""
26
+ n, p = len(y), basis(X).shape[1]
27
+ yr = resid(y[:, None], X)[:, 0]
28
+ Gr = resid(G, X)
29
+ ss = (Gr ** 2).sum(0)
30
+ ok = ss > 1e-12 * max(ss.max(), 1e-300)
31
+ beta = np.where(ok, Gr.T @ yr / np.where(ok, ss, 1), np.nan)
32
+ rss = (yr ** 2).sum() - np.where(ok, beta ** 2 * ss, 0)
33
+ df = n - p - 1
34
+ se = np.sqrt(np.maximum(rss, 1e-300) / df / np.where(ok, ss, 1))
35
+ se = np.where(ok, se, np.nan)
36
+ pval = 2 * stats.t.sf(np.abs(beta / se), df)
37
+ return beta, se, pval
38
+
39
+
40
+ def reml(y, X, Ks, init=None):
41
+ """REML for V = sum_k s_k K_k + s_e I. Returns variance components (len(Ks)+1,) and V."""
42
+ n = len(y)
43
+ X = basis(X)
44
+ mats = list(Ks) + [np.eye(n)]
45
+ vy = float(np.var(resid(y[:, None], X)))
46
+
47
+ def nll(logs):
48
+ s = np.exp(logs)
49
+ V = sum(si * M for si, M in zip(s, mats))
50
+ try:
51
+ L = np.linalg.cholesky(V)
52
+ except np.linalg.LinAlgError:
53
+ return 1e20
54
+ Li_X = np.linalg.solve(L, X)
55
+ Li_y = np.linalg.solve(L, y)
56
+ XtVX = Li_X.T @ Li_X
57
+ b = np.linalg.solve(XtVX, Li_X.T @ Li_y)
58
+ r = Li_y - Li_X @ b
59
+ sign, ld = np.linalg.slogdet(XtVX)
60
+ return 0.5 * (2 * np.log(np.diag(L)).sum() + ld + r @ r)
61
+
62
+ x0 = np.log(np.full(len(mats), vy / len(mats))) if init is None else np.log(np.maximum(init, 1e-6 * vy))
63
+ res = optimize.minimize(nll, x0, method="L-BFGS-B", bounds=[(np.log(1e-8 * vy + 1e-12), np.log(10 * vy + 1e-12))] * len(mats))
64
+ s = np.exp(res.x)
65
+ V = sum(si * M for si, M in zip(s, mats))
66
+ return s, V, float(res.fun)
67
+
68
+
69
+ def reml_eig1(y, X, ev, Q):
70
+ """Exact fast path of reml() for one kernel: V = s1 K + s2 I with K = Q diag(ev) Q^T (eigendecomposed once and reused
71
+ across traits). Same objective, start and bounds as reml(); each evaluation is O(n p^2). Returns (s, W, fun) with the
72
+ whitening matrix W = diag(s1 ev + s2)^-1/2 Q^T (W^T W = V^-1; GLS is invariant to the choice of whitening)."""
73
+ Xb = basis(X)
74
+ vy = float(np.var(resid(y[:, None], Xb)))
75
+ Xt, yt = Q.T @ Xb, Q.T @ y
76
+
77
+ def nll(logs):
78
+ s1, s2 = np.exp(logs)
79
+ d = s1 * ev + s2
80
+ if np.any(d <= 0):
81
+ return 1e20
82
+ w = 1.0 / d
83
+ XtVX = (Xt * w[:, None]).T @ Xt
84
+ b = np.linalg.solve(XtVX, (Xt * w[:, None]).T @ yt)
85
+ r = yt - Xt @ b
86
+ _, ld = np.linalg.slogdet(XtVX)
87
+ return 0.5 * (np.log(d).sum() + ld + (r * r * w).sum())
88
+
89
+ x0 = np.log(np.full(2, vy / 2))
90
+ res = optimize.minimize(nll, x0, method="L-BFGS-B", bounds=[(np.log(1e-8 * vy + 1e-12), np.log(10 * vy + 1e-12))] * 2)
91
+ s = np.exp(res.x)
92
+ W = (Q / np.sqrt(s[0] * ev + s[1])[None, :]).T
93
+ return s, W, float(res.fun)
94
+
95
+
96
+ def gls_scan(y, G, X, V=None, W=None):
97
+ """GLS per locus with fixed V (estimated under the null); or with a whitening matrix W (W^T W = V^-1)."""
98
+ X = basis(X)
99
+ if W is not None:
100
+ yw, Xw, Gw = W @ y, W @ X, W @ G
101
+ else:
102
+ L = np.linalg.cholesky(V)
103
+ yw = np.linalg.solve(L, y)
104
+ Xw = np.linalg.solve(L, X)
105
+ Gw = np.linalg.solve(L, G)
106
+ n, p = X.shape
107
+ yr = resid(yw[:, None], Xw)[:, 0]
108
+ Gr = resid(Gw, Xw)
109
+ ss = (Gr ** 2).sum(0)
110
+ beta = Gr.T @ yr / np.maximum(ss, 1e-300)
111
+ # V is scaled to the residual variance by REML, so the Wald statistic uses unit residual variance
112
+ sigma2 = ((yr ** 2).sum() - beta ** 2 * ss) / (n - p - 1)
113
+ se = np.sqrt(np.maximum(sigma2, 1e-300) / np.maximum(ss, 1e-300))
114
+ pval = 2 * stats.t.sf(np.abs(beta / se), n - p - 1)
115
+ return beta, se, pval
116
+
117
+
118
+ def within_scan(y, G, X, groups):
119
+ """Within-family OLS: demean y, G and X inside groups of size >= 2; singletons dropped."""
120
+ groups = np.asarray(groups)
121
+ keep = np.array([np.sum(groups == g) >= 2 for g in groups])
122
+ yk, Gk, Xk, gk = y[keep], G[keep], X[keep], groups[keep]
123
+ if keep.sum() < 10:
124
+ nan = np.full(G.shape[1], np.nan)
125
+ return nan, nan, nan, int(keep.sum())
126
+
127
+ def dm(M):
128
+ M = M.astype(float).copy()
129
+ for g in np.unique(gk):
130
+ idx = gk == g
131
+ M[idx] -= M[idx].mean(0)
132
+ return M
133
+ Xd = dm(Xk[:, 1:]) if Xk.shape[1] > 1 else np.zeros((len(yk), 0))
134
+ Xd = Xd[:, Xd.std(0) > 1e-12] if Xd.shape[1] else Xd
135
+ nfam = len(np.unique(gk))
136
+ yd, Gd = dm(yk[:, None])[:, 0], dm(Gk)
137
+ Xuse = Xd if Xd.shape[1] else np.zeros((len(yk), 1))
138
+ b, se, p = ols_scan(yd, Gd, Xuse)
139
+ # degrees of freedom lost to family means
140
+ df_ols = len(yk) - Xuse.shape[1] - 1
141
+ df = max(df_ols - nfam, 3)
142
+ se = se * np.sqrt(df_ols / df)
143
+ p = 2 * stats.t.sf(np.abs(b / se), df)
144
+ return b, se, p, int(keep.sum())
145
+
146
+
147
+ def lambda_gc(p):
148
+ p = p[np.isfinite(p)]
149
+ chi = stats.chi2.isf(p, 1)
150
+ return float(np.median(chi) / stats.chi2.ppf(0.5, 1))
151
+
152
+
153
+ def int_transform(y):
154
+ """Rank-based inverse normal transform (Blom). NaNs kept."""
155
+ out = np.full(len(y), np.nan)
156
+ ok = np.isfinite(y)
157
+ r = stats.rankdata(y[ok])
158
+ out[ok] = stats.norm.ppf((r - 0.375) / (ok.sum() + 0.25))
159
+ return out
160
+
161
+
162
+ def m_eff(G):
163
+ """Li-Ji effective number of independent tests from the locus correlation matrix."""
164
+ C = np.corrcoef(G, rowvar=False)
165
+ C = np.nan_to_num(C)
166
+ ev = np.abs(np.linalg.eigvalsh(C))
167
+ return float(np.sum((ev >= 1).astype(float) + (ev - np.floor(ev))))
168
+
169
+
170
+ def bh(p, q=0.05):
171
+ p = np.asarray(p)
172
+ ok = np.isfinite(p)
173
+ out = np.zeros(len(p), bool)
174
+ ps = np.sort(p[ok])
175
+ m = len(ps)
176
+ thr = ps[ps <= q * np.arange(1, m + 1) / m]
177
+ if len(thr):
178
+ out[ok] = p[ok] <= thr.max()
179
+ return out
code/src/analysis/scan_extras.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Scan diagnostics and module-level tests (RESEARCH_PLAN 7.4, 7.5).
3
+
4
+ lambda_GC with a family-block bootstrap (1,000 resamples of descent families; naive OLS re-run, MM-fd as fixed-V GLS
5
+ with variance components from the full-sample REML), linkage-score regression (chi^2 on the per-locus linkage score
6
+ l_j = sum_k r_jk^2 over loci; intercept ~ confounding), module kernel score tests (variance component of the module's
7
+ expressed kernel over the null mixed model with the left-out-block function kernel and the descent kernel;
8
+ Satterthwaite approximation), and SuSiE (L = 10) in significant modules plus same-layer neighbours on the
9
+ relatedness-whitened residual.
10
+
11
+ python src/analysis/scan_extras.py --geno data/processed/qwen05 --pheno results/phenotypes/qwen05
12
+ --scan results/scans/qwen05 --out results/scans/qwen05/extras.json [--claim] [--shard i --nshards n]
13
+ Per-trait results go to <out>.parts/<trait>.json as they finish (resumable; with --claim any number of processes share the
14
+ traits through lock files, D-036); <out> is written once every primary trait has a part. The bootstrap RNG is seeded per
15
+ trait by (seed, trait index).
16
+ """
17
+ import argparse
18
+ import json
19
+ import os
20
+ import signal
21
+ import sys
22
+
23
+ import numpy as np
24
+ from scipy import optimize, stats
25
+
26
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
27
+ from src.analysis.population import build # noqa: E402
28
+ from src.analysis.scan import basis, bh, gls_scan, lambda_gc, ols_scan, reml # noqa: E402
29
+ from src.run.intervene import HELD, claim, unlock # noqa: E402
30
+ from src.run.scan_run import blocks_of, cosine # noqa: E402
31
+
32
+
33
+ def susie(X, y, L=10, iters=200, tol=1e-5):
34
+ """Sum of single effects regression (IBSS; Wang et al. 2020), uniform prior over columns, prior variances by ML."""
35
+ n, p = X.shape
36
+ X = X - X.mean(0)
37
+ y = y - y.mean()
38
+ d = np.maximum((X ** 2).sum(0), 1e-12)
39
+ s2 = float(np.var(y))
40
+ alpha, mu, mu2 = np.zeros((L, p)), np.zeros((L, p)), np.zeros((L, p))
41
+ V = np.full(L, 0.2 * s2)
42
+ Xr = np.zeros(n)
43
+ prev = None
44
+ for _ in range(iters):
45
+ for l in range(L):
46
+ Xr_l = Xr - X @ (alpha[l] * mu[l])
47
+ r = y - Xr_l
48
+ xtr = X.T @ r
49
+ b, s2b = xtr / d, s2 / d
50
+
51
+ def neg(lv):
52
+ v = np.exp(lv)
53
+ lbf = 0.5 * np.log(s2b / (v + s2b)) + 0.5 * b ** 2 / s2b * v / (v + s2b)
54
+ m = lbf.max()
55
+ return -(m + np.log(np.mean(np.exp(lbf - m))))
56
+ res = optimize.minimize_scalar(neg, bounds=(np.log(1e-12 * s2 + 1e-300), np.log(10 * s2 + 1e-300)), method="bounded")
57
+ V[l] = np.exp(res.x) if -res.fun > 0 else 0.0
58
+ if V[l] > 0:
59
+ lbf = 0.5 * np.log(s2b / (V[l] + s2b)) + 0.5 * b ** 2 / s2b * V[l] / (V[l] + s2b)
60
+ w = np.exp(lbf - lbf.max())
61
+ alpha[l] = w / w.sum()
62
+ pv = 1 / (1 / V[l] + d / s2)
63
+ mu[l] = pv * xtr / s2
64
+ mu2[l] = pv + mu[l] ** 2
65
+ else:
66
+ alpha[l], mu[l], mu2[l] = 1.0 / p, 0.0, 0.0
67
+ Xr = Xr_l + X @ (alpha[l] * mu[l])
68
+ erss = ((y - Xr) ** 2).sum() - sum(((X @ (alpha[l] * mu[l])) ** 2).sum() for l in range(L)) + (d * (alpha * mu2).sum(0)).sum()
69
+ s2 = max(float(erss / n), 1e-12)
70
+ if prev is not None and np.abs(alpha - prev).max() < tol:
71
+ break
72
+ prev = alpha.copy()
73
+ act = V > 0 # effects with zero prior variance are null and excluded from PIPs (as in susieR)
74
+ pip = 1 - np.prod(1 - alpha[act], 0) if act.any() else np.zeros(p)
75
+ R = np.corrcoef(X, rowvar=False)
76
+ cs = []
77
+ for l in range(L):
78
+ if V[l] == 0:
79
+ continue
80
+ o = np.argsort(-alpha[l])
81
+ k = int(np.searchsorted(np.cumsum(alpha[l][o]), 0.95) + 1)
82
+ s = o[:k]
83
+ pur = float(np.min(np.abs(R[np.ix_(s, s)]))) if k > 1 else 1.0
84
+ if pur >= 0.5:
85
+ cs.append({"members": s.tolist(), "coverage": float(alpha[l][s].sum()), "purity": pur, "prior_var": float(V[l])})
86
+ return pip, cs
87
+
88
+
89
+ def score_test(y, X, V, Km):
90
+ Vi = np.linalg.inv(V)
91
+ Xb = basis(X)
92
+ VX = Vi @ Xb
93
+ Pm = Vi - VX @ np.linalg.solve(Xb.T @ VX, VX.T)
94
+ r = Pm @ y
95
+ Q = 0.5 * r @ Km @ r
96
+ PK = Pm @ Km
97
+ e = 0.5 * np.trace(PK)
98
+ v = 0.5 * np.sum(PK * PK.T)
99
+ k, nu = v / (2 * e), 2 * e ** 2 / v
100
+ return float(Q), float(stats.chi2.sf(Q / k, nu))
101
+
102
+
103
+ def main():
104
+ ap = argparse.ArgumentParser()
105
+ ap.add_argument("--geno", required=True)
106
+ ap.add_argument("--pheno", required=True)
107
+ ap.add_argument("--scan", required=True)
108
+ ap.add_argument("--out", required=True)
109
+ ap.add_argument("--recipe_threshold", type=float, default=None)
110
+ ap.add_argument("--n_boot", type=int, default=1000)
111
+ ap.add_argument("--seed", type=int, default=0)
112
+ ap.add_argument("--claim", action="store_true")
113
+ ap.add_argument("--stale", type=float, default=14400)
114
+ ap.add_argument("--shard", type=int, default=0)
115
+ ap.add_argument("--nshards", type=int, default=1)
116
+ a = ap.parse_args()
117
+ signal.signal(signal.SIGTERM, lambda *_: sys.exit(143)) # runs the finally: lock release (D-036)
118
+ pd = a.out + ".parts"
119
+ os.makedirs(pd, exist_ok=True)
120
+ P = build(a.geno, a.pheno, recipe_threshold=a.recipe_threshold)
121
+ prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
122
+ n = len(P["names"])
123
+ A = json.load(open(os.path.join(a.geno, "adapters.json")))
124
+ keep = np.array([x in set(P["names"]) for x in A["names"]])
125
+ mods = json.load(open(os.path.join(a.geno, "modules.json")))
126
+ ge = np.load(os.path.join(a.geno, "grams_exp.npy"), mmap_mode="r")
127
+ Sb = np.zeros((8, n, n))
128
+ for mi, k in enumerate(mods):
129
+ Sb[blocks_of(k)] += np.asarray(ge[mi])[np.ix_(keep, keep)]
130
+ S = Sb.sum(0)
131
+ Kf_blocks = [cosine(S - Sb[b]) for b in range(8)]
132
+ Kd, X, G = P["K_desc"], P["X"], P["G"]
133
+ blk = np.array([blocks_of(l["module"]) for l in P["loci"]])
134
+ Rg = np.corrcoef(G, rowvar=False)
135
+ lscore = np.nansum(Rg ** 2, 0)
136
+ fams = {}
137
+ for i, f in enumerate(P["fam_d"]):
138
+ fams.setdefault(int(f), []).append(i)
139
+ fl = list(fams)
140
+ for ti, t in enumerate(prim):
141
+ pf = os.path.join(pd, t + ".json")
142
+ if ti % a.nshards != a.shard or os.path.exists(pf):
143
+ continue
144
+ if a.claim:
145
+ if not claim(pf + ".lock", a.stale):
146
+ continue
147
+ HELD[:] = [pf + ".lock"]
148
+ if os.path.exists(pf):
149
+ unlock(HELD)
150
+ continue
151
+ rng = np.random.default_rng([a.seed, ti])
152
+ y = P["Yt"][:, P["traits"].index(t)]
153
+ ok = np.where(np.isfinite(y))[0]
154
+ rec = {}
155
+ # linkage-score regression on naive chi^2
156
+ b, se, p = ols_scan(y[ok], G[ok], X[ok])
157
+ chi = (b / se) ** 2
158
+ m = np.isfinite(chi)
159
+ sl, ic, rr, pp, _ = stats.linregress(lscore[m], chi[m])
160
+ rec["linkage_score_regression_naive"] = {"slope": sl, "intercept": ic, "r": rr}
161
+ # REML per block once (MM-fd null)
162
+ vcs, Vs = {}, {}
163
+ for bk in sorted(set(blk)):
164
+ Kf = P["K_func"] if bk == -1 else Kf_blocks[bk]
165
+ Ks = [Kf[np.ix_(ok, ok)] + 1e-6 * np.eye(len(ok)), Kd[np.ix_(ok, ok)] + 1e-6 * np.eye(len(ok))]
166
+ vcs[bk], Vs[bk], _ = reml(y[ok], X[ok], Ks)
167
+ # family-block bootstrap of lambda_GC
168
+ lam = {"naive": [], "mm_fd": []}
169
+ okset = set(ok.tolist())
170
+ for _ in range(a.n_boot):
171
+ rows = np.array([i for f in rng.choice(len(fl), len(fl)) for i in fams[fl[f]] if i in okset])
172
+ lam["naive"].append(lambda_gc(ols_scan(y[rows], G[rows], X[rows])[2]))
173
+ pv = np.full(G.shape[1], np.nan)
174
+ for bk, vc in vcs.items():
175
+ cols = np.where(blk == bk)[0]
176
+ Kf = P["K_func"] if bk == -1 else Kf_blocks[bk]
177
+ V = vc[0] * Kf[np.ix_(rows, rows)] + vc[1] * Kd[np.ix_(rows, rows)] + (vc[2] + 1e-6 * vc[:2].sum()) * np.eye(len(rows))
178
+ pv[cols] = gls_scan(y[rows], G[np.ix_(rows, cols)], X[rows], V)[2]
179
+ lam["mm_fd"].append(lambda_gc(pv))
180
+ rec["lambda_gc_boot_ci95"] = {k: np.percentile(v, [2.5, 97.5]).tolist() for k, v in lam.items()}
181
+ # module kernel score tests
182
+ mt = {}
183
+ for mi, k in enumerate(mods):
184
+ bk = blocks_of(k)
185
+ Km = cosine(np.asarray(ge[mi])[np.ix_(keep, keep)] + 1e-12 * np.eye(n))[np.ix_(ok, ok)]
186
+ mt[k] = score_test(y[ok], X[ok], Vs[bk], Km)
187
+ pm = np.array([v[1] for v in mt.values()])
188
+ sig = [k for k, s in zip(mt, bh(pm)) if s]
189
+ rec["module_tests"] = {"n_modules": len(mt), "n_sig_fdr": len(sig), "sig": sig,
190
+ "p": {k: v[1] for k, v in mt.items()}}
191
+ # SuSiE in significant modules and same-layer neighbours, on the whitened residual (MM-fd, full-kernel null)
192
+ fm = []
193
+ for k in sig:
194
+ layer = k.split(".")[0]
195
+ cols = [j for j, l in enumerate(P["loci"]) if l["module"].split(".")[0] == layer]
196
+ bk = blocks_of(k)
197
+ Lc = np.linalg.cholesky(Vs[bk])
198
+ Xw = np.linalg.solve(Lc, basis(X[ok]))
199
+ yw = np.linalg.solve(Lc, y[ok])
200
+ Gw = np.linalg.solve(Lc, G[np.ix_(ok, cols)])
201
+ res_y = yw - Xw @ np.linalg.lstsq(Xw, yw, rcond=None)[0]
202
+ res_G = Gw - Xw @ np.linalg.lstsq(Xw, Gw, rcond=None)[0]
203
+ pip, cs = susie(res_G, res_y)
204
+ fm.append({"module": k, "loci": cols, "top_pip": float(pip.max()),
205
+ "credible_sets": [{**c, "members": [cols[j] for j in c["members"]]} for c in cs]})
206
+ rec["susie"] = fm
207
+ json.dump(rec, open(pf + ".tmp", "w"), indent=1, default=float)
208
+ os.replace(pf + ".tmp", pf)
209
+ unlock(HELD)
210
+ print(t, "lsr intercept", round(ic, 2), "sig modules", len(sig), "lambda CI", rec["lambda_gc_boot_ci95"], flush=True)
211
+ if all(os.path.exists(os.path.join(pd, t + ".json")) for t in prim):
212
+ out = {"traits": {t: json.load(open(os.path.join(pd, t + ".json"))) for t in prim}, "seed": a.seed,
213
+ "n_boot": a.n_boot, "rng": "per trait: default_rng([seed, trait index])"}
214
+ json.dump(out, open(a.out, "w"), indent=1, default=float)
215
+ print("EXTRASDONE", flush=True)
216
+ else:
217
+ print("EXTRAS_PARTIAL", sum(os.path.exists(os.path.join(pd, t + ".json")) for t in prim), "/", len(prim), flush=True)
218
+
219
+
220
+ if __name__ == "__main__":
221
+ try:
222
+ main()
223
+ finally:
224
+ unlock(HELD)
code/src/analysis/scan_report.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Text summary of a scan directory: population sizes, lambda_GC and hit counts per estimator, null diagnostics,
3
+ descent variance share (python src/analysis/scan_report.py [scan_dir])."""
4
+ import sys
5
+ import json, numpy as np
6
+ S = json.load(open((sys.argv[1] if len(sys.argv) > 1 else "results/scans/qwen05") + "/summary.json"))
7
+ print({k: S[k] for k in ("n", "n_loci", "M_eff", "bonferroni_p", "n_eff_desc", "n_eff_func", "n_desc_families", "n_recipe_families", "share_with_relative", "split_sizes")})
8
+ E = ["naive", "pc", "mm_f", "mm_fd", "wf_d", "wf_r", "dup_afe"]
9
+ T = S["traits"]
10
+ prim = [t for t in T if not t.startswith("__")]
11
+ for t in [x for x in T if x.startswith("__")]:
12
+ print(t, {e: round(T[t]["lambda_gc"][e], 2) for e in E}, "bonf", T[t]["hits_bonf_full"], "fdrD", T[t]["hits_fdr_D"])
13
+ lam = np.array([[T[t]["lambda_gc"][e] for e in E] for t in prim])
14
+ print("median lambda over", len(prim), "traits", dict(zip(E, np.round(np.median(lam, 0), 2))))
15
+ print("max lambda", dict(zip(E, np.round(lam.max(0), 2))), "min", dict(zip(E, np.round(lam.min(0), 2))))
16
+ print("traits with lambda_naive>1.1:", int((lam[:, 0] > 1.1).sum()))
17
+ hb = np.array([[T[t]["hits_bonf_full"][e] for e in E] for t in prim]); hf = np.array([[T[t]["hits_fdr_D"][e] for e in E] for t in prim])
18
+ print("total bonf hits", dict(zip(E, hb.sum(0))), "\ntotal fdr D hits", dict(zip(E, hf.sum(0))))
19
+ vd = []
20
+ for t in prim:
21
+ v = T[t]["variance_components_full"].get("mm_fd", {})
22
+ for b, c in v.items():
23
+ vd.append(c[1] / sum(c))
24
+ vd = np.array(vd); print("mm_fd descent VC share: median", np.median(vd).round(4), "share>0.01", (vd > 0.01).mean().round(3), "max", vd.max().round(3))
code/src/analysis/spikein.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License, Bryan Cheng, 2026.
2
+ """Spike-ins (RESEARCH_PLAN 10; E5): plan and analysis.
3
+
4
+ plan directions: the 4 opposite pairs (trained, 3 seeds per side), up to 8 validated loci (largest |z| of gamma_do,
5
+ distinct modules) and 4 random rank-4 directions (random modules with loci; seeds 0-3). Carrier designs per
6
+ seed 0-4: nested random sets of 1, 5 and 20 percent of the population and whole descent families (random order)
7
+ until >= 5 percent. Carriers to measure = union over seeds and designs.
8
+ analyze per direction, seed, design, dose: trait = ECDF-mapped change of the direction's target trait (primary trait
9
+ with the largest |effect| on the base at 1 SD) for carriers, 0 for non-carriers; carriers' genotypes shift by
10
+ dose x SD x the direction's projection on each locus. All scan_run.py estimators on the full set. True loci:
11
+ |projection| x SD / sigma_l >= 0.5. Discoveries at BH 0.05; precision, recall; bias of the implied effect
12
+ along the direction (sum over true loci of beta_l x projection_l) relative to the measured mean change per unit.
13
+
14
+ python src/analysis/spikein.py plan --geno ... --pheno ... --scan ... --calib ... --trained data/raw/trained/opposite
15
+ --adapters_dir ... --base ... --out results/spikein/plan_qwen05.json
16
+ python src/analysis/spikein.py analyze --geno ... --pheno ... --scan ... --plan ... --spike results/spikein/qwen05 --out x.json
17
+ """
18
+ import argparse
19
+ import json
20
+ import os
21
+ import sys
22
+ from multiprocessing import Pool
23
+
24
+ import numpy as np
25
+ import torch
26
+ from scipy import stats
27
+
28
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
29
+ from src.analysis.calibrate import ecdf_map # noqa: E402
30
+ from src.analysis.population import build # noqa: E402
31
+ from src.analysis.scan import bh # noqa: E402
32
+ from src.run.scan_run import EST, blocks_of, cosine, run_estimators # noqa: E402
33
+
34
+ OPP = [("french", "english"), ("concise", "long"), ("markdown", "plain"), ("formal", "casual")]
35
+ W = {}
36
+
37
+
38
+ def carrier_sets(names, fam_d, seed):
39
+ rng = np.random.default_rng(seed)
40
+ n = len(names)
41
+ perm = rng.permutation(n)
42
+ sets = {f"rand{p}": sorted(perm[: max(1, int(round(n * p / 100)))].tolist()) for p in (1, 5, 20)}
43
+ fams = rng.permutation(np.unique(fam_d))
44
+ fs = []
45
+ for f in fams:
46
+ if len(fs) >= 0.05 * n:
47
+ break
48
+ fs += np.where(fam_d == f)[0].tolist()
49
+ sets["families"] = sorted(fs)
50
+ return sets
51
+
52
+
53
+ def job(args):
54
+ did, seed, design, dose = args
55
+ w = W
56
+ car = np.array(w["sets"][seed][design])
57
+ tr = w["target"][did]
58
+ y = np.zeros(w["n"])
59
+ ok = np.ones(len(car), bool)
60
+ for k, i in enumerate(car):
61
+ rec = w["meas"][did].get(w["names"][i])
62
+ if rec is None:
63
+ ok[k] = False
64
+ continue
65
+ y[i] = w["maps"][tr](rec[str(dose)][tr][0]) - w["maps"][tr](rec["0.0"][tr][0])
66
+ car = car[ok]
67
+ G = w["G"].copy()
68
+ s = dose * w["sigma"][did]
69
+ G[car] += s * w["proj"][did][None]
70
+ G -= G.mean(0)
71
+ idx = np.arange(w["n"])
72
+ res = run_estimators(y, G, w["X"], w["Kfb"], w["Kf"], w["Kd"], w["fam_d"], w["fam_r"], w["authors"], w["blk"],
73
+ w["pcs"], idx, {})
74
+ T = w["true"][did]
75
+ beta_true = y[car].mean() / s if len(car) else np.nan
76
+ out = {"direction": did, "seed": seed, "design": design, "dose": dose, "n_carriers": int(len(car)), "n_true": int(T.sum())}
77
+ for e in EST:
78
+ b, se, p = res[e]
79
+ disc = bh(np.where(np.isfinite(p), p, 1.0))
80
+ tp = int((disc & T).sum())
81
+ out[e] = {"n_disc": int(disc.sum()), "precision": tp / disc.sum() if disc.sum() else np.nan,
82
+ "recall": tp / T.sum() if T.sum() else np.nan,
83
+ "bias": float(np.nansum(b[T] * w["proj"][did][T]) / beta_true - 1) if T.sum() and beta_true != 0 else np.nan}
84
+ return out
85
+
86
+
87
+ def main():
88
+ ap = argparse.ArgumentParser()
89
+ ap.add_argument("cmd", choices=["plan", "analyze"])
90
+ for k in ("geno", "pheno", "scan", "out"):
91
+ ap.add_argument("--" + k, required=True)
92
+ for k in ("calib", "trained", "adapters_dir", "base", "plan", "spike"):
93
+ ap.add_argument("--" + k)
94
+ ap.add_argument("--workers", type=int, default=int(os.environ.get("SLURM_CPUS_PER_TASK", 4)))
95
+ ap.add_argument("--recipe_threshold", type=float, default=None,
96
+ help="plan 5.3 cut (D-039: 0.9361427475490963); WF-r uses recipe families. None = population fallback")
97
+ a = ap.parse_args()
98
+ if a.recipe_threshold is None:
99
+ print("WARNING: no --recipe_threshold; WF-r uses the population fallback cut, not plan 5.3 (D-039)", flush=True)
100
+ P = build(a.geno, a.pheno, recipe_threshold=a.recipe_threshold)
101
+ prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
102
+ names = P["names"]
103
+ if a.cmd == "plan":
104
+ dirs = [{"id": f"opp_{x}_vs_{y}", "kind": "opposite",
105
+ "side_a": [os.path.join(a.trained, f"opp_{x}_s{s}") for s in range(3)],
106
+ "side_b": [os.path.join(a.trained, f"opp_{y}_s{s}") for s in range(3)]} for x, y in OPP]
107
+ if a.calib and os.path.exists(a.calib):
108
+ C = json.load(open(a.calib))["per_direction"]
109
+ rows = []
110
+ for v in C.values():
111
+ if v["kind"] == "locus" and v.get("source"):
112
+ z = max(abs(v["traits"][t]["gamma_do"]) / np.sqrt(max(v["traits"][t]["var_do"], 1e-300)) for t in prim)
113
+ rows.append((z, v["module"], v["l"]))
114
+ used = set()
115
+ for z, m, l in sorted(rows, reverse=True):
116
+ if m not in used and z > stats.norm.isf(0.025) and len(used) < 8:
117
+ used.add(m)
118
+ dirs.append({"id": f"loc_{m}_{l}", "kind": "locus", "module": m, "l": l})
119
+ loci = json.load(open(os.path.join(a.scan, "loci.json")))
120
+ mods = sorted({l["module"] for l in loci if not l["module"].startswith("presence")})
121
+ rng = np.random.default_rng(0)
122
+ for s in range(4):
123
+ dirs.append({"id": f"rnd_{s}", "kind": "random", "module": str(rng.choice(mods)), "seed": 9000 + s})
124
+ sets = {s: carrier_sets(names, P["fam_d"], s) for s in range(5)}
125
+ union = sorted({names[i] for st in sets.values() for v in st.values() for i in v})
126
+ plan = {"base": a.base, "adapters_dir": a.adapters_dir, "geno_dir": a.geno, "doses": [0.5, 1.0, 2.0],
127
+ "directions": dirs, "carriers": union, "sets": {str(k): v for k, v in sets.items()}}
128
+ json.dump(plan, open(a.out, "w"), indent=1)
129
+ print("directions", len(dirs), "carriers", len(union), flush=True)
130
+ return
131
+ plan = json.load(open(a.plan))
132
+ n = len(names)
133
+ A = json.load(open(os.path.join(a.geno, "adapters.json")))
134
+ keep = np.array([x in set(names) for x in A["names"]])
135
+ mods = json.load(open(os.path.join(a.geno, "modules.json")))
136
+ ge = np.load(os.path.join(a.geno, "grams_exp.npy"), mmap_mode="r")
137
+ Sb = np.zeros((8, n, n))
138
+ for mi, k in enumerate(mods):
139
+ Sb[blocks_of(k)] += np.asarray(ge[mi])[np.ix_(keep, keep)]
140
+ S = Sb.sum(0)
141
+ lociL = torch.load(os.path.join(a.geno, "loci.pt"))
142
+ W.update({"n": n, "names": names, "G": P["G"], "X": P["X"], "Kfb": [cosine(S - Sb[b]) for b in range(8)],
143
+ "Kf": P["K_func"], "Kd": P["K_desc"], "fam_d": P["fam_d"], "fam_r": P["fam_r"], "authors": P["authors"],
144
+ "blk": np.array([blocks_of(l["module"]) for l in P["loci"]]),
145
+ "pcs": np.linalg.eigh(P["K_func"])[1][:, ::-1][:, :10],
146
+ "maps": {t: ecdf_map(P["Y"][0, :, P["traits"].index(t)])[0] for t in prim},
147
+ "sets": {int(k): v for k, v in plan["sets"].items()}, "meas": {}, "proj": {}, "sigma": {}, "target": {}, "true": {}})
148
+ sig_l = np.array([l["sigma"] for l in P["loci"]])
149
+ jobs = []
150
+ for d in plan["directions"]:
151
+ od = os.path.join(a.spike, d["id"])
152
+ if not os.path.exists(os.path.join(od, "direction.npz")):
153
+ continue
154
+ z = np.load(os.path.join(od, "direction.npz"))
155
+ pr = np.zeros(len(P["loci"]))
156
+ for j, l in enumerate(P["loci"]):
157
+ if l["module"].startswith("presence"):
158
+ continue
159
+ lo = lociL[l["module"]]
160
+ pr[j] = float(z["proj"][mods.index(l["module"])] @ lo["U"][:, l["l"]].double().numpy() / np.sqrt(float(lo["lam"][l["l"]])))
161
+ meas = {}
162
+ for x in names + ["__base__"]:
163
+ f = os.path.join(od, f"{x}.json")
164
+ if os.path.exists(f):
165
+ meas[x] = json.load(open(f))["doses"]
166
+ if "__base__" not in meas:
167
+ continue
168
+ bse = meas["__base__"]
169
+ tr = max(prim, key=lambda t: abs(W["maps"][t](bse["1.0"][t][0]) - W["maps"][t](bse["0.0"][t][0])))
170
+ tf = os.path.join(od, "target.json") # target-only runs (D-032) fix the target at measurement time
171
+ if os.path.exists(tf):
172
+ tr_run = json.load(open(tf))["target"]
173
+ W.setdefault("target_mismatch", {})[d["id"]] = tr_run != tr
174
+ tr = tr_run
175
+ W["meas"][d["id"]], W["proj"][d["id"]], W["sigma"][d["id"]], W["target"][d["id"]] = meas, pr, float(z["sigma"]), tr
176
+ W["true"][d["id"]] = np.abs(pr) * float(z["sigma"]) / np.maximum(sig_l, 1e-300) >= 0.5
177
+ jobs += [(d["id"], s, ds, dose) for s in range(5) for ds in ("rand1", "rand5", "rand20", "families") for dose in plan["doses"]]
178
+ with Pool(a.workers) as pool:
179
+ rows = pool.map(job, jobs)
180
+ summ = {}
181
+ for kind in ("opposite", "locus", "random"):
182
+ for ds in ("rand1", "rand5", "rand20", "families"):
183
+ rr = [r for r in rows if r["direction"].startswith(kind[:3]) and r["design"] == ds]
184
+ if rr:
185
+ summ[f"{kind}:{ds}"] = {e: {m: float(np.nanmean([r[e][m] for r in rr])) for m in ("precision", "recall", "bias")}
186
+ for e in EST}
187
+ json.dump({"summary": summ, "rows": rows, "targets": W["target"], "target_mismatch": W.get("target_mismatch", {})}, open(a.out, "w"), indent=1, default=float)
188
+ print(json.dumps(summ, default=float)[:3000], flush=True)
189
+
190
+
191
+ if __name__ == "__main__":
192
+ main()
code/src/lorapop/__init__.py ADDED
File without changes