LJYAI commited on
Commit
4ec314f
·
verified ·
1 Parent(s): 25c2a4b

Native MKA Llama Base MLP-only FiT batch1

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_01_fit.json +256 -0
  2. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_02_fit.json +256 -0
  3. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_03_fit.json +256 -0
  4. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_04_fit.json +256 -0
  5. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_05_fit.json +256 -0
  6. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_06_fit.json +256 -0
  7. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_07_fit.json +256 -0
  8. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_08_fit.json +256 -0
  9. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/data_fingerprints.json +14 -0
  10. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/selection.json +0 -0
  11. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/selection_inputs.json +10 -0
  12. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/batch_profile.json +82 -0
  13. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/abprune_compact.py +284 -0
  14. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/bootstrap_llama31_come_fit2.sh +52 -0
  15. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/collect_mka_batch_comparison.py +66 -0
  16. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/come.py +612 -0
  17. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/eval_llama31_8b_12bench.py +194 -0
  18. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/eval_llama31_fit_ablation_one.sh +63 -0
  19. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/evaluate_abprune_compact_ppl.py +187 -0
  20. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/evaluate_hchc_wikitext2_ppl.py +152 -0
  21. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/finalize_mka_batch_report.py +218 -0
  22. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/fit_ablation_come.py +54 -0
  23. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/fit_ablation_mka.py +482 -0
  24. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/fuse_layers.py +0 -0
  25. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/fuse_layers_distill.py +0 -0
  26. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/launch_llama31_come_fit2.sh +123 -0
  27. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/launch_mka_batch_comparison.py +268 -0
  28. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/mka.py +505 -0
  29. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/offline_eval_policy.py +26 -0
  30. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/package_final_fit_backup.py +60 -0
  31. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/prepare_lmeval9_local_cache.py +108 -0
  32. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/prepare_mka_batch_calibration.py +108 -0
  33. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/prepare_offline_ppl_cache.py +30 -0
  34. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/project_commit.txt +1 -0
  35. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/run_external_abprune_instruct_order.py +140 -0
  36. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/run_llama31_base_fit_ablation.py +869 -0
  37. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/run_llama31_come_fit_arm.sh +37 -0
  38. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/run_mka_batch_arm.sh +28 -0
  39. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/source_feature_transport.py +342 -0
  40. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/validate_mka_first_selection.py +57 -0
  41. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/validate_mka_runtime_geometry.py +174 -0
  42. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/compact/stage_08/layer_original_0010.pt +3 -0
  43. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/compact/stage_08/layer_original_0018.pt +3 -0
  44. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/compact/stage_08/layer_original_0021.pt +3 -0
  45. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/compact/stage_08/layer_original_0023.pt +3 -0
  46. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/compact/stage_08/layer_original_0026.pt +3 -0
  47. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/compact/stage_08/metadata.json +98 -0
  48. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/eval/final_14bench.json +37 -0
  49. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/eval/final_lmeval9.json +1402 -0
  50. runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/eval/final_opencompass5.json +44 -0
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_01_fit.json ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "enabled": true,
3
+ "epochs": 1.0,
4
+ "requested_epochs": 1.0,
5
+ "skip_train": false,
6
+ "trained": true,
7
+ "lr": 0.0001,
8
+ "hidden_mse_weight": 1.0,
9
+ "attn_mse_weight": 0.0,
10
+ "mlp_mse_weight": 1.0,
11
+ "eta": 0.0,
12
+ "gamma": 0.0,
13
+ "attn_reg_scale": 1.0,
14
+ "mlp_reg_scale": 1.0,
15
+ "param_subset": "mlp",
16
+ "train_subset": "mlp",
17
+ "num_gates": 3,
18
+ "num_attn_gates": 0,
19
+ "num_mlp_gates": 3,
20
+ "num_other_gates": 0,
21
+ "num_trainable_attn_gates": 0,
22
+ "num_trainable_mlp_gates": 3,
23
+ "num_trainable_other_gates": 0,
24
+ "lambda_init_summary": {
25
+ "num_tensors": 3,
26
+ "num_elements": 3,
27
+ "mean": 0.6240300536155701,
28
+ "std": 0.0,
29
+ "min": 0.6240300536155701,
30
+ "max": 0.6240300536155701,
31
+ "mean_abs_from_0_5": 0.12403005361557007,
32
+ "per_tensor": {
33
+ "mlp.gate_proj.weight": {
34
+ "mean": 0.6240300536155701,
35
+ "std": 0.0,
36
+ "min": 0.6240300536155701,
37
+ "max": 0.6240300536155701,
38
+ "mean_abs_from_0_5": 0.12403005361557007
39
+ },
40
+ "mlp.up_proj.weight": {
41
+ "mean": 0.6240300536155701,
42
+ "std": 0.0,
43
+ "min": 0.6240300536155701,
44
+ "max": 0.6240300536155701,
45
+ "mean_abs_from_0_5": 0.12403005361557007
46
+ },
47
+ "mlp.down_proj.weight": {
48
+ "mean": 0.6240300536155701,
49
+ "std": 0.0,
50
+ "min": 0.6240300536155701,
51
+ "max": 0.6240300536155701,
52
+ "mean_abs_from_0_5": 0.12403005361557007
53
+ }
54
+ }
55
+ },
56
+ "lambda_final_summary": {
57
+ "num_tensors": 3,
58
+ "num_elements": 3,
59
+ "mean": 0.6240301132202148,
60
+ "std": 0.00011399101194493286,
61
+ "min": 0.6240301132202148,
62
+ "max": 0.6240301132202148,
63
+ "mean_abs_from_0_5": 0.12403011322021484,
64
+ "per_tensor": {
65
+ "mlp.gate_proj.weight": {
66
+ "mean": 0.6240301132202148,
67
+ "std": 0.00011399101194493286,
68
+ "min": 0.6240301132202148,
69
+ "max": 0.6240301132202148,
70
+ "mean_abs_from_0_5": 0.12403011322021484
71
+ },
72
+ "mlp.up_proj.weight": {
73
+ "mean": 0.6240301132202148,
74
+ "std": 0.00011399101194493286,
75
+ "min": 0.6240301132202148,
76
+ "max": 0.6240301132202148,
77
+ "mean_abs_from_0_5": 0.12403011322021484
78
+ },
79
+ "mlp.down_proj.weight": {
80
+ "mean": 0.6240301132202148,
81
+ "std": 0.00011399101194493286,
82
+ "min": 0.6240301132202148,
83
+ "max": 0.6240301132202148,
84
+ "mean_abs_from_0_5": 0.12403011322021484
85
+ }
86
+ }
87
+ },
88
+ "lambda_delta_from_init": {
89
+ "num_tensors": 3,
90
+ "num_elements": 3,
91
+ "mean_abs": 0.0,
92
+ "rms": 0.0,
93
+ "max_abs": 0.0,
94
+ "per_tensor": {
95
+ "mlp.gate_proj.weight": {
96
+ "mean_abs": 0.0,
97
+ "rms": 0.0,
98
+ "max_abs": 0.0
99
+ },
100
+ "mlp.up_proj.weight": {
101
+ "mean_abs": 0.0,
102
+ "rms": 0.0,
103
+ "max_abs": 0.0
104
+ },
105
+ "mlp.down_proj.weight": {
106
+ "mean_abs": 0.0,
107
+ "rms": 0.0,
108
+ "max_abs": 0.0
109
+ }
110
+ }
111
+ },
112
+ "first_grad_summary": {
113
+ "joint": {
114
+ "step": 1,
115
+ "phase": "joint",
116
+ "gate": {
117
+ "num_tensors": 3,
118
+ "num_tensors_without_grad": 3,
119
+ "num_elements": 0,
120
+ "l2": 0.0,
121
+ "mean_abs": null,
122
+ "max_abs": 0.0
123
+ },
124
+ "u": {
125
+ "num_tensors": 3,
126
+ "num_tensors_without_grad": 0,
127
+ "num_elements": 176160768,
128
+ "l2": 0.07090424919084783,
129
+ "mean_abs": 3.280336732998313e-06,
130
+ "max_abs": 0.0010373592376708984
131
+ },
132
+ "rho": {
133
+ "num_tensors": 0,
134
+ "num_tensors_without_grad": 0,
135
+ "num_elements": 0,
136
+ "l2": 0.0,
137
+ "mean_abs": null,
138
+ "max_abs": 0.0
139
+ }
140
+ }
141
+ },
142
+ "u_delta_summary": {
143
+ "num_tensors": 3,
144
+ "num_elements": 176160768,
145
+ "mean": 3.671569396872309e-06,
146
+ "std": 0.0021163119338189528,
147
+ "rms": 0.002116315118701927,
148
+ "mean_abs": 0.0016939347343785422,
149
+ "min": -0.027031200006604195,
150
+ "max": 0.027949713170528412,
151
+ "per_tensor": {
152
+ "mlp.gate_proj.weight": {
153
+ "mean": 1.074287242123059e-05,
154
+ "std": 0.0021362828880463285,
155
+ "rms": 0.0021363098995855964,
156
+ "mean_abs": 0.0017099047877958842,
157
+ "min": -0.027031200006604195,
158
+ "max": 0.027949713170528412
159
+ },
160
+ "mlp.up_proj.weight": {
161
+ "mean": 1.7228359995767407e-07,
162
+ "std": 0.0020713264127663646,
163
+ "rms": 0.0020713264199312513,
164
+ "mean_abs": 0.0016601820077214921,
165
+ "min": -0.022097114473581314,
166
+ "max": 0.02654845453798771
167
+ },
168
+ "mlp.down_proj.weight": {
169
+ "mean": 9.955216942866432e-08,
170
+ "std": 0.0021405970919478956,
171
+ "rms": 0.002140597094262818,
172
+ "mean_abs": 0.00171171740761825,
173
+ "min": -0.025797182694077492,
174
+ "max": 0.026696184650063515
175
+ }
176
+ }
177
+ },
178
+ "rho_objective": "none",
179
+ "rho_schedule": "joint",
180
+ "additive_u": true,
181
+ "rho_epochs": 0.0,
182
+ "rho_lr": null,
183
+ "rho_bounds": null,
184
+ "rho_after_phase": null,
185
+ "rho_final": {},
186
+ "u_fisher_orthogonality": {},
187
+ "runtime": {
188
+ "seconds": 265.45442260894924,
189
+ "dataset_tokens": 524288,
190
+ "tokens_per_second": 1975.0584482532736,
191
+ "batch_size": 1,
192
+ "batches_per_epoch": 512,
193
+ "grad_accumulation": 1,
194
+ "peak_allocated_bytes": 38916334592,
195
+ "peak_reserved_bytes": 40705720320,
196
+ "gpu_total_bytes": 85094825984,
197
+ "actual_forward_shapes": {
198
+ "teacher:1x1024": 512,
199
+ "student:1x1024": 512
200
+ }
201
+ },
202
+ "ablation": {
203
+ "lambda": 0.6240301169976673,
204
+ "endpoint_clamping": false,
205
+ "initial_u_nonzero": 0,
206
+ "merged_parameters": [
207
+ "mlp.gate_proj.weight",
208
+ "mlp.up_proj.weight",
209
+ "mlp.down_proj.weight"
210
+ ],
211
+ "parameterization": "W_initial + U_add",
212
+ "fisher_computed": false,
213
+ "fit_scope": "mlp",
214
+ "attention_initialization": "MKA_merge",
215
+ "norm_initialization": "anchor_Wa",
216
+ "norms_trainable": false,
217
+ "frozen_MKA_parameters": [
218
+ "self_attn.q_proj.weight",
219
+ "self_attn.k_proj.weight",
220
+ "self_attn.v_proj.weight",
221
+ "self_attn.o_proj.weight",
222
+ "input_layernorm.weight",
223
+ "post_attention_layernorm.weight"
224
+ ],
225
+ "frozen_attention_norm_expected_sha256": {
226
+ "self_attn.q_proj.weight": "4a1304ccf61920a97636331ade2fa8e57952e2592a59a3923abf20b5a1575c49",
227
+ "self_attn.k_proj.weight": "6710bf5362c49a99451481e33e0b3ce5e9cd9181d086d75a866e7f16b338c1e3",
228
+ "self_attn.v_proj.weight": "30b51dc5274bf74b3e6d4820f1b58e4aa9e2fe144a998c9fb9a5326d746d4e2f",
229
+ "self_attn.o_proj.weight": "d438bc8a8906f12fc134841c45241cf5847136143ba1f871b06c29b6eead7d34",
230
+ "input_layernorm.weight": "f856da6761e60707e41aac347e76b1e89f061b141683614d6d181ca7940c638c",
231
+ "post_attention_layernorm.weight": "392084c4b287c1be3dc86b898f84579f8145d981ccc71d02c85ae14a40da0e3f"
232
+ },
233
+ "frozen_attention_norm_before_sha256": {
234
+ "self_attn.q_proj.weight": "4a1304ccf61920a97636331ade2fa8e57952e2592a59a3923abf20b5a1575c49",
235
+ "self_attn.k_proj.weight": "6710bf5362c49a99451481e33e0b3ce5e9cd9181d086d75a866e7f16b338c1e3",
236
+ "self_attn.v_proj.weight": "30b51dc5274bf74b3e6d4820f1b58e4aa9e2fe144a998c9fb9a5326d746d4e2f",
237
+ "self_attn.o_proj.weight": "d438bc8a8906f12fc134841c45241cf5847136143ba1f871b06c29b6eead7d34",
238
+ "input_layernorm.weight": "f856da6761e60707e41aac347e76b1e89f061b141683614d6d181ca7940c638c",
239
+ "post_attention_layernorm.weight": "392084c4b287c1be3dc86b898f84579f8145d981ccc71d02c85ae14a40da0e3f"
240
+ },
241
+ "frozen_attention_norm_after_sha256": {
242
+ "self_attn.q_proj.weight": "4a1304ccf61920a97636331ade2fa8e57952e2592a59a3923abf20b5a1575c49",
243
+ "self_attn.k_proj.weight": "6710bf5362c49a99451481e33e0b3ce5e9cd9181d086d75a866e7f16b338c1e3",
244
+ "self_attn.v_proj.weight": "30b51dc5274bf74b3e6d4820f1b58e4aa9e2fe144a998c9fb9a5326d746d4e2f",
245
+ "self_attn.o_proj.weight": "d438bc8a8906f12fc134841c45241cf5847136143ba1f871b06c29b6eead7d34",
246
+ "input_layernorm.weight": "f856da6761e60707e41aac347e76b1e89f061b141683614d6d181ca7940c638c",
247
+ "post_attention_layernorm.weight": "392084c4b287c1be3dc86b898f84579f8145d981ccc71d02c85ae14a40da0e3f"
248
+ },
249
+ "frozen_attention_norm_unchanged": true,
250
+ "source_feature_transport": false,
251
+ "initializer": "mka",
252
+ "removed_count_per_cycle": 1,
253
+ "teacher_boundary_current_layer": 22,
254
+ "teacher_boundary_original_layer": 22
255
+ }
256
+ }
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_02_fit.json ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "enabled": true,
3
+ "epochs": 1.0,
4
+ "requested_epochs": 1.0,
5
+ "skip_train": false,
6
+ "trained": true,
7
+ "lr": 0.0001,
8
+ "hidden_mse_weight": 1.0,
9
+ "attn_mse_weight": 0.0,
10
+ "mlp_mse_weight": 1.0,
11
+ "eta": 0.0,
12
+ "gamma": 0.0,
13
+ "attn_reg_scale": 1.0,
14
+ "mlp_reg_scale": 1.0,
15
+ "param_subset": "mlp",
16
+ "train_subset": "mlp",
17
+ "num_gates": 3,
18
+ "num_attn_gates": 0,
19
+ "num_mlp_gates": 3,
20
+ "num_other_gates": 0,
21
+ "num_trainable_attn_gates": 0,
22
+ "num_trainable_mlp_gates": 3,
23
+ "num_trainable_other_gates": 0,
24
+ "lambda_init_summary": {
25
+ "num_tensors": 3,
26
+ "num_elements": 3,
27
+ "mean": 0.6239535212516785,
28
+ "std": 0.0,
29
+ "min": 0.6239535212516785,
30
+ "max": 0.6239535212516785,
31
+ "mean_abs_from_0_5": 0.12395352125167847,
32
+ "per_tensor": {
33
+ "mlp.gate_proj.weight": {
34
+ "mean": 0.6239535212516785,
35
+ "std": 0.0,
36
+ "min": 0.6239535212516785,
37
+ "max": 0.6239535212516785,
38
+ "mean_abs_from_0_5": 0.12395352125167847
39
+ },
40
+ "mlp.up_proj.weight": {
41
+ "mean": 0.6239535212516785,
42
+ "std": 0.0,
43
+ "min": 0.6239535212516785,
44
+ "max": 0.6239535212516785,
45
+ "mean_abs_from_0_5": 0.12395352125167847
46
+ },
47
+ "mlp.down_proj.weight": {
48
+ "mean": 0.6239535212516785,
49
+ "std": 0.0,
50
+ "min": 0.6239535212516785,
51
+ "max": 0.6239535212516785,
52
+ "mean_abs_from_0_5": 0.12395352125167847
53
+ }
54
+ }
55
+ },
56
+ "lambda_final_summary": {
57
+ "num_tensors": 3,
58
+ "num_elements": 3,
59
+ "mean": 0.6239535212516785,
60
+ "std": 0.0,
61
+ "min": 0.6239535212516785,
62
+ "max": 0.6239535212516785,
63
+ "mean_abs_from_0_5": 0.12395352125167847,
64
+ "per_tensor": {
65
+ "mlp.gate_proj.weight": {
66
+ "mean": 0.6239535212516785,
67
+ "std": 0.0,
68
+ "min": 0.6239535212516785,
69
+ "max": 0.6239535212516785,
70
+ "mean_abs_from_0_5": 0.12395352125167847
71
+ },
72
+ "mlp.up_proj.weight": {
73
+ "mean": 0.6239535212516785,
74
+ "std": 0.0,
75
+ "min": 0.6239535212516785,
76
+ "max": 0.6239535212516785,
77
+ "mean_abs_from_0_5": 0.12395352125167847
78
+ },
79
+ "mlp.down_proj.weight": {
80
+ "mean": 0.6239535212516785,
81
+ "std": 0.0,
82
+ "min": 0.6239535212516785,
83
+ "max": 0.6239535212516785,
84
+ "mean_abs_from_0_5": 0.12395352125167847
85
+ }
86
+ }
87
+ },
88
+ "lambda_delta_from_init": {
89
+ "num_tensors": 3,
90
+ "num_elements": 3,
91
+ "mean_abs": 0.0,
92
+ "rms": 0.0,
93
+ "max_abs": 0.0,
94
+ "per_tensor": {
95
+ "mlp.gate_proj.weight": {
96
+ "mean_abs": 0.0,
97
+ "rms": 0.0,
98
+ "max_abs": 0.0
99
+ },
100
+ "mlp.up_proj.weight": {
101
+ "mean_abs": 0.0,
102
+ "rms": 0.0,
103
+ "max_abs": 0.0
104
+ },
105
+ "mlp.down_proj.weight": {
106
+ "mean_abs": 0.0,
107
+ "rms": 0.0,
108
+ "max_abs": 0.0
109
+ }
110
+ }
111
+ },
112
+ "first_grad_summary": {
113
+ "joint": {
114
+ "step": 1,
115
+ "phase": "joint",
116
+ "gate": {
117
+ "num_tensors": 3,
118
+ "num_tensors_without_grad": 3,
119
+ "num_elements": 0,
120
+ "l2": 0.0,
121
+ "mean_abs": null,
122
+ "max_abs": 0.0
123
+ },
124
+ "u": {
125
+ "num_tensors": 3,
126
+ "num_tensors_without_grad": 0,
127
+ "num_elements": 176160768,
128
+ "l2": 0.025573986383354865,
129
+ "mean_abs": 6.011936951229776e-07,
130
+ "max_abs": 0.005155682563781738
131
+ },
132
+ "rho": {
133
+ "num_tensors": 0,
134
+ "num_tensors_without_grad": 0,
135
+ "num_elements": 0,
136
+ "l2": 0.0,
137
+ "mean_abs": null,
138
+ "max_abs": 0.0
139
+ }
140
+ }
141
+ },
142
+ "u_delta_summary": {
143
+ "num_tensors": 3,
144
+ "num_elements": 176160768,
145
+ "mean": 1.2063732399491572e-06,
146
+ "std": 0.002185601732405863,
147
+ "rms": 0.0021856020653430726,
148
+ "mean_abs": 0.0017307128402448836,
149
+ "min": -0.035907041281461716,
150
+ "max": 0.03141474351286888,
151
+ "per_tensor": {
152
+ "mlp.gate_proj.weight": {
153
+ "mean": 3.4483681312329802e-06,
154
+ "std": 0.0022464659936055954,
155
+ "rms": 0.0022464686402594502,
156
+ "mean_abs": 0.001783097961119243,
157
+ "min": -0.030953383073210716,
158
+ "max": 0.03141474351286888
159
+ },
160
+ "mlp.up_proj.weight": {
161
+ "mean": -2.771454481782192e-07,
162
+ "std": 0.002113365014379343,
163
+ "rms": 0.0021133650325516886,
164
+ "mean_abs": 0.0016748620463269098,
165
+ "min": -0.0330694280564785,
166
+ "max": 0.02791440486907959
167
+ },
168
+ "mlp.down_proj.weight": {
169
+ "mean": 4.478970367927104e-07,
170
+ "std": 0.0021949113537914496,
171
+ "rms": 0.0021949113994907334,
172
+ "mean_abs": 0.001734178513288498,
173
+ "min": -0.035907041281461716,
174
+ "max": 0.030650388449430466
175
+ }
176
+ }
177
+ },
178
+ "rho_objective": "none",
179
+ "rho_schedule": "joint",
180
+ "additive_u": true,
181
+ "rho_epochs": 0.0,
182
+ "rho_lr": null,
183
+ "rho_bounds": null,
184
+ "rho_after_phase": null,
185
+ "rho_final": {},
186
+ "u_fisher_orthogonality": {},
187
+ "runtime": {
188
+ "seconds": 258.9080006470904,
189
+ "dataset_tokens": 524288,
190
+ "tokens_per_second": 2024.9972912758344,
191
+ "batch_size": 1,
192
+ "batches_per_epoch": 512,
193
+ "grad_accumulation": 1,
194
+ "peak_allocated_bytes": 38329381376,
195
+ "peak_reserved_bytes": 51063554048,
196
+ "gpu_total_bytes": 85094825984,
197
+ "actual_forward_shapes": {
198
+ "teacher:1x1024": 512,
199
+ "student:1x1024": 512
200
+ }
201
+ },
202
+ "ablation": {
203
+ "lambda": 0.6239535078432399,
204
+ "endpoint_clamping": false,
205
+ "initial_u_nonzero": 0,
206
+ "merged_parameters": [
207
+ "mlp.gate_proj.weight",
208
+ "mlp.up_proj.weight",
209
+ "mlp.down_proj.weight"
210
+ ],
211
+ "parameterization": "W_initial + U_add",
212
+ "fisher_computed": false,
213
+ "fit_scope": "mlp",
214
+ "attention_initialization": "MKA_merge",
215
+ "norm_initialization": "anchor_Wa",
216
+ "norms_trainable": false,
217
+ "frozen_MKA_parameters": [
218
+ "self_attn.q_proj.weight",
219
+ "self_attn.k_proj.weight",
220
+ "self_attn.v_proj.weight",
221
+ "self_attn.o_proj.weight",
222
+ "input_layernorm.weight",
223
+ "post_attention_layernorm.weight"
224
+ ],
225
+ "frozen_attention_norm_expected_sha256": {
226
+ "self_attn.q_proj.weight": "f709ca0a962e7eae7c133eb4bf36c4673b6fb7b9e1044e2aba54e4fb04bc91eb",
227
+ "self_attn.k_proj.weight": "928fbc8422b84a889d9c32aecd5775ff7ad62bd1e2ed9190bca99a4de1312ffd",
228
+ "self_attn.v_proj.weight": "7008b0949c8b95f60376e2e137435a60d9e4a4fc34f3d148b0c875dc8cb32132",
229
+ "self_attn.o_proj.weight": "f5eb7153ad242efe732e0d5de0aebc09f35752fd2622803a1b568561b1a40676",
230
+ "input_layernorm.weight": "2e51ae768cf6bf12d1903474b16741c383154686c8da264bfb44713bacaa0621",
231
+ "post_attention_layernorm.weight": "b3191d2dd3776ffff6f3dc74aebe2ddd40c82210ceba22c221eff83b1aeb1f95"
232
+ },
233
+ "frozen_attention_norm_before_sha256": {
234
+ "self_attn.q_proj.weight": "f709ca0a962e7eae7c133eb4bf36c4673b6fb7b9e1044e2aba54e4fb04bc91eb",
235
+ "self_attn.k_proj.weight": "928fbc8422b84a889d9c32aecd5775ff7ad62bd1e2ed9190bca99a4de1312ffd",
236
+ "self_attn.v_proj.weight": "7008b0949c8b95f60376e2e137435a60d9e4a4fc34f3d148b0c875dc8cb32132",
237
+ "self_attn.o_proj.weight": "f5eb7153ad242efe732e0d5de0aebc09f35752fd2622803a1b568561b1a40676",
238
+ "input_layernorm.weight": "2e51ae768cf6bf12d1903474b16741c383154686c8da264bfb44713bacaa0621",
239
+ "post_attention_layernorm.weight": "b3191d2dd3776ffff6f3dc74aebe2ddd40c82210ceba22c221eff83b1aeb1f95"
240
+ },
241
+ "frozen_attention_norm_after_sha256": {
242
+ "self_attn.q_proj.weight": "f709ca0a962e7eae7c133eb4bf36c4673b6fb7b9e1044e2aba54e4fb04bc91eb",
243
+ "self_attn.k_proj.weight": "928fbc8422b84a889d9c32aecd5775ff7ad62bd1e2ed9190bca99a4de1312ffd",
244
+ "self_attn.v_proj.weight": "7008b0949c8b95f60376e2e137435a60d9e4a4fc34f3d148b0c875dc8cb32132",
245
+ "self_attn.o_proj.weight": "f5eb7153ad242efe732e0d5de0aebc09f35752fd2622803a1b568561b1a40676",
246
+ "input_layernorm.weight": "2e51ae768cf6bf12d1903474b16741c383154686c8da264bfb44713bacaa0621",
247
+ "post_attention_layernorm.weight": "b3191d2dd3776ffff6f3dc74aebe2ddd40c82210ceba22c221eff83b1aeb1f95"
248
+ },
249
+ "frozen_attention_norm_unchanged": true,
250
+ "source_feature_transport": false,
251
+ "initializer": "mka",
252
+ "removed_count_per_cycle": 1,
253
+ "teacher_boundary_current_layer": 19,
254
+ "teacher_boundary_original_layer": 19
255
+ }
256
+ }
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_03_fit.json ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "enabled": true,
3
+ "epochs": 1.0,
4
+ "requested_epochs": 1.0,
5
+ "skip_train": false,
6
+ "trained": true,
7
+ "lr": 0.0001,
8
+ "hidden_mse_weight": 1.0,
9
+ "attn_mse_weight": 0.0,
10
+ "mlp_mse_weight": 1.0,
11
+ "eta": 0.0,
12
+ "gamma": 0.0,
13
+ "attn_reg_scale": 1.0,
14
+ "mlp_reg_scale": 1.0,
15
+ "param_subset": "mlp",
16
+ "train_subset": "mlp",
17
+ "num_gates": 3,
18
+ "num_attn_gates": 0,
19
+ "num_mlp_gates": 3,
20
+ "num_other_gates": 0,
21
+ "num_trainable_attn_gates": 0,
22
+ "num_trainable_mlp_gates": 3,
23
+ "num_trainable_other_gates": 0,
24
+ "lambda_init_summary": {
25
+ "num_tensors": 3,
26
+ "num_elements": 3,
27
+ "mean": 0.6236124038696289,
28
+ "std": 0.00010829558707242834,
29
+ "min": 0.6236124038696289,
30
+ "max": 0.6236124038696289,
31
+ "mean_abs_from_0_5": 0.1236124038696289,
32
+ "per_tensor": {
33
+ "mlp.gate_proj.weight": {
34
+ "mean": 0.6236124038696289,
35
+ "std": 0.00010829558707242834,
36
+ "min": 0.6236124038696289,
37
+ "max": 0.6236124038696289,
38
+ "mean_abs_from_0_5": 0.1236124038696289
39
+ },
40
+ "mlp.up_proj.weight": {
41
+ "mean": 0.6236124038696289,
42
+ "std": 0.00010829558707242834,
43
+ "min": 0.6236124038696289,
44
+ "max": 0.6236124038696289,
45
+ "mean_abs_from_0_5": 0.1236124038696289
46
+ },
47
+ "mlp.down_proj.weight": {
48
+ "mean": 0.6236124038696289,
49
+ "std": 0.00010829558707242834,
50
+ "min": 0.6236124038696289,
51
+ "max": 0.6236124038696289,
52
+ "mean_abs_from_0_5": 0.1236124038696289
53
+ }
54
+ }
55
+ },
56
+ "lambda_final_summary": {
57
+ "num_tensors": 3,
58
+ "num_elements": 3,
59
+ "mean": 0.6236124038696289,
60
+ "std": 0.00010829558707242834,
61
+ "min": 0.6236124038696289,
62
+ "max": 0.6236124038696289,
63
+ "mean_abs_from_0_5": 0.1236124038696289,
64
+ "per_tensor": {
65
+ "mlp.gate_proj.weight": {
66
+ "mean": 0.6236124038696289,
67
+ "std": 0.00010829558707242834,
68
+ "min": 0.6236124038696289,
69
+ "max": 0.6236124038696289,
70
+ "mean_abs_from_0_5": 0.1236124038696289
71
+ },
72
+ "mlp.up_proj.weight": {
73
+ "mean": 0.6236124038696289,
74
+ "std": 0.00010829558707242834,
75
+ "min": 0.6236124038696289,
76
+ "max": 0.6236124038696289,
77
+ "mean_abs_from_0_5": 0.1236124038696289
78
+ },
79
+ "mlp.down_proj.weight": {
80
+ "mean": 0.6236124038696289,
81
+ "std": 0.00010829558707242834,
82
+ "min": 0.6236124038696289,
83
+ "max": 0.6236124038696289,
84
+ "mean_abs_from_0_5": 0.1236124038696289
85
+ }
86
+ }
87
+ },
88
+ "lambda_delta_from_init": {
89
+ "num_tensors": 3,
90
+ "num_elements": 3,
91
+ "mean_abs": 0.0,
92
+ "rms": 0.0,
93
+ "max_abs": 0.0,
94
+ "per_tensor": {
95
+ "mlp.gate_proj.weight": {
96
+ "mean_abs": 0.0,
97
+ "rms": 0.0,
98
+ "max_abs": 0.0
99
+ },
100
+ "mlp.up_proj.weight": {
101
+ "mean_abs": 0.0,
102
+ "rms": 0.0,
103
+ "max_abs": 0.0
104
+ },
105
+ "mlp.down_proj.weight": {
106
+ "mean_abs": 0.0,
107
+ "rms": 0.0,
108
+ "max_abs": 0.0
109
+ }
110
+ }
111
+ },
112
+ "first_grad_summary": {
113
+ "joint": {
114
+ "step": 1,
115
+ "phase": "joint",
116
+ "gate": {
117
+ "num_tensors": 3,
118
+ "num_tensors_without_grad": 3,
119
+ "num_elements": 0,
120
+ "l2": 0.0,
121
+ "mean_abs": null,
122
+ "max_abs": 0.0
123
+ },
124
+ "u": {
125
+ "num_tensors": 3,
126
+ "num_tensors_without_grad": 0,
127
+ "num_elements": 176160768,
128
+ "l2": 0.04599066735713981,
129
+ "mean_abs": 1.1552578512020687e-06,
130
+ "max_abs": 0.007817268371582031
131
+ },
132
+ "rho": {
133
+ "num_tensors": 0,
134
+ "num_tensors_without_grad": 0,
135
+ "num_elements": 0,
136
+ "l2": 0.0,
137
+ "mean_abs": null,
138
+ "max_abs": 0.0
139
+ }
140
+ }
141
+ },
142
+ "u_delta_summary": {
143
+ "num_tensors": 3,
144
+ "num_elements": 176160768,
145
+ "mean": 3.35226394283728e-06,
146
+ "std": 0.0019707838773274557,
147
+ "rms": 0.00197078672839234,
148
+ "mean_abs": 0.0015529942299638475,
149
+ "min": -0.03118722513318062,
150
+ "max": 0.02375617064535618,
151
+ "per_tensor": {
152
+ "mlp.gate_proj.weight": {
153
+ "mean": 1.0493488974004452e-05,
154
+ "std": 0.001971187254034228,
155
+ "rms": 0.0019712151845442563,
156
+ "mean_abs": 0.0015550487275634492,
157
+ "min": -0.03118722513318062,
158
+ "max": 0.022198408842086792
159
+ },
160
+ "mlp.up_proj.weight": {
161
+ "mean": -2.129057910289183e-07,
162
+ "std": 0.0019124203300064184,
163
+ "rms": 0.0019124203418575986,
164
+ "mean_abs": 0.0015084812683718546,
165
+ "min": -0.024248087778687477,
166
+ "max": 0.02375617064535618
167
+ },
168
+ "mlp.down_proj.weight": {
169
+ "mean": -2.2379135446369348e-07,
170
+ "std": 0.0020270569968826716,
171
+ "rms": 0.0020270570092361896,
172
+ "mean_abs": 0.0015954526939562389,
173
+ "min": -0.02256276085972786,
174
+ "max": 0.023056089878082275
175
+ }
176
+ }
177
+ },
178
+ "rho_objective": "none",
179
+ "rho_schedule": "joint",
180
+ "additive_u": true,
181
+ "rho_epochs": 0.0,
182
+ "rho_lr": null,
183
+ "rho_bounds": null,
184
+ "rho_after_phase": null,
185
+ "rho_final": {},
186
+ "u_fisher_orthogonality": {},
187
+ "runtime": {
188
+ "seconds": 254.6957472008653,
189
+ "dataset_tokens": 524288,
190
+ "tokens_per_second": 2058.487453214212,
191
+ "batch_size": 1,
192
+ "batches_per_epoch": 512,
193
+ "grad_accumulation": 1,
194
+ "peak_allocated_bytes": 36885946880,
195
+ "peak_reserved_bytes": 49897537536,
196
+ "gpu_total_bytes": 85094825984,
197
+ "actual_forward_shapes": {
198
+ "teacher:1x1024": 512,
199
+ "student:1x1024": 512
200
+ }
201
+ },
202
+ "ablation": {
203
+ "lambda": 0.6236124286569557,
204
+ "endpoint_clamping": false,
205
+ "initial_u_nonzero": 0,
206
+ "merged_parameters": [
207
+ "mlp.gate_proj.weight",
208
+ "mlp.up_proj.weight",
209
+ "mlp.down_proj.weight"
210
+ ],
211
+ "parameterization": "W_initial + U_add",
212
+ "fisher_computed": false,
213
+ "fit_scope": "mlp",
214
+ "attention_initialization": "MKA_merge",
215
+ "norm_initialization": "anchor_Wa",
216
+ "norms_trainable": false,
217
+ "frozen_MKA_parameters": [
218
+ "self_attn.q_proj.weight",
219
+ "self_attn.k_proj.weight",
220
+ "self_attn.v_proj.weight",
221
+ "self_attn.o_proj.weight",
222
+ "input_layernorm.weight",
223
+ "post_attention_layernorm.weight"
224
+ ],
225
+ "frozen_attention_norm_expected_sha256": {
226
+ "self_attn.q_proj.weight": "81352cc5b420b73a8f85dfce88f4adbc11c2d7bf1e71e2eb1d5fbd29ec43ccb2",
227
+ "self_attn.k_proj.weight": "3cdf110456a36babbd5b0d31d2640615d9df7513f31f040b3b8c9202fbc2cd98",
228
+ "self_attn.v_proj.weight": "66fff30a6d517798d4bb4ad4d987b4bc787f2658e5abab84bb640cf518598f75",
229
+ "self_attn.o_proj.weight": "1619eda87f7aa3e3dbf4ece561180a4e05fa5bd38c7a4dbae29480ab6b8619ef",
230
+ "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7",
231
+ "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715"
232
+ },
233
+ "frozen_attention_norm_before_sha256": {
234
+ "self_attn.q_proj.weight": "81352cc5b420b73a8f85dfce88f4adbc11c2d7bf1e71e2eb1d5fbd29ec43ccb2",
235
+ "self_attn.k_proj.weight": "3cdf110456a36babbd5b0d31d2640615d9df7513f31f040b3b8c9202fbc2cd98",
236
+ "self_attn.v_proj.weight": "66fff30a6d517798d4bb4ad4d987b4bc787f2658e5abab84bb640cf518598f75",
237
+ "self_attn.o_proj.weight": "1619eda87f7aa3e3dbf4ece561180a4e05fa5bd38c7a4dbae29480ab6b8619ef",
238
+ "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7",
239
+ "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715"
240
+ },
241
+ "frozen_attention_norm_after_sha256": {
242
+ "self_attn.q_proj.weight": "81352cc5b420b73a8f85dfce88f4adbc11c2d7bf1e71e2eb1d5fbd29ec43ccb2",
243
+ "self_attn.k_proj.weight": "3cdf110456a36babbd5b0d31d2640615d9df7513f31f040b3b8c9202fbc2cd98",
244
+ "self_attn.v_proj.weight": "66fff30a6d517798d4bb4ad4d987b4bc787f2658e5abab84bb640cf518598f75",
245
+ "self_attn.o_proj.weight": "1619eda87f7aa3e3dbf4ece561180a4e05fa5bd38c7a4dbae29480ab6b8619ef",
246
+ "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7",
247
+ "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715"
248
+ },
249
+ "frozen_attention_norm_unchanged": true,
250
+ "source_feature_transport": false,
251
+ "initializer": "mka",
252
+ "removed_count_per_cycle": 1,
253
+ "teacher_boundary_current_layer": 22,
254
+ "teacher_boundary_original_layer": 24
255
+ }
256
+ }
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_04_fit.json ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "enabled": true,
3
+ "epochs": 1.0,
4
+ "requested_epochs": 1.0,
5
+ "skip_train": false,
6
+ "trained": true,
7
+ "lr": 0.0001,
8
+ "hidden_mse_weight": 1.0,
9
+ "attn_mse_weight": 0.0,
10
+ "mlp_mse_weight": 1.0,
11
+ "eta": 0.0,
12
+ "gamma": 0.0,
13
+ "attn_reg_scale": 1.0,
14
+ "mlp_reg_scale": 1.0,
15
+ "param_subset": "mlp",
16
+ "train_subset": "mlp",
17
+ "num_gates": 3,
18
+ "num_attn_gates": 0,
19
+ "num_mlp_gates": 3,
20
+ "num_other_gates": 0,
21
+ "num_trainable_attn_gates": 0,
22
+ "num_trainable_mlp_gates": 3,
23
+ "num_trainable_other_gates": 0,
24
+ "lambda_init_summary": {
25
+ "num_tensors": 3,
26
+ "num_elements": 3,
27
+ "mean": 0.6225138902664185,
28
+ "std": 0.0,
29
+ "min": 0.6225138902664185,
30
+ "max": 0.6225138902664185,
31
+ "mean_abs_from_0_5": 0.12251389026641846,
32
+ "per_tensor": {
33
+ "mlp.gate_proj.weight": {
34
+ "mean": 0.6225138902664185,
35
+ "std": 0.0,
36
+ "min": 0.6225138902664185,
37
+ "max": 0.6225138902664185,
38
+ "mean_abs_from_0_5": 0.12251389026641846
39
+ },
40
+ "mlp.up_proj.weight": {
41
+ "mean": 0.6225138902664185,
42
+ "std": 0.0,
43
+ "min": 0.6225138902664185,
44
+ "max": 0.6225138902664185,
45
+ "mean_abs_from_0_5": 0.12251389026641846
46
+ },
47
+ "mlp.down_proj.weight": {
48
+ "mean": 0.6225138902664185,
49
+ "std": 0.0,
50
+ "min": 0.6225138902664185,
51
+ "max": 0.6225138902664185,
52
+ "mean_abs_from_0_5": 0.12251389026641846
53
+ }
54
+ }
55
+ },
56
+ "lambda_final_summary": {
57
+ "num_tensors": 3,
58
+ "num_elements": 3,
59
+ "mean": 0.6225138902664185,
60
+ "std": 0.0,
61
+ "min": 0.6225138902664185,
62
+ "max": 0.6225138902664185,
63
+ "mean_abs_from_0_5": 0.12251389026641846,
64
+ "per_tensor": {
65
+ "mlp.gate_proj.weight": {
66
+ "mean": 0.6225138902664185,
67
+ "std": 0.0,
68
+ "min": 0.6225138902664185,
69
+ "max": 0.6225138902664185,
70
+ "mean_abs_from_0_5": 0.12251389026641846
71
+ },
72
+ "mlp.up_proj.weight": {
73
+ "mean": 0.6225138902664185,
74
+ "std": 0.0,
75
+ "min": 0.6225138902664185,
76
+ "max": 0.6225138902664185,
77
+ "mean_abs_from_0_5": 0.12251389026641846
78
+ },
79
+ "mlp.down_proj.weight": {
80
+ "mean": 0.6225138902664185,
81
+ "std": 0.0,
82
+ "min": 0.6225138902664185,
83
+ "max": 0.6225138902664185,
84
+ "mean_abs_from_0_5": 0.12251389026641846
85
+ }
86
+ }
87
+ },
88
+ "lambda_delta_from_init": {
89
+ "num_tensors": 3,
90
+ "num_elements": 3,
91
+ "mean_abs": 0.0,
92
+ "rms": 0.0,
93
+ "max_abs": 0.0,
94
+ "per_tensor": {
95
+ "mlp.gate_proj.weight": {
96
+ "mean_abs": 0.0,
97
+ "rms": 0.0,
98
+ "max_abs": 0.0
99
+ },
100
+ "mlp.up_proj.weight": {
101
+ "mean_abs": 0.0,
102
+ "rms": 0.0,
103
+ "max_abs": 0.0
104
+ },
105
+ "mlp.down_proj.weight": {
106
+ "mean_abs": 0.0,
107
+ "rms": 0.0,
108
+ "max_abs": 0.0
109
+ }
110
+ }
111
+ },
112
+ "first_grad_summary": {
113
+ "joint": {
114
+ "step": 1,
115
+ "phase": "joint",
116
+ "gate": {
117
+ "num_tensors": 3,
118
+ "num_tensors_without_grad": 3,
119
+ "num_elements": 0,
120
+ "l2": 0.0,
121
+ "mean_abs": null,
122
+ "max_abs": 0.0
123
+ },
124
+ "u": {
125
+ "num_tensors": 3,
126
+ "num_tensors_without_grad": 0,
127
+ "num_elements": 176160768,
128
+ "l2": 0.10121190556865976,
129
+ "mean_abs": 1.7872365398423945e-06,
130
+ "max_abs": 0.020038723945617676
131
+ },
132
+ "rho": {
133
+ "num_tensors": 0,
134
+ "num_tensors_without_grad": 0,
135
+ "num_elements": 0,
136
+ "l2": 0.0,
137
+ "mean_abs": null,
138
+ "max_abs": 0.0
139
+ }
140
+ }
141
+ },
142
+ "u_delta_summary": {
143
+ "num_tensors": 3,
144
+ "num_elements": 176160768,
145
+ "mean": 9.57356205400997e-07,
146
+ "std": 0.0020727978546810173,
147
+ "rms": 0.002072798075766458,
148
+ "mean_abs": 0.001623758026176975,
149
+ "min": -0.03150757774710655,
150
+ "max": 0.028904635459184647,
151
+ "per_tensor": {
152
+ "mlp.gate_proj.weight": {
153
+ "mean": 2.8221124271762425e-06,
154
+ "std": 0.0021090265075942123,
155
+ "rms": 0.002109028395743782,
156
+ "mean_abs": 0.0016554977212633406,
157
+ "min": -0.031088540330529213,
158
+ "max": 0.028904635459184647
159
+ },
160
+ "mlp.up_proj.weight": {
161
+ "mean": -6.691745316597267e-08,
162
+ "std": 0.002068883523215431,
163
+ "rms": 0.0020688835242976445,
164
+ "mean_abs": 0.0016271011637789862,
165
+ "min": -0.03150757774710655,
166
+ "max": 0.027144618332386017
167
+ },
168
+ "mlp.down_proj.weight": {
169
+ "mean": 1.168736421927211e-07,
170
+ "std": 0.0020399009201135516,
171
+ "rms": 0.0020399009234616182,
172
+ "mean_abs": 0.0015886751934885979,
173
+ "min": -0.023659130558371544,
174
+ "max": 0.019915008917450905
175
+ }
176
+ }
177
+ },
178
+ "rho_objective": "none",
179
+ "rho_schedule": "joint",
180
+ "additive_u": true,
181
+ "rho_epochs": 0.0,
182
+ "rho_lr": null,
183
+ "rho_bounds": null,
184
+ "rho_after_phase": null,
185
+ "rho_final": {},
186
+ "u_fisher_orthogonality": {},
187
+ "runtime": {
188
+ "seconds": 247.87098502134904,
189
+ "dataset_tokens": 524288,
190
+ "tokens_per_second": 2115.164870768732,
191
+ "batch_size": 1,
192
+ "batches_per_epoch": 512,
193
+ "grad_accumulation": 1,
194
+ "peak_allocated_bytes": 35442512384,
195
+ "peak_reserved_bytes": 48576331776,
196
+ "gpu_total_bytes": 85094825984,
197
+ "actual_forward_shapes": {
198
+ "teacher:1x1024": 512,
199
+ "student:1x1024": 512
200
+ }
201
+ },
202
+ "ablation": {
203
+ "lambda": 0.6225139171112987,
204
+ "endpoint_clamping": false,
205
+ "initial_u_nonzero": 0,
206
+ "merged_parameters": [
207
+ "mlp.gate_proj.weight",
208
+ "mlp.up_proj.weight",
209
+ "mlp.down_proj.weight"
210
+ ],
211
+ "parameterization": "W_initial + U_add",
212
+ "fisher_computed": false,
213
+ "fit_scope": "mlp",
214
+ "attention_initialization": "MKA_merge",
215
+ "norm_initialization": "anchor_Wa",
216
+ "norms_trainable": false,
217
+ "frozen_MKA_parameters": [
218
+ "self_attn.q_proj.weight",
219
+ "self_attn.k_proj.weight",
220
+ "self_attn.v_proj.weight",
221
+ "self_attn.o_proj.weight",
222
+ "input_layernorm.weight",
223
+ "post_attention_layernorm.weight"
224
+ ],
225
+ "frozen_attention_norm_expected_sha256": {
226
+ "self_attn.q_proj.weight": "33b21da5061da0ec77d277926d59f986cc5e1d1893f00f38619cae760e5eb945",
227
+ "self_attn.k_proj.weight": "49d25f8013eb4d095a71b895e0f4b240daf6d1076a12f4cb7af93834107b2446",
228
+ "self_attn.v_proj.weight": "0527e56a96e09c5796430829b05c0b16d4926bd35ddbd64621bb3b9ff368f795",
229
+ "self_attn.o_proj.weight": "ad8ab4fcbafde7e0bdf34acd82f5e6ea2f3ec61b90dcdb9f515b183b8954cade",
230
+ "input_layernorm.weight": "442962ef4923e31f331597e007c41301c88b9cf34900e9e6c9570fba7b887f6d",
231
+ "post_attention_layernorm.weight": "16325c0e3226964c4e7ec0b20cd2a522cbd0380ec694f34d9aede17cc217b462"
232
+ },
233
+ "frozen_attention_norm_before_sha256": {
234
+ "self_attn.q_proj.weight": "33b21da5061da0ec77d277926d59f986cc5e1d1893f00f38619cae760e5eb945",
235
+ "self_attn.k_proj.weight": "49d25f8013eb4d095a71b895e0f4b240daf6d1076a12f4cb7af93834107b2446",
236
+ "self_attn.v_proj.weight": "0527e56a96e09c5796430829b05c0b16d4926bd35ddbd64621bb3b9ff368f795",
237
+ "self_attn.o_proj.weight": "ad8ab4fcbafde7e0bdf34acd82f5e6ea2f3ec61b90dcdb9f515b183b8954cade",
238
+ "input_layernorm.weight": "442962ef4923e31f331597e007c41301c88b9cf34900e9e6c9570fba7b887f6d",
239
+ "post_attention_layernorm.weight": "16325c0e3226964c4e7ec0b20cd2a522cbd0380ec694f34d9aede17cc217b462"
240
+ },
241
+ "frozen_attention_norm_after_sha256": {
242
+ "self_attn.q_proj.weight": "33b21da5061da0ec77d277926d59f986cc5e1d1893f00f38619cae760e5eb945",
243
+ "self_attn.k_proj.weight": "49d25f8013eb4d095a71b895e0f4b240daf6d1076a12f4cb7af93834107b2446",
244
+ "self_attn.v_proj.weight": "0527e56a96e09c5796430829b05c0b16d4926bd35ddbd64621bb3b9ff368f795",
245
+ "self_attn.o_proj.weight": "ad8ab4fcbafde7e0bdf34acd82f5e6ea2f3ec61b90dcdb9f515b183b8954cade",
246
+ "input_layernorm.weight": "442962ef4923e31f331597e007c41301c88b9cf34900e9e6c9570fba7b887f6d",
247
+ "post_attention_layernorm.weight": "16325c0e3226964c4e7ec0b20cd2a522cbd0380ec694f34d9aede17cc217b462"
248
+ },
249
+ "frozen_attention_norm_unchanged": true,
250
+ "source_feature_transport": false,
251
+ "initializer": "mka",
252
+ "removed_count_per_cycle": 1,
253
+ "teacher_boundary_current_layer": 25,
254
+ "teacher_boundary_original_layer": 28
255
+ }
256
+ }
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_05_fit.json ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "enabled": true,
3
+ "epochs": 1.0,
4
+ "requested_epochs": 1.0,
5
+ "skip_train": false,
6
+ "trained": true,
7
+ "lr": 0.0001,
8
+ "hidden_mse_weight": 1.0,
9
+ "attn_mse_weight": 0.0,
10
+ "mlp_mse_weight": 1.0,
11
+ "eta": 0.0,
12
+ "gamma": 0.0,
13
+ "attn_reg_scale": 1.0,
14
+ "mlp_reg_scale": 1.0,
15
+ "param_subset": "mlp",
16
+ "train_subset": "mlp",
17
+ "num_gates": 3,
18
+ "num_attn_gates": 0,
19
+ "num_mlp_gates": 3,
20
+ "num_other_gates": 0,
21
+ "num_trainable_attn_gates": 0,
22
+ "num_trainable_mlp_gates": 3,
23
+ "num_trainable_other_gates": 0,
24
+ "lambda_init_summary": {
25
+ "num_tensors": 3,
26
+ "num_elements": 3,
27
+ "mean": 0.6214566230773926,
28
+ "std": 0.0,
29
+ "min": 0.6214566230773926,
30
+ "max": 0.6214566230773926,
31
+ "mean_abs_from_0_5": 0.12145662307739258,
32
+ "per_tensor": {
33
+ "mlp.gate_proj.weight": {
34
+ "mean": 0.6214566230773926,
35
+ "std": 0.0,
36
+ "min": 0.6214566230773926,
37
+ "max": 0.6214566230773926,
38
+ "mean_abs_from_0_5": 0.12145662307739258
39
+ },
40
+ "mlp.up_proj.weight": {
41
+ "mean": 0.6214566230773926,
42
+ "std": 0.0,
43
+ "min": 0.6214566230773926,
44
+ "max": 0.6214566230773926,
45
+ "mean_abs_from_0_5": 0.12145662307739258
46
+ },
47
+ "mlp.down_proj.weight": {
48
+ "mean": 0.6214566230773926,
49
+ "std": 0.0,
50
+ "min": 0.6214566230773926,
51
+ "max": 0.6214566230773926,
52
+ "mean_abs_from_0_5": 0.12145662307739258
53
+ }
54
+ }
55
+ },
56
+ "lambda_final_summary": {
57
+ "num_tensors": 3,
58
+ "num_elements": 3,
59
+ "mean": 0.6214566230773926,
60
+ "std": 0.0,
61
+ "min": 0.6214566230773926,
62
+ "max": 0.6214566230773926,
63
+ "mean_abs_from_0_5": 0.12145662307739258,
64
+ "per_tensor": {
65
+ "mlp.gate_proj.weight": {
66
+ "mean": 0.6214566230773926,
67
+ "std": 0.0,
68
+ "min": 0.6214566230773926,
69
+ "max": 0.6214566230773926,
70
+ "mean_abs_from_0_5": 0.12145662307739258
71
+ },
72
+ "mlp.up_proj.weight": {
73
+ "mean": 0.6214566230773926,
74
+ "std": 0.0,
75
+ "min": 0.6214566230773926,
76
+ "max": 0.6214566230773926,
77
+ "mean_abs_from_0_5": 0.12145662307739258
78
+ },
79
+ "mlp.down_proj.weight": {
80
+ "mean": 0.6214566230773926,
81
+ "std": 0.0,
82
+ "min": 0.6214566230773926,
83
+ "max": 0.6214566230773926,
84
+ "mean_abs_from_0_5": 0.12145662307739258
85
+ }
86
+ }
87
+ },
88
+ "lambda_delta_from_init": {
89
+ "num_tensors": 3,
90
+ "num_elements": 3,
91
+ "mean_abs": 0.0,
92
+ "rms": 0.0,
93
+ "max_abs": 0.0,
94
+ "per_tensor": {
95
+ "mlp.gate_proj.weight": {
96
+ "mean_abs": 0.0,
97
+ "rms": 0.0,
98
+ "max_abs": 0.0
99
+ },
100
+ "mlp.up_proj.weight": {
101
+ "mean_abs": 0.0,
102
+ "rms": 0.0,
103
+ "max_abs": 0.0
104
+ },
105
+ "mlp.down_proj.weight": {
106
+ "mean_abs": 0.0,
107
+ "rms": 0.0,
108
+ "max_abs": 0.0
109
+ }
110
+ }
111
+ },
112
+ "first_grad_summary": {
113
+ "joint": {
114
+ "step": 1,
115
+ "phase": "joint",
116
+ "gate": {
117
+ "num_tensors": 3,
118
+ "num_tensors_without_grad": 3,
119
+ "num_elements": 0,
120
+ "l2": 0.0,
121
+ "mean_abs": null,
122
+ "max_abs": 0.0
123
+ },
124
+ "u": {
125
+ "num_tensors": 3,
126
+ "num_tensors_without_grad": 0,
127
+ "num_elements": 176160768,
128
+ "l2": 0.023798749097841396,
129
+ "mean_abs": 9.989126478363427e-07,
130
+ "max_abs": 0.0003024935722351074
131
+ },
132
+ "rho": {
133
+ "num_tensors": 0,
134
+ "num_tensors_without_grad": 0,
135
+ "num_elements": 0,
136
+ "l2": 0.0,
137
+ "mean_abs": null,
138
+ "max_abs": 0.0
139
+ }
140
+ }
141
+ },
142
+ "u_delta_summary": {
143
+ "num_tensors": 3,
144
+ "num_elements": 176160768,
145
+ "mean": -2.4014854034248856e-06,
146
+ "std": 0.0022764703419805446,
147
+ "rms": 0.0022764716086630995,
148
+ "mean_abs": 0.0018195857160857745,
149
+ "min": -0.018383406102657318,
150
+ "max": 0.026860229671001434,
151
+ "per_tensor": {
152
+ "mlp.gate_proj.weight": {
153
+ "mean": -7.068362590091835e-06,
154
+ "std": 0.002411570403725625,
155
+ "rms": 0.002411580762461643,
156
+ "mean_abs": 0.0019284343080861227,
157
+ "min": -0.018383406102657318,
158
+ "max": 0.018306558951735497
159
+ },
160
+ "mlp.up_proj.weight": {
161
+ "mean": -4.068786308510296e-07,
162
+ "std": 0.002189818944928721,
163
+ "rms": 0.0021898189827286997,
164
+ "mean_abs": 0.0017497043258377484,
165
+ "min": -0.018327346071600914,
166
+ "max": 0.01832541450858116
167
+ },
168
+ "mlp.down_proj.weight": {
169
+ "mean": 2.7078501066820794e-07,
170
+ "std": 0.002221697533605536,
171
+ "rms": 0.0022216975501074495,
172
+ "mean_abs": 0.0017806185143334524,
173
+ "min": -0.01715226285159588,
174
+ "max": 0.026860229671001434
175
+ }
176
+ }
177
+ },
178
+ "rho_objective": "none",
179
+ "rho_schedule": "joint",
180
+ "additive_u": true,
181
+ "rho_epochs": 0.0,
182
+ "rho_lr": null,
183
+ "rho_bounds": null,
184
+ "rho_after_phase": null,
185
+ "rho_final": {},
186
+ "u_fisher_orthogonality": {},
187
+ "runtime": {
188
+ "seconds": 236.93127163220197,
189
+ "dataset_tokens": 524288,
190
+ "tokens_per_second": 2212.82735870288,
191
+ "batch_size": 1,
192
+ "batches_per_epoch": 512,
193
+ "grad_accumulation": 1,
194
+ "peak_allocated_bytes": 36425770496,
195
+ "peak_reserved_bytes": 47255126016,
196
+ "gpu_total_bytes": 85094825984,
197
+ "actual_forward_shapes": {
198
+ "teacher:1x1024": 512,
199
+ "student:1x1024": 512
200
+ }
201
+ },
202
+ "ablation": {
203
+ "lambda": 0.6214566168768135,
204
+ "endpoint_clamping": false,
205
+ "initial_u_nonzero": 0,
206
+ "merged_parameters": [
207
+ "mlp.gate_proj.weight",
208
+ "mlp.up_proj.weight",
209
+ "mlp.down_proj.weight"
210
+ ],
211
+ "parameterization": "W_initial + U_add",
212
+ "fisher_computed": false,
213
+ "fit_scope": "mlp",
214
+ "attention_initialization": "MKA_merge",
215
+ "norm_initialization": "anchor_Wa",
216
+ "norms_trainable": false,
217
+ "frozen_MKA_parameters": [
218
+ "self_attn.q_proj.weight",
219
+ "self_attn.k_proj.weight",
220
+ "self_attn.v_proj.weight",
221
+ "self_attn.o_proj.weight",
222
+ "input_layernorm.weight",
223
+ "post_attention_layernorm.weight"
224
+ ],
225
+ "frozen_attention_norm_expected_sha256": {
226
+ "self_attn.q_proj.weight": "bf0e59a55fa3fc0130c97bdf597ff34a976fee914528ac5d3d63c877294b075a",
227
+ "self_attn.k_proj.weight": "4e1fe89c06588e47ab8f43470661506cc3730a4c4d90efb75f8ac652be0bfe8f",
228
+ "self_attn.v_proj.weight": "0825f04e2d23afa8838f7ec3684926e83e374ef44e0b7f93b28bd6d888d8d10d",
229
+ "self_attn.o_proj.weight": "ebe6857d3c7b8df7a2b2cfb7185b4029e2bd4c05a6c78033331cc80d44aec42f",
230
+ "input_layernorm.weight": "215a4054b42dffd42acdc2d290049db92fba6920b1d5cc1e6bdb9d5a2cb4ed6c",
231
+ "post_attention_layernorm.weight": "880bfd813c0b0ae9ab6deed30a3dd1aef4ebf2b1fb8604921beb732a83deaf0b"
232
+ },
233
+ "frozen_attention_norm_before_sha256": {
234
+ "self_attn.q_proj.weight": "bf0e59a55fa3fc0130c97bdf597ff34a976fee914528ac5d3d63c877294b075a",
235
+ "self_attn.k_proj.weight": "4e1fe89c06588e47ab8f43470661506cc3730a4c4d90efb75f8ac652be0bfe8f",
236
+ "self_attn.v_proj.weight": "0825f04e2d23afa8838f7ec3684926e83e374ef44e0b7f93b28bd6d888d8d10d",
237
+ "self_attn.o_proj.weight": "ebe6857d3c7b8df7a2b2cfb7185b4029e2bd4c05a6c78033331cc80d44aec42f",
238
+ "input_layernorm.weight": "215a4054b42dffd42acdc2d290049db92fba6920b1d5cc1e6bdb9d5a2cb4ed6c",
239
+ "post_attention_layernorm.weight": "880bfd813c0b0ae9ab6deed30a3dd1aef4ebf2b1fb8604921beb732a83deaf0b"
240
+ },
241
+ "frozen_attention_norm_after_sha256": {
242
+ "self_attn.q_proj.weight": "bf0e59a55fa3fc0130c97bdf597ff34a976fee914528ac5d3d63c877294b075a",
243
+ "self_attn.k_proj.weight": "4e1fe89c06588e47ab8f43470661506cc3730a4c4d90efb75f8ac652be0bfe8f",
244
+ "self_attn.v_proj.weight": "0825f04e2d23afa8838f7ec3684926e83e374ef44e0b7f93b28bd6d888d8d10d",
245
+ "self_attn.o_proj.weight": "ebe6857d3c7b8df7a2b2cfb7185b4029e2bd4c05a6c78033331cc80d44aec42f",
246
+ "input_layernorm.weight": "215a4054b42dffd42acdc2d290049db92fba6920b1d5cc1e6bdb9d5a2cb4ed6c",
247
+ "post_attention_layernorm.weight": "880bfd813c0b0ae9ab6deed30a3dd1aef4ebf2b1fb8604921beb732a83deaf0b"
248
+ },
249
+ "frozen_attention_norm_unchanged": true,
250
+ "source_feature_transport": false,
251
+ "initializer": "mka",
252
+ "removed_count_per_cycle": 1,
253
+ "teacher_boundary_current_layer": 11,
254
+ "teacher_boundary_original_layer": 11
255
+ }
256
+ }
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_06_fit.json ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "enabled": true,
3
+ "epochs": 1.0,
4
+ "requested_epochs": 1.0,
5
+ "skip_train": false,
6
+ "trained": true,
7
+ "lr": 0.0001,
8
+ "hidden_mse_weight": 1.0,
9
+ "attn_mse_weight": 0.0,
10
+ "mlp_mse_weight": 1.0,
11
+ "eta": 0.0,
12
+ "gamma": 0.0,
13
+ "attn_reg_scale": 1.0,
14
+ "mlp_reg_scale": 1.0,
15
+ "param_subset": "mlp",
16
+ "train_subset": "mlp",
17
+ "num_gates": 3,
18
+ "num_attn_gates": 0,
19
+ "num_mlp_gates": 3,
20
+ "num_other_gates": 0,
21
+ "num_trainable_attn_gates": 0,
22
+ "num_trainable_mlp_gates": 3,
23
+ "num_trainable_other_gates": 0,
24
+ "lambda_init_summary": {
25
+ "num_tensors": 3,
26
+ "num_elements": 3,
27
+ "mean": 0.6218733787536621,
28
+ "std": 0.0,
29
+ "min": 0.6218733787536621,
30
+ "max": 0.6218733787536621,
31
+ "mean_abs_from_0_5": 0.12187337875366211,
32
+ "per_tensor": {
33
+ "mlp.gate_proj.weight": {
34
+ "mean": 0.6218733787536621,
35
+ "std": 0.0,
36
+ "min": 0.6218733787536621,
37
+ "max": 0.6218733787536621,
38
+ "mean_abs_from_0_5": 0.12187337875366211
39
+ },
40
+ "mlp.up_proj.weight": {
41
+ "mean": 0.6218733787536621,
42
+ "std": 0.0,
43
+ "min": 0.6218733787536621,
44
+ "max": 0.6218733787536621,
45
+ "mean_abs_from_0_5": 0.12187337875366211
46
+ },
47
+ "mlp.down_proj.weight": {
48
+ "mean": 0.6218733787536621,
49
+ "std": 0.0,
50
+ "min": 0.6218733787536621,
51
+ "max": 0.6218733787536621,
52
+ "mean_abs_from_0_5": 0.12187337875366211
53
+ }
54
+ }
55
+ },
56
+ "lambda_final_summary": {
57
+ "num_tensors": 3,
58
+ "num_elements": 3,
59
+ "mean": 0.6218733787536621,
60
+ "std": 0.0,
61
+ "min": 0.6218733787536621,
62
+ "max": 0.6218733787536621,
63
+ "mean_abs_from_0_5": 0.12187337875366211,
64
+ "per_tensor": {
65
+ "mlp.gate_proj.weight": {
66
+ "mean": 0.6218733787536621,
67
+ "std": 0.0,
68
+ "min": 0.6218733787536621,
69
+ "max": 0.6218733787536621,
70
+ "mean_abs_from_0_5": 0.12187337875366211
71
+ },
72
+ "mlp.up_proj.weight": {
73
+ "mean": 0.6218733787536621,
74
+ "std": 0.0,
75
+ "min": 0.6218733787536621,
76
+ "max": 0.6218733787536621,
77
+ "mean_abs_from_0_5": 0.12187337875366211
78
+ },
79
+ "mlp.down_proj.weight": {
80
+ "mean": 0.6218733787536621,
81
+ "std": 0.0,
82
+ "min": 0.6218733787536621,
83
+ "max": 0.6218733787536621,
84
+ "mean_abs_from_0_5": 0.12187337875366211
85
+ }
86
+ }
87
+ },
88
+ "lambda_delta_from_init": {
89
+ "num_tensors": 3,
90
+ "num_elements": 3,
91
+ "mean_abs": 0.0,
92
+ "rms": 0.0,
93
+ "max_abs": 0.0,
94
+ "per_tensor": {
95
+ "mlp.gate_proj.weight": {
96
+ "mean_abs": 0.0,
97
+ "rms": 0.0,
98
+ "max_abs": 0.0
99
+ },
100
+ "mlp.up_proj.weight": {
101
+ "mean_abs": 0.0,
102
+ "rms": 0.0,
103
+ "max_abs": 0.0
104
+ },
105
+ "mlp.down_proj.weight": {
106
+ "mean_abs": 0.0,
107
+ "rms": 0.0,
108
+ "max_abs": 0.0
109
+ }
110
+ }
111
+ },
112
+ "first_grad_summary": {
113
+ "joint": {
114
+ "step": 1,
115
+ "phase": "joint",
116
+ "gate": {
117
+ "num_tensors": 3,
118
+ "num_tensors_without_grad": 3,
119
+ "num_elements": 0,
120
+ "l2": 0.0,
121
+ "mean_abs": null,
122
+ "max_abs": 0.0
123
+ },
124
+ "u": {
125
+ "num_tensors": 3,
126
+ "num_tensors_without_grad": 0,
127
+ "num_elements": 176160768,
128
+ "l2": 0.016505673702003048,
129
+ "mean_abs": 7.002506122045729e-07,
130
+ "max_abs": 0.0006823539733886719
131
+ },
132
+ "rho": {
133
+ "num_tensors": 0,
134
+ "num_tensors_without_grad": 0,
135
+ "num_elements": 0,
136
+ "l2": 0.0,
137
+ "mean_abs": null,
138
+ "max_abs": 0.0
139
+ }
140
+ }
141
+ },
142
+ "u_delta_summary": {
143
+ "num_tensors": 3,
144
+ "num_elements": 176160768,
145
+ "mean": 1.5972473084686845e-06,
146
+ "std": 0.0021573101691507945,
147
+ "rms": 0.00215731076044236,
148
+ "mean_abs": 0.0017025845923594066,
149
+ "min": -0.027069417759776115,
150
+ "max": 0.026983391493558884,
151
+ "per_tensor": {
152
+ "mlp.gate_proj.weight": {
153
+ "mean": 4.690805716173989e-06,
154
+ "std": 0.0022876066067622114,
155
+ "rms": 0.002287611416075813,
156
+ "mean_abs": 0.0018131939162101065,
157
+ "min": -0.023049581795930862,
158
+ "max": 0.02186824195086956
159
+ },
160
+ "mlp.up_proj.weight": {
161
+ "mean": -4.236452306421208e-08,
162
+ "std": 0.0021124171804714235,
163
+ "rms": 0.002112417180896234,
164
+ "mean_abs": 0.0016683756506868771,
165
+ "min": -0.019246947020292282,
166
+ "max": 0.023856760933995247
167
+ },
168
+ "mlp.down_proj.weight": {
169
+ "mean": 1.4330073229627616e-07,
170
+ "std": 0.0020655499978746833,
171
+ "rms": 0.0020655500028455382,
172
+ "mean_abs": 0.0016261842101812363,
173
+ "min": -0.027069417759776115,
174
+ "max": 0.026983391493558884
175
+ }
176
+ }
177
+ },
178
+ "rho_objective": "none",
179
+ "rho_schedule": "joint",
180
+ "additive_u": true,
181
+ "rho_epochs": 0.0,
182
+ "rho_lr": null,
183
+ "rho_bounds": null,
184
+ "rho_after_phase": null,
185
+ "rho_final": {},
186
+ "u_fisher_orthogonality": {},
187
+ "runtime": {
188
+ "seconds": 235.3195459600538,
189
+ "dataset_tokens": 524288,
190
+ "tokens_per_second": 2227.98322111755,
191
+ "batch_size": 1,
192
+ "batches_per_epoch": 512,
193
+ "grad_accumulation": 1,
194
+ "peak_allocated_bytes": 34411349504,
195
+ "peak_reserved_bytes": 45933920256,
196
+ "gpu_total_bytes": 85094825984,
197
+ "actual_forward_shapes": {
198
+ "teacher:1x1024": 512,
199
+ "student:1x1024": 512
200
+ }
201
+ },
202
+ "ablation": {
203
+ "lambda": 0.6218733904661418,
204
+ "endpoint_clamping": false,
205
+ "initial_u_nonzero": 0,
206
+ "merged_parameters": [
207
+ "mlp.gate_proj.weight",
208
+ "mlp.up_proj.weight",
209
+ "mlp.down_proj.weight"
210
+ ],
211
+ "parameterization": "W_initial + U_add",
212
+ "fisher_computed": false,
213
+ "fit_scope": "mlp",
214
+ "attention_initialization": "MKA_merge",
215
+ "norm_initialization": "anchor_Wa",
216
+ "norms_trainable": false,
217
+ "frozen_MKA_parameters": [
218
+ "self_attn.q_proj.weight",
219
+ "self_attn.k_proj.weight",
220
+ "self_attn.v_proj.weight",
221
+ "self_attn.o_proj.weight",
222
+ "input_layernorm.weight",
223
+ "post_attention_layernorm.weight"
224
+ ],
225
+ "frozen_attention_norm_expected_sha256": {
226
+ "self_attn.q_proj.weight": "338b2a143af52ffabc02a40fb54c4db56b33434bf86acff791c78e464abe7471",
227
+ "self_attn.k_proj.weight": "a19fba8a25fcc3cc3d40012b491266ff9b726660ff733b408a2d91c4c8310c22",
228
+ "self_attn.v_proj.weight": "d045c6248610a810bcc8369f7c276cb7ab57688311892e2699f035d3f761e61e",
229
+ "self_attn.o_proj.weight": "032fe63aa06393b51c7cc46d4760288cee833b97efe83427d7bf186985503686",
230
+ "input_layernorm.weight": "2e51ae768cf6bf12d1903474b16741c383154686c8da264bfb44713bacaa0621",
231
+ "post_attention_layernorm.weight": "b3191d2dd3776ffff6f3dc74aebe2ddd40c82210ceba22c221eff83b1aeb1f95"
232
+ },
233
+ "frozen_attention_norm_before_sha256": {
234
+ "self_attn.q_proj.weight": "338b2a143af52ffabc02a40fb54c4db56b33434bf86acff791c78e464abe7471",
235
+ "self_attn.k_proj.weight": "a19fba8a25fcc3cc3d40012b491266ff9b726660ff733b408a2d91c4c8310c22",
236
+ "self_attn.v_proj.weight": "d045c6248610a810bcc8369f7c276cb7ab57688311892e2699f035d3f761e61e",
237
+ "self_attn.o_proj.weight": "032fe63aa06393b51c7cc46d4760288cee833b97efe83427d7bf186985503686",
238
+ "input_layernorm.weight": "2e51ae768cf6bf12d1903474b16741c383154686c8da264bfb44713bacaa0621",
239
+ "post_attention_layernorm.weight": "b3191d2dd3776ffff6f3dc74aebe2ddd40c82210ceba22c221eff83b1aeb1f95"
240
+ },
241
+ "frozen_attention_norm_after_sha256": {
242
+ "self_attn.q_proj.weight": "338b2a143af52ffabc02a40fb54c4db56b33434bf86acff791c78e464abe7471",
243
+ "self_attn.k_proj.weight": "a19fba8a25fcc3cc3d40012b491266ff9b726660ff733b408a2d91c4c8310c22",
244
+ "self_attn.v_proj.weight": "d045c6248610a810bcc8369f7c276cb7ab57688311892e2699f035d3f761e61e",
245
+ "self_attn.o_proj.weight": "032fe63aa06393b51c7cc46d4760288cee833b97efe83427d7bf186985503686",
246
+ "input_layernorm.weight": "2e51ae768cf6bf12d1903474b16741c383154686c8da264bfb44713bacaa0621",
247
+ "post_attention_layernorm.weight": "b3191d2dd3776ffff6f3dc74aebe2ddd40c82210ceba22c221eff83b1aeb1f95"
248
+ },
249
+ "frozen_attention_norm_unchanged": true,
250
+ "source_feature_transport": false,
251
+ "initializer": "mka",
252
+ "removed_count_per_cycle": 1,
253
+ "teacher_boundary_current_layer": 18,
254
+ "teacher_boundary_original_layer": 20
255
+ }
256
+ }
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_07_fit.json ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "enabled": true,
3
+ "epochs": 1.0,
4
+ "requested_epochs": 1.0,
5
+ "skip_train": false,
6
+ "trained": true,
7
+ "lr": 0.0001,
8
+ "hidden_mse_weight": 1.0,
9
+ "attn_mse_weight": 0.0,
10
+ "mlp_mse_weight": 1.0,
11
+ "eta": 0.0,
12
+ "gamma": 0.0,
13
+ "attn_reg_scale": 1.0,
14
+ "mlp_reg_scale": 1.0,
15
+ "param_subset": "mlp",
16
+ "train_subset": "mlp",
17
+ "num_gates": 3,
18
+ "num_attn_gates": 0,
19
+ "num_mlp_gates": 3,
20
+ "num_other_gates": 0,
21
+ "num_trainable_attn_gates": 0,
22
+ "num_trainable_mlp_gates": 3,
23
+ "num_trainable_other_gates": 0,
24
+ "lambda_init_summary": {
25
+ "num_tensors": 3,
26
+ "num_elements": 3,
27
+ "mean": 0.6204370260238647,
28
+ "std": 0.00010531781478674324,
29
+ "min": 0.6204370260238647,
30
+ "max": 0.6204370260238647,
31
+ "mean_abs_from_0_5": 0.12043702602386475,
32
+ "per_tensor": {
33
+ "mlp.gate_proj.weight": {
34
+ "mean": 0.6204370260238647,
35
+ "std": 0.00010531781478674324,
36
+ "min": 0.6204370260238647,
37
+ "max": 0.6204370260238647,
38
+ "mean_abs_from_0_5": 0.12043702602386475
39
+ },
40
+ "mlp.up_proj.weight": {
41
+ "mean": 0.6204370260238647,
42
+ "std": 0.00010531781478674324,
43
+ "min": 0.6204370260238647,
44
+ "max": 0.6204370260238647,
45
+ "mean_abs_from_0_5": 0.12043702602386475
46
+ },
47
+ "mlp.down_proj.weight": {
48
+ "mean": 0.6204370260238647,
49
+ "std": 0.00010531781478674324,
50
+ "min": 0.6204370260238647,
51
+ "max": 0.6204370260238647,
52
+ "mean_abs_from_0_5": 0.12043702602386475
53
+ }
54
+ }
55
+ },
56
+ "lambda_final_summary": {
57
+ "num_tensors": 3,
58
+ "num_elements": 3,
59
+ "mean": 0.6204370856285095,
60
+ "std": 0.0,
61
+ "min": 0.6204370856285095,
62
+ "max": 0.6204370856285095,
63
+ "mean_abs_from_0_5": 0.12043708562850952,
64
+ "per_tensor": {
65
+ "mlp.gate_proj.weight": {
66
+ "mean": 0.6204370856285095,
67
+ "std": 0.0,
68
+ "min": 0.6204370856285095,
69
+ "max": 0.6204370856285095,
70
+ "mean_abs_from_0_5": 0.12043708562850952
71
+ },
72
+ "mlp.up_proj.weight": {
73
+ "mean": 0.6204370856285095,
74
+ "std": 0.0,
75
+ "min": 0.6204370856285095,
76
+ "max": 0.6204370856285095,
77
+ "mean_abs_from_0_5": 0.12043708562850952
78
+ },
79
+ "mlp.down_proj.weight": {
80
+ "mean": 0.6204370856285095,
81
+ "std": 0.0,
82
+ "min": 0.6204370856285095,
83
+ "max": 0.6204370856285095,
84
+ "mean_abs_from_0_5": 0.12043708562850952
85
+ }
86
+ }
87
+ },
88
+ "lambda_delta_from_init": {
89
+ "num_tensors": 3,
90
+ "num_elements": 3,
91
+ "mean_abs": 0.0,
92
+ "rms": 0.0,
93
+ "max_abs": 0.0,
94
+ "per_tensor": {
95
+ "mlp.gate_proj.weight": {
96
+ "mean_abs": 0.0,
97
+ "rms": 0.0,
98
+ "max_abs": 0.0
99
+ },
100
+ "mlp.up_proj.weight": {
101
+ "mean_abs": 0.0,
102
+ "rms": 0.0,
103
+ "max_abs": 0.0
104
+ },
105
+ "mlp.down_proj.weight": {
106
+ "mean_abs": 0.0,
107
+ "rms": 0.0,
108
+ "max_abs": 0.0
109
+ }
110
+ }
111
+ },
112
+ "first_grad_summary": {
113
+ "joint": {
114
+ "step": 1,
115
+ "phase": "joint",
116
+ "gate": {
117
+ "num_tensors": 3,
118
+ "num_tensors_without_grad": 3,
119
+ "num_elements": 0,
120
+ "l2": 0.0,
121
+ "mean_abs": null,
122
+ "max_abs": 0.0
123
+ },
124
+ "u": {
125
+ "num_tensors": 3,
126
+ "num_tensors_without_grad": 0,
127
+ "num_elements": 176160768,
128
+ "l2": 0.07638957439096815,
129
+ "mean_abs": 2.0682674576597664e-06,
130
+ "max_abs": 0.008464813232421875
131
+ },
132
+ "rho": {
133
+ "num_tensors": 0,
134
+ "num_tensors_without_grad": 0,
135
+ "num_elements": 0,
136
+ "l2": 0.0,
137
+ "mean_abs": null,
138
+ "max_abs": 0.0
139
+ }
140
+ }
141
+ },
142
+ "u_delta_summary": {
143
+ "num_tensors": 3,
144
+ "num_elements": 176160768,
145
+ "mean": 2.609734738576836e-07,
146
+ "std": 0.00201541303839106,
147
+ "rms": 0.0020154130552876345,
148
+ "mean_abs": 0.0015936125779435748,
149
+ "min": -0.038418885320425034,
150
+ "max": 0.038319963961839676,
151
+ "per_tensor": {
152
+ "mlp.gate_proj.weight": {
153
+ "mean": 5.965531662306083e-07,
154
+ "std": 0.00205783501094422,
155
+ "rms": 0.0020578350974126856,
156
+ "mean_abs": 0.0016328911962253706,
157
+ "min": -0.038418885320425034,
158
+ "max": 0.038319963961839676
159
+ },
160
+ "mlp.up_proj.weight": {
161
+ "mean": -1.996037488944629e-07,
162
+ "std": 0.0019500534675952355,
163
+ "rms": 0.0019500534778107647,
164
+ "mean_abs": 0.001546303741633892,
165
+ "min": -0.032755427062511444,
166
+ "max": 0.03332352638244629
167
+ },
168
+ "mlp.down_proj.weight": {
169
+ "mean": 3.859710042369053e-07,
170
+ "std": 0.002036731535287005,
171
+ "rms": 0.002036731571858741,
172
+ "mean_abs": 0.0016016427959714616,
173
+ "min": -0.024363642558455467,
174
+ "max": 0.023109588772058487
175
+ }
176
+ }
177
+ },
178
+ "rho_objective": "none",
179
+ "rho_schedule": "joint",
180
+ "additive_u": true,
181
+ "rho_epochs": 0.0,
182
+ "rho_lr": null,
183
+ "rho_bounds": null,
184
+ "rho_after_phase": null,
185
+ "rho_final": {},
186
+ "u_fisher_orthogonality": {},
187
+ "runtime": {
188
+ "seconds": 232.81762517197058,
189
+ "dataset_tokens": 524288,
190
+ "tokens_per_second": 2251.9257277568013,
191
+ "batch_size": 1,
192
+ "batches_per_epoch": 512,
193
+ "grad_accumulation": 1,
194
+ "peak_allocated_bytes": 32825135616,
195
+ "peak_reserved_bytes": 44612714496,
196
+ "gpu_total_bytes": 85094825984,
197
+ "actual_forward_shapes": {
198
+ "teacher:1x1024": 512,
199
+ "student:1x1024": 512
200
+ }
201
+ },
202
+ "ablation": {
203
+ "lambda": 0.6204370597270433,
204
+ "endpoint_clamping": false,
205
+ "initial_u_nonzero": 0,
206
+ "merged_parameters": [
207
+ "mlp.gate_proj.weight",
208
+ "mlp.up_proj.weight",
209
+ "mlp.down_proj.weight"
210
+ ],
211
+ "parameterization": "W_initial + U_add",
212
+ "fisher_computed": false,
213
+ "fit_scope": "mlp",
214
+ "attention_initialization": "MKA_merge",
215
+ "norm_initialization": "anchor_Wa",
216
+ "norms_trainable": false,
217
+ "frozen_MKA_parameters": [
218
+ "self_attn.q_proj.weight",
219
+ "self_attn.k_proj.weight",
220
+ "self_attn.v_proj.weight",
221
+ "self_attn.o_proj.weight",
222
+ "input_layernorm.weight",
223
+ "post_attention_layernorm.weight"
224
+ ],
225
+ "frozen_attention_norm_expected_sha256": {
226
+ "self_attn.q_proj.weight": "27f6eb4e6316e6aaf540f236ed375e34c0a374359eba9d1bcef9edb11768fb95",
227
+ "self_attn.k_proj.weight": "b2675ac98375f71b329bdbfcb9167cdcf53c8693e70ffd77d007571fda86ec03",
228
+ "self_attn.v_proj.weight": "70d5aa8d6334cb1b2ef399e98217c5dcce79a6eb64f1b7f119f8b70ca0706b96",
229
+ "self_attn.o_proj.weight": "affed10b757e083fe5ff8e135ad760004b4a54aeddee7e5572a88a0d34c92fe6",
230
+ "input_layernorm.weight": "59692da85e68baf38d412451434e1af6f8bb48bed59b76130478c63ca90110a3",
231
+ "post_attention_layernorm.weight": "23ee031769609bc4df38dcee4097aef3e72dc262c567e2220eaaf1c25d60816a"
232
+ },
233
+ "frozen_attention_norm_before_sha256": {
234
+ "self_attn.q_proj.weight": "27f6eb4e6316e6aaf540f236ed375e34c0a374359eba9d1bcef9edb11768fb95",
235
+ "self_attn.k_proj.weight": "b2675ac98375f71b329bdbfcb9167cdcf53c8693e70ffd77d007571fda86ec03",
236
+ "self_attn.v_proj.weight": "70d5aa8d6334cb1b2ef399e98217c5dcce79a6eb64f1b7f119f8b70ca0706b96",
237
+ "self_attn.o_proj.weight": "affed10b757e083fe5ff8e135ad760004b4a54aeddee7e5572a88a0d34c92fe6",
238
+ "input_layernorm.weight": "59692da85e68baf38d412451434e1af6f8bb48bed59b76130478c63ca90110a3",
239
+ "post_attention_layernorm.weight": "23ee031769609bc4df38dcee4097aef3e72dc262c567e2220eaaf1c25d60816a"
240
+ },
241
+ "frozen_attention_norm_after_sha256": {
242
+ "self_attn.q_proj.weight": "27f6eb4e6316e6aaf540f236ed375e34c0a374359eba9d1bcef9edb11768fb95",
243
+ "self_attn.k_proj.weight": "b2675ac98375f71b329bdbfcb9167cdcf53c8693e70ffd77d007571fda86ec03",
244
+ "self_attn.v_proj.weight": "70d5aa8d6334cb1b2ef399e98217c5dcce79a6eb64f1b7f119f8b70ca0706b96",
245
+ "self_attn.o_proj.weight": "affed10b757e083fe5ff8e135ad760004b4a54aeddee7e5572a88a0d34c92fe6",
246
+ "input_layernorm.weight": "59692da85e68baf38d412451434e1af6f8bb48bed59b76130478c63ca90110a3",
247
+ "post_attention_layernorm.weight": "23ee031769609bc4df38dcee4097aef3e72dc262c567e2220eaaf1c25d60816a"
248
+ },
249
+ "frozen_attention_norm_unchanged": true,
250
+ "source_feature_transport": false,
251
+ "initializer": "mka",
252
+ "removed_count_per_cycle": 1,
253
+ "teacher_boundary_current_layer": 22,
254
+ "teacher_boundary_original_layer": 27
255
+ }
256
+ }
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/cycle_08_fit.json ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "enabled": true,
3
+ "epochs": 1.0,
4
+ "requested_epochs": 1.0,
5
+ "skip_train": false,
6
+ "trained": true,
7
+ "lr": 0.0001,
8
+ "hidden_mse_weight": 1.0,
9
+ "attn_mse_weight": 0.0,
10
+ "mlp_mse_weight": 1.0,
11
+ "eta": 0.0,
12
+ "gamma": 0.0,
13
+ "attn_reg_scale": 1.0,
14
+ "mlp_reg_scale": 1.0,
15
+ "param_subset": "mlp",
16
+ "train_subset": "mlp",
17
+ "num_gates": 3,
18
+ "num_attn_gates": 0,
19
+ "num_mlp_gates": 3,
20
+ "num_other_gates": 0,
21
+ "num_trainable_attn_gates": 0,
22
+ "num_trainable_mlp_gates": 3,
23
+ "num_trainable_other_gates": 0,
24
+ "lambda_init_summary": {
25
+ "num_tensors": 3,
26
+ "num_elements": 3,
27
+ "mean": 0.6198245882987976,
28
+ "std": 0.0,
29
+ "min": 0.6198245882987976,
30
+ "max": 0.6198245882987976,
31
+ "mean_abs_from_0_5": 0.11982458829879761,
32
+ "per_tensor": {
33
+ "mlp.gate_proj.weight": {
34
+ "mean": 0.6198245882987976,
35
+ "std": 0.0,
36
+ "min": 0.6198245882987976,
37
+ "max": 0.6198245882987976,
38
+ "mean_abs_from_0_5": 0.11982458829879761
39
+ },
40
+ "mlp.up_proj.weight": {
41
+ "mean": 0.6198245882987976,
42
+ "std": 0.0,
43
+ "min": 0.6198245882987976,
44
+ "max": 0.6198245882987976,
45
+ "mean_abs_from_0_5": 0.11982458829879761
46
+ },
47
+ "mlp.down_proj.weight": {
48
+ "mean": 0.6198245882987976,
49
+ "std": 0.0,
50
+ "min": 0.6198245882987976,
51
+ "max": 0.6198245882987976,
52
+ "mean_abs_from_0_5": 0.11982458829879761
53
+ }
54
+ }
55
+ },
56
+ "lambda_final_summary": {
57
+ "num_tensors": 3,
58
+ "num_elements": 3,
59
+ "mean": 0.6198245882987976,
60
+ "std": 0.0,
61
+ "min": 0.6198245882987976,
62
+ "max": 0.6198245882987976,
63
+ "mean_abs_from_0_5": 0.11982458829879761,
64
+ "per_tensor": {
65
+ "mlp.gate_proj.weight": {
66
+ "mean": 0.6198245882987976,
67
+ "std": 0.0,
68
+ "min": 0.6198245882987976,
69
+ "max": 0.6198245882987976,
70
+ "mean_abs_from_0_5": 0.11982458829879761
71
+ },
72
+ "mlp.up_proj.weight": {
73
+ "mean": 0.6198245882987976,
74
+ "std": 0.0,
75
+ "min": 0.6198245882987976,
76
+ "max": 0.6198245882987976,
77
+ "mean_abs_from_0_5": 0.11982458829879761
78
+ },
79
+ "mlp.down_proj.weight": {
80
+ "mean": 0.6198245882987976,
81
+ "std": 0.0,
82
+ "min": 0.6198245882987976,
83
+ "max": 0.6198245882987976,
84
+ "mean_abs_from_0_5": 0.11982458829879761
85
+ }
86
+ }
87
+ },
88
+ "lambda_delta_from_init": {
89
+ "num_tensors": 3,
90
+ "num_elements": 3,
91
+ "mean_abs": 0.0,
92
+ "rms": 0.0,
93
+ "max_abs": 0.0,
94
+ "per_tensor": {
95
+ "mlp.gate_proj.weight": {
96
+ "mean_abs": 0.0,
97
+ "rms": 0.0,
98
+ "max_abs": 0.0
99
+ },
100
+ "mlp.up_proj.weight": {
101
+ "mean_abs": 0.0,
102
+ "rms": 0.0,
103
+ "max_abs": 0.0
104
+ },
105
+ "mlp.down_proj.weight": {
106
+ "mean_abs": 0.0,
107
+ "rms": 0.0,
108
+ "max_abs": 0.0
109
+ }
110
+ }
111
+ },
112
+ "first_grad_summary": {
113
+ "joint": {
114
+ "step": 1,
115
+ "phase": "joint",
116
+ "gate": {
117
+ "num_tensors": 3,
118
+ "num_tensors_without_grad": 3,
119
+ "num_elements": 0,
120
+ "l2": 0.0,
121
+ "mean_abs": null,
122
+ "max_abs": 0.0
123
+ },
124
+ "u": {
125
+ "num_tensors": 3,
126
+ "num_tensors_without_grad": 0,
127
+ "num_elements": 176160768,
128
+ "l2": 0.04856508392957567,
129
+ "mean_abs": 1.294511797650124e-06,
130
+ "max_abs": 0.006938457489013672
131
+ },
132
+ "rho": {
133
+ "num_tensors": 0,
134
+ "num_tensors_without_grad": 0,
135
+ "num_elements": 0,
136
+ "l2": 0.0,
137
+ "mean_abs": null,
138
+ "max_abs": 0.0
139
+ }
140
+ }
141
+ },
142
+ "u_delta_summary": {
143
+ "num_tensors": 3,
144
+ "num_elements": 176160768,
145
+ "mean": 6.485743440299259e-07,
146
+ "std": 0.001983281186995129,
147
+ "rms": 0.0019832812930438,
148
+ "mean_abs": 0.0015548129255572956,
149
+ "min": -0.03879503533244133,
150
+ "max": 0.037791673094034195,
151
+ "per_tensor": {
152
+ "mlp.gate_proj.weight": {
153
+ "mean": 2.1037132163265985e-06,
154
+ "std": 0.0021137019708207623,
155
+ "rms": 0.0021137030177063357,
156
+ "mean_abs": 0.0016634500186358178,
157
+ "min": -0.03879503533244133,
158
+ "max": 0.037791673094034195
159
+ },
160
+ "mlp.up_proj.weight": {
161
+ "mean": 5.434173999674385e-09,
162
+ "std": 0.0019752057093611686,
163
+ "rms": 0.001975205709368644,
164
+ "mean_abs": 0.0015518537589481898,
165
+ "min": -0.03496667370200157,
166
+ "max": 0.03368644416332245
167
+ },
168
+ "mlp.down_proj.weight": {
169
+ "mean": -1.6342435823649533e-07,
170
+ "std": 0.0018523055886979305,
171
+ "rms": 0.0018523055959071947,
172
+ "mean_abs": 0.0014491349990878785,
173
+ "min": -0.023061256855726242,
174
+ "max": 0.027801021933555603
175
+ }
176
+ }
177
+ },
178
+ "rho_objective": "none",
179
+ "rho_schedule": "joint",
180
+ "additive_u": true,
181
+ "rho_epochs": 0.0,
182
+ "rho_lr": null,
183
+ "rho_bounds": null,
184
+ "rho_after_phase": null,
185
+ "rho_final": {},
186
+ "u_fisher_orthogonality": {},
187
+ "runtime": {
188
+ "seconds": 224.35353699093685,
189
+ "dataset_tokens": 524288,
190
+ "tokens_per_second": 2336.8831489435333,
191
+ "batch_size": 1,
192
+ "batches_per_epoch": 512,
193
+ "grad_accumulation": 1,
194
+ "peak_allocated_bytes": 32095467008,
195
+ "peak_reserved_bytes": 43291508736,
196
+ "gpu_total_bytes": 85094825984,
197
+ "actual_forward_shapes": {
198
+ "teacher:1x1024": 512,
199
+ "student:1x1024": 512
200
+ }
201
+ },
202
+ "ablation": {
203
+ "lambda": 0.6198245714075894,
204
+ "endpoint_clamping": false,
205
+ "initial_u_nonzero": 0,
206
+ "merged_parameters": [
207
+ "mlp.gate_proj.weight",
208
+ "mlp.up_proj.weight",
209
+ "mlp.down_proj.weight"
210
+ ],
211
+ "parameterization": "W_initial + U_add",
212
+ "fisher_computed": false,
213
+ "fit_scope": "mlp",
214
+ "attention_initialization": "MKA_merge",
215
+ "norm_initialization": "anchor_Wa",
216
+ "norms_trainable": false,
217
+ "frozen_MKA_parameters": [
218
+ "self_attn.q_proj.weight",
219
+ "self_attn.k_proj.weight",
220
+ "self_attn.v_proj.weight",
221
+ "self_attn.o_proj.weight",
222
+ "input_layernorm.weight",
223
+ "post_attention_layernorm.weight"
224
+ ],
225
+ "frozen_attention_norm_expected_sha256": {
226
+ "self_attn.q_proj.weight": "e4947d79567ecc8d3baca7486179776cc67ba8205232561ebe207b45e6ab55eb",
227
+ "self_attn.k_proj.weight": "29aa0b1c7114df948b8cc999cff28d11e3a5b973674eac5bf3262ca2c061e2d5",
228
+ "self_attn.v_proj.weight": "d0fd338ac6491924b22d47f421800701746c10606e8086d187cc713d0dc97f89",
229
+ "self_attn.o_proj.weight": "af1ba467e186a58b94e80a8c5ca5a196b38b7e4a5f142ad1511c0155c0c0d606",
230
+ "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7",
231
+ "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715"
232
+ },
233
+ "frozen_attention_norm_before_sha256": {
234
+ "self_attn.q_proj.weight": "e4947d79567ecc8d3baca7486179776cc67ba8205232561ebe207b45e6ab55eb",
235
+ "self_attn.k_proj.weight": "29aa0b1c7114df948b8cc999cff28d11e3a5b973674eac5bf3262ca2c061e2d5",
236
+ "self_attn.v_proj.weight": "d0fd338ac6491924b22d47f421800701746c10606e8086d187cc713d0dc97f89",
237
+ "self_attn.o_proj.weight": "af1ba467e186a58b94e80a8c5ca5a196b38b7e4a5f142ad1511c0155c0c0d606",
238
+ "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7",
239
+ "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715"
240
+ },
241
+ "frozen_attention_norm_after_sha256": {
242
+ "self_attn.q_proj.weight": "e4947d79567ecc8d3baca7486179776cc67ba8205232561ebe207b45e6ab55eb",
243
+ "self_attn.k_proj.weight": "29aa0b1c7114df948b8cc999cff28d11e3a5b973674eac5bf3262ca2c061e2d5",
244
+ "self_attn.v_proj.weight": "d0fd338ac6491924b22d47f421800701746c10606e8086d187cc713d0dc97f89",
245
+ "self_attn.o_proj.weight": "af1ba467e186a58b94e80a8c5ca5a196b38b7e4a5f142ad1511c0155c0c0d606",
246
+ "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7",
247
+ "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715"
248
+ },
249
+ "frozen_attention_norm_unchanged": true,
250
+ "source_feature_transport": false,
251
+ "initializer": "mka",
252
+ "removed_count_per_cycle": 1,
253
+ "teacher_boundary_current_layer": 20,
254
+ "teacher_boundary_original_layer": 25
255
+ }
256
+ }
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/data_fingerprints.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "calib_loader": {
3
+ "sequences": 64,
4
+ "sha256": "fa4a6219f7a7b17364eef6b5b7771533b57a407f1d26db1d483bbd955814ce38",
5
+ "attention_mask_sha256": "b1476de1907209012e63fa502715fd97db26e595352faa808d8c10433a1472a4",
6
+ "valid_tokens": 65536
7
+ },
8
+ "distill_loader": {
9
+ "sequences": 512,
10
+ "sha256": "2b2d044c8c040f67891817ecc110f0fa0de2f469db4c6731114ff7816bbf1cd0",
11
+ "attention_mask_sha256": "c8e7f8e30cd532b82e6af4b98d596bc7106f29f9fb2b398b44355e624898a30d",
12
+ "valid_tokens": 524288
13
+ }
14
+ }
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/selection.json ADDED
The diff for this file is too large to render. See raw diff
 
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/audit/selection_inputs.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075",
3
+ "attention_mask_sha256": "ffe472b00e055e867ecb0129008048236f4d8f7a3730ec6fecda87fc1666dd88",
4
+ "sequences": 100,
5
+ "sequence_length": 512,
6
+ "valid_tokens": 51200,
7
+ "source": "/workspace/mka-fit-batch-20261126/calibration/selection.pt",
8
+ "independent_of_fit_loader": true,
9
+ "selection_protocol": "native_MKA_saved_geometry_dynamic_NPIB"
10
+ }
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/batch_profile.json ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "profiles": [
3
+ {
4
+ "batch_size": 1,
5
+ "return_code": 0,
6
+ "completed": true,
7
+ "seconds": 32.977131435181946,
8
+ "dataset_tokens": 65536,
9
+ "tokens_per_second": 1987.3165781206287,
10
+ "batches_per_epoch": 64,
11
+ "grad_accumulation": 1,
12
+ "peak_allocated_bytes": 38916334592,
13
+ "peak_reserved_bytes": 40705720320,
14
+ "gpu_total_bytes": 85094825984,
15
+ "actual_forward_shapes": {
16
+ "teacher:1x1024": 64,
17
+ "student:1x1024": 64
18
+ },
19
+ "memory_margin_bytes": 44389105664
20
+ },
21
+ {
22
+ "batch_size": 2,
23
+ "return_code": 0,
24
+ "completed": true,
25
+ "seconds": 25.37713863281533,
26
+ "dataset_tokens": 65536,
27
+ "tokens_per_second": 2582.481852987752,
28
+ "batches_per_epoch": 32,
29
+ "grad_accumulation": 1,
30
+ "peak_allocated_bytes": 42557828096,
31
+ "peak_reserved_bytes": 45833256960,
32
+ "gpu_total_bytes": 85094825984,
33
+ "actual_forward_shapes": {
34
+ "teacher:2x1024": 32,
35
+ "student:2x1024": 32
36
+ },
37
+ "memory_margin_bytes": 39261569024
38
+ },
39
+ {
40
+ "batch_size": 4,
41
+ "return_code": 0,
42
+ "completed": true,
43
+ "seconds": 22.732720613945276,
44
+ "dataset_tokens": 65536,
45
+ "tokens_per_second": 2882.8929503403683,
46
+ "batches_per_epoch": 16,
47
+ "grad_accumulation": 1,
48
+ "peak_allocated_bytes": 49839612928,
49
+ "peak_reserved_bytes": 56088330240,
50
+ "gpu_total_bytes": 85094825984,
51
+ "actual_forward_shapes": {
52
+ "teacher:4x1024": 16,
53
+ "student:4x1024": 16
54
+ },
55
+ "memory_margin_bytes": 29006495744
56
+ },
57
+ {
58
+ "batch_size": 8,
59
+ "return_code": 0,
60
+ "completed": true,
61
+ "seconds": 21.956195652019233,
62
+ "dataset_tokens": 65536,
63
+ "tokens_per_second": 2984.852250301973,
64
+ "batches_per_epoch": 8,
65
+ "grad_accumulation": 1,
66
+ "peak_allocated_bytes": 64399123456,
67
+ "peak_reserved_bytes": 76701237248,
68
+ "gpu_total_bytes": 85094825984,
69
+ "actual_forward_shapes": {
70
+ "teacher:8x1024": 8,
71
+ "student:8x1024": 8
72
+ },
73
+ "memory_margin_bytes": 8393588736
74
+ }
75
+ ],
76
+ "selected_larger_batch": 8,
77
+ "selection_rule": "Required user comparison batch, profiled with >=4GiB margin",
78
+ "training_updates_per_stage": {
79
+ "batch1": 512,
80
+ "batch_large": 64
81
+ }
82
+ }
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/abprune_compact.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Package and reconstruct compact ABPrune stage checkpoints.
2
+
3
+ ABPrune already writes ``fused_layer.pt`` for every cycle. This utility makes
4
+ those files portable by pairing them with an explicit, immutable stage record;
5
+ the dense base model plus that record is sufficient to reconstruct a student.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse, hashlib, json, shutil
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import torch
14
+
15
+
16
+ def copy_stage_state(src: Path, dst: Path, *, hard_link: bool = False) -> None:
17
+ """Optionally share immutable stage bytes within one experiment filesystem."""
18
+ if not hard_link:
19
+ shutil.copy2(src, dst)
20
+ elif dst.exists():
21
+ if not src.samefile(dst):
22
+ raise FileExistsError(f"Refusing to replace existing non-linked stage: {dst}")
23
+ else:
24
+ # Fail instead of silently consuming space if cross-device linking is
25
+ # unavailable. The caller explicitly selected the storage strategy.
26
+ dst.hardlink_to(src)
27
+
28
+
29
+ def sha256(path: Path) -> str:
30
+ h = hashlib.sha256()
31
+ with path.open("rb") as f:
32
+ for chunk in iter(lambda: f.read(8 * 1024 * 1024), b""):
33
+ h.update(chunk)
34
+ return h.hexdigest()
35
+
36
+
37
+ def post_merge_scale(source_cycle: Path) -> dict | None:
38
+ """Return the deployable post-merge scale stored for a cycle, if present."""
39
+ metadata_path = source_cycle / "cycle_metadata.json"
40
+ if not metadata_path.is_file():
41
+ return None
42
+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
43
+ distill = metadata.get("distill", {})
44
+ scale = distill.get("post_merge_nll_scale") or {}
45
+ source = "post_merge_nll"
46
+ if not scale.get("enabled"):
47
+ scale = (distill.get("reparam_stats") or {}).get("residual_scale") or {}
48
+ source = "scale_aware_fit"
49
+ if not scale.get("enabled"):
50
+ return None
51
+ gamma = scale["gamma"]
52
+ cumulative_gamma = scale["cumulative_gamma"]
53
+ if not isinstance(gamma, list):
54
+ gamma = float(gamma)
55
+ else:
56
+ gamma = [float(value) for value in gamma]
57
+ if not isinstance(cumulative_gamma, list):
58
+ cumulative_gamma = float(cumulative_gamma)
59
+ else:
60
+ cumulative_gamma = [float(value) for value in cumulative_gamma]
61
+ result = {
62
+ "enabled": True,
63
+ "mode": scale.get("mode", "residual"),
64
+ "scale_parameterization": scale.get("scale_parameterization", "scalar"),
65
+ "gamma": gamma,
66
+ "cumulative_gamma": cumulative_gamma,
67
+ "source": source,
68
+ }
69
+ for field in (
70
+ "optimization_mode",
71
+ "gamma_gradient_sources",
72
+ "theta_gradient_sources",
73
+ "nll_used",
74
+ ):
75
+ if field in scale:
76
+ result[field] = scale[field]
77
+ if "cumulative_gamma_statistics" in scale:
78
+ result["cumulative_gamma_statistics"] = scale["cumulative_gamma_statistics"]
79
+ if "raw" in scale and "ppl" in scale["raw"]:
80
+ result["calibration_raw_ppl"] = float(scale["raw"]["ppl"])
81
+ if "fitted" in scale and "ppl" in scale["fitted"]:
82
+ result["calibration_fitted_ppl"] = float(scale["fitted"]["ppl"])
83
+ return result
84
+
85
+
86
+ def read_compact_metadata(compact_stage: Path) -> dict[str, Any]:
87
+ return json.loads((compact_stage / "metadata.json").read_text(encoding="utf-8"))
88
+
89
+
90
+ def compact_scale_targets(metadata: dict[str, Any]) -> list[dict[str, Any]]:
91
+ """Return residual scales and current student indices for a compact stage."""
92
+ if metadata.get("format") == "abprune_compact_stage_v2":
93
+ active = [int(value) for value in metadata["active_original_layers"]]
94
+ current_index = {original: index for index, original in enumerate(active)}
95
+ targets = []
96
+ for state in metadata.get("retained_layer_states", []):
97
+ scale = state.get("post_merge_scale") or {}
98
+ if scale.get("enabled") and scale.get("mode") == "residual":
99
+ original = int(state["original_layer"])
100
+ targets.append(
101
+ {
102
+ "original_layer": original,
103
+ "student_index": current_index[original],
104
+ "scale": scale,
105
+ }
106
+ )
107
+ return targets
108
+
109
+ scale = metadata.get("post_merge_scale") or {}
110
+ if scale.get("enabled") and scale.get("mode") == "residual":
111
+ return [
112
+ {
113
+ "original_layer": int(metadata["anchor_index"]),
114
+ "student_index": int(metadata["anchor_index"]),
115
+ "scale": scale,
116
+ }
117
+ ]
118
+ return []
119
+
120
+
121
+ def _package_topology_aware(args, source: Path, out: Path, order: list[int]) -> None:
122
+ """Package cycles whose recipients may switch between pair boundaries."""
123
+ if int(getattr(args, "start_cycle", 1)) != 1:
124
+ raise ValueError("topology-aware compact packaging must start at cycle 1")
125
+
126
+ removed: set[int] = set()
127
+ latest_states: dict[int, dict[str, Any]] = {}
128
+ stages: list[dict[str, Any]] = []
129
+ original_layer_count: int | None = None
130
+
131
+ for cycle in range(1, args.cycles + 1):
132
+ source_cycle = source / f"cycle_{cycle}"
133
+ src = source_cycle / "fused_layer.pt"
134
+ if not src.is_file():
135
+ raise FileNotFoundError(src)
136
+ cycle_metadata_path = source_cycle / "cycle_metadata.json"
137
+ if not cycle_metadata_path.is_file():
138
+ raise FileNotFoundError(cycle_metadata_path)
139
+ cycle_metadata = json.loads(cycle_metadata_path.read_text(encoding="utf-8"))
140
+ recipient = int(cycle_metadata["recipient_original_layer"])
141
+ removed_original = int(cycle_metadata["removed_original_layer"])
142
+ recipient_side = str(cycle_metadata["recipient_side"])
143
+ if recipient_side not in {"left", "right"}:
144
+ raise ValueError(f"invalid recipient_side at cycle {cycle}: {recipient_side}")
145
+ if original_layer_count is None:
146
+ original_layer_count = int(cycle_metadata["num_layers_before"])
147
+ if removed_original in removed:
148
+ raise ValueError(f"original layer {removed_original} removed more than once")
149
+ if recipient in removed:
150
+ raise ValueError(f"cycle {cycle} selects removed recipient {recipient}")
151
+
152
+ removed.add(removed_original)
153
+ latest_states.pop(removed_original, None)
154
+ latest_states[recipient] = {
155
+ "original_layer": recipient,
156
+ "source_cycle": cycle,
157
+ "recipient_side": recipient_side,
158
+ "source_state": src,
159
+ "post_merge_scale": post_merge_scale(source_cycle),
160
+ }
161
+
162
+ stage_dir = out / f"stage_{cycle:02d}"
163
+ stage_dir.mkdir(exist_ok=True)
164
+ retained_states = []
165
+ for original, record in sorted(latest_states.items()):
166
+ state_name = f"layer_original_{original:04d}.pt"
167
+ state_path = stage_dir / state_name
168
+ copy_stage_state(record["source_state"], state_path, hard_link=bool(getattr(args, "hard_link", False)))
169
+ packaged = {
170
+ "original_layer": original,
171
+ "state_file": state_name,
172
+ "sha256": sha256(state_path),
173
+ "source_cycle": int(record["source_cycle"]),
174
+ "recipient_side": record["recipient_side"],
175
+ }
176
+ if record["post_merge_scale"] is not None:
177
+ packaged["post_merge_scale"] = record["post_merge_scale"]
178
+ retained_states.append(packaged)
179
+
180
+ assert original_layer_count is not None
181
+ active = [
182
+ original
183
+ for original in range(original_layer_count)
184
+ if original not in removed
185
+ ]
186
+ meta = {
187
+ "format": "abprune_compact_stage_v2",
188
+ "model": args.model,
189
+ "base_model_revision": args.base_revision,
190
+ "run_id": args.run_id,
191
+ "target_prune_count": args.cycles,
192
+ "stage": cycle,
193
+ "removed_count": len(removed),
194
+ "original_layer_count": original_layer_count,
195
+ "layer_order": order,
196
+ "latest_pair_index": order[cycle - 1],
197
+ "latest_recipient_side": recipient_side,
198
+ "latest_recipient_original_layer": recipient,
199
+ "latest_removed_original_layer": removed_original,
200
+ "removed_original_layers": sorted(removed),
201
+ "active_original_layers": active,
202
+ "retained_layer_states": retained_states,
203
+ "source_cycle": f"cycle_{cycle}",
204
+ }
205
+ (stage_dir / "metadata.json").write_text(
206
+ json.dumps(meta, indent=2) + "\n", encoding="utf-8"
207
+ )
208
+ stages.append(meta)
209
+
210
+ manifest = {
211
+ "format": "abprune_compact_manifest_v2",
212
+ "model": args.model,
213
+ "base_model_revision": args.base_revision,
214
+ "run_id": args.run_id,
215
+ "target_prune_count": args.cycles,
216
+ "original_layer_count": original_layer_count,
217
+ "layer_order": order,
218
+ "stages": stages,
219
+ }
220
+ (out / "manifest.json").write_text(
221
+ json.dumps(manifest, indent=2) + "\n", encoding="utf-8"
222
+ )
223
+
224
+
225
+ def package(args):
226
+ source = Path(args.run_root); out = Path(args.output_root); out.mkdir(parents=True, exist_ok=True)
227
+ order = [int(x) for x in args.layer_order.replace(',', ' ').split()]
228
+ start_cycle = int(getattr(args, "start_cycle", 1))
229
+ expected_order = args.cycles - start_cycle + 1
230
+ if not 1 <= start_cycle <= args.cycles:
231
+ raise ValueError("start_cycle must be between 1 and cycles")
232
+ if len(order) != expected_order:
233
+ raise ValueError("layer_order length must equal cycles - start_cycle + 1")
234
+ first_metadata_path = source / f"cycle_{start_cycle}" / "cycle_metadata.json"
235
+ if first_metadata_path.is_file():
236
+ first_metadata = json.loads(first_metadata_path.read_text(encoding="utf-8"))
237
+ topology_fields = {
238
+ "recipient_side",
239
+ "recipient_original_layer",
240
+ "removed_original_layer",
241
+ }
242
+ if topology_fields.issubset(first_metadata):
243
+ _package_topology_aware(args, source, out, order)
244
+ return
245
+ stages = []
246
+ for cycle in range(start_cycle, args.cycles + 1):
247
+ order_index = cycle - start_cycle
248
+ source_cycle = source / f"cycle_{cycle}"
249
+ src = source_cycle / "fused_layer.pt"
250
+ if not src.exists(): raise FileNotFoundError(src)
251
+ dst_dir = out / f"stage_{cycle:02d}"; dst_dir.mkdir(exist_ok=True)
252
+ dst = dst_dir / "anchor_layer.pt"; copy_stage_state(src, dst, hard_link=bool(getattr(args, "hard_link", False)))
253
+ meta = {
254
+ "format": "abprune_compact_stage_v1", "model": args.model,
255
+ "base_model_revision": args.base_revision, "run_id": args.run_id,
256
+ "target_prune_count": args.cycles, "stage": cycle,
257
+ "removed_count": cycle, "anchor_index": order[order_index],
258
+ "layer_order": order,
259
+ "packaged_stage_range": [start_cycle, args.cycles],
260
+ "removed_original_layers": list(range(order[order_index] + 1, order[order_index] + cycle + 1)),
261
+ "source_cycle": f"cycle_{cycle}", "anchor_state_file": "anchor_layer.pt",
262
+ "sha256": sha256(dst),
263
+ }
264
+ scale = post_merge_scale(source_cycle)
265
+ if scale is not None:
266
+ meta["post_merge_scale"] = scale
267
+ (dst_dir / "metadata.json").write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8")
268
+ stages.append(meta)
269
+ manifest = {"format": "abprune_compact_manifest_v1", "model": args.model,
270
+ "base_model_revision": args.base_revision, "run_id": args.run_id,
271
+ "target_prune_count": args.cycles, "layer_order": order, "stages": stages}
272
+ (out / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
273
+
274
+
275
+ def main():
276
+ p = argparse.ArgumentParser(); p.add_argument("--run-root", required=True); p.add_argument("--output-root", required=True)
277
+ p.add_argument("--model", required=True); p.add_argument("--base-revision", required=True); p.add_argument("--run-id", required=True)
278
+ p.add_argument("--cycles", type=int, required=True); p.add_argument("--layer-order", required=True)
279
+ p.add_argument("--start-cycle", type=int, default=1)
280
+ p.add_argument("--hard-link", action="store_true", help="Hard-link immutable stage weights on the same filesystem")
281
+ package(p.parse_args())
282
+
283
+
284
+ if __name__ == "__main__": main()
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/bootstrap_llama31_come_fit2.sh ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ project="$1"; external="$2"; root="$3"; base_model="$4"; inst_model="$5"
4
+ export HF_HOME=/workspace/.hf_home HF_TOKEN_PATH=/root/.cache/huggingface/token
5
+ export HF_DATASETS_CACHE=/workspace/.hf_datasets36 HF_DATASETS_TRUST_REMOTE_CODE=1
6
+ export PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false OMP_NUM_THREADS=4 HF_XET_HIGH_PERFORMANCE=1
7
+ mkdir -p "$root" "$(dirname "$external")"
8
+ trap 'rc=$?; if ((rc)); then touch "$root/BOOTSTRAP_FAILED"; fi' EXIT
9
+ python -m pip install 'transformers==5.15.1' 'datasets==3.6.0' 'huggingface_hub==1.33.0' \
10
+ 'lm_eval==0.4.12' accelerate scipy scikit-learn sentencepiece protobuf pytest
11
+ if [[ ! -d "$external/.git" ]]; then git clone "$project/vendor/abprune_experiment_base_39e.bundle" "$external"; fi
12
+ python - "$external" <<'PY'
13
+ from huggingface_hub import hf_hub_download
14
+ from pathlib import Path
15
+ import hashlib,shutil,sys
16
+ r=Path(sys.argv[1]);prefix='runs/vast-paper_revision-llama31-base-fit4-54645332-20261007/20261007-llama-base-fit4/wa/code/'
17
+ for n in ['fuse_layers.py','fuse_layers_distill.py','source_feature_transport.py']:
18
+ p=Path(hf_hub_download('LJYAI/paper_revision',prefix+n,revision='61734e7b1a77fd279fe1e2584f7a0fdc26c175c2'))
19
+ shutil.copy2(p,r/'src'/n); print('PINNED_SOURCE',n,hashlib.sha256(p.read_bytes()).hexdigest(),flush=True)
20
+ PY
21
+ if ! grep -q '^def model_is_sharded' "$external/src/progressive_loader.py"; then
22
+ git -C "$external" apply "$project/patches/0005-Add-progressive-loader-device-helpers.patch"
23
+ fi
24
+ git -C "$external" apply --check "$project/patches/abprune_transport_instruction_masks.patch"
25
+ git -C "$external" apply "$project/patches/abprune_transport_instruction_masks.patch"
26
+ python -m compileall -q "$external/src"
27
+ touch "$root/DEPS_READY"
28
+ python - "$root" "$base_model" "$inst_model" <<'PY'
29
+ from concurrent.futures import ThreadPoolExecutor
30
+ from pathlib import Path
31
+ from huggingface_hub import snapshot_download
32
+ from datasets import load_dataset
33
+ import sys
34
+ root=Path(sys.argv[1])
35
+ def prepare(family,model_id,model_rev,local,dataset,data_rev):
36
+ def model():
37
+ return snapshot_download(model_id,revision=model_rev,local_dir=local,
38
+ allow_patterns=['*.json','*.safetensors','tokenizer*','*.model','*.jinja'],max_workers=12)
39
+ def data():
40
+ snapshot_download(dataset,repo_type='dataset',revision=data_rev,max_workers=12)
41
+ return len(load_dataset(dataset,name=None,split='train',revision=data_rev,trust_remote_code=True))
42
+ with ThreadPoolExecutor(max_workers=2) as p:
43
+ for f in [p.submit(model),p.submit(data)]: print(family,'SNAPSHOT_READY',f.result(),flush=True)
44
+ (root/(family.upper()+'_READY')).touch()
45
+ with ThreadPoolExecutor(max_workers=2) as p:
46
+ jobs=[p.submit(prepare,'base','meta-llama/Llama-3.1-8B','d04e592bb4f6aa9cfee91e2e20afa771667e1d4b',sys.argv[2],
47
+ 'DKYoon/SlimPajama-6B','b5f90f419b7489cdba26fdbc8c022fcb5562f968'),
48
+ p.submit(prepare,'instruct','meta-llama/Llama-3.1-8B-Instruct','0e9e39f249a16976918f6564b8830bc894c89659',sys.argv[3],
49
+ 'Open-Orca/SlimOrca','ce9ed009ef3292bac33d3520afaf5ec804066120')]
50
+ for f in jobs:f.result()
51
+ PY
52
+ touch "$root/BOOTSTRAP_COMPLETE"
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/collect_mka_batch_comparison.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Collect the native-MKA MLP FiT pair, reporting Bench12, MMLU and CMMLU."""
2
+ import argparse
3
+ import json
4
+ import math
5
+ from pathlib import Path
6
+
7
+
8
+ def main():
9
+ p = argparse.ArgumentParser(description=__doc__)
10
+ p.add_argument("root", type=Path)
11
+ p.add_argument("--output", type=Path)
12
+ a = p.parse_args()
13
+ rows = []
14
+ for arm in ("batch1", "batch_large"):
15
+ run = a.root / "full" / arm
16
+ scores = json.loads((run / "eval/final_14bench.json").read_text())["task_scores"]
17
+ tasks = [name for name in scores if name not in ("mmlu", "cmmlu")]
18
+ assert len(tasks) == 12 and len(scores) == 14
19
+ assert all(math.isfinite(v) and 0 <= v <= 1 for v in scores.values())
20
+ fits = [json.loads((run / "audit" / f"cycle_{cycle:02d}_fit.json").read_text())
21
+ for cycle in range(1, 9)]
22
+ for fit in fits:
23
+ assert fit["trained"] and fit["num_trainable_mlp_gates"] == 3
24
+ assert fit["num_trainable_attn_gates"] == fit["num_trainable_other_gates"] == 0
25
+ assert fit["ablation"]["frozen_attention_norm_unchanged"]
26
+ fingerprints = json.loads((run / "audit/data_fingerprints.json").read_text())
27
+ ppl = json.loads((run / "eval/final_ppl.json").read_text())
28
+ metrics = ppl.get("metrics", ppl)
29
+ value = next((metrics[k] for k in ("ppl", "perplexity") if k in metrics), None)
30
+ assert value is not None and math.isfinite(value) and value > 0
31
+ batch = fits[0]["runtime"]["batch_size"]
32
+ native = json.loads((run / "audit/selection_inputs.json").read_text())
33
+ rows.append({"arm": arm, "batch_size": batch, "fit_scope": "mlp",
34
+ "bench12": sum(scores[k] for k in tasks) / 12,
35
+ "mmlu": scores["mmlu"], "cmmlu": scores["cmmlu"], "ppl": value,
36
+ "task_scores": scores,
37
+ "training_wall_seconds": json.loads((run / "training_elapsed.json").read_text())["wall_seconds"],
38
+ "fit_seconds": sum(f["runtime"]["seconds"] for f in fits),
39
+ "peak_allocated_bytes": max(f["runtime"]["peak_allocated_bytes"] for f in fits),
40
+ "peak_reserved_bytes": max(f["runtime"]["peak_reserved_bytes"] for f in fits),
41
+ "optimizer_updates_per_stage": 512 // batch,
42
+ "fit_input_sha256": fingerprints["distill_loader"]["sha256"],
43
+ "fit_mask_sha256": fingerprints["distill_loader"]["attention_mask_sha256"],
44
+ "selection_input_sha256": native["input_ids_sha256"],
45
+ "selection_inputs": native, "cycles": fits,
46
+ "selection_trace": json.loads((run / "audit/selection.json").read_text()),
47
+ "backup": json.loads((a.root / f"{arm}_backup.json").read_text())})
48
+ for field in ("fit_input_sha256", "fit_mask_sha256", "selection_input_sha256"):
49
+ assert rows[0][field] == rows[1][field]
50
+ assert rows[0]["fit_input_sha256"] == "2b2d044c8c040f67891817ecc110f0fa0de2f469db4c6731114ff7816bbf1cd0"
51
+ assert rows[0]["fit_mask_sha256"] == "c8e7f8e30cd532b82e6af4b98d596bc7106f29f9fb2b398b44355e624898a30d"
52
+ result = {"model": "meta-llama/Llama-3.1-8B", "removed_blocks": 8,
53
+ "method": "native MKA plus stagewise MLP-only FiT", "fit_scope": "mlp",
54
+ "accuracy_scale": "fraction", "rows": rows,
55
+ "profile": json.loads((a.root / "batch_profile.json").read_text()),
56
+ "selection_provenance": json.loads((a.root / "selection_provenance.json").read_text()),
57
+ "qualification": "Native MKA100x512 seed0 geometry; same FiT512x1024/LR/loss/epochs as CoMe controls; larger batch has fewer optimizer updates and may change later pair selections"}
58
+ destination = a.output or a.root / "summary.json"
59
+ destination.parent.mkdir(parents=True, exist_ok=True)
60
+ destination.write_text(json.dumps(result, indent=2) + "\n")
61
+ for row in rows:
62
+ print({key: row[key] for key in ("arm", "batch_size", "bench12", "mmlu", "cmmlu", "ppl", "training_wall_seconds")})
63
+
64
+
65
+ if __name__ == "__main__":
66
+ main()
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/come.py ADDED
@@ -0,0 +1,612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Native Hugging Face implementation of CoMe structured layer pruning.
2
+
3
+ This module implements the pruning-only portion of CoMe for decoder-only
4
+ models whose blocks use Llama-style attention and gated MLP projections. It
5
+ intentionally does not implement post-pruning distillation.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import math
12
+ from dataclasses import asdict, dataclass
13
+ from pathlib import Path
14
+ from typing import Iterable, Sequence
15
+
16
+ import torch
17
+ from torch import Tensor, nn
18
+ from tqdm.auto import tqdm
19
+
20
+
21
+ @dataclass
22
+ class CalibrationScores:
23
+ """Scores collected from one pass over the calibration sequences."""
24
+
25
+ block_importance: list[float]
26
+ pair_similarity: list[float]
27
+ attention_groups: list[Tensor]
28
+ mlp_neurons: list[Tensor]
29
+
30
+
31
+ @dataclass
32
+ class MergeRecord:
33
+ step: int
34
+ left_index: int
35
+ source_layers: list[list[int]]
36
+ retention_ratios: list[float]
37
+ retained_attention_groups: list[int]
38
+ retained_mlp_neurons: list[int]
39
+ pair_score: float
40
+
41
+
42
+ def allocate_retained_channels(total: int, ratios: Sequence[float]) -> list[int]:
43
+ """Allocate exactly ``total`` channels, putting rounding slack in the max arm."""
44
+
45
+ if total < 1:
46
+ raise ValueError("total must be positive")
47
+ if not ratios or any(value < 0 for value in ratios):
48
+ raise ValueError("ratios must be a non-empty sequence of non-negative values")
49
+ ratio_sum = float(sum(ratios))
50
+ if ratio_sum <= 0:
51
+ normalized = [1.0 / len(ratios)] * len(ratios)
52
+ else:
53
+ normalized = [float(value) / ratio_sum for value in ratios]
54
+
55
+ largest = max(range(len(normalized)), key=normalized.__getitem__)
56
+ counts = [0] * len(normalized)
57
+ for index, ratio in enumerate(normalized):
58
+ if index != largest:
59
+ counts[index] = math.floor(total * ratio)
60
+ counts[largest] = total - sum(counts)
61
+ return counts
62
+
63
+
64
+ def gqa_projection_indices(
65
+ groups: Tensor,
66
+ *,
67
+ num_attention_heads: int,
68
+ num_key_value_heads: int,
69
+ head_dim: int,
70
+ ) -> tuple[Tensor, Tensor]:
71
+ """Return Q and KV row indices for complete GQA groups.
72
+
73
+ Hugging Face stores query heads contiguously by KV group. Expanding a KV
74
+ mask with ``repeat`` mixes these groups for GQA models; this explicit
75
+ mapping keeps all query heads belonging to each selected KV head together.
76
+ """
77
+
78
+ if num_attention_heads % num_key_value_heads:
79
+ raise ValueError("num_attention_heads must be divisible by num_key_value_heads")
80
+ queries_per_kv = num_attention_heads // num_key_value_heads
81
+ q_parts: list[Tensor] = []
82
+ kv_parts: list[Tensor] = []
83
+ for group in groups.to(dtype=torch.long, device="cpu").tolist():
84
+ if group < 0 or group >= num_key_value_heads:
85
+ raise IndexError(f"KV group {group} is outside [0, {num_key_value_heads})")
86
+ q_start = group * queries_per_kv * head_dim
87
+ kv_start = group * head_dim
88
+ q_parts.append(torch.arange(q_start, q_start + queries_per_kv * head_dim))
89
+ kv_parts.append(torch.arange(kv_start, kv_start + head_dim))
90
+ empty = torch.empty(0, dtype=torch.long)
91
+ return (
92
+ torch.cat(q_parts) if q_parts else empty,
93
+ torch.cat(kv_parts) if kv_parts else empty,
94
+ )
95
+
96
+
97
+ def _copy_tensor(target: Tensor, value: Tensor) -> None:
98
+ with torch.no_grad():
99
+ target.copy_(value.to(device=target.device, dtype=target.dtype))
100
+
101
+
102
+ def _selected_indices(scores: Tensor, count: int) -> Tensor:
103
+ if count == 0:
104
+ return torch.empty(0, dtype=torch.long)
105
+ if count > scores.numel():
106
+ raise ValueError(f"cannot select {count} values from {scores.numel()} scores")
107
+ # Sorting the selected indices preserves the original within-layer order.
108
+ return torch.sort(torch.topk(scores.float(), count, largest=True).indices).values.cpu()
109
+
110
+
111
+ def _cat_selected(
112
+ modules: Sequence[nn.Linear],
113
+ indices: Sequence[Tensor],
114
+ *,
115
+ dimension: int,
116
+ ) -> Tensor:
117
+ chunks = []
118
+ for module, selected in zip(modules, indices, strict=True):
119
+ chunks.append(torch.index_select(module.weight.detach(), dimension, selected.to(module.weight.device)))
120
+ return torch.cat(chunks, dim=dimension)
121
+
122
+
123
+ def _weighted_optional_bias(modules: Sequence[nn.Linear], ratios: Sequence[float]) -> Tensor | None:
124
+ biases = [module.bias for module in modules]
125
+ if all(bias is None for bias in biases):
126
+ return None
127
+ if any(bias is None for bias in biases):
128
+ raise ValueError("projection bias presence differs across the layers being merged")
129
+ assert all(bias is not None for bias in biases)
130
+ result = torch.zeros_like(biases[0])
131
+ for bias, ratio in zip(biases, ratios, strict=True):
132
+ result.add_(bias.detach().to(result.device), alpha=float(ratio))
133
+ return result
134
+
135
+
136
+ def merge_attention(
137
+ layers: Sequence[nn.Module],
138
+ ratios: Sequence[float],
139
+ group_scores: Sequence[Tensor],
140
+ ) -> list[int]:
141
+ """Merge attention projections in-place into the first decoder layer."""
142
+
143
+ attentions = [layer.self_attn for layer in layers]
144
+ first = attentions[0]
145
+ q_heads = int(first.config.num_attention_heads)
146
+ kv_heads = int(first.config.num_key_value_heads)
147
+ head_dim = int(getattr(first, "head_dim", first.q_proj.out_features // q_heads))
148
+ counts = allocate_retained_channels(kv_heads, ratios)
149
+ groups = [_selected_indices(score, count) for score, count in zip(group_scores, counts, strict=True)]
150
+ q_indices: list[Tensor] = []
151
+ kv_indices: list[Tensor] = []
152
+ for selected in groups:
153
+ q_index, kv_index = gqa_projection_indices(
154
+ selected,
155
+ num_attention_heads=q_heads,
156
+ num_key_value_heads=kv_heads,
157
+ head_dim=head_dim,
158
+ )
159
+ q_indices.append(q_index)
160
+ kv_indices.append(kv_index)
161
+
162
+ q_modules = [attention.q_proj for attention in attentions]
163
+ k_modules = [attention.k_proj for attention in attentions]
164
+ v_modules = [attention.v_proj for attention in attentions]
165
+ o_modules = [attention.o_proj for attention in attentions]
166
+ q_weight = _cat_selected(q_modules, q_indices, dimension=0)
167
+ k_weight = _cat_selected(k_modules, kv_indices, dimension=0)
168
+ v_weight = _cat_selected(v_modules, kv_indices, dimension=0)
169
+ o_weight = _cat_selected(o_modules, q_indices, dimension=1)
170
+
171
+ _copy_tensor(first.q_proj.weight, q_weight)
172
+ _copy_tensor(first.k_proj.weight, k_weight)
173
+ _copy_tensor(first.v_proj.weight, v_weight)
174
+ _copy_tensor(first.o_proj.weight, o_weight)
175
+ for destination, source_modules, selected in (
176
+ (first.q_proj, q_modules, q_indices),
177
+ (first.k_proj, k_modules, kv_indices),
178
+ (first.v_proj, v_modules, kv_indices),
179
+ ):
180
+ biases = [module.bias for module in source_modules]
181
+ if not all(bias is None for bias in biases):
182
+ if any(bias is None for bias in biases):
183
+ raise ValueError("projection bias presence differs across merged layers")
184
+ bias_chunks = [
185
+ torch.index_select(module.bias.detach(), 0, index.to(module.bias.device))
186
+ for module, index in zip(source_modules, selected, strict=True)
187
+ ]
188
+ assert destination.bias is not None
189
+ _copy_tensor(destination.bias, torch.cat(bias_chunks))
190
+ merged_o_bias = _weighted_optional_bias(o_modules, ratios)
191
+ if merged_o_bias is not None:
192
+ assert first.o_proj.bias is not None
193
+ _copy_tensor(first.o_proj.bias, merged_o_bias)
194
+
195
+ # Qwen3 applies a shared per-head RMSNorm after Q/K projection. It cannot
196
+ # be sliced by group, so use the same convex merge as other shared values.
197
+ for norm_name in ("q_norm", "k_norm"):
198
+ norms = [getattr(attention, norm_name, None) for attention in attentions]
199
+ if all(norm is None for norm in norms):
200
+ continue
201
+ if any(norm is None for norm in norms):
202
+ raise ValueError(f"{norm_name} presence differs across merged layers")
203
+ destination = norms[0]
204
+ merged = torch.zeros_like(destination.weight)
205
+ for norm, ratio in zip(norms, ratios, strict=True):
206
+ merged.add_(norm.weight.detach().to(merged.device), alpha=float(ratio))
207
+ _copy_tensor(destination.weight, merged)
208
+
209
+ return counts
210
+
211
+
212
+ def merge_mlp(
213
+ layers: Sequence[nn.Module],
214
+ ratios: Sequence[float],
215
+ neuron_scores: Sequence[Tensor],
216
+ ) -> list[int]:
217
+ """Merge gated MLP projections in-place into the first decoder layer."""
218
+
219
+ mlps = [layer.mlp for layer in layers]
220
+ intermediate_size = int(mlps[0].gate_proj.out_features)
221
+ counts = allocate_retained_channels(intermediate_size, ratios)
222
+ selected = [_selected_indices(score, count) for score, count in zip(neuron_scores, counts, strict=True)]
223
+
224
+ for name in ("gate_proj", "up_proj"):
225
+ modules = [getattr(mlp, name) for mlp in mlps]
226
+ merged = _cat_selected(modules, selected, dimension=0)
227
+ destination = getattr(mlps[0], name)
228
+ _copy_tensor(destination.weight, merged)
229
+ biases = [module.bias for module in modules]
230
+ if not all(bias is None for bias in biases):
231
+ if any(bias is None for bias in biases):
232
+ raise ValueError(f"{name} bias presence differs across merged layers")
233
+ bias_chunks = [
234
+ torch.index_select(module.bias.detach(), 0, index.to(module.bias.device))
235
+ for module, index in zip(modules, selected, strict=True)
236
+ ]
237
+ assert destination.bias is not None
238
+ _copy_tensor(destination.bias, torch.cat(bias_chunks))
239
+
240
+ down_modules = [mlp.down_proj for mlp in mlps]
241
+ _copy_tensor(mlps[0].down_proj.weight, _cat_selected(down_modules, selected, dimension=1))
242
+ merged_bias = _weighted_optional_bias(down_modules, ratios)
243
+ if merged_bias is not None:
244
+ assert mlps[0].down_proj.bias is not None
245
+ _copy_tensor(mlps[0].down_proj.bias, merged_bias)
246
+ return counts
247
+
248
+
249
+ def merge_norms(layers: Sequence[nn.Module]) -> None:
250
+ """Average the two residual-stream norms into the destination block."""
251
+
252
+ for name in ("input_layernorm", "post_attention_layernorm"):
253
+ norms = [getattr(layer, name) for layer in layers]
254
+ destination = norms[0]
255
+ _copy_tensor(destination.weight, torch.stack([norm.weight.detach().to(destination.weight.device) for norm in norms]).mean(0))
256
+ destination_bias = getattr(destination, "bias", None)
257
+ if destination_bias is not None:
258
+ source_biases = [getattr(norm, "bias", None) for norm in norms]
259
+ if any(bias is None for bias in source_biases):
260
+ raise ValueError(f"{name} bias presence differs across merged layers")
261
+ _copy_tensor(
262
+ destination_bias,
263
+ torch.stack([bias.detach().to(destination_bias.device) for bias in source_biases]).mean(0),
264
+ )
265
+
266
+
267
+ def compute_retention_ratios(
268
+ importance: Sequence[float],
269
+ *,
270
+ power: float,
271
+ minimum: float,
272
+ ) -> list[float]:
273
+ if power < 0:
274
+ raise ValueError("power must be non-negative")
275
+ if not 0 <= minimum <= 1:
276
+ raise ValueError("minimum must be in [0, 1]")
277
+ values = [max(float(value), 0.0) ** power for value in importance]
278
+ total = sum(values)
279
+ ratios = [value / total for value in values] if total > 0 else [1 / len(values)] * len(values)
280
+ largest = max(range(len(ratios)), key=ratios.__getitem__)
281
+ if ratios[largest] < minimum:
282
+ if len(ratios) == 1:
283
+ return [1.0]
284
+ remainder = sum(ratios) - ratios[largest]
285
+ scale = (1.0 - minimum) / remainder if remainder > 0 else 0.0
286
+ ratios = [ratio * scale for ratio in ratios]
287
+ ratios[largest] = minimum
288
+ return ratios
289
+
290
+
291
+ class _ProjectionScoreCollector:
292
+ def __init__(self, modules: Sequence[nn.Linear]):
293
+ self.scores = [torch.zeros(module.in_features, dtype=torch.float64) for module in modules]
294
+ self._handles = []
295
+ for index, module in enumerate(modules):
296
+ self._handles.append(module.register_forward_pre_hook(self._hook(index)))
297
+
298
+ def _hook(self, index: int):
299
+ def collect(module: nn.Linear, inputs: tuple[Tensor, ...]) -> None:
300
+ activation = inputs[0].detach().float().abs()
301
+ reduce_dims = tuple(range(activation.ndim - 1))
302
+ activation_sum = activation.sum(dim=reduce_dims)
303
+ weight_l1 = module.weight.detach().float().abs().sum(dim=0)
304
+ self.scores[index].add_((activation_sum * weight_l1).double().cpu())
305
+
306
+ return collect
307
+
308
+ def close(self) -> None:
309
+ for handle in self._handles:
310
+ handle.remove()
311
+
312
+
313
+ def _angular_distance(left: Tensor, right: Tensor, *, last_token_only: bool) -> Tensor:
314
+ if last_token_only:
315
+ left = left[:, -1:, :]
316
+ right = right[:, -1:, :]
317
+ cosine = torch.nn.functional.cosine_similarity(left.float(), right.float(), dim=-1)
318
+ if last_token_only:
319
+ return torch.acos(cosine.clamp(0, 1)) / math.pi
320
+ return 1 - cosine
321
+
322
+
323
+ @torch.inference_mode()
324
+ def collect_calibration_scores(
325
+ model: nn.Module,
326
+ batches: Iterable[dict[str, Tensor]],
327
+ *,
328
+ sbi_metric: str = "angular_last",
329
+ ) -> CalibrationScores:
330
+ """Collect CoMe block, adjacent-pair, attention, and MLP scores."""
331
+
332
+ if sbi_metric not in {"angular_last", "cosine_all"}:
333
+ raise ValueError("sbi_metric must be 'angular_last' or 'cosine_all'")
334
+ backbone = model.model
335
+ layers = list(backbone.layers)
336
+ attention = _ProjectionScoreCollector([layer.self_attn.o_proj for layer in layers])
337
+ mlp = _ProjectionScoreCollector([layer.mlp.down_proj for layer in layers])
338
+ block_sums = torch.zeros(len(layers), dtype=torch.float64)
339
+ pair_sums = torch.zeros(len(layers) - 1, dtype=torch.float64)
340
+ block_count = 0
341
+ pair_count = 0
342
+ input_device = model.get_input_embeddings().weight.device
343
+ try:
344
+ for batch in tqdm(batches, desc=f"CoMe calibration ({len(layers)} layers)"):
345
+ prepared = {key: value.to(input_device) for key, value in batch.items()}
346
+ outputs = backbone(
347
+ **prepared,
348
+ use_cache=False,
349
+ output_hidden_states=True,
350
+ return_dict=True,
351
+ )
352
+ hidden = outputs.hidden_states
353
+ for index in range(len(layers)):
354
+ distance = _angular_distance(hidden[index], hidden[index + 1], last_token_only=False)
355
+ block_sums[index] += distance.double().sum().cpu()
356
+ batch_token_count = hidden[0].shape[0] * hidden[0].shape[1]
357
+ block_count += batch_token_count
358
+ for index in range(len(layers) - 1):
359
+ distance = _angular_distance(
360
+ hidden[index],
361
+ hidden[index + 2],
362
+ last_token_only=sbi_metric == "angular_last",
363
+ )
364
+ pair_sums[index] += distance.double().sum().cpu()
365
+ pair_count += hidden[0].shape[0] if sbi_metric == "angular_last" else batch_token_count
366
+ finally:
367
+ attention.close()
368
+ mlp.close()
369
+
370
+ if block_count == 0:
371
+ raise ValueError("calibration batches are empty")
372
+ attention_groups: list[Tensor] = []
373
+ for layer, score in zip(layers, attention.scores, strict=True):
374
+ attn = layer.self_attn
375
+ q_heads = int(attn.config.num_attention_heads)
376
+ kv_heads = int(attn.config.num_key_value_heads)
377
+ head_dim = int(getattr(attn, "head_dim", attn.q_proj.out_features // q_heads))
378
+ queries_per_kv = q_heads // kv_heads
379
+ expected = kv_heads * queries_per_kv * head_dim
380
+ if score.numel() != expected:
381
+ raise ValueError(f"unexpected attention input width {score.numel()} (expected {expected})")
382
+ attention_groups.append(score.reshape(kv_heads, queries_per_kv, head_dim).mean((1, 2)))
383
+ return CalibrationScores(
384
+ block_importance=(block_sums / block_count).tolist(),
385
+ pair_similarity=(pair_sums / max(pair_count, 1)).tolist(),
386
+ attention_groups=attention_groups,
387
+ mlp_neurons=mlp.scores,
388
+ )
389
+
390
+
391
+ def _choose_pair(pair_scores: Sequence[float], lineage: Sequence[Sequence[int]], allow_repeat: bool) -> int:
392
+ candidates = []
393
+ for index, score in enumerate(pair_scores):
394
+ repeated = len(lineage[index]) > 1 or len(lineage[index + 1]) > 1
395
+ if allow_repeat or not repeated:
396
+ candidates.append((float(score), index))
397
+ if not candidates:
398
+ raise RuntimeError(
399
+ "no legal adjacent pair remains; use --allow-repeat or choose a target at least ceil(original_layers / 2)"
400
+ )
401
+ return min(candidates)[1]
402
+
403
+
404
+ def _update_config_after_delete(model: nn.Module, deleted_index: int) -> None:
405
+ model.config.num_hidden_layers = len(model.model.layers)
406
+ if hasattr(model.config, "layer_types") and model.config.layer_types is not None:
407
+ layer_types = list(model.config.layer_types)
408
+ if deleted_index < len(layer_types):
409
+ del layer_types[deleted_index]
410
+ model.config.layer_types = layer_types
411
+ for index, layer in enumerate(model.model.layers):
412
+ if hasattr(layer.self_attn, "layer_idx"):
413
+ layer.self_attn.layer_idx = index
414
+
415
+
416
+ @torch.inference_mode()
417
+ def progressive_prune(
418
+ model: nn.Module,
419
+ calibration_batches: Sequence[dict[str, Tensor]],
420
+ *,
421
+ target_layers: int,
422
+ power: float = 1.0,
423
+ minimum_retention: float = 0.0,
424
+ allow_repeat: bool = False,
425
+ sbi_metric: str = "angular_last",
426
+ ) -> list[MergeRecord]:
427
+ """Progressively merge adjacent layer pairs until ``target_layers`` remain."""
428
+
429
+ original_layers = len(model.model.layers)
430
+ if not 1 <= target_layers <= original_layers:
431
+ raise ValueError(f"target_layers must be in [1, {original_layers}]")
432
+ if not allow_repeat and target_layers < math.ceil(original_layers / 2):
433
+ raise ValueError("without repeated merges, target_layers cannot be below ceil(original_layers / 2)")
434
+ lineage: list[list[int]] = [[index] for index in range(original_layers)]
435
+ records: list[MergeRecord] = []
436
+ model.eval()
437
+ model.config.use_cache = False
438
+
439
+ while len(model.model.layers) > target_layers:
440
+ scores = collect_calibration_scores(model, calibration_batches, sbi_metric=sbi_metric)
441
+ left = _choose_pair(scores.pair_similarity, lineage, allow_repeat)
442
+ indices = [left, left + 1]
443
+ leaf_count = sum(len(lineage[index]) for index in indices)
444
+ adjusted_minimum = minimum_retention
445
+ if allow_repeat and minimum_retention > 0 and leaf_count > 2:
446
+ adjusted_minimum = minimum_retention ** (1 / (leaf_count - 1))
447
+ ratios = compute_retention_ratios(
448
+ [scores.block_importance[index] for index in indices],
449
+ power=power,
450
+ minimum=adjusted_minimum,
451
+ )
452
+ print(
453
+ f"CoMe step {len(records) + 1}: merge current layers {left}/{left + 1} "
454
+ f"(sources {lineage[left]} + {lineage[left + 1]}, ratios={ratios})",
455
+ flush=True,
456
+ )
457
+ merge_layers = [model.model.layers[index] for index in indices]
458
+ attention_counts = merge_attention(
459
+ merge_layers,
460
+ ratios,
461
+ [scores.attention_groups[index] for index in indices],
462
+ )
463
+ mlp_counts = merge_mlp(
464
+ merge_layers,
465
+ ratios,
466
+ [scores.mlp_neurons[index] for index in indices],
467
+ )
468
+ merge_norms(merge_layers)
469
+ records.append(
470
+ MergeRecord(
471
+ step=len(records) + 1,
472
+ left_index=left,
473
+ source_layers=[list(lineage[index]) for index in indices],
474
+ retention_ratios=ratios,
475
+ retained_attention_groups=attention_counts,
476
+ retained_mlp_neurons=mlp_counts,
477
+ pair_score=float(scores.pair_similarity[left]),
478
+ )
479
+ )
480
+ del model.model.layers[left + 1]
481
+ lineage[left] = lineage[left] + lineage[left + 1]
482
+ del lineage[left + 1]
483
+ _update_config_after_delete(model, left + 1)
484
+ if torch.cuda.is_available():
485
+ torch.cuda.empty_cache()
486
+ return records
487
+
488
+
489
+ def build_wikitext2_calibration(
490
+ tokenizer,
491
+ *,
492
+ samples: int,
493
+ sequence_length: int,
494
+ seed: int,
495
+ ) -> list[dict[str, Tensor]]:
496
+ """Reproduce CoMe's shuffled WikiText-2 prefix calibration stream.
497
+
498
+ The upstream ``nsamples`` argument counts shuffled dataset rows, not 2,048
499
+ token windows. Full windows are carved from their concatenated token stream
500
+ and the short tail is discarded.
501
+ """
502
+
503
+ from datasets import load_dataset
504
+
505
+ dataset = load_dataset("wikitext", "wikitext-2-raw-v1", split="train").shuffle(seed=seed)
506
+ selected = dataset.select(range(min(samples, len(dataset))))
507
+ text = "\n\n".join(selected["text"])
508
+ token_ids = tokenizer(text, return_tensors="pt").input_ids[0]
509
+ windows = token_ids.numel() // sequence_length
510
+ if windows == 0:
511
+ raise ValueError("selected WikiText-2 rows contain fewer tokens than sequence_length")
512
+ batches = []
513
+ for index in range(windows):
514
+ start = index * sequence_length
515
+ input_ids = token_ids[start : start + sequence_length].unsqueeze(0)
516
+ batches.append({"input_ids": input_ids, "attention_mask": torch.ones_like(input_ids)})
517
+ return batches
518
+
519
+
520
+ def build_slimpajama_calibration(
521
+ tokenizer,
522
+ *,
523
+ rows: int,
524
+ sequence_length: int,
525
+ seed: int,
526
+ shuffle_buffer: int = 10_000,
527
+ ) -> list[dict[str, Tensor]]:
528
+ """Pack full windows after concatenating shuffled SlimPajama rows.
529
+
530
+ This mirrors upstream CoMe's WikiText loader: ``nsamples`` counts dataset
531
+ rows, not model-forward windows.
532
+ """
533
+
534
+ from datasets import load_dataset
535
+
536
+ if rows < 1:
537
+ raise ValueError("rows must be positive")
538
+ dataset = load_dataset(
539
+ "DKYoon/SlimPajama-6B",
540
+ split="train",
541
+ streaming=True,
542
+ ).shuffle(seed=seed, buffer_size=shuffle_buffer)
543
+ token_buffer: list[int] = []
544
+ selected_rows = 0
545
+ for row in dataset:
546
+ text = row.get("text")
547
+ selected_rows += 1
548
+ if isinstance(text, str):
549
+ token_buffer.extend(tokenizer.encode(text, add_special_tokens=False))
550
+ if selected_rows == rows:
551
+ break
552
+ if selected_rows != rows:
553
+ raise RuntimeError(f"could only read {selected_rows}/{rows} SlimPajama rows")
554
+ windows = len(token_buffer) // sequence_length
555
+ if windows == 0:
556
+ raise ValueError("selected SlimPajama rows contain fewer tokens than sequence_length")
557
+ batches: list[dict[str, Tensor]] = []
558
+ for index in range(windows):
559
+ start = index * sequence_length
560
+ input_ids = torch.tensor(token_buffer[start : start + sequence_length], dtype=torch.long).unsqueeze(0)
561
+ batches.append({"input_ids": input_ids, "attention_mask": torch.ones_like(input_ids)})
562
+ return batches
563
+
564
+
565
+ def batch_calibration(
566
+ samples: Sequence[dict[str, Tensor]], batch_size: int
567
+ ) -> list[dict[str, Tensor]]:
568
+ if batch_size < 1:
569
+ raise ValueError("batch_size must be positive")
570
+ batches = []
571
+ for start in range(0, len(samples), batch_size):
572
+ chunk = samples[start : start + batch_size]
573
+ batches.append({key: torch.cat([item[key] for item in chunk], dim=0) for key in chunk[0]})
574
+ return batches
575
+
576
+
577
+ def save_merge_metadata(
578
+ output_dir: str | Path,
579
+ *,
580
+ source_model: str,
581
+ records: Sequence[MergeRecord],
582
+ arguments: dict,
583
+ ) -> None:
584
+ path = Path(output_dir) / "come_pruning.json"
585
+ payload = {
586
+ "method": "CoMe structured pruning (no distillation)",
587
+ "source_model": source_model,
588
+ "arguments": arguments,
589
+ "merges": [asdict(record) for record in records],
590
+ }
591
+ path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
592
+
593
+
594
+ def enable_torch24_dtensor_save_compat() -> None:
595
+ """Expose PyTorch 2.4's private DTensor where Transformers 4.52 expects it."""
596
+
597
+ try:
598
+ import torch.distributed.tensor as public_tensor
599
+ except ImportError:
600
+ return
601
+ if hasattr(public_tensor, "DTensor"):
602
+ return
603
+ try:
604
+ from torch.distributed._tensor import DTensor
605
+ except ImportError:
606
+ return
607
+ public_tensor.DTensor = DTensor
608
+ # Transformers 4.52 imports this name only when it detects torch >= 2.5,
609
+ # but save_pretrained references it unconditionally on torch 2.4.
610
+ import transformers.modeling_utils as modeling_utils
611
+
612
+ modeling_utils.DTensor = DTensor
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/eval_llama31_8b_12bench.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Evaluate the lm-eval portion of the requested Llama benchmark suite.
3
+
4
+ RACE-H/M, C3, CMNLI, and CHID are evaluated with their canonical OpenCompass
5
+ PPL task definitions by the companion launcher. This script handles the
6
+ remaining eight tasks plus full zero-shot MMLU and CMMLU.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ import torch
18
+ from transformers import AutoModelForCausalLM, AutoTokenizer
19
+
20
+
21
+ TASKS = (
22
+ "piqa",
23
+ "winogrande",
24
+ "hellaswag",
25
+ "arc_challenge",
26
+ "arc_easy",
27
+ "openbookqa",
28
+ "sciq",
29
+ "mmlu",
30
+ "cmmlu",
31
+ )
32
+
33
+ # Use normalized accuracy where the standard harness exposes it. The
34
+ # extraction code falls back to plain accuracy for tasks/versions without it.
35
+ PREFERRED_METRICS = {
36
+ "piqa": "acc_norm,none",
37
+ "hellaswag": "acc_norm,none",
38
+ "arc_challenge": "acc_norm,none",
39
+ "arc_easy": "acc_norm,none",
40
+ "openbookqa": "acc_norm,none",
41
+ "sciq": "acc_norm,none",
42
+ }
43
+
44
+
45
+ def _score(task: str, result: dict[str, Any]) -> tuple[str, float]:
46
+ preferred = PREFERRED_METRICS.get(task, "acc,none")
47
+ candidates = (preferred, "acc_norm,none", "acc,none")
48
+ for metric in candidates:
49
+ value = result.get(metric)
50
+ if value is not None:
51
+ return metric, float(value)
52
+ available = sorted(key for key in result if "," in key and not key.endswith("_stderr,none"))
53
+ raise KeyError(f"No supported accuracy metric for {task}; available={available}")
54
+
55
+
56
+ def _load_model(args: argparse.Namespace):
57
+ if args.compact_stage is None:
58
+ model = AutoModelForCausalLM.from_pretrained(
59
+ args.model,
60
+ revision=args.revision,
61
+ torch_dtype=torch.bfloat16,
62
+ attn_implementation="eager",
63
+ local_files_only=args.local_files_only,
64
+ ).cuda().eval()
65
+ tokenizer = AutoTokenizer.from_pretrained(
66
+ args.model,
67
+ revision=args.revision,
68
+ local_files_only=args.local_files_only,
69
+ )
70
+ return model, tokenizer
71
+
72
+ if args.cycle is None or args.anchor is None:
73
+ raise ValueError("--compact-stage requires --cycle and --anchor")
74
+ from fusegpt.abprune_stagewise_geometry import load_compact_model
75
+
76
+ model = load_compact_model(
77
+ args.model,
78
+ args.compact_stage,
79
+ cycle=args.cycle,
80
+ anchor=args.anchor,
81
+ dtype=torch.bfloat16,
82
+ device=torch.device("cuda"),
83
+ attn="eager",
84
+ revision=args.revision,
85
+ )
86
+ tokenizer = AutoTokenizer.from_pretrained(
87
+ args.model, revision=args.revision, local_files_only=args.local_files_only)
88
+ return model, tokenizer
89
+
90
+
91
+ def main() -> None:
92
+ parser = argparse.ArgumentParser()
93
+ parser.add_argument("--model", required=True)
94
+ parser.add_argument("--revision", default=None)
95
+ parser.add_argument("--local-files-only", action="store_true")
96
+ parser.add_argument("--compact-stage", type=Path, default=None)
97
+ parser.add_argument("--cycle", type=int, default=None)
98
+ parser.add_argument("--anchor", type=int, default=None)
99
+ parser.add_argument("--batch-size", default="auto:4")
100
+ parser.add_argument("--limit", type=float, default=None)
101
+ parser.add_argument("--output", type=Path, required=True)
102
+ parser.add_argument("--dataset-cache", type=Path, default=None)
103
+ parser.add_argument("--tasks", nargs="+", choices=TASKS, default=list(TASKS),
104
+ help="Evaluate a subset without repeating already scored tasks")
105
+ args = parser.parse_args()
106
+ if len(set(args.tasks)) != len(args.tasks):
107
+ parser.error("--tasks must not contain duplicates")
108
+
109
+ # CMMLU is still distributed through a Hugging Face dataset loading
110
+ # script. Opt in explicitly so non-interactive experiment jobs do not
111
+ # stop at the datasets trust prompt.
112
+ os.environ.setdefault("HF_DATASETS_TRUST_REMOTE_CODE", "1")
113
+
114
+ from lm_eval import evaluator
115
+ from lm_eval.models.huggingface import HFLM
116
+
117
+ if args.dataset_cache is not None:
118
+ from prepare_lmeval9_local_cache import install_local_loader
119
+ install_local_loader(args.dataset_cache)
120
+
121
+ model, tokenizer = _load_model(args)
122
+ model.config.use_cache = False
123
+ if getattr(model, "generation_config", None) is not None:
124
+ model.generation_config.use_cache = False
125
+ for layer_idx, layer in enumerate(model.model.layers):
126
+ if hasattr(layer, "self_attn") and hasattr(layer.self_attn, "layer_idx"):
127
+ layer.self_attn.layer_idx = layer_idx
128
+
129
+ lm = HFLM(
130
+ pretrained=model,
131
+ tokenizer=tokenizer,
132
+ backend="causal",
133
+ batch_size=args.batch_size,
134
+ )
135
+ raw = evaluator.simple_evaluate(
136
+ model=lm,
137
+ tasks=args.tasks,
138
+ num_fewshot=0,
139
+ batch_size=args.batch_size,
140
+ random_seed=0,
141
+ numpy_random_seed=1234,
142
+ torch_random_seed=1234,
143
+ fewshot_random_seed=1234,
144
+ bootstrap_iters=0,
145
+ limit=args.limit,
146
+ )
147
+
148
+ scores: dict[str, float] = {}
149
+ metrics: dict[str, str] = {}
150
+ for task in args.tasks:
151
+ source = raw.get("groups", {}) if task in {"mmlu", "cmmlu"} else raw["results"]
152
+ if task not in source:
153
+ raise KeyError(
154
+ f"Requested task {task!r} missing from lm-eval results: "
155
+ f"results={sorted(raw['results'])}, groups={sorted(raw.get('groups', {}))}"
156
+ )
157
+ metric, value = _score(task, source[task])
158
+ metrics[task] = metric
159
+ scores[task] = value
160
+
161
+ report = {
162
+ "model": args.model,
163
+ "revision": args.revision,
164
+ "compact_stage": str(args.compact_stage) if args.compact_stage else None,
165
+ "cycle": args.cycle,
166
+ "anchor": args.anchor,
167
+ "tasks": args.tasks,
168
+ "num_fewshot": 0,
169
+ "batch_size": args.batch_size,
170
+ "limit": args.limit,
171
+ "dataset_cache": str(args.dataset_cache) if args.dataset_cache else None,
172
+ "preferred_metrics": metrics,
173
+ "task_scores": scores,
174
+ "macro_mean_all_rows": sum(scores.values()) / len(scores),
175
+ "lm_eval_results": raw["results"],
176
+ "lm_eval_groups": raw.get("groups"),
177
+ "lm_eval_versions": raw.get("versions"),
178
+ "lm_eval_config": raw.get("config"),
179
+ }
180
+ args.output.parent.mkdir(parents=True, exist_ok=True)
181
+ args.output.write_text(
182
+ json.dumps(report, indent=2, ensure_ascii=False, default=str) + "\n",
183
+ encoding="utf-8",
184
+ )
185
+ print(
186
+ json.dumps(
187
+ {"task_scores": scores, "macro_mean_all_rows": report["macro_mean_all_rows"]},
188
+ indent=2,
189
+ )
190
+ )
191
+
192
+
193
+ if __name__ == "__main__":
194
+ main()
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/eval_llama31_fit_ablation_one.sh ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ project="$1"; root="$2"; model="$3"; data="$4"; python="$5"
4
+ anchor="$6"; cycles="$7"; gpu="$8"
5
+ stage="$root/compact/stage_$(printf '%02d' "$cycles")"
6
+ export HF_HOME=/workspace/.hf_home HF_TOKEN_PATH=/root/.cache/huggingface/token
7
+ export HF_DATASETS_CACHE=/workspace/.hf_datasets36 HF_DATASETS_TRUST_REMOTE_CODE=1
8
+ export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 PYTHONPATH="$project/src"
9
+ revision="${MODEL_REVISION:-49e3418fbbbca6ecbdf9608b4d22e5a407081db4}"
10
+ if [[ -n "${LMEVAL_LOCAL_CACHE:-}" ]]; then
11
+ export HF_HUB_OFFLINE=1 HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1
12
+ [[ -d "$model" ]] || { echo 'Offline bench requires a local model directory'; exit 1; }
13
+ "$python" "$project/scripts/prepare_lmeval9_local_cache.py" "$LMEVAL_LOCAL_CACHE" --validate-local
14
+ for file in race/test/high.jsonl race/test/middle.jsonl CLUE/C3/dev_0.json CLUE/cmnli/cmnli_public/dev.json FewCLUE/chid/dev_few_all.json; do
15
+ [[ -s "$data/$file" ]] || { echo "Offline OpenCompass input missing: $file"; exit 1; }
16
+ done
17
+ echo 'STRICT_OFFLINE_BENCH_PREFLIGHT_OK'
18
+ fi
19
+ opencompass_gpu="$gpu"; lmeval_gpu="${9:-$gpu}"
20
+ if [[ -f "$root/eval/gpu_assignment.json" ]]; then
21
+ read -r opencompass_gpu lmeval_gpu < <("$python" - "$root/eval/gpu_assignment.json" <<'PY'
22
+ import json, sys
23
+ assignment = json.load(open(sys.argv[1]))
24
+ values = [assignment[key] for key in ("opencompass_gpu", "lmeval_gpu")]
25
+ assert all(type(value) is int and value >= 0 for value in values)
26
+ print(*values)
27
+ PY
28
+ )
29
+ fi
30
+ run_opencompass() {
31
+ [[ -f "$root/eval/final_opencompass5.json" ]] && return 0
32
+ CUDA_VISIBLE_DEVICES="$opencompass_gpu" "$python" "$project/scripts/eval_opencompass_ppl_fast.py" \
33
+ --model "$model" --revision "$revision" --tokenizer "$model" \
34
+ --compact-stage "$stage" --cycle "$cycles" --anchor "$anchor" \
35
+ --data-root "$data" --max-batch 32 --token-budget 8192 \
36
+ --output "$root/eval/final_opencompass5.json"
37
+ }
38
+ run_lmeval() {
39
+ [[ -f "$root/eval/final_lmeval9.json" ]] && return 0
40
+ local cache_args=()
41
+ if [[ -n "${LMEVAL_LOCAL_CACHE:-}" ]]; then
42
+ [[ -f "$LMEVAL_LOCAL_CACHE/manifest.json" ]] || return 1
43
+ cache_args=(--dataset-cache "$LMEVAL_LOCAL_CACHE" --local-files-only)
44
+ export HF_HUB_OFFLINE=1 HF_DATASETS_OFFLINE=1
45
+ fi
46
+ CUDA_VISIBLE_DEVICES="$lmeval_gpu" "$python" "$project/scripts/eval_llama31_8b_12bench.py" \
47
+ --model "$model" --revision "$revision" --compact-stage "$stage" \
48
+ --cycle "$cycles" --anchor "$anchor" --batch-size auto:4 \
49
+ --output "$root/eval/final_lmeval9.json" "${cache_args[@]}"
50
+ }
51
+ if [[ "$opencompass_gpu" != "$lmeval_gpu" ]]; then
52
+ echo "Parallel evaluation: OpenCompass GPU=$opencompass_gpu; lm-eval GPU=$lmeval_gpu"
53
+ run_opencompass >> "$root/logs/eval_opencompass.log" 2>&1 & oc_pid=$!
54
+ run_lmeval >> "$root/logs/eval_lmeval.log" 2>&1 & lm_pid=$!
55
+ status=0
56
+ wait "$oc_pid" || status=1
57
+ wait "$lm_pid" || status=1
58
+ if ((status)); then exit 1; fi
59
+ else
60
+ run_opencompass >> "$root/logs/eval14.log" 2>&1
61
+ run_lmeval >> "$root/logs/eval14.log" 2>&1
62
+ fi
63
+ "$python" "$project/scripts/aggregate_transport_rho_fit_14bench.py" "$root"
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/evaluate_abprune_compact_ppl.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Evaluate an unscaled or residual-scaled compact ABPrune checkpoint."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ from contextlib import ExitStack
9
+ from pathlib import Path
10
+ import sys
11
+
12
+ from offline_eval_policy import apply_run_offline_policy
13
+
14
+ OFFLINE_POLICY = apply_run_offline_policy(sys.argv)
15
+
16
+ import torch
17
+
18
+ from evaluate_hchc_wikitext2_ppl import evaluate_perplexity, packed_wikitext_tokens
19
+ from fusegpt.abprune_residual_scale import residual_scale_hook
20
+ from fusegpt.abprune_compact import compact_scale_targets, read_compact_metadata
21
+ from fusegpt.abprune_stagewise_geometry import load_compact_model
22
+ from fusegpt.hadamard_channel_fusion import linear_patch_hook
23
+
24
+
25
+ def main() -> None:
26
+ parser = argparse.ArgumentParser()
27
+ parser.add_argument("--model", required=True)
28
+ parser.add_argument("--revision", required=True)
29
+ parser.add_argument("--compact-stage", type=Path, required=True)
30
+ parser.add_argument("--output", type=Path, required=True)
31
+ parser.add_argument("--anchor", type=int, default=None)
32
+ parser.add_argument("--cycles", type=int, required=True)
33
+ parser.add_argument("--original-layers", type=int, required=True)
34
+ parser.add_argument("--seq-len", type=int, default=2048)
35
+ parser.add_argument("--batch-size", type=int, default=4)
36
+ parser.add_argument("--device", default="cuda")
37
+ parser.add_argument("--apply-post-merge-scale", action="store_true")
38
+ parser.add_argument("--linear-patch", type=Path, default=None)
39
+ args = parser.parse_args()
40
+
41
+ # Long training supervisors may be asked to stop after model construction.
42
+ # A run-local marker makes that request durable without killing training.
43
+ run_root = args.output.parent.parent
44
+ if (run_root / "DEFER_EVAL").exists():
45
+ print(f"[eval] deferred by {run_root / 'DEFER_EVAL'}", flush=True)
46
+ raise SystemExit(75)
47
+
48
+ device = torch.device(args.device)
49
+ model = load_compact_model(
50
+ args.model,
51
+ args.compact_stage,
52
+ cycle=args.cycles,
53
+ anchor=args.anchor,
54
+ dtype=torch.bfloat16,
55
+ device=device,
56
+ attn="eager",
57
+ revision=args.revision,
58
+ )
59
+ model.eval()
60
+ expected_depth = args.original_layers - args.cycles
61
+ if len(model.model.layers) != expected_depth:
62
+ raise RuntimeError(
63
+ f"Unexpected decoder depth: {len(model.model.layers)} != {expected_depth}"
64
+ )
65
+
66
+ from transformers import AutoTokenizer
67
+
68
+ if OFFLINE_POLICY and not Path(args.model).is_dir():
69
+ raise ValueError('Strict offline PPL requires a local model directory')
70
+ tokenizer = AutoTokenizer.from_pretrained(
71
+ args.model, revision=args.revision, local_files_only=bool(OFFLINE_POLICY))
72
+ applied_scales = []
73
+ scale_stack = ExitStack()
74
+ linear_patch = None
75
+ if args.apply_post_merge_scale:
76
+ metadata = read_compact_metadata(args.compact_stage)
77
+ targets = compact_scale_targets(metadata)
78
+ if not targets:
79
+ raise RuntimeError(
80
+ "--apply-post-merge-scale requires enabled residual scale metadata"
81
+ )
82
+ for target in targets:
83
+ stored_scale = target["scale"]["cumulative_gamma"]
84
+ applied = (
85
+ torch.tensor(stored_scale, device=device, dtype=torch.float32)
86
+ if isinstance(stored_scale, list)
87
+ else float(stored_scale)
88
+ )
89
+ scale_stack.enter_context(
90
+ residual_scale_hook(model, int(target["student_index"]), applied)
91
+ )
92
+ applied_scales.append(
93
+ {
94
+ "original_layer": int(target["original_layer"]),
95
+ "student_index": int(target["student_index"]),
96
+ "value": applied,
97
+ }
98
+ )
99
+ if args.linear_patch is not None:
100
+ linear_patch = json.loads(args.linear_patch.read_text(encoding="utf-8"))
101
+ patch_scale = torch.tensor(
102
+ linear_patch["scale"], device=device, dtype=torch.float32
103
+ )
104
+ patch_anchor = int(linear_patch["anchor_student_index"])
105
+ scale_stack.enter_context(
106
+ linear_patch_hook(
107
+ model.model.layers[patch_anchor],
108
+ patch_scale,
109
+ hadamard=linear_patch["mode"] == "hadamard",
110
+ )
111
+ )
112
+
113
+ with scale_stack:
114
+ tokens = packed_wikitext_tokens(
115
+ tokenizer, "test", dataset_cache=(
116
+ Path(OFFLINE_POLICY['wikitext_cache']) if OFFLINE_POLICY else None))
117
+ metrics = evaluate_perplexity(
118
+ model=model,
119
+ tokens=tokens,
120
+ sequence_length=args.seq_len,
121
+ batch_size=args.batch_size,
122
+ )
123
+
124
+ report = {
125
+ "model": args.model,
126
+ "revision": args.revision,
127
+ "compact_stage": str(args.compact_stage),
128
+ "dataset": "Salesforce/wikitext:wikitext-2-raw-v1:test",
129
+ "offline_policy": OFFLINE_POLICY,
130
+ "protocol": (
131
+ "HCHC experiment.py: filter empty rows, join with double newline, "
132
+ "then tokenize the complete stream once"
133
+ ),
134
+ "sequence_length": args.seq_len,
135
+ "batch_size": args.batch_size,
136
+ "dtype": "bfloat16",
137
+ "metrics": metrics,
138
+ "anchor": args.anchor,
139
+ "cycles": args.cycles,
140
+ "original_layers": args.original_layers,
141
+ "decoder_layers": len(model.model.layers),
142
+ "post_merge_residual_scale": (
143
+ applied_scales[0]["value"].tolist()
144
+ if len(applied_scales) == 1
145
+ and torch.is_tensor(applied_scales[0]["value"])
146
+ else (
147
+ applied_scales[0]["value"]
148
+ if len(applied_scales) == 1
149
+ else None
150
+ )
151
+ ),
152
+ "post_merge_residual_scales": [
153
+ {
154
+ "original_layer": item["original_layer"],
155
+ "student_index": item["student_index"],
156
+ "parameterization": (
157
+ "vector" if torch.is_tensor(item["value"]) else "scalar"
158
+ ),
159
+ "value": (
160
+ item["value"].tolist()
161
+ if torch.is_tensor(item["value"])
162
+ else item["value"]
163
+ ),
164
+ }
165
+ for item in applied_scales
166
+ ],
167
+ "parameterization": (
168
+ "X_interface <- X_interface H D H.T"
169
+ if linear_patch and linear_patch["mode"] == "hadamard"
170
+ else (
171
+ "X_interface <- X_interface D"
172
+ if linear_patch
173
+ else (
174
+ "h_out = h_in + gamma * (block(h_in) - h_in)"
175
+ if applied_scales else "unscaled compact ABPrune"
176
+ )
177
+ )
178
+ ),
179
+ "linear_patch": linear_patch,
180
+ }
181
+ args.output.parent.mkdir(parents=True, exist_ok=True)
182
+ args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
183
+ print(json.dumps(report, indent=2), flush=True)
184
+
185
+
186
+ if __name__ == "__main__":
187
+ main()
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/evaluate_hchc_wikitext2_ppl.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Evaluate a saved causal LM with the HCHC WikiText-2 PPL protocol."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import math
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import torch
13
+ from datasets import load_dataset, load_from_disk
14
+
15
+
16
+ def primary(output: Any) -> torch.Tensor:
17
+ if torch.is_tensor(output):
18
+ return output
19
+ if isinstance(output, (tuple, list)) and output and torch.is_tensor(output[0]):
20
+ return output[0]
21
+ raise TypeError(f"Unsupported decoder-layer output type: {type(output)!r}")
22
+
23
+
24
+ def replace_primary(output: Any, hidden: torch.Tensor) -> Any:
25
+ if torch.is_tensor(output):
26
+ return hidden
27
+ if isinstance(output, tuple):
28
+ return (hidden, *output[1:])
29
+ if isinstance(output, list):
30
+ return [hidden, *output[1:]]
31
+ raise TypeError(f"Unsupported decoder-layer output type: {type(output)!r}")
32
+
33
+
34
+ def register_residual_scale_hook(layer, gamma: float):
35
+ """Install h_out = h_in + gamma * (block(h_in) - h_in)."""
36
+ scale = torch.tensor(gamma, device=next(layer.parameters()).device)
37
+
38
+ def hook(_module, inputs, output):
39
+ if not inputs or not torch.is_tensor(inputs[0]):
40
+ raise RuntimeError("Could not capture decoder-layer residual input")
41
+ layer_input = inputs[0]
42
+ corrected = layer_input + scale * (primary(output) - layer_input)
43
+ return replace_primary(output, corrected)
44
+
45
+ return layer.register_forward_hook(hook)
46
+
47
+
48
+ def packed_wikitext_tokens(tokenizer, split: str, *, dataset_cache: Path | None = None) -> torch.Tensor:
49
+ """Reproduce the canonical HCHC WikiText-2 packing protocol."""
50
+ if dataset_cache is not None:
51
+ dataset = load_from_disk(str(dataset_cache))[split]
52
+ else:
53
+ dataset = load_dataset(
54
+ "Salesforce/wikitext", "wikitext-2-raw-v1", split=split
55
+ )
56
+ text = "\n\n".join(row for row in dataset["text"] if row.strip())
57
+ return tokenizer(
58
+ text, add_special_tokens=False, return_tensors="pt"
59
+ ).input_ids[0]
60
+
61
+
62
+ @torch.no_grad()
63
+ def evaluate_perplexity(
64
+ model,
65
+ tokens: torch.Tensor,
66
+ sequence_length: int,
67
+ batch_size: int,
68
+ ) -> dict[str, float | int]:
69
+ num_sequences = tokens.numel() // sequence_length
70
+ ids = tokens[: num_sequences * sequence_length].view(num_sequences, sequence_length)
71
+ total_nll = 0.0
72
+ total_predicted_tokens = 0
73
+ model.eval()
74
+ for start in range(0, num_sequences, batch_size):
75
+ batch = ids[start : start + batch_size].to("cuda")
76
+ output = model(input_ids=batch, labels=batch, use_cache=False)
77
+ predicted = batch.shape[0] * (batch.shape[1] - 1)
78
+ total_nll += output.loss.float().item() * predicted
79
+ total_predicted_tokens += predicted
80
+ mean_nll = total_nll / total_predicted_tokens
81
+ return {
82
+ "nll": mean_nll,
83
+ "perplexity": math.exp(mean_nll),
84
+ "tokens": total_predicted_tokens,
85
+ "sequences": num_sequences,
86
+ "source_tokens": int(tokens.numel()),
87
+ }
88
+
89
+
90
+ def main() -> None:
91
+ parser = argparse.ArgumentParser()
92
+ parser.add_argument("--model", type=Path, required=True)
93
+ parser.add_argument("--output", type=Path, required=True)
94
+ parser.add_argument("--sequence-length", type=int, default=2048)
95
+ parser.add_argument("--batch-size", type=int, default=8)
96
+ parser.add_argument("--residual-anchor", type=int)
97
+ parser.add_argument("--residual-gamma", type=float)
98
+ args = parser.parse_args()
99
+
100
+ if (args.residual_anchor is None) != (args.residual_gamma is None):
101
+ parser.error("--residual-anchor and --residual-gamma must be supplied together")
102
+
103
+ from transformers import AutoModelForCausalLM, AutoTokenizer
104
+
105
+ tokenizer = AutoTokenizer.from_pretrained(args.model, local_files_only=True)
106
+ model = AutoModelForCausalLM.from_pretrained(
107
+ args.model,
108
+ torch_dtype=torch.bfloat16,
109
+ local_files_only=True,
110
+ low_cpu_mem_usage=True,
111
+ attn_implementation="sdpa",
112
+ ).to("cuda")
113
+ model.config.use_cache = False
114
+
115
+ handle = None
116
+ if args.residual_gamma is not None:
117
+ if args.residual_anchor >= len(model.model.layers):
118
+ raise ValueError(
119
+ f"Residual anchor {args.residual_anchor} is outside decoder depth "
120
+ f"{len(model.model.layers)}"
121
+ )
122
+ handle = register_residual_scale_hook(
123
+ model.model.layers[args.residual_anchor], args.residual_gamma
124
+ )
125
+
126
+ tokens = packed_wikitext_tokens(tokenizer, "test")
127
+ try:
128
+ metrics = evaluate_perplexity(
129
+ model, tokens, args.sequence_length, args.batch_size
130
+ )
131
+ finally:
132
+ if handle is not None:
133
+ handle.remove()
134
+
135
+ report = {
136
+ "model": str(args.model),
137
+ "dataset": "Salesforce/wikitext:wikitext-2-raw-v1:test",
138
+ "protocol": "HCHC experiment.py: non-empty rows joined with double newline before one-shot tokenization",
139
+ "sequence_length": args.sequence_length,
140
+ "batch_size": args.batch_size,
141
+ "dtype": "bfloat16",
142
+ "residual_anchor": args.residual_anchor,
143
+ "residual_gamma": args.residual_gamma,
144
+ "metrics": metrics,
145
+ }
146
+ args.output.parent.mkdir(parents=True, exist_ok=True)
147
+ args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
148
+ print(json.dumps(report, indent=2), flush=True)
149
+
150
+
151
+ if __name__ == "__main__":
152
+ main()
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/finalize_mka_batch_report.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Register the completed MKA MLP-only FiT pair and its matched-data controls."""
2
+ import argparse
3
+ import csv
4
+ import io
5
+ import json
6
+ import math
7
+ from pathlib import Path
8
+ import re
9
+ import subprocess
10
+
11
+
12
+ RESULT_NAME = "llama31_mka_mlp_batch_20261126"
13
+ STATE_NAME = "mka-fit-batch-20261126"
14
+ NOTE_NAME = "2026-11-26_llama31-mka-mlp-batch-comparison.md"
15
+ SESSION = "vast-paper_revision-come-attn-fit-20261126-62646539"
16
+ EXPERIMENT = "20261126-llama31-mka-mlp-batch"
17
+ INSTANCE = 62646539
18
+ MODEL_REVISION = "d04e592bb4f6aa9cfee91e2e20afa771667e1d4b"
19
+ MKA_INPUT = "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075"
20
+ COME_INPUT = "0d5ee3894a716120c8f738c25d05838ca6871137f7b471d4616da55cab4a7361"
21
+ FIT_INPUT = "2b2d044c8c040f67891817ecc110f0fa0de2f469db4c6731114ff7816bbf1cd0"
22
+ FIT_MASK = "c8e7f8e30cd532b82e6af4b98d596bc7106f29f9fb2b398b44355e624898a30d"
23
+
24
+
25
+ def load(path):
26
+ return json.loads(path.read_text(encoding="utf-8-sig"))
27
+
28
+
29
+ def read_catalog(path):
30
+ with path.open(encoding="utf-8-sig", newline="") as stream:
31
+ reader = csv.DictReader(stream)
32
+ return reader.fieldnames, list(reader)
33
+
34
+
35
+ def historical_catalog_row(path, record_id):
36
+ return next(row for row in read_catalog(path)[1] if row["record_id"] == record_id)
37
+
38
+
39
+ def validate_scores(row):
40
+ for key in ("bench12", "mmlu", "cmmlu"):
41
+ assert math.isfinite(row[key]) and 0 <= row[key] <= 1, key
42
+ assert math.isfinite(row["ppl"]) and row["ppl"] > 0
43
+
44
+
45
+ def main():
46
+ parser = argparse.ArgumentParser(description=__doc__)
47
+ parser.add_argument("--reference", type=Path,
48
+ help="Optional verified historical MKA no-FiT reference JSON, one row or {'rows': [...]} with fraction scores and source")
49
+ args = parser.parse_args()
50
+ repo = Path(__file__).resolve().parents[1]
51
+ root = repo / "results" / RESULT_NAME
52
+ summary = load(root / "summary.json")
53
+ assert summary["model"] == "meta-llama/Llama-3.1-8B" and summary["removed_blocks"] == 8
54
+ assert summary["fit_scope"] == "mlp" and len(summary["rows"]) == 2
55
+ assert {row["batch_size"] for row in summary["rows"]} == {1, 8}
56
+ assert {row["arm"] for row in summary["rows"]} == {"batch1", "batch_large"}
57
+ audit = load(repo / "outputs" / STATE_NAME / "model_backup_audit.json")
58
+ assert audit["verified"] and len(audit["records"]) == 2
59
+ assert all(record["verified"] and record["all_payload_hashes_verified"] for record in audit["records"])
60
+ audited = {(record["path_in_repo"], record["revision"]) for record in audit["records"]}
61
+ commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo).decode().strip()
62
+ catalog = repo / "results/instruct_pruning_experiment_catalog.csv"
63
+ fields, old_rows = read_catalog(catalog)
64
+ old_ids = {row["record_id"]: row for row in old_rows}
65
+ assert len(old_rows) == len(old_ids), "Existing catalog contains duplicate record IDs"
66
+
67
+ come = historical_catalog_row(repo / "results/laco_come_experiment_catalog.csv",
68
+ "llama31_base_come_allowrepeat_8block")
69
+ ab = old_ids["llama31_base_transport_8block"]
70
+ ab_nofit = next(row for row in load(
71
+ repo / "results/llama31_base_nofit_transport_bench14_20261009/summary.json")["rows"]
72
+ if row["transport"] == "on")
73
+ comparison = [
74
+ {"method": "CoMe without FiT", "fit_scope": "none", "fit_batch": None,
75
+ "bench12": float(come["zs12_mean"]), "mmlu": float(come["mmlu"]),
76
+ "cmmlu": float(come["cmmlu"]), "ppl": float(come["ppl"]),
77
+ "source": "llama31_base_come_allowrepeat_8block", "new_run": False,
78
+ "selection_input_sha256": COME_INPUT},
79
+ {"method": "ABPrune without FiT", "fit_scope": "none", "fit_batch": None,
80
+ "bench12": ab_nofit["zs12"], "mmlu": ab_nofit["mmlu"],
81
+ "cmmlu": ab_nofit["cmmlu"], "ppl": ab_nofit["ppl"],
82
+ "source": "llama31_base_nofit_transport_bench14_20261009/on", "new_run": False},
83
+ {"method": "ABPrune + MLP FiT", "fit_scope": "mlp", "fit_batch": 1,
84
+ "bench12": float(ab["zs12_mean"]), "mmlu": float(ab["mmlu"]),
85
+ "cmmlu": float(ab["cmmlu"]), "ppl": float(ab["ppl"]),
86
+ "source": "llama31_base_transport_8block", "new_run": False},
87
+ ]
88
+ if args.reference:
89
+ reference = load(args.reference)
90
+ references = reference["rows"] if "rows" in reference else [reference]
91
+ for row in references:
92
+ validate_scores(row)
93
+ assert row.get("source") and row.get("method"), "Reference must name its method and source"
94
+ assert row.get("fit_scope", "none") == "none", "Only a no-FiT MKA reference is accepted"
95
+ assert row.get("selection_input_sha256") == MKA_INPUT, "Historical native MKA inputs must match"
96
+ comparison.append({**row, "fit_scope": "none", "fit_batch": None, "new_run": False})
97
+ prior = load(repo / "results/llama31_come_batch_20261126/summary.json")
98
+ for row in prior["rows"]:
99
+ assert row["selection_input_sha256"] == COME_INPUT
100
+ assert row["fit_input_sha256"] == FIT_INPUT and row["fit_mask_sha256"] == FIT_MASK
101
+ comparison.append({"method": "CoMe + MLP FiT", "fit_scope": "mlp", "fit_batch": row["batch_size"],
102
+ **{key: row[key] for key in ("bench12", "mmlu", "cmmlu", "ppl", "training_wall_seconds",
103
+ "selection_input_sha256", "fit_input_sha256", "fit_mask_sha256")},
104
+ "source": "llama31_come_batch_20261126/" + row["arm"], "new_run": False,
105
+ "hf_path": row["backup"]["path_in_repo"], "hf_revision": row["backup"]["revision"]})
106
+
107
+ additions = []
108
+ for row in summary["rows"]:
109
+ validate_scores(row)
110
+ assert row["selection_input_sha256"] == MKA_INPUT
111
+ assert row["fit_input_sha256"] == FIT_INPUT and row["fit_mask_sha256"] == FIT_MASK
112
+ arm, batch, receipt = row["arm"], row["batch_size"], row["backup"]
113
+ assert receipt["verified"] and (receipt["path_in_repo"], receipt["revision"]) in audited
114
+ assert receipt["path_in_repo"] == f"runs/{SESSION}/{EXPERIMENT}/{arm}"
115
+ assert re.fullmatch(r"[0-9a-f]{40}", receipt["revision"])
116
+ assert row["optimizer_updates_per_stage"] == 512 // batch
117
+ scores = row["task_scores"]
118
+ assert len(scores) == 14
119
+ assert abs(sum(v for k, v in scores.items() if k not in ("mmlu", "cmmlu")) / 12 - row["bench12"]) < 1e-12
120
+ assert scores["mmlu"] == row["mmlu"] and scores["cmmlu"] == row["cmmlu"]
121
+ assert len(row["cycles"]) == 8
122
+ for fit in row["cycles"]:
123
+ assert fit["trained"] and fit["num_trainable_mlp_gates"] == 3
124
+ assert fit["num_trainable_attn_gates"] == fit["num_trainable_other_gates"] == 0
125
+ assert fit["ablation"]["frozen_attention_norm_unchanged"]
126
+ assert fit["ablation"]["attention_initialization"] == "MKA_merge"
127
+ assert not fit["ablation"]["norms_trainable"]
128
+ execution_commit = (root / arm / "execution_commit.txt").read_text().strip()
129
+ assert re.fullmatch(r"[0-9a-f]{40}", execution_commit)
130
+ comparison.append({"method": "MKA + MLP FiT", "fit_scope": "mlp", "fit_batch": batch,
131
+ **{key: row[key] for key in ("bench12", "mmlu", "cmmlu", "ppl", "training_wall_seconds",
132
+ "selection_input_sha256", "fit_input_sha256", "fit_mask_sha256")},
133
+ "source": RESULT_NAME + "/" + arm, "new_run": True,
134
+ "hf_path": receipt["path_in_repo"], "hf_revision": receipt["revision"]})
135
+ settings = {"method": "native stagewise MKA + MLP-only FiT",
136
+ "selection": {"dataset": "DKYoon/SlimPajama-6B", "samples": 100,
137
+ "sequence_length": 512, "seed": 0, "batch_size": 1,
138
+ "geometry": "native MKA dynamic adjacent NPIB", "input_ids_sha256": MKA_INPUT,
139
+ "attention_mask_sha256": row["selection_inputs"].get("attention_mask_sha256"),
140
+ "sample_source": "Frozen historical native MKA Base calibration cache"},
141
+ "training": {"samples": 512, "sequence_length": 1024, "tokens_per_stage": 524288,
142
+ "epochs_per_stage": 1, "batch_size": batch, "grad_accumulation": 1,
143
+ "optimizer_updates_per_stage": 512 // batch, "lr": 1e-4,
144
+ "weight_decay": 0, "clip": 1, "hidden_mse": 1, "mlp_mse": 1,
145
+ "attention_mse": 0, "kl_weight": .02, "temperature": 4, "seed": 42,
146
+ "teacher": "previous_cycle", "scope": "mlp", "trainable_projection_tensors": 3,
147
+ "attention_trainable": False, "norms_trainable": False,
148
+ "input_ids_sha256": FIT_INPUT, "mask_sha256": FIT_MASK},
149
+ "initialization": {"attention": "native MKA weighted merge", "mlp": "native MKA weighted merge",
150
+ "norms": "recipient anchor Wa", "source_feature_transport": False},
151
+ "selection_provenance": summary.get("selection_provenance", {})}
152
+ record_id = f"llama31_base_mka_mlp_fit_batch{batch}_8block_20261126"
153
+ record = {key: "" for key in fields}
154
+ record.update({"record_id": record_id, "model_name": "meta-llama/Llama-3.1-8B",
155
+ "model_revision": MODEL_REVISION, "model_variant": "Base", "method": "MKA+MLP-FiT",
156
+ "blocks_removed": 8, "selector": "Frozen historical MKA100x512/seed0; dynamic NPIB reselection after FiT",
157
+ "removed_interval": "non-contiguous; see selection trace", "ppl": row["ppl"],
158
+ "zs12_count": 12, "zs12_mean": row["bench12"], "mmlu": row["mmlu"], "cmmlu": row["cmmlu"],
159
+ "macro14_mean": sum(scores.values()) / 14, "metric_scale": "accuracy_fraction_0_to_1",
160
+ "experiment_settings": f"Native MKA100x512/seed0; FiT512x1024/1epoch/LR1e-4/MLP3/frozen-attention-norms/batch{batch}/seed42",
161
+ "experiment_settings_json": json.dumps(settings, separators=(",", ":")),
162
+ "experiment_date": "2026-11-26", "status": "complete", "storage_host": SESSION,
163
+ "vast_instance": INSTANCE, "weight_path": f"/workspace/{STATE_NAME}/full/{arm}/compact/stage_08",
164
+ "hf_backup_path": f"hf://LJYAI/paper_revision/{receipt['path_in_repo']}@{receipt['revision']}",
165
+ "backup_status": "verified_huggingface_backup", "journal_commit": commit,
166
+ "code_commit": execution_commit,
167
+ "protocol_path": f"hf://LJYAI/paper_revision/{receipt['path_in_repo']}/protocol.md@{receipt['revision']}",
168
+ "ppl_result_path": f"results/{RESULT_NAME}/{arm}/final_ppl.json",
169
+ "bench14_result_path": f"results/{RESULT_NAME}/{arm}/final_14bench.json",
170
+ "evaluation_protocol": "Packed WikiText2 seq2048 BF16; canonical OpenCompass5 full-prompt PPL; lm-eval0.4.12 zero-shot auto:4, full offline131 cache",
171
+ "experiment_log": "exp_md/" + NOTE_NAME,
172
+ "notes": f"Native MKA selection cache differs from native CoMe; FiT input IDs/masks exactly match CoMe controls. {512//batch} optimizer updates/stage. Exact frozen MKA attention and anchor norm hashes verified at all8 stages. Instance62646539 retained; explicit user return instruction required."})
173
+ record.update(scores)
174
+ record = {key: str(value) if value is not None else "" for key, value in record.items() if key in fields}
175
+ if record_id in old_ids:
176
+ existing = old_ids[record_id]
177
+ for key in ("zs12_mean", "mmlu", "cmmlu", "ppl", "hf_backup_path", "experiment_settings_json"):
178
+ assert existing[key] == record[key], f"Existing record conflicts: {record_id}/{key}"
179
+ else:
180
+ additions.append(record)
181
+
182
+ for row in comparison:
183
+ validate_scores(row)
184
+ comparison_result = {"rows": comparison, "accuracy_scale": "fraction", "model": "Llama-3.1-8B Base",
185
+ "removed_blocks": 8, "reference_rows": "Historical results, not fresh benchmark reruns",
186
+ "qualification": "MKA and CoMe retain their own native selection inputs (100x512 seed0 vs91x2048 seed10); matched512x1024 FiT data/masks/LR/loss/epochs and MLP-only scope. Batch1/8 use512/64 updates/stage. ABPrune uses its own selection/transport. No merged Bench14 average substitutes for Bench12, MMLU, CMMLU."}
187
+ # Preserve the exact bytes of every existing canonical record and append only new IDs.
188
+ payload = catalog.read_bytes()
189
+ if additions:
190
+ assert not payload or payload.endswith(b"\n"), "Canonical catalog must end with a newline"
191
+ buffer = io.StringIO(newline="")
192
+ writer = csv.DictWriter(buffer, fields, quoting=csv.QUOTE_ALL, lineterminator="\n")
193
+ writer.writerows(additions)
194
+ updated = payload + buffer.getvalue().encode("utf-8")
195
+ parsed = list(csv.DictReader(io.StringIO(updated.decode("utf-8-sig"))))
196
+ assert len(parsed) == len(old_rows) + len(additions)
197
+ assert parsed[:len(old_rows)] == old_rows
198
+ assert len({row["record_id"] for row in parsed}) == len(parsed)
199
+ temporary = catalog.with_suffix(".csv.partial")
200
+ temporary.write_bytes(updated)
201
+ temporary.replace(catalog)
202
+ (root / "comparison.json").write_text(json.dumps(comparison_result, indent=2) + "\n", encoding="utf-8")
203
+ with (root / "comparison.csv").open("w", encoding="utf-8-sig", newline="") as stream:
204
+ columns = ["method", "fit_scope", "fit_batch", "bench12_pct", "mmlu_pct", "cmmlu_pct", "ppl",
205
+ "training_wall_seconds", "new_run", "source", "selection_input_sha256",
206
+ "fit_input_sha256", "fit_mask_sha256", "hf_revision"]
207
+ writer = csv.DictWriter(stream, columns)
208
+ writer.writeheader()
209
+ for row in comparison:
210
+ data = {key: row.get(key, "") for key in columns}
211
+ data.update({key + "_pct": row[key] * 100 for key in ("bench12", "mmlu", "cmmlu")})
212
+ writer.writerow(data)
213
+ (root / "backup_audit.json").write_text(json.dumps(audit, indent=2) + "\n", encoding="utf-8")
214
+ print(f"MKA_FINAL_COMPARISON_WRITTEN rows={len(comparison)} canonical_additions={len(additions)}")
215
+
216
+
217
+ if __name__ == "__main__":
218
+ main()
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/fit_ablation_come.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CoMe initialization for stagewise full-block additive-U fitting.
2
+
3
+ Use native CoMe selection/channel allocation; never mutate the teacher model.
4
+ Instruction calibration trims right padding before native CoMe scoring, so
5
+ angular-last measures the last valid token and channel scores omit padding.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+
11
+ import torch
12
+
13
+ from fusegpt import come
14
+
15
+
16
+ def valid_calibration_batches(loader):
17
+ batches = []
18
+ for item in loader:
19
+ ids, masks = (item["input_ids"], item["attention_mask"]) if isinstance(item, dict) else item[:2]
20
+ for row, mask in zip(ids, masks, strict=True):
21
+ n = int(mask.sum())
22
+ if n < 1 or not bool(mask[:n].all()) or bool(mask[n:].any()):
23
+ raise ValueError("CoMe calibration requires nonempty right-padded records")
24
+ batches.append({"input_ids": row[:n][None, :], "attention_mask": mask[:n][None, :]})
25
+ return batches
26
+
27
+
28
+ def select_and_initialize(model, loader, lineage, *, minimum=.97, power=1.):
29
+ scores = come.collect_calibration_scores(
30
+ model, valid_calibration_batches(loader), sbi_metric="angular_last")
31
+ left = come._choose_pair(scores.pair_similarity, lineage, allow_repeat=True)
32
+ indices = [left, left + 1]
33
+ leaves = sum(len(lineage[i]) for i in indices)
34
+ adjusted = minimum ** (1 / (leaves - 1)) if leaves > 2 and minimum > 0 else minimum
35
+ ratios = come.compute_retention_ratios(
36
+ [scores.block_importance[i] for i in indices], power=power, minimum=adjusted)
37
+ # Small block copies only. Native helpers modify these, never the live
38
+ # previous-cycle teacher or the layer objects used to collect scores.
39
+ pair = [copy.deepcopy(model.model.layers[i]).cpu() for i in indices]
40
+ attention = come.merge_attention(pair, ratios, [scores.attention_groups[i] for i in indices])
41
+ mlp = come.merge_mlp(pair, ratios, [scores.mlp_neurons[i] for i in indices])
42
+ come.merge_norms(pair)
43
+ initial = {n: p.detach().float().clone() for n, p in pair[0].named_parameters()}
44
+ audit = {
45
+ "source_lineage": [list(lineage[i]) for i in indices],
46
+ "retention_ratios": ratios, "retained_attention_groups": attention,
47
+ "retained_mlp_neurons": mlp, "pair_score": scores.pair_similarity[left],
48
+ "minimum_retention": minimum, "adjusted_minimum": adjusted,
49
+ "power": power, "allow_repeat": True, "sbi_metric": "angular_last",
50
+ "calibration_padding": "trim_right_padding_before_native_CoMe_scoring",
51
+ "teacher_mutated_during_initialization": False,
52
+ }
53
+ del pair, scores
54
+ return left, initial, audit
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/fit_ablation_mka.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Corrected MKA variant: adjacent NPIB selection, upstream lambda, real fusion.
2
+
3
+ Not an exact reproduction of the paper: use sequence-level pooled activations,
4
+ recompute geometry after every merge, and resolve NPIB ties back-to-front.
5
+ The seven projection weights are fused; residual and Q/K norms stay at anchor.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import math
12
+ import random
13
+ from collections.abc import Callable, Iterable, Sequence
14
+ from dataclasses import asdict, dataclass
15
+
16
+ import numpy as np
17
+ import torch
18
+ from scipy.linalg import eigh
19
+ from scipy.spatial.distance import pdist, squareform
20
+ from sklearn.feature_selection import mutual_info_regression
21
+ from sklearn.neighbors import NearestNeighbors
22
+ from torch import Tensor, nn
23
+
24
+ PROJECTION_WEIGHTS = (
25
+ "mlp.down_proj.weight",
26
+ "mlp.up_proj.weight",
27
+ "mlp.gate_proj.weight",
28
+ "self_attn.k_proj.weight",
29
+ "self_attn.o_proj.weight",
30
+ "self_attn.q_proj.weight",
31
+ "self_attn.v_proj.weight",
32
+ )
33
+ UPSTREAM = "https://github.com/SempraETY/Pruning-via-Merging"
34
+ UPSTREAM_COMMIT = "3b60b002a0963266e2f4ca78f133b4e091bc607a"
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class GeometryConfig:
39
+ sigma: float = 8.0
40
+ alpha: float = 0.5
41
+ dimensions: int = 2
42
+ mi_neighbors: int = 5
43
+ entropy_neighbors: int = 50
44
+ beta: float = 1.0
45
+ seed: int = 0
46
+ pooling: str = "mean"
47
+
48
+ def validate(self) -> None:
49
+ if not math.isfinite(self.sigma) or self.sigma <= 0:
50
+ raise ValueError("sigma must be positive and finite")
51
+ if not math.isfinite(self.alpha) or not 0 <= self.alpha <= 1:
52
+ raise ValueError("alpha must be finite and in [0, 1]")
53
+ if self.dimensions < 1 or min(self.mi_neighbors, self.entropy_neighbors) < 1:
54
+ raise ValueError("dimensions and neighbor counts must be positive")
55
+ if not math.isfinite(self.beta) or self.beta < 0:
56
+ raise ValueError("beta must be non-negative and finite")
57
+ if self.pooling not in {"mean", "last"}:
58
+ raise ValueError("pooling must be 'mean' or 'last'")
59
+
60
+
61
+ def sample_slimpajama(
62
+ tokenizer,
63
+ *,
64
+ samples: int = 100,
65
+ sequence_length: int = 512,
66
+ seed: int = 0,
67
+ revision: str = "b5f90f419b7489cdba26fdbc8c022fcb5562f968",
68
+ shuffle_buffer: int = 10000,
69
+ max_documents: int = 100000,
70
+ documents: Iterable[dict] | None = None,
71
+ ) -> tuple[list[dict[str, Tensor]], dict]:
72
+ """Exactly one random fixed-length, no-BOS window from each distinct document.
73
+
74
+ Unlike CoMe's row-packing loader, ``samples`` is the number of sequences.
75
+ Persist returned IDs and provenance; do not sample again between stages.
76
+ """
77
+ if min(samples, sequence_length, shuffle_buffer, max_documents) < 1:
78
+ raise ValueError("sampling counts, length and buffer must be positive")
79
+ if documents is None:
80
+ from datasets import load_dataset
81
+
82
+ documents = load_dataset(
83
+ "DKYoon/SlimPajama-6B", revision=revision, split="train", streaming=True
84
+ ).shuffle(seed=seed, buffer_size=shuffle_buffer)
85
+ rng = random.Random(seed)
86
+ batches, records, seen = [], [], set()
87
+ iterator = iter(documents)
88
+ try:
89
+ for row_index, row in enumerate(iterator):
90
+ if row_index >= max_documents:
91
+ break
92
+ text = row.get("text")
93
+ if not isinstance(text, str) or not text.strip():
94
+ continue
95
+ digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
96
+ if digest in seen:
97
+ continue
98
+ seen.add(digest)
99
+ ids = tokenizer.encode(text, add_special_tokens=False)
100
+ if len(ids) < sequence_length:
101
+ continue
102
+ start = rng.randrange(len(ids) - sequence_length + 1)
103
+ tensor = torch.tensor(
104
+ ids[start : start + sequence_length], dtype=torch.long
105
+ )[None, :]
106
+ batches.append(
107
+ {"input_ids": tensor, "attention_mask": torch.ones_like(tensor)}
108
+ )
109
+ records.append(
110
+ {
111
+ "stream_row": row_index,
112
+ "document_sha256": digest,
113
+ "document_tokens": len(ids),
114
+ "window_start": start,
115
+ }
116
+ )
117
+ if len(batches) == samples:
118
+ break
119
+ finally:
120
+ close = getattr(iterator, "close", None)
121
+ if close is not None:
122
+ close()
123
+ if len(batches) != samples:
124
+ raise RuntimeError(
125
+ f"Only found {len(batches)}/{samples} distinct sufficiently long documents"
126
+ )
127
+ checksum = hashlib.sha256()
128
+ for batch in batches:
129
+ checksum.update(batch["input_ids"].numpy().astype("<i8").tobytes())
130
+ metadata = {
131
+ "dataset": "DKYoon/SlimPajama-6B",
132
+ "revision": revision,
133
+ "split": "train",
134
+ "samples": samples,
135
+ "sequence_length": sequence_length,
136
+ "seed": seed,
137
+ "shuffle_buffer": shuffle_buffer,
138
+ "add_special_tokens": False,
139
+ "sampling": "one random window per distinct document",
140
+ "input_ids_sha256": checksum.hexdigest(),
141
+ "records": records,
142
+ }
143
+ return batches, metadata
144
+
145
+
146
+ @torch.inference_mode()
147
+ def collect_features(
148
+ model: nn.Module, batches: Sequence[dict[str, Tensor]], *, pooling: str = "mean"
149
+ ) -> list[np.ndarray]:
150
+ """One backbone forward per batch; block hooks avoid hidden-state off-by-one.
151
+
152
+ Collect outputs *before* the final backbone norm, including the final block.
153
+ Pool only valid tokens; activations are CPU float32 after pooling.
154
+ """
155
+ if pooling not in {"mean", "last"} or not batches:
156
+ raise ValueError("valid pooling and nonempty calibration batches are required")
157
+ layers = model.model.layers
158
+ features: list[list[Tensor]] = [[] for _ in layers]
159
+ current_mask: Tensor | None = None
160
+
161
+ def hook(index):
162
+ def capture(module, inputs, output):
163
+ hidden = output[0] if isinstance(output, (tuple, list)) else output
164
+ mask = current_mask.to(hidden.device, dtype=torch.bool)
165
+ if hidden.shape[:2] != mask.shape or (mask.sum(-1) == 0).any():
166
+ raise ValueError("block output and valid-token mask do not match")
167
+ if pooling == "mean":
168
+ value = (hidden.float() * mask[:, :, None]).sum(1) / mask.sum(1)[
169
+ :, None
170
+ ]
171
+ else:
172
+ positions = torch.arange(mask.shape[1], device=mask.device)[None, :]
173
+ last = positions.expand_as(mask).masked_fill(~mask, -1).max(1).values
174
+ value = hidden[
175
+ torch.arange(hidden.shape[0], device=hidden.device), last
176
+ ].float()
177
+ if not torch.isfinite(value).all():
178
+ raise FloatingPointError(f"nonfinite activation in block {index}")
179
+ features[index].append(value.cpu())
180
+
181
+ return capture
182
+
183
+ handles = [layer.register_forward_hook(hook(i)) for i, layer in enumerate(layers)]
184
+ was_training = model.training
185
+ model.eval()
186
+ try:
187
+ device = model.get_input_embeddings().weight.device
188
+ for batch in batches:
189
+ prepared = {key: value.to(device) for key, value in batch.items()}
190
+ current_mask = prepared.get(
191
+ "attention_mask", torch.ones_like(prepared["input_ids"])
192
+ )
193
+ model.model(**prepared, use_cache=False, return_dict=True)
194
+ finally:
195
+ for handle in handles:
196
+ handle.remove()
197
+ model.train(was_training)
198
+ expected = sum(batch["input_ids"].shape[0] for batch in batches)
199
+ arrays = [torch.cat(parts, dim=0).numpy() for parts in features]
200
+ if any(array.shape[0] != expected for array in arrays):
201
+ raise RuntimeError("not all calibration examples reached each decoder block")
202
+ return arrays
203
+
204
+
205
+ def diffusion_embedding(
206
+ features: np.ndarray, config: GeometryConfig
207
+ ) -> tuple[np.ndarray, dict]:
208
+ """Correctly shaped sample-by-sample diffusion kernel, following upstream SVD geometry."""
209
+ config.validate()
210
+ x = np.asarray(features, dtype=np.float64)
211
+ if x.ndim != 2 or not np.isfinite(x).all() or len(x) <= config.dimensions + 1:
212
+ raise ValueError(
213
+ "features must be finite [samples, features], samples > dimensions + 1"
214
+ )
215
+ distance = squareform(pdist(x, metric="euclidean"))
216
+ if distance.max() <= np.finfo(float).eps:
217
+ raise ValueError(
218
+ "constant calibration features: cannot estimate manifold geometry"
219
+ )
220
+ kernel = np.exp(-np.sqrt(distance / config.sigma))
221
+ p = kernel.sum(0)
222
+ normalized = kernel / np.outer(p, p) ** config.alpha
223
+ v = np.sqrt(normalized.sum(0))
224
+ operator = normalized / np.outer(v, v)
225
+ condition = float(np.linalg.cond(operator))
226
+ regularization = 1e-6 if not math.isfinite(condition) or condition > 1e12 else 0.0
227
+ if regularization:
228
+ operator += regularization * np.eye(len(x))
229
+ values, vectors = eigh(
230
+ operator, subset_by_index=(len(x) - config.dimensions - 1, len(x) - 1)
231
+ )
232
+ values, vectors = values[::-1], vectors[:, ::-1]
233
+ # Fix arbitrary eigenvector signs; the leading vector of this positive kernel is positive.
234
+ for dim in range(vectors.shape[1]):
235
+ if vectors[np.argmax(np.abs(vectors[:, dim])), dim] < 0:
236
+ vectors[:, dim] *= -1
237
+ if np.any(np.abs(vectors[:, 0]) < 1e-12):
238
+ raise FloatingPointError(
239
+ "diffusion normalization has a near-zero leading eigenvector"
240
+ )
241
+ embedding = vectors[:, 1:] / vectors[:, :1]
242
+ if not np.isfinite(embedding).all():
243
+ raise FloatingPointError("nonfinite diffusion embedding")
244
+ # Upstream uses per-axis rank normalization before its KNN estimators.
245
+ embedding = np.argsort(
246
+ np.argsort(embedding, axis=0, kind="stable"), axis=0, kind="stable"
247
+ ) / len(x)
248
+ return embedding, {
249
+ "samples": len(x),
250
+ "condition_number": condition if math.isfinite(condition) else None,
251
+ "regularization": regularization,
252
+ "eigenvalues": values.tolist(),
253
+ }
254
+
255
+
256
+ def entropy_knn(x: np.ndarray, neighbors: int) -> float:
257
+ """Upstream differential-entropy estimator, evaluated in log space."""
258
+ n, dimensions = x.shape
259
+ k = min(neighbors, n - 1)
260
+ distances = NearestNeighbors(n_neighbors=k + 1).fit(x).kneighbors(x)[0][:, -1]
261
+ if np.any(distances <= 0) or not np.isfinite(distances).all():
262
+ raise FloatingPointError(
263
+ "duplicate/degenerate manifold points in entropy estimator"
264
+ )
265
+ return float(math.log(n / k) + dimensions * np.log(distances).mean())
266
+
267
+
268
+ def npib_matrix(
269
+ embeddings: Sequence[np.ndarray], config: GeometryConfig
270
+ ) -> tuple[np.ndarray, list[float]]:
271
+ """Match upstream axis-wise MI average and symmetric sqrt(H_i*H_j) normalization.
272
+
273
+ Differential entropies can be negative. Preserve upstream's formula when
274
+ their product is positive; fail clearly for zero/negative products or NaNs.
275
+ This estimator is a heuristic, not a guaranteed [0, 1] similarity.
276
+ """
277
+ config.validate()
278
+ if not embeddings or len({x.shape for x in embeddings}) != 1:
279
+ raise ValueError("embeddings must have identical sample/coordinate shapes")
280
+ n = len(embeddings[0])
281
+ if n < 3 or any(not np.isfinite(x).all() for x in embeddings):
282
+ raise ValueError("need at least three finite manifold points")
283
+ entropies = [entropy_knn(x, config.entropy_neighbors) for x in embeddings]
284
+ scores = np.empty((len(embeddings), len(embeddings)), dtype=np.float64)
285
+ for i, left in enumerate(embeddings):
286
+ for j in range(i, len(embeddings)):
287
+ right = embeddings[j]
288
+ product = entropies[i] * entropies[j]
289
+ if not math.isfinite(product) or product <= 1e-12:
290
+ raise FloatingPointError(
291
+ f"invalid entropy product at ({i}, {j}): {entropies[i]}, {entropies[j]}"
292
+ )
293
+ mi = np.mean(
294
+ [
295
+ np.mean(
296
+ mutual_info_regression(
297
+ left,
298
+ right[:, dim],
299
+ n_neighbors=min(config.mi_neighbors, n - 1),
300
+ random_state=config.seed,
301
+ )
302
+ )
303
+ for dim in range(right.shape[1])
304
+ ]
305
+ )
306
+ scores[i, j] = scores[j, i] = mi / math.sqrt(product)
307
+ if not np.isfinite(scores).all():
308
+ raise FloatingPointError("NPIB contains nonfinite scores")
309
+ return scores, entropies
310
+
311
+
312
+ def upstream_lambda(
313
+ scores: np.ndarray, left: int, right: int, beta: float = 1.0
314
+ ) -> float:
315
+ """Exactly upstream's sigmoid(beta * row_mean_i / (row_mean_i + row_mean_j))."""
316
+ means = np.mean(scores[[left, right]], axis=1)
317
+ total = float(means.sum())
318
+ if not np.isfinite(means).all() or (means < 0).any() or total <= 1e-12:
319
+ raise FloatingPointError(
320
+ "cannot compute upstream lambda from nonpositive/nonfinite row means"
321
+ )
322
+ if not math.isfinite(beta) or beta < 0:
323
+ raise ValueError("beta must be non-negative and finite")
324
+ value = beta * float(means[0]) / total
325
+ return 1.0 / (1.0 + math.exp(-value))
326
+
327
+
328
+ def select_pair(
329
+ scores: np.ndarray,
330
+ *,
331
+ selection: str = "npib",
332
+ protected_first: int = 0,
333
+ protected_last: int = 0,
334
+ ) -> int:
335
+ """Adjacent pairs only; NPIB descending, and deeper pair wins exact ties."""
336
+ n = len(scores)
337
+ if scores.shape != (n, n) or not np.isfinite(scores).all():
338
+ raise ValueError("scores must be a finite square matrix")
339
+ if min(protected_first, protected_last) < 0:
340
+ raise ValueError("protected layer counts must be non-negative")
341
+ candidates = range(protected_first, n - protected_last - 1)
342
+ if not candidates:
343
+ raise ValueError("no eligible adjacent pair remains")
344
+ if selection == "back-to-front":
345
+ return candidates[-1]
346
+ if selection != "npib":
347
+ raise ValueError("selection must be 'npib' or 'back-to-front'")
348
+ return max(candidates, key=lambda i: (float(scores[i, i + 1]), i))
349
+
350
+
351
+ @torch.inference_mode()
352
+ def merge_pair(model: nn.Module, left: int, ratio: float) -> int:
353
+ """FP32 weighted sum copied into real parameters, then delete the right block."""
354
+ layers = model.model.layers
355
+ if (
356
+ not 0 <= left < len(layers) - 1
357
+ or not math.isfinite(ratio)
358
+ or not 0 <= ratio <= 1
359
+ ):
360
+ raise ValueError("invalid adjacent pair or merge ratio")
361
+ destination, source = layers[left], layers[left + 1]
362
+ pairs = []
363
+ for name in PROJECTION_WEIGHTS:
364
+ pairs.append((destination.get_parameter(name), source.get_parameter(name)))
365
+ # Qwen2.5 has Q/K/V biases. Fuse them with the same coefficient;
366
+ # Llama and Qwen3 (bias-free projections) retain their existing behavior.
367
+ module_name = name.rsplit('.', 1)[0]
368
+ a_bias = getattr(destination.get_submodule(module_name), 'bias', None)
369
+ b_bias = getattr(source.get_submodule(module_name), 'bias', None)
370
+ if (a_bias is None) != (b_bias is None):
371
+ raise ValueError('projection bias presence differs between merge layers')
372
+ if a_bias is not None:
373
+ pairs.append((a_bias, b_bias))
374
+ # Validate all shapes/values/config before any model mutation.
375
+ if any(a.shape != b.shape for a, b in pairs):
376
+ raise ValueError("projection shapes differ between merge layers")
377
+ if any(not torch.isfinite(p).all() for pair in pairs for p in pair):
378
+ raise FloatingPointError("nonfinite source weight")
379
+ configs = [model.config, model.model.config]
380
+ for config in configs:
381
+ types = getattr(config, "layer_types", None)
382
+ if types is not None and len(types) != len(layers):
383
+ raise ValueError("config.layer_types length does not match decoder depth")
384
+ changed = 0
385
+ for target, other in pairs:
386
+ merged = torch.lerp(
387
+ other.detach().to(target.device, dtype=torch.float32), target.float(), ratio
388
+ )
389
+ merged = merged.to(target.dtype)
390
+ if not torch.isfinite(merged).all():
391
+ raise FloatingPointError("merge overflow after conversion to model dtype")
392
+ changed += int(not torch.equal(target, merged))
393
+ target.copy_(merged)
394
+ del layers[left + 1]
395
+ handled = set()
396
+ for config in configs:
397
+ if id(config) in handled:
398
+ continue
399
+ handled.add(id(config))
400
+ config.num_hidden_layers = len(layers)
401
+ if getattr(config, "layer_types", None) is not None:
402
+ config.layer_types = list(config.layer_types[: left + 1]) + list(
403
+ config.layer_types[left + 2 :]
404
+ )
405
+ for index, layer in enumerate(layers):
406
+ if hasattr(layer.self_attn, "layer_idx"):
407
+ layer.self_attn.layer_idx = index
408
+ return changed
409
+
410
+
411
+ def progressive_prune(
412
+ model: nn.Module,
413
+ batches: Sequence[dict[str, Tensor]],
414
+ *,
415
+ target_layers: int,
416
+ geometry: GeometryConfig | None = None,
417
+ selection: str = "npib",
418
+ protected_first: int = 0,
419
+ protected_last: int = 0,
420
+ on_stage: Callable[[nn.Module, dict], None] | None = None,
421
+ ) -> list[dict]:
422
+ """Recompute activations/manifolds/NPIB on fixed data after every accepted merge.
423
+
424
+ No threshold or forced fallbacks; stop at the requested exact depth. Repeated
425
+ merging of a previously merged block is allowed and recorded in its lineage.
426
+ """
427
+ geometry = geometry or GeometryConfig()
428
+ geometry.validate()
429
+ depth = len(model.model.layers)
430
+ if min(protected_first, protected_last) < 0 or not 1 <= target_layers <= depth:
431
+ raise ValueError("invalid target depth or protected counts")
432
+ if target_layers < protected_first + protected_last + 1:
433
+ raise ValueError("target depth would remove protected layers")
434
+ if selection not in {"npib", "back-to-front"}:
435
+ raise ValueError("invalid selection mode")
436
+ lineage = [[i] for i in range(depth)]
437
+ records = []
438
+ model.eval()
439
+ while len(model.model.layers) > target_layers:
440
+ step = len(records) + 1
441
+ print(
442
+ f"MKA stage {step}: collecting features for {len(lineage)} layers",
443
+ flush=True,
444
+ )
445
+ features = collect_features(model, batches, pooling=geometry.pooling)
446
+ results = [diffusion_embedding(x, geometry) for x in features]
447
+ del features
448
+ scores, entropies = npib_matrix([x[0] for x in results], geometry)
449
+ left = select_pair(
450
+ scores,
451
+ selection=selection,
452
+ protected_first=protected_first,
453
+ protected_last=protected_last,
454
+ )
455
+ ratio = upstream_lambda(scores, left, left + 1, geometry.beta)
456
+ record = {
457
+ "step": step,
458
+ "selection": selection,
459
+ "left_index": left,
460
+ "source_layers": [lineage[left][:], lineage[left + 1][:]],
461
+ "pair_npib": float(scores[left, left + 1]),
462
+ "lambda_left": ratio,
463
+ "lambda_right": 1 - ratio,
464
+ "row_means": scores.mean(1).tolist(),
465
+ "npib_matrix": scores.tolist(),
466
+ "entropies": entropies,
467
+ "geometry": asdict(geometry),
468
+ "manifolds": [x[1] for x in results],
469
+ }
470
+ record["changed_parameter_tensors"] = merge_pair(model, left, ratio)
471
+ lineage[left] += lineage.pop(left + 1)
472
+ record["lineage_after"] = [x[:] for x in lineage]
473
+ record["remaining_layers"] = len(lineage)
474
+ records.append(record)
475
+ print(
476
+ f"MKA stage {step}: merge {left}/{left + 1}, NPIB={record['pair_npib']:.6g}, "
477
+ f"lambda={ratio:.6g}, remaining={len(lineage)}",
478
+ flush=True,
479
+ )
480
+ if on_stage is not None:
481
+ on_stage(model, record)
482
+ return records
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/fuse_layers.py ADDED
The diff for this file is too large to render. See raw diff
 
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/fuse_layers_distill.py ADDED
The diff for this file is too large to render. See raw diff
 
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/launch_llama31_come_fit2.sh ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ project="$1"; external="$2"; root="$3"; base_model="$4"; inst_model="$5"; alias="$6"
4
+ scope="${7:-full}"; fit=(--fit-full-block); experiment=20261008-llama31-come-fullblock-fit2
5
+ protocol=exp_md/2026-10-08_llama31-come-stagewise-fullblock-fit2.md
6
+ if [[ "$scope" == mlp ]]; then
7
+ fit=(--fit-come-mlp); experiment=20261008-llama31-come-mlp-fit2
8
+ protocol=exp_md/2026-10-08_llama31-come-stagewise-mlp-fit2.md
9
+ elif [[ "$scope" != full ]]; then exit 2; fi
10
+ export HF_HOME=/workspace/.hf_home HF_TOKEN_PATH=/root/.cache/huggingface/token
11
+ export HF_DATASETS_CACHE=/workspace/.hf_datasets36 HF_DATASETS_TRUST_REMOTE_CODE=1
12
+ export PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false OMP_NUM_THREADS=4
13
+ export PYTHONPATH="$project/src:$external/src"
14
+ mkdir -p "$root"
15
+ trap 'rc=$?; if ((rc)); then touch "$root/FAILED"; fi' EXIT
16
+ while [[ ! -f "$root/DEPS_READY" ]]; do [[ ! -f "$root/BOOTSTRAP_FAILED" ]] || exit 1; sleep 3; done
17
+ python -m pytest -q "$project/tests/test_come.py" > "$root/unit_tests.log" 2>&1
18
+ python "$project/scripts/run_llama31_base_fit_ablation.py" --external-root "$external" \
19
+ --initializer come "${fit[@]}" --audit-root "$root/algebra" --self-test >> "$root/unit_tests.log" 2>&1
20
+ # Evaluation preparation runs independently: it must never block fitting or PPL.
21
+ prepare_eval() (
22
+ [[ ! -f "$root/EVAL_READY" ]] || exit 0
23
+ trap 'rc=$?; if ((rc)); then touch "$root/EVAL_PREP_FAILED"; fi' EXIT
24
+ mkdir -p "$root/eval_data"
25
+ while [[ ! -f "$root/EVAL_ASSETS_READY" ]]; do sleep 3; done
26
+ tar -xzf "$root/opencompass5-data.tar.gz" -C "$root/eval_data"
27
+ if [[ -f "$root/lmeval-cache-131.tar.gz" ]]; then
28
+ mkdir -p "$root/lmeval_cache"
29
+ tar -xzf "$root/lmeval-cache-131.tar.gz" -C "$root/lmeval_cache"
30
+ else
31
+ # Slow SSH cache transfers must not turn into GPU-idle serialization.
32
+ # Warm common archives once, then materialize identical task definitions in
33
+ # parallel. Retry preserves completed source.json caches after extraction races.
34
+ python - <<'PY'
35
+ import datasets
36
+ from concurrent.futures import ThreadPoolExecutor
37
+ jobs=[('cais/mmlu','anatomy'),('haonan-li/cmmlu','anatomy'),('Salesforce/wikitext','wikitext-2-raw-v1')]
38
+ with ThreadPoolExecutor(max_workers=3) as p:
39
+ for f in [p.submit(datasets.load_dataset,*j,trust_remote_code=True) for j in jobs]:f.result()
40
+ PY
41
+ for attempt in 1 2 3; do
42
+ python "$project/scripts/prepare_lmeval9_local_cache.py" "$root/lmeval_cache" --workers 8 && break
43
+ [[ "$attempt" -lt 3 ]] || exit 1
44
+ done
45
+ fi
46
+ HF_HUB_OFFLINE=1 HF_DATASETS_OFFLINE=1 python "$project/scripts/prepare_lmeval9_local_cache.py" \
47
+ "$root/lmeval_cache" --validate-local
48
+ python "$project/scripts/prepare_offline_ppl_cache.py" "$root"
49
+ touch "$root/EVAL_READY"
50
+ )
51
+ prepare_eval > "$root/eval_prepare.log" 2>&1 & eval_pid=$!
52
+ run_job() (
53
+ family="$1"; gpu="$2"; model="$base_model"; revision=d04e592bb4f6aa9cfee91e2e20afa771667e1d4b
54
+ if [[ "$family" == instruct ]]; then model="$inst_model"; revision=0e9e39f249a16976918f6564b8830bc894c89659; fi
55
+ ready="${family^^}_READY"
56
+ trap 'rc=$?; if ((rc)); then touch "$root/FAILED" "$root/${family}_FAILED"; fi' EXIT
57
+ while [[ ! -f "$root/$ready" ]]; do [[ ! -f "$root/BOOTSTRAP_FAILED" ]] || exit 1; sleep 3; done
58
+ smoke="$root/smoke/$family"
59
+ if [[ ! -f "$smoke/SMOKE_VERIFIED" ]]; then
60
+ if [[ ! -f "$smoke/TRAIN_COMPLETE" ]]; then
61
+ bash "$project/scripts/run_llama31_come_fit_arm.sh" "$project" "$external" "$smoke" "$model" "$family" "$gpu" smoke "$scope"
62
+ fi
63
+ python - "$smoke" "$scope" <<'PY'
64
+ import json,sys
65
+ from pathlib import Path
66
+ r=Path(sys.argv[1])
67
+ mlp=sys.argv[2]=='mlp'
68
+ for c in (1,2):
69
+ f=json.loads((r/f'audit/cycle_{c:02d}_fit.json').read_text()); ab=f['ablation']
70
+ assert f['trained'] and f['additive_u'] and ab['fit_scope']==('mlp' if mlp else 'full_block_including_norms')
71
+ assert ab['attention_initialization']=='CoMe_channel_merge' and ab['norms_trainable']==(not mlp)
72
+ assert not ab['fisher_computed'] and not ab['source_feature_transport']
73
+ count=3 if mlp else 9
74
+ assert f['num_trainable_attn_gates']==(0 if mlp else 4) and f['num_trainable_mlp_gates']==3 and f['num_trainable_other_gates']==(0 if mlp else 2)
75
+ for phase in f['first_grad_summary'].values():
76
+ assert phase['u']['num_tensors']==count and phase['u']['num_tensors_without_grad']==0 and phase['u']['l2']>0
77
+ d=f['u_delta_summary']['per_tensor']
78
+ assert len(d)==count and all(v['rms']>0 for v in d.values()), d
79
+ assert sum('layernorm' in k for k in d)==(0 if mlp else 2)
80
+ if mlp:
81
+ assert len(ab['frozen_CoMe_parameters'])==6
82
+ print('TWO_CYCLES_FIT_SCOPE_UPDATES_VERIFIED',sys.argv[2],flush=True)
83
+ PY
84
+ touch "$smoke/SMOKE_VERIFIED"
85
+ fi
86
+ output="$root/full/$family"
87
+ if [[ ! -f "$output/TRAIN_COMPLETE" ]]; then
88
+ bash "$project/scripts/run_llama31_come_fit_arm.sh" "$project" "$external" "$output" "$model" "$family" "$gpu" full "$scope"
89
+ fi
90
+ mkdir -p "$output/eval"
91
+ export MODEL_REVISION="$revision"
92
+ if [[ ! -f "$output/eval/final_ppl.json" ]]; then
93
+ CUDA_VISIBLE_DEVICES="$gpu" python "$project/scripts/evaluate_abprune_compact_ppl.py" \
94
+ --model "$model" --revision "$revision" --compact-stage "$output/compact/stage_08" \
95
+ --anchor 21 --cycles 8 --original-layers 32 --seq-len 2048 --batch-size 8 \
96
+ --output "$output/eval/final_ppl.json" > "$output/logs/ppl.log" 2>&1
97
+ fi
98
+ while [[ ! -f "$root/EVAL_READY" ]]; do [[ ! -f "$root/EVAL_PREP_FAILED" ]] || exit 1; sleep 3; done
99
+ export LMEVAL_LOCAL_CACHE="$root/lmeval_cache"
100
+ bash "$project/scripts/eval_llama31_fit_ablation_one.sh" "$project" "$output" "$model" \
101
+ "$root/eval_data/data" "$(command -v python)" 21 8 "$gpu"
102
+ touch "$output/EVAL_COMPLETE"
103
+ backup="$root/backup/$family"
104
+ if [[ ! -d "$backup" ]]; then
105
+ python "$project/scripts/package_final_fit_backup.py" "$output" "$backup" "$project" "$external" --protocol "$protocol"
106
+ git -C "$project" rev-parse HEAD > "$backup/code/project_commit.txt"
107
+ python "$project/scripts/write_tree_manifest.py" "$backup"
108
+ fi
109
+ # Evaluation stays offline; uploading must explicitly override inherited flags.
110
+ HF_HUB_OFFLINE=0 HF_DATASETS_OFFLINE=0 TRANSFORMERS_OFFLINE=0 \
111
+ python "$project/scripts/upload_verified_hf_tree.py" "$backup" --repo-id LJYAI/paper_revision \
112
+ --path-in-repo "runs/$alias/$experiment/$family" \
113
+ --commit-message "Llama31 $family CoMe stagewise $scope FiT final weights PPL bench14" > "$root/${family}_backup.json"
114
+ touch "$output/BACKUP_COMPLETE"
115
+ )
116
+ run_job base 0 > "$root/base_pipeline.log" 2>&1 & base_pid=$!
117
+ run_job instruct 1 > "$root/instruct_pipeline.log" 2>&1 & inst_pid=$!
118
+ failed=0
119
+ for pid in "$base_pid" "$inst_pid" "$eval_pid"; do wait "$pid" || failed=1; done
120
+ ((failed == 0)) || exit 1
121
+ python "$project/scripts/collect_llama31_come_fit2.py" "$root"
122
+ touch "$root/COMPLETE"
123
+ echo "CoMe $scope FiT evaluated/backed up; retain instance pending user instruction."
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/launch_mka_batch_comparison.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run native-MKA MLP-only FiT on an existing host, keeping the host running."""
2
+ import argparse
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ import hashlib
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ import threading
12
+ import time
13
+
14
+
15
+ FIT_IDS = "2b2d044c8c040f67891817ecc110f0fa0de2f469db4c6731114ff7816bbf1cd0"
16
+ FIT_MASK = "c8e7f8e30cd532b82e6af4b98d596bc7106f29f9fb2b398b44355e624898a30d"
17
+ REVISION = "d04e592bb4f6aa9cfee91e2e20afa771667e1d4b"
18
+
19
+
20
+ def main():
21
+ p = argparse.ArgumentParser(description=__doc__)
22
+ p.add_argument("--project", type=Path, required=True)
23
+ p.add_argument("--external", type=Path, required=True)
24
+ p.add_argument("--root", type=Path, required=True)
25
+ p.add_argument("--model", required=True)
26
+ p.add_argument("--session", required=True)
27
+ p.add_argument("--selection-data", type=Path, required=True)
28
+ p.add_argument("--selection-metadata", type=Path)
29
+ p.add_argument("--expected-selection-hash", required=True)
30
+ p.add_argument("--eval-root", type=Path, required=True,
31
+ help="Existing completed run with eval_data, lmeval_cache and offline WikiText policy")
32
+ p.add_argument("--larger-batch", type=int, default=8)
33
+ p.add_argument("--profile-only", action="store_true",
34
+ help="Stop after validated probes so the controller can audit native first-stage selection")
35
+ p.add_argument("--experiment-id", default="20261126-llama31-mka-mlp-batch")
36
+ p.add_argument("--protocol", default="exp_md/2026-11-26_llama31-mka-mlp-batch-comparison.md")
37
+ a = p.parse_args()
38
+ root = a.root.resolve()
39
+ root.mkdir(parents=True, exist_ok=True)
40
+ env = dict(os.environ, HF_HOME="/workspace/.hf_home",
41
+ HF_TOKEN_PATH="/root/.cache/huggingface/token",
42
+ HF_DATASETS_CACHE="/workspace/.hf_datasets36", HF_DATASETS_TRUST_REMOTE_CODE="1",
43
+ HF_HUB_OFFLINE="1", HF_DATASETS_OFFLINE="1", TRANSFORMERS_OFFLINE="1",
44
+ PYTHONUNBUFFERED="1", TOKENIZERS_PARALLELISM="false", OMP_NUM_THREADS="4",
45
+ PYTHONPATH=f"{a.project}/src:{a.external}/src")
46
+ state = {"experiment": a.experiment_id, "session": a.session, "fit_scope": "mlp",
47
+ "method": "native MKA + MLP-only FiT", "phase": "validation", "arms": {},
48
+ "instance_return_policy": "explicit_user_instruction_only", "auto_return": False}
49
+ lock = threading.RLock()
50
+
51
+ def save():
52
+ with lock:
53
+ state["updated_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
54
+ temporary = root / "status.partial"
55
+ temporary.write_text(json.dumps(state, indent=2) + "\n")
56
+ temporary.replace(root / "status.json")
57
+
58
+ def run(command, log, gpu=None, check=True):
59
+ child_env = dict(env)
60
+ if gpu is not None:
61
+ child_env["CUDA_VISIBLE_DEVICES"] = str(gpu)
62
+ log.parent.mkdir(parents=True, exist_ok=True)
63
+ with log.open("a") as stream:
64
+ result = subprocess.run([str(x) for x in command], env=child_env, cwd=a.project,
65
+ stdout=stream, stderr=subprocess.STDOUT)
66
+ if check and result.returncode:
67
+ raise RuntimeError(f"Command failed ({result.returncode}); see {log}")
68
+ return result.returncode
69
+
70
+ def validate_fit(fit, batch, tokens, require_gradients=False):
71
+ assert fit["trained"] and fit["num_trainable_mlp_gates"] == 3
72
+ assert fit["num_trainable_attn_gates"] == 0 and fit["num_trainable_other_gates"] == 0
73
+ audit = fit["ablation"]
74
+ assert audit["fit_scope"] == "mlp" and audit["attention_initialization"] == "MKA_merge"
75
+ assert not audit["norms_trainable"] and audit["frozen_attention_norm_unchanged"]
76
+ expected = audit["frozen_attention_norm_expected_sha256"]
77
+ assert len(expected) == 6
78
+ assert audit["frozen_attention_norm_before_sha256"] == expected
79
+ assert audit["frozen_attention_norm_after_sha256"] == expected
80
+ assert not audit["source_feature_transport"]
81
+ assert fit["runtime"]["batch_size"] == batch
82
+ assert fit["runtime"]["dataset_tokens"] == tokens
83
+ if require_gradients:
84
+ assert fit["first_grad_summary"]["joint"]["u"]["num_tensors_without_grad"] == 0
85
+ changes = fit["u_delta_summary"]["per_tensor"]
86
+ assert len(changes) == 3 and all(v["rms"] > 0 for v in changes.values())
87
+
88
+ selection = root / "calibration/selection.pt"
89
+
90
+ def train_command(out, batch, gpu, cycles=8, tokens=524288):
91
+ return ["bash", a.project / "scripts/run_mka_batch_arm.sh", a.project, a.external,
92
+ out, a.model, selection, batch, gpu, cycles, tokens, a.expected_selection_hash]
93
+
94
+ def complete_arm(name, batch, gpu):
95
+ out = root / "full" / name
96
+ out.mkdir(parents=True, exist_ok=True)
97
+ with lock:
98
+ state["arms"][name] = {"phase": "training", "batch_size": batch, "gpu": gpu,
99
+ "started_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
100
+ save()
101
+ if not (out / "TRAIN_COMPLETE").exists():
102
+ started = time.time()
103
+ run(train_command(out, batch, gpu), root / f"{name}_pipeline.log")
104
+ (out / "training_elapsed.json").write_text(json.dumps({
105
+ "wall_seconds": time.time() - started,
106
+ "completed_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}, indent=2) + "\n")
107
+ for cycle in range(1, 9):
108
+ validate_fit(json.loads((out / "audit" / f"cycle_{cycle:02d}_fit.json").read_text()),
109
+ batch, 524288, require_gradients=True)
110
+ fingerprints = json.loads((out / "audit/data_fingerprints.json").read_text())
111
+ assert fingerprints["distill_loader"]["sha256"] == FIT_IDS
112
+ assert fingerprints["distill_loader"]["attention_mask_sha256"] == FIT_MASK
113
+ native = json.loads((out / "audit/selection_inputs.json").read_text())
114
+ assert native["input_ids_sha256"] == a.expected_selection_hash and native["sequences"] == 100
115
+ with lock:
116
+ state["arms"][name]["phase"] = "evaluation"
117
+ save()
118
+ (out / "eval").mkdir(exist_ok=True)
119
+ if not (out / "eval/final_ppl.json").exists():
120
+ run([sys.executable, a.project / "scripts/evaluate_abprune_compact_ppl.py",
121
+ "--model", a.model, "--revision", REVISION,
122
+ "--compact-stage", out / "compact/stage_08", "--anchor", 21, "--cycles", 8,
123
+ "--original-layers", 32, "--seq-len", 2048, "--batch-size", 8,
124
+ "--output", out / "eval/final_ppl.json"], root / f"{name}_ppl.log", gpu)
125
+ eval_env = dict(env, LMEVAL_LOCAL_CACHE=str(a.eval_root / "lmeval_cache"), MODEL_REVISION=REVISION)
126
+ with (root / f"{name}_eval.log").open("a") as stream:
127
+ subprocess.run(["bash", str(a.project / "scripts/eval_llama31_fit_ablation_one.sh"),
128
+ str(a.project), str(out), a.model, str(a.eval_root / "eval_data/data"),
129
+ sys.executable, "21", "8", str(gpu)], env=eval_env, check=True,
130
+ stdout=stream, stderr=subprocess.STDOUT)
131
+ (out / "EVAL_COMPLETE").touch()
132
+ with lock:
133
+ state["arms"][name]["phase"] = "backup"
134
+ save()
135
+ backup = root / "backup" / name
136
+ if not backup.exists():
137
+ run([sys.executable, a.project / "scripts/package_final_fit_backup.py", out, backup,
138
+ a.project, a.external, "--protocol", a.protocol], root / f"{name}_backup.log")
139
+ for filename in ("launch_mka_batch_comparison.py", "run_mka_batch_arm.sh",
140
+ "collect_mka_batch_comparison.py", "prepare_mka_batch_calibration.py",
141
+ "validate_mka_first_selection.py", "validate_mka_runtime_geometry.py",
142
+ "finalize_mka_batch_report.py"):
143
+ shutil.copy2(a.project / "scripts" / filename, backup / "code" / filename)
144
+ shutil.copy2(a.project / "src/fusegpt/fit_ablation_mka.py", backup / "code/fit_ablation_mka.py")
145
+ shutil.copy2(a.project / "src/fusegpt/mka.py", backup / "code/mka.py")
146
+ for filename in ("selection_provenance.json", "batch_profile.json", "native_first_selection.json"):
147
+ shutil.copy2(root / filename, backup / filename)
148
+ shutil.copy2(out / "training_elapsed.json", backup / "training_elapsed.json")
149
+ (backup / "code/project_commit.txt").write_text(subprocess.check_output(
150
+ ["git", "rev-parse", "HEAD"], cwd=a.project, text=True))
151
+ run([sys.executable, a.project / "scripts/write_tree_manifest.py", backup],
152
+ root / f"{name}_backup.log")
153
+ upload_env = dict(env, HF_HUB_OFFLINE="0", HF_DATASETS_OFFLINE="0", TRANSFORMERS_OFFLINE="0")
154
+ with (root / f"{name}_backup.json").open("w") as stream:
155
+ subprocess.run([sys.executable, str(a.project / "scripts/upload_verified_hf_tree.py"), str(backup),
156
+ "--repo-id", "LJYAI/paper_revision", "--path-in-repo",
157
+ f"runs/{a.session}/{a.experiment_id}/{name}", "--commit-message",
158
+ f"Native MKA Llama Base MLP-only FiT {name}"],
159
+ env=upload_env, stdout=stream, check=True)
160
+ (out / "BACKUP_COMPLETE").touch()
161
+ with lock:
162
+ state["arms"][name]["phase"] = "complete"
163
+ save()
164
+
165
+ save()
166
+ try:
167
+ # Inspect only frozen inputs; never regenerate native geometry samples.
168
+ import torch
169
+ batches = torch.load(a.selection_data, weights_only=True, map_location="cpu")
170
+ assert len(batches) == 100
171
+ ids_hash, masks_hash = hashlib.sha256(), hashlib.sha256()
172
+ for batch in batches:
173
+ ids, mask = batch["input_ids"], batch["attention_mask"]
174
+ assert tuple(ids.shape) == (1, 512) and ids.shape == mask.shape and bool(mask.any())
175
+ ids_hash.update(ids.numpy().astype("<i8").tobytes())
176
+ masks_hash.update(mask.numpy().astype("<i8").tobytes())
177
+ assert ids_hash.hexdigest() == a.expected_selection_hash
178
+ metadata_path = a.selection_metadata or a.selection_data.with_suffix(".json")
179
+ native_metadata = json.loads(metadata_path.read_text())
180
+ if "input_ids_sha256" in native_metadata:
181
+ assert native_metadata["input_ids_sha256"] == ids_hash.hexdigest()
182
+ provenance = {"input_ids_sha256": ids_hash.hexdigest(),
183
+ "attention_mask_sha256": masks_hash.hexdigest(), "sequences": 100,
184
+ "sequence_length": 512, "seed": 0, "source": str(a.selection_data),
185
+ "native_metadata": native_metadata, "independent_of_fit_loader": True}
186
+ selection.parent.mkdir(exist_ok=True)
187
+ if a.selection_data.resolve() != selection.resolve():
188
+ if selection.exists():
189
+ assert selection.read_bytes() == a.selection_data.read_bytes()
190
+ else:
191
+ shutil.copy2(a.selection_data, selection)
192
+ (root / "selection_provenance.json").write_text(json.dumps(provenance, indent=2) + "\n")
193
+ del batches
194
+ assert Path(a.model).is_dir() and (a.project / a.protocol).is_file()
195
+ policy_file = a.eval_root / "full/batch1/offline_eval.json"
196
+ policy = json.loads(policy_file.read_text())
197
+ assert (Path(policy["wikitext_cache"]) / "dataset_dict.json").is_file()
198
+ for arm in ("batch1", "batch_large"):
199
+ target = root / "full" / arm / "offline_eval.json"
200
+ target.parent.mkdir(parents=True, exist_ok=True)
201
+ target.write_text(json.dumps(policy, indent=2) + "\n")
202
+ for name in ("race/test/high.jsonl", "race/test/middle.jsonl", "CLUE/C3/dev_0.json",
203
+ "CLUE/cmnli/cmnli_public/dev.json", "FewCLUE/chid/dev_few_all.json"):
204
+ assert (a.eval_root / "eval_data/data" / name).is_file(), name
205
+ run([sys.executable, a.project / "scripts/prepare_lmeval9_local_cache.py",
206
+ a.eval_root / "lmeval_cache", "--validate-local"], root / "eval_prepare.log")
207
+ (root / "offline_preflight.json").write_text(json.dumps({
208
+ "eval_root": str(a.eval_root), "strict_offline": True,
209
+ "lmeval131_validated": True, "wikitext_policy": policy}, indent=2) + "\n")
210
+ run([sys.executable, "-m", "pytest", "-q", str(a.project / "tests/test_mka.py"),
211
+ str(a.project / "tests/test_mka_runner.py")], root / "tests.log")
212
+ run([sys.executable, a.project / "scripts/run_llama31_base_fit_ablation.py",
213
+ "--external-root", a.external, "--initializer", "mka", "--fit-mka-mlp",
214
+ "--audit-root", root / "algebra", "--self-test"], root / "tests.log", 0)
215
+ state["phase"] = "batch_profiling"
216
+ save()
217
+ profiles = []
218
+ for batch in (1, 2, 4, 8):
219
+ probe = root / "probes" / f"batch{batch}"
220
+ audit_path = probe / "audit/cycle_01_fit.json"
221
+ rc = 0 if (probe / "TRAIN_COMPLETE").exists() and audit_path.exists() else run(
222
+ train_command(probe, batch, 1, cycles=1, tokens=65536),
223
+ root / "batch_profile.log", check=False)
224
+ row = {"batch_size": batch, "return_code": rc, "completed": rc == 0 and audit_path.exists()}
225
+ if row["completed"]:
226
+ fit = json.loads(audit_path.read_text())
227
+ validate_fit(fit, batch, 65536, require_gradients=True)
228
+ row.update(fit["runtime"])
229
+ row["memory_margin_bytes"] = row["gpu_total_bytes"] - row["peak_reserved_bytes"]
230
+ profiles.append(row)
231
+ (root / "batch_profile.json").write_text(json.dumps({"profiles": profiles}, indent=2) + "\n")
232
+ eligible = [r for r in profiles if r["completed"] and r["batch_size"] > 1
233
+ and r["memory_margin_bytes"] >= 4 * 1024**3]
234
+ if a.larger_batch not in {r["batch_size"] for r in eligible}:
235
+ raise RuntimeError("Required larger batch failed profile/memory gates; do not reduce silently")
236
+ profile = {"profiles": profiles, "selected_larger_batch": a.larger_batch,
237
+ "selection_rule": "Required user comparison batch, profiled with >=4GiB margin",
238
+ "training_updates_per_stage": {"batch1": 512, "batch_large": 512 // a.larger_batch}}
239
+ (root / "batch_profile.json").write_text(json.dumps(profile, indent=2) + "\n")
240
+ if a.profile_only:
241
+ state["phase"] = "profile_complete"
242
+ state["larger_batch"] = a.larger_batch
243
+ save()
244
+ (root / "PROFILE_COMPLETE").touch()
245
+ return
246
+ native_check = json.loads((root / "native_first_selection.json").read_text())
247
+ assert native_check["passed"], "Historical pre-FiT MKA selection must pass before production"
248
+ state["phase"] = "production"
249
+ state["larger_batch"] = a.larger_batch
250
+ save()
251
+ with ThreadPoolExecutor(max_workers=2) as pool:
252
+ jobs = [pool.submit(complete_arm, "batch1", 1, 0),
253
+ pool.submit(complete_arm, "batch_large", a.larger_batch, 1)]
254
+ for job in jobs:
255
+ job.result()
256
+ state["phase"] = "complete"
257
+ save()
258
+ (root / "COMPLETE").touch()
259
+ except Exception as error:
260
+ state["phase"] = "failed"
261
+ state["error"] = str(error)
262
+ save()
263
+ (root / "FAILED").touch()
264
+ raise
265
+
266
+
267
+ if __name__ == "__main__":
268
+ main()
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/mka.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Corrected MKA variant: adjacent NPIB selection, upstream lambda, real fusion.
2
+
3
+ Not an exact reproduction of the paper: use sequence-level pooled activations,
4
+ recompute geometry after every merge, and resolve NPIB ties back-to-front.
5
+ The seven projection weights are fused; residual and Q/K norms stay at anchor.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import math
12
+ import random
13
+ import time
14
+ from collections.abc import Callable, Iterable, Sequence
15
+ from dataclasses import asdict, dataclass
16
+
17
+ import numpy as np
18
+ import torch
19
+ from scipy.linalg import eigh
20
+ from scipy.spatial.distance import pdist, squareform
21
+ from sklearn.feature_selection import mutual_info_regression
22
+ from sklearn.neighbors import NearestNeighbors
23
+ from torch import Tensor, nn
24
+
25
+ PROJECTION_WEIGHTS = (
26
+ "mlp.down_proj.weight",
27
+ "mlp.up_proj.weight",
28
+ "mlp.gate_proj.weight",
29
+ "self_attn.k_proj.weight",
30
+ "self_attn.o_proj.weight",
31
+ "self_attn.q_proj.weight",
32
+ "self_attn.v_proj.weight",
33
+ )
34
+ UPSTREAM = "https://github.com/SempraETY/Pruning-via-Merging"
35
+ UPSTREAM_COMMIT = "3b60b002a0963266e2f4ca78f133b4e091bc607a"
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class GeometryConfig:
40
+ sigma: float = 8.0
41
+ alpha: float = 0.5
42
+ dimensions: int = 2
43
+ mi_neighbors: int = 5
44
+ entropy_neighbors: int = 50
45
+ beta: float = 1.0
46
+ seed: int = 0
47
+ pooling: str = "mean"
48
+
49
+ def validate(self) -> None:
50
+ if not math.isfinite(self.sigma) or self.sigma <= 0:
51
+ raise ValueError("sigma must be positive and finite")
52
+ if not math.isfinite(self.alpha) or not 0 <= self.alpha <= 1:
53
+ raise ValueError("alpha must be finite and in [0, 1]")
54
+ if self.dimensions < 1 or min(self.mi_neighbors, self.entropy_neighbors) < 1:
55
+ raise ValueError("dimensions and neighbor counts must be positive")
56
+ if not math.isfinite(self.beta) or self.beta < 0:
57
+ raise ValueError("beta must be non-negative and finite")
58
+ if self.pooling not in {"mean", "last"}:
59
+ raise ValueError("pooling must be 'mean' or 'last'")
60
+
61
+
62
+ def sample_slimpajama(
63
+ tokenizer,
64
+ *,
65
+ samples: int = 100,
66
+ sequence_length: int = 512,
67
+ seed: int = 0,
68
+ revision: str = "b5f90f419b7489cdba26fdbc8c022fcb5562f968",
69
+ shuffle_buffer: int = 10000,
70
+ max_documents: int = 100000,
71
+ documents: Iterable[dict] | None = None,
72
+ ) -> tuple[list[dict[str, Tensor]], dict]:
73
+ """Exactly one random fixed-length, no-BOS window from each distinct document.
74
+
75
+ Unlike CoMe's row-packing loader, ``samples`` is the number of sequences.
76
+ Persist returned IDs and provenance; do not sample again between stages.
77
+ """
78
+ if min(samples, sequence_length, shuffle_buffer, max_documents) < 1:
79
+ raise ValueError("sampling counts, length and buffer must be positive")
80
+ if documents is None:
81
+ from datasets import load_dataset
82
+
83
+ documents = load_dataset(
84
+ "DKYoon/SlimPajama-6B", revision=revision, split="train", streaming=True
85
+ ).shuffle(seed=seed, buffer_size=shuffle_buffer)
86
+ rng = random.Random(seed)
87
+ batches, records, seen = [], [], set()
88
+ iterator = iter(documents)
89
+ try:
90
+ for row_index, row in enumerate(iterator):
91
+ if row_index >= max_documents:
92
+ break
93
+ text = row.get("text")
94
+ if not isinstance(text, str) or not text.strip():
95
+ continue
96
+ digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
97
+ if digest in seen:
98
+ continue
99
+ seen.add(digest)
100
+ ids = tokenizer.encode(text, add_special_tokens=False)
101
+ if len(ids) < sequence_length:
102
+ continue
103
+ start = rng.randrange(len(ids) - sequence_length + 1)
104
+ tensor = torch.tensor(
105
+ ids[start : start + sequence_length], dtype=torch.long
106
+ )[None, :]
107
+ batches.append(
108
+ {"input_ids": tensor, "attention_mask": torch.ones_like(tensor)}
109
+ )
110
+ records.append(
111
+ {
112
+ "stream_row": row_index,
113
+ "document_sha256": digest,
114
+ "document_tokens": len(ids),
115
+ "window_start": start,
116
+ }
117
+ )
118
+ if len(batches) == samples:
119
+ break
120
+ finally:
121
+ close = getattr(iterator, "close", None)
122
+ if close is not None:
123
+ close()
124
+ if len(batches) != samples:
125
+ raise RuntimeError(
126
+ f"Only found {len(batches)}/{samples} distinct sufficiently long documents"
127
+ )
128
+ checksum = hashlib.sha256()
129
+ for batch in batches:
130
+ checksum.update(batch["input_ids"].numpy().astype("<i8").tobytes())
131
+ metadata = {
132
+ "dataset": "DKYoon/SlimPajama-6B",
133
+ "revision": revision,
134
+ "split": "train",
135
+ "samples": samples,
136
+ "sequence_length": sequence_length,
137
+ "seed": seed,
138
+ "shuffle_buffer": shuffle_buffer,
139
+ "add_special_tokens": False,
140
+ "sampling": "one random window per distinct document",
141
+ "input_ids_sha256": checksum.hexdigest(),
142
+ "records": records,
143
+ }
144
+ return batches, metadata
145
+
146
+
147
+ @torch.inference_mode()
148
+ def collect_features(
149
+ model: nn.Module, batches: Sequence[dict[str, Tensor]], *, pooling: str = "mean"
150
+ ) -> list[np.ndarray]:
151
+ """One backbone forward per batch; block hooks avoid hidden-state off-by-one.
152
+
153
+ Collect outputs *before* the final backbone norm, including the final block.
154
+ Pool only valid tokens; activations are CPU float32 after pooling.
155
+ """
156
+ if pooling not in {"mean", "last"} or not batches:
157
+ raise ValueError("valid pooling and nonempty calibration batches are required")
158
+ layers = model.model.layers
159
+ features: list[list[Tensor]] = [[] for _ in layers]
160
+ current_mask: Tensor | None = None
161
+
162
+ def hook(index):
163
+ def capture(module, inputs, output):
164
+ hidden = output[0] if isinstance(output, (tuple, list)) else output
165
+ mask = current_mask.to(hidden.device, dtype=torch.bool)
166
+ if hidden.shape[:2] != mask.shape or (mask.sum(-1) == 0).any():
167
+ raise ValueError("block output and valid-token mask do not match")
168
+ if pooling == "mean":
169
+ value = (hidden.float() * mask[:, :, None]).sum(1) / mask.sum(1)[
170
+ :, None
171
+ ]
172
+ else:
173
+ positions = torch.arange(mask.shape[1], device=mask.device)[None, :]
174
+ last = positions.expand_as(mask).masked_fill(~mask, -1).max(1).values
175
+ value = hidden[
176
+ torch.arange(hidden.shape[0], device=hidden.device), last
177
+ ].float()
178
+ if not torch.isfinite(value).all():
179
+ raise FloatingPointError(f"nonfinite activation in block {index}")
180
+ features[index].append(value.cpu())
181
+
182
+ return capture
183
+
184
+ handles = [layer.register_forward_hook(hook(i)) for i, layer in enumerate(layers)]
185
+ was_training = model.training
186
+ model.eval()
187
+ try:
188
+ device = model.get_input_embeddings().weight.device
189
+ for batch in batches:
190
+ prepared = {key: value.to(device) for key, value in batch.items()}
191
+ current_mask = prepared.get(
192
+ "attention_mask", torch.ones_like(prepared["input_ids"])
193
+ )
194
+ model.model(**prepared, use_cache=False, return_dict=True)
195
+ finally:
196
+ for handle in handles:
197
+ handle.remove()
198
+ model.train(was_training)
199
+ expected = sum(batch["input_ids"].shape[0] for batch in batches)
200
+ arrays = [torch.cat(parts, dim=0).numpy() for parts in features]
201
+ if any(array.shape[0] != expected for array in arrays):
202
+ raise RuntimeError("not all calibration examples reached each decoder block")
203
+ return arrays
204
+
205
+
206
+ def diffusion_embedding(
207
+ features: np.ndarray, config: GeometryConfig
208
+ ) -> tuple[np.ndarray, dict]:
209
+ """Correctly shaped sample-by-sample diffusion kernel, following upstream SVD geometry."""
210
+ config.validate()
211
+ x = np.asarray(features, dtype=np.float64)
212
+ if x.ndim != 2 or not np.isfinite(x).all() or len(x) <= config.dimensions + 1:
213
+ raise ValueError(
214
+ "features must be finite [samples, features], samples > dimensions + 1"
215
+ )
216
+ distance = squareform(pdist(x, metric="euclidean"))
217
+ if distance.max() <= np.finfo(float).eps:
218
+ raise ValueError(
219
+ "constant calibration features: cannot estimate manifold geometry"
220
+ )
221
+ kernel = np.exp(-np.sqrt(distance / config.sigma))
222
+ p = kernel.sum(0)
223
+ normalized = kernel / np.outer(p, p) ** config.alpha
224
+ v = np.sqrt(normalized.sum(0))
225
+ operator = normalized / np.outer(v, v)
226
+ condition = float(np.linalg.cond(operator))
227
+ regularization = 1e-6 if not math.isfinite(condition) or condition > 1e12 else 0.0
228
+ if regularization:
229
+ operator += regularization * np.eye(len(x))
230
+ values, vectors = eigh(
231
+ operator, subset_by_index=(len(x) - config.dimensions - 1, len(x) - 1)
232
+ )
233
+ values, vectors = values[::-1], vectors[:, ::-1]
234
+ # Fix arbitrary eigenvector signs; the leading vector of this positive kernel is positive.
235
+ for dim in range(vectors.shape[1]):
236
+ if vectors[np.argmax(np.abs(vectors[:, dim])), dim] < 0:
237
+ vectors[:, dim] *= -1
238
+ if np.any(np.abs(vectors[:, 0]) < 1e-12):
239
+ raise FloatingPointError(
240
+ "diffusion normalization has a near-zero leading eigenvector"
241
+ )
242
+ embedding = vectors[:, 1:] / vectors[:, :1]
243
+ if not np.isfinite(embedding).all():
244
+ raise FloatingPointError("nonfinite diffusion embedding")
245
+ # Upstream uses per-axis rank normalization before its KNN estimators.
246
+ embedding = np.argsort(
247
+ np.argsort(embedding, axis=0, kind="stable"), axis=0, kind="stable"
248
+ ) / len(x)
249
+ return embedding, {
250
+ "samples": len(x),
251
+ "condition_number": condition if math.isfinite(condition) else None,
252
+ "regularization": regularization,
253
+ "eigenvalues": values.tolist(),
254
+ }
255
+
256
+
257
+ def entropy_knn(x: np.ndarray, neighbors: int) -> float:
258
+ """Upstream differential-entropy estimator, evaluated in log space."""
259
+ n, dimensions = x.shape
260
+ k = min(neighbors, n - 1)
261
+ distances = NearestNeighbors(n_neighbors=k + 1).fit(x).kneighbors(x)[0][:, -1]
262
+ if np.any(distances <= 0) or not np.isfinite(distances).all():
263
+ raise FloatingPointError(
264
+ "duplicate/degenerate manifold points in entropy estimator"
265
+ )
266
+ return float(math.log(n / k) + dimensions * np.log(distances).mean())
267
+
268
+
269
+ def npib_matrix(
270
+ embeddings: Sequence[np.ndarray], config: GeometryConfig
271
+ ) -> tuple[np.ndarray, list[float]]:
272
+ """Match upstream axis-wise MI average and symmetric sqrt(H_i*H_j) normalization.
273
+
274
+ Differential entropies can be negative. Preserve upstream's formula when
275
+ their product is positive; fail clearly for zero/negative products or NaNs.
276
+ This estimator is a heuristic, not a guaranteed [0, 1] similarity.
277
+ """
278
+ config.validate()
279
+ if not embeddings or len({x.shape for x in embeddings}) != 1:
280
+ raise ValueError("embeddings must have identical sample/coordinate shapes")
281
+ n = len(embeddings[0])
282
+ if n < 3 or any(not np.isfinite(x).all() for x in embeddings):
283
+ raise ValueError("need at least three finite manifold points")
284
+ entropies = [entropy_knn(x, config.entropy_neighbors) for x in embeddings]
285
+ scores = np.empty((len(embeddings), len(embeddings)), dtype=np.float64)
286
+ for i, left in enumerate(embeddings):
287
+ for j in range(i, len(embeddings)):
288
+ right = embeddings[j]
289
+ product = entropies[i] * entropies[j]
290
+ if not math.isfinite(product) or product <= 1e-12:
291
+ raise FloatingPointError(
292
+ f"invalid entropy product at ({i}, {j}): {entropies[i]}, {entropies[j]}"
293
+ )
294
+ mi = np.mean(
295
+ [
296
+ np.mean(
297
+ mutual_info_regression(
298
+ left,
299
+ right[:, dim],
300
+ n_neighbors=min(config.mi_neighbors, n - 1),
301
+ random_state=config.seed,
302
+ )
303
+ )
304
+ for dim in range(right.shape[1])
305
+ ]
306
+ )
307
+ scores[i, j] = scores[j, i] = mi / math.sqrt(product)
308
+ if not np.isfinite(scores).all():
309
+ raise FloatingPointError("NPIB contains nonfinite scores")
310
+ return scores, entropies
311
+
312
+
313
+ def upstream_lambda(
314
+ scores: np.ndarray, left: int, right: int, beta: float = 1.0
315
+ ) -> float:
316
+ """Exactly upstream's sigmoid(beta * row_mean_i / (row_mean_i + row_mean_j))."""
317
+ means = np.mean(scores[[left, right]], axis=1)
318
+ total = float(means.sum())
319
+ if not np.isfinite(means).all() or (means < 0).any() or total <= 1e-12:
320
+ raise FloatingPointError(
321
+ "cannot compute upstream lambda from nonpositive/nonfinite row means"
322
+ )
323
+ if not math.isfinite(beta) or beta < 0:
324
+ raise ValueError("beta must be non-negative and finite")
325
+ value = beta * float(means[0]) / total
326
+ return 1.0 / (1.0 + math.exp(-value))
327
+
328
+
329
+ def select_pair(
330
+ scores: np.ndarray,
331
+ *,
332
+ selection: str = "npib",
333
+ protected_first: int = 0,
334
+ protected_last: int = 0,
335
+ ) -> int:
336
+ """Adjacent pairs only; NPIB descending, and deeper pair wins exact ties."""
337
+ n = len(scores)
338
+ if scores.shape != (n, n) or not np.isfinite(scores).all():
339
+ raise ValueError("scores must be a finite square matrix")
340
+ if min(protected_first, protected_last) < 0:
341
+ raise ValueError("protected layer counts must be non-negative")
342
+ candidates = range(protected_first, n - protected_last - 1)
343
+ if not candidates:
344
+ raise ValueError("no eligible adjacent pair remains")
345
+ if selection == "back-to-front":
346
+ return candidates[-1]
347
+ if selection != "npib":
348
+ raise ValueError("selection must be 'npib' or 'back-to-front'")
349
+ return max(candidates, key=lambda i: (float(scores[i, i + 1]), i))
350
+
351
+
352
+ @torch.inference_mode()
353
+ def merge_pair(model: nn.Module, left: int, ratio: float) -> int:
354
+ """FP32 weighted sum copied into real parameters, then delete the right block."""
355
+ layers = model.model.layers
356
+ if (
357
+ not 0 <= left < len(layers) - 1
358
+ or not math.isfinite(ratio)
359
+ or not 0 <= ratio <= 1
360
+ ):
361
+ raise ValueError("invalid adjacent pair or merge ratio")
362
+ destination, source = layers[left], layers[left + 1]
363
+ pairs = []
364
+ for name in PROJECTION_WEIGHTS:
365
+ pairs.append((destination.get_parameter(name), source.get_parameter(name)))
366
+ # Qwen2.5 has Q/K/V biases. Fuse them with the same coefficient;
367
+ # Llama and Qwen3 (bias-free projections) retain their existing behavior.
368
+ module_name = name.rsplit('.', 1)[0]
369
+ a_bias = getattr(destination.get_submodule(module_name), 'bias', None)
370
+ b_bias = getattr(source.get_submodule(module_name), 'bias', None)
371
+ if (a_bias is None) != (b_bias is None):
372
+ raise ValueError('projection bias presence differs between merge layers')
373
+ if a_bias is not None:
374
+ pairs.append((a_bias, b_bias))
375
+ # Validate all shapes/values/config before any model mutation.
376
+ if any(a.shape != b.shape for a, b in pairs):
377
+ raise ValueError("projection shapes differ between merge layers")
378
+ if any(not torch.isfinite(p).all() for pair in pairs for p in pair):
379
+ raise FloatingPointError("nonfinite source weight")
380
+ configs = [model.config, model.model.config]
381
+ for config in configs:
382
+ types = getattr(config, "layer_types", None)
383
+ if types is not None and len(types) != len(layers):
384
+ raise ValueError("config.layer_types length does not match decoder depth")
385
+ changed = 0
386
+ for target, other in pairs:
387
+ merged = torch.lerp(
388
+ other.detach().to(target.device, dtype=torch.float32), target.float(), ratio
389
+ )
390
+ merged = merged.to(target.dtype)
391
+ if not torch.isfinite(merged).all():
392
+ raise FloatingPointError("merge overflow after conversion to model dtype")
393
+ changed += int(not torch.equal(target, merged))
394
+ target.copy_(merged)
395
+ del layers[left + 1]
396
+ handled = set()
397
+ for config in configs:
398
+ if id(config) in handled:
399
+ continue
400
+ handled.add(id(config))
401
+ config.num_hidden_layers = len(layers)
402
+ if getattr(config, "layer_types", None) is not None:
403
+ config.layer_types = list(config.layer_types[: left + 1]) + list(
404
+ config.layer_types[left + 2 :]
405
+ )
406
+ for index, layer in enumerate(layers):
407
+ if hasattr(layer.self_attn, "layer_idx"):
408
+ layer.self_attn.layer_idx = index
409
+ return changed
410
+
411
+
412
+ def progressive_prune(
413
+ model: nn.Module,
414
+ batches: Sequence[dict[str, Tensor]],
415
+ *,
416
+ target_layers: int,
417
+ geometry: GeometryConfig | None = None,
418
+ selection: str = "npib",
419
+ protected_first: int = 0,
420
+ protected_last: int = 0,
421
+ on_stage: Callable[[nn.Module, dict], None] | None = None,
422
+ transport: bool = False,
423
+ transport_ridge: float = 1e-3,
424
+ transport_fit_fraction: float = 0.8,
425
+ initial_lineage: Sequence[Sequence[int]] | None = None,
426
+ ) -> list[dict]:
427
+ """Recompute activations/manifolds/NPIB on fixed data after every accepted merge.
428
+
429
+ No threshold or forced fallbacks; stop at the requested exact depth. Repeated
430
+ merging of a previously merged block is allowed and recorded in its lineage.
431
+ """
432
+ geometry = geometry or GeometryConfig()
433
+ geometry.validate()
434
+ depth = len(model.model.layers)
435
+ if min(protected_first, protected_last) < 0 or not 1 <= target_layers <= depth:
436
+ raise ValueError("invalid target depth or protected counts")
437
+ if target_layers < protected_first + protected_last + 1:
438
+ raise ValueError("target depth would remove protected layers")
439
+ if selection not in {"npib", "back-to-front"}:
440
+ raise ValueError("invalid selection mode")
441
+ lineage = ([list(group) for group in initial_lineage] if initial_lineage is not None
442
+ else [[i] for i in range(depth)])
443
+ flattened = [index for group in lineage for index in group]
444
+ if (len(lineage) != depth or any(not group for group in lineage)
445
+ or any(type(index) is not int for index in flattened)
446
+ or flattened != list(range(len(flattened)))):
447
+ raise ValueError("initial lineage must partition original layers in order")
448
+ stage_offset = len(flattened) - depth
449
+ records = []
450
+ model.eval()
451
+ while len(model.model.layers) > target_layers:
452
+ started = time.monotonic()
453
+ step = stage_offset + len(records) + 1
454
+ print(
455
+ f"MKA stage {step}: collecting features for {len(lineage)} layers",
456
+ flush=True,
457
+ )
458
+ features = collect_features(model, batches, pooling=geometry.pooling)
459
+ results = [diffusion_embedding(x, geometry) for x in features]
460
+ del features
461
+ scores, entropies = npib_matrix([x[0] for x in results], geometry)
462
+ left = select_pair(
463
+ scores,
464
+ selection=selection,
465
+ protected_first=protected_first,
466
+ protected_last=protected_last,
467
+ )
468
+ ratio = upstream_lambda(scores, left, left + 1, geometry.beta)
469
+ record = {
470
+ "step": step,
471
+ "selection": selection,
472
+ "left_index": left,
473
+ "source_layers": [lineage[left][:], lineage[left + 1][:]],
474
+ "pair_npib": float(scores[left, left + 1]),
475
+ "lambda_left": ratio,
476
+ "lambda_right": 1 - ratio,
477
+ "row_means": scores.mean(1).tolist(),
478
+ "npib_matrix": scores.tolist(),
479
+ "entropies": entropies,
480
+ "geometry": asdict(geometry),
481
+ "manifolds": [x[1] for x in results],
482
+ }
483
+ if transport:
484
+ from .mka_transport import transport_merge_pair
485
+ changed, diagnostic = transport_merge_pair(
486
+ model, batches, left, ratio, ridge_relative=transport_ridge,
487
+ fit_fraction=transport_fit_fraction,
488
+ )
489
+ record["changed_parameter_tensors"] = changed
490
+ record["transport"] = diagnostic
491
+ else:
492
+ record["changed_parameter_tensors"] = merge_pair(model, left, ratio)
493
+ lineage[left] += lineage.pop(left + 1)
494
+ record["lineage_after"] = [x[:] for x in lineage]
495
+ record["remaining_layers"] = len(lineage)
496
+ record["elapsed_seconds"] = time.monotonic() - started
497
+ records.append(record)
498
+ print(
499
+ f"MKA stage {step}: merge {left}/{left + 1}, NPIB={record['pair_npib']:.6g}, "
500
+ f"lambda={ratio:.6g}, remaining={len(lineage)}",
501
+ flush=True,
502
+ )
503
+ if on_stage is not None:
504
+ on_stage(model, record)
505
+ return records
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/offline_eval_policy.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run-local offline policy, applied before importing Hugging Face libraries."""
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+
6
+
7
+ def apply_run_offline_policy(argv):
8
+ output = None
9
+ for index, value in enumerate(argv):
10
+ if value == '--output' and index + 1 < len(argv):
11
+ output = argv[index + 1]
12
+ elif value.startswith('--output='):
13
+ output = value.split('=', 1)[1]
14
+ if output is None:
15
+ return None
16
+ policy_path = Path(output).parent.parent / 'offline_eval.json'
17
+ if not policy_path.is_file():
18
+ return None
19
+ policy = json.loads(policy_path.read_text())
20
+ cache = Path(policy['wikitext_cache'])
21
+ if not (cache / 'dataset_dict.json').is_file():
22
+ raise FileNotFoundError(f'Offline WikiText cache missing: {cache}; no online fallback')
23
+ for key in ('HF_HUB_OFFLINE', 'HF_DATASETS_OFFLINE', 'TRANSFORMERS_OFFLINE'):
24
+ os.environ[key] = '1'
25
+ print('STRICT_OFFLINE_RUN_POLICY_APPLIED', flush=True)
26
+ return policy
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/package_final_fit_backup.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Final compact reconstruction only; exclude intermediate/duplicate weights."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+ import shutil
6
+
7
+ p = argparse.ArgumentParser()
8
+ p.add_argument("run", type=Path)
9
+ p.add_argument("output", type=Path)
10
+ p.add_argument("project", type=Path)
11
+ p.add_argument("external", type=Path)
12
+ p.add_argument("--protocol", default="exp_md/2026-10-08_llama31-come-stagewise-fullblock-fit2.md")
13
+ p.add_argument("--cycles", type=int, default=8)
14
+ p.add_argument("--original-layers", type=int, default=32)
15
+ a = p.parse_args()
16
+ if a.output.exists():
17
+ raise FileExistsError(a.output)
18
+ stage_name = f"stage_{a.cycles:02d}"
19
+ stage = a.run / "compact" / stage_name
20
+ meta = json.loads((stage / "metadata.json").read_text())
21
+ assert meta["stage"] == a.cycles and meta["removed_count"] == a.cycles
22
+ if meta.get("format") == "abprune_compact_stage_v2":
23
+ assert len(meta["active_original_layers"]) == a.original_layers - a.cycles
24
+ expected = {s["state_file"] for s in meta["retained_layer_states"]}
25
+ else:
26
+ assert meta["format"] == "abprune_compact_stage_v1"
27
+ anchor = int(meta["anchor_index"])
28
+ assert meta["removed_original_layers"] == list(range(anchor + 1, anchor + 1 + a.cycles))
29
+ assert anchor + a.cycles < a.original_layers
30
+ expected = {meta["anchor_state_file"]}
31
+ assert expected == {f.name for f in stage.glob("*.pt")}
32
+ assert len(expected) >= 1
33
+ shutil.copytree(stage, a.output / "compact" / stage_name)
34
+ if (a.run / "offline_eval.json").is_file():
35
+ shutil.copy2(a.run / "offline_eval.json", a.output / "offline_eval.json")
36
+ if (a.run.parent.parent / "offline_preflight.json").is_file():
37
+ shutil.copy2(a.run.parent.parent / "offline_preflight.json", a.output / "offline_preflight.json")
38
+ for folder in ("audit", "eval", "logs"):
39
+ shutil.copytree(a.run / folder, a.output / folder)
40
+ for f in (a.run / "run").glob("cycle_*/cycle_metadata.json"):
41
+ d = a.output / "stage_metadata" / f.parent.name
42
+ d.mkdir(parents=True, exist_ok=True)
43
+ shutil.copy2(f, d / f.name)
44
+ code = a.output / "code"
45
+ code.mkdir()
46
+ for name in ("run_llama31_base_fit_ablation.py", "run_llama31_come_fit_arm.sh",
47
+ "bootstrap_llama31_come_fit2.sh", "launch_llama31_come_fit2.sh",
48
+ "package_final_fit_backup.py", "run_external_abprune_instruct_order.py",
49
+ "offline_eval_policy.py", "evaluate_abprune_compact_ppl.py",
50
+ "evaluate_hchc_wikitext2_ppl.py", "eval_llama31_fit_ablation_one.sh",
51
+ "eval_llama31_8b_12bench.py", "prepare_lmeval9_local_cache.py",
52
+ "prepare_offline_ppl_cache.py"):
53
+ shutil.copy2(a.project / "scripts" / name, code / name)
54
+ for name in ("come.py", "fit_ablation_come.py", "abprune_compact.py"):
55
+ shutil.copy2(a.project / "src/fusegpt" / name, code / name)
56
+ for name in ("fuse_layers.py", "fuse_layers_distill.py", "source_feature_transport.py"):
57
+ shutil.copy2(a.external / "src" / name, code / name)
58
+ shutil.copy2(a.project / a.protocol, a.output / "protocol.md")
59
+ assert set(a.output.rglob("*.pt")) == {a.output / "compact" / stage_name / n for n in expected}
60
+ print("FINAL_ONLY_BACKUP", len(expected), "retained blocks", flush=True)
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/prepare_lmeval9_local_cache.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Materialize the exact harness datasets once, without changing task definitions."""
2
+ import argparse
3
+ from concurrent.futures import ThreadPoolExecutor, as_completed
4
+ import hashlib
5
+ import json
6
+ from pathlib import Path
7
+ import time
8
+
9
+ import datasets
10
+ from lm_eval.tasks import TaskManager
11
+
12
+
13
+ def cache_key(path, name, kwargs):
14
+ return hashlib.sha256(json.dumps([path, name, kwargs], sort_keys=True).encode()).hexdigest()
15
+
16
+
17
+ def specs():
18
+ manager = TaskManager()
19
+ names = ["piqa", "winogrande", "hellaswag", "arc_challenge", "arc_easy", "openbookqa", "sciq"]
20
+ entries = [manager.task_index[n] for n in names]
21
+ entries += [e for e in manager.task_index.values()
22
+ if e.yaml_path and e.yaml_path.parent.name == "default"
23
+ and (e.cfg or {}).get("dataset_path") == "cais/mmlu"]
24
+ entries += [e for e in manager.task_index.values()
25
+ if (e.cfg or {}).get("dataset_path") == "haonan-li/cmmlu"]
26
+ unique = {}
27
+ for entry in entries:
28
+ cfg = entry.cfg
29
+ path, name, kwargs = cfg["dataset_path"], cfg.get("dataset_name"), cfg.get("dataset_kwargs") or {}
30
+ unique[cache_key(path, name, kwargs)] = {"path": path, "name": name, "kwargs": kwargs}
31
+ assert len(unique) == 131, len(unique)
32
+ return unique
33
+
34
+
35
+ def materialize(root, key, spec, offline):
36
+ target = root / key
37
+ metadata = target / "source.json"
38
+ if metadata.is_file():
39
+ return key, json.loads(metadata.read_text())
40
+ start = time.monotonic()
41
+ try:
42
+ data = datasets.load_dataset(spec["path"], spec["name"], **spec["kwargs"])
43
+ except Exception:
44
+ if offline:
45
+ return key, None
46
+ raise
47
+ data.save_to_disk(str(target))
48
+ report = {**spec, "splits": {k: {"rows": len(v), "fingerprint": v._fingerprint}
49
+ for k, v in data.items()}}
50
+ metadata.write_text(json.dumps(report, indent=2) + "\n")
51
+ restored = datasets.load_from_disk(str(target))
52
+ assert {k: len(v) for k, v in restored.items()} == {k: len(v) for k, v in data.items()}
53
+ assert all(restored[k].features == data[k].features for k in data)
54
+ assert all(restored[k].data.table.equals(data[k].data.table) for k in data)
55
+ print("READY", spec["path"], spec["name"], round(time.monotonic() - start, 2), flush=True)
56
+ return key, report
57
+
58
+
59
+ def install_local_loader(root):
60
+ manifest = json.loads((root / "manifest.json").read_text())
61
+ assert len(manifest) == 131
62
+ memo = {}
63
+
64
+ def local_load(path, name=None, **kwargs):
65
+ key = cache_key(path, name, kwargs)
66
+ if key not in manifest:
67
+ raise RuntimeError(f"Unprepared dataset request: {path}/{name}; no online fallback")
68
+ if key not in memo:
69
+ memo[key] = datasets.load_from_disk(str(root / key))
70
+ print("LOCAL_DATASET", path, name, flush=True)
71
+ return memo[key]
72
+
73
+ datasets.load_dataset = local_load
74
+
75
+
76
+ if __name__ == "__main__":
77
+ parser = argparse.ArgumentParser()
78
+ parser.add_argument("root", type=Path)
79
+ parser.add_argument("--offline-export", action="store_true")
80
+ parser.add_argument("--validate-local", action="store_true",
81
+ help="Validate a complete transferred cache without Hub requests")
82
+ parser.add_argument("--workers", type=int, default=8)
83
+ args = parser.parse_args()
84
+ args.root.mkdir(parents=True, exist_ok=True)
85
+ sources = specs()
86
+ if args.validate_local:
87
+ manifest = json.loads((args.root / "manifest.json").read_text())
88
+ assert set(manifest) == set(sources), "Task configuration mismatch"
89
+ for key, spec in sources.items():
90
+ report = manifest[key]
91
+ assert all(report[k] == v for k, v in spec.items())
92
+ assert json.loads((args.root / key / "source.json").read_text()) == report
93
+ data = datasets.load_from_disk(str(args.root / key))
94
+ assert {k: len(v) for k, v in data.items()} == {
95
+ k: v["rows"] for k, v in report["splits"].items()}
96
+ print("VALIDATED_LOCAL", len(manifest), "NO_HUB_REQUESTS", flush=True)
97
+ raise SystemExit(0)
98
+ completed = {}
99
+ with ThreadPoolExecutor(max_workers=1 if args.offline_export else args.workers) as executor:
100
+ futures = [executor.submit(materialize, args.root, k, v, args.offline_export)
101
+ for k, v in sources.items()]
102
+ for future in as_completed(futures):
103
+ key, result = future.result()
104
+ if result is not None:
105
+ completed[key] = result
106
+ print("PREPARED", len(completed), "OF", len(sources), flush=True)
107
+ if len(completed) == len(sources):
108
+ (args.root / "manifest.json").write_text(json.dumps(completed, indent=2) + "\n")
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/prepare_mka_batch_calibration.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Convert the immutable historical native MKA cache without resampling data."""
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import torch
9
+
10
+
11
+ SOURCE_REVISION = "1bc4be66370f487b1c2ba4e7a2b4b35ae76758a3"
12
+ SOURCE_PREFIX = (
13
+ "runs/vast-paper_revision-mka-all-small-5090x8-ca-54482709/"
14
+ "20261006-mka-small-13checkpoints/llama31_base_remove8/model"
15
+ )
16
+ RAW_SHA256 = "8e893e97e0a1f277802a6993588a8fe083cdb0d7579359da789fbf8871f2d08b"
17
+ INPUT_SHA256 = "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075"
18
+ MODEL = "meta-llama/Llama-3.1-8B"
19
+ MODEL_REVISION = "d04e592bb4f6aa9cfee91e2e20afa771667e1d4b"
20
+ VOCAB_SHA256 = "869dd26a7a4c36e0324cb1011416f764302d33093f5c0f5c06d6615cc017010f"
21
+
22
+
23
+ def require(condition, message):
24
+ if not condition:
25
+ raise ValueError(message)
26
+
27
+
28
+ def main():
29
+ parser = argparse.ArgumentParser(description=__doc__)
30
+ parser.add_argument("--source", type=Path, required=True,
31
+ help="Downloaded original calibration_ids.pt")
32
+ parser.add_argument("--output", type=Path, required=True)
33
+ parser.add_argument("--model", type=Path,
34
+ help="Optional local model/tokenizer directory for vocabulary verification")
35
+ args = parser.parse_args()
36
+
37
+ raw_hash = hashlib.sha256(args.source.read_bytes()).hexdigest()
38
+ require(raw_hash == RAW_SHA256, "Source file does not match the immutable native MKA cache")
39
+ bundle = torch.load(args.source, map_location="cpu", weights_only=True)
40
+ metadata, chunks = bundle["metadata"], bundle["input_ids"]
41
+ require(metadata["tokenizer"] == MODEL, "Native cache tokenizer identity differs")
42
+ require(metadata["tokenizer_revision"] == MODEL_REVISION, "Native cache tokenizer revision differs")
43
+ require(metadata["tokenizer_vocab_sha256"] == VOCAB_SHA256, "Native cache vocabulary hash differs")
44
+ require(metadata["input_ids_sha256"] == INPUT_SHA256, "Native cache declared token hash differs")
45
+ require(metadata["samples"] == 100 and metadata["sequence_length"] == 512
46
+ and metadata["seed"] == 0, "Expected the historical 100x512 seed0 cache")
47
+ require(len(metadata["records"]) == 100, "Native document provenance is incomplete")
48
+ require(isinstance(chunks, (list, tuple)) and len(chunks) == 100,
49
+ "Expected exactly 100 native calibration sequences")
50
+ require(all(isinstance(ids, torch.Tensor) and ids.dtype == torch.long
51
+ and tuple(ids.shape) == (512,) for ids in chunks),
52
+ "Native calibration IDs must be int64 vectors of length512")
53
+
54
+ tokenizer_verified = False
55
+ if args.model is not None:
56
+ from transformers import AutoTokenizer
57
+
58
+ tokenizer = AutoTokenizer.from_pretrained(str(args.model), local_files_only=True)
59
+ serialized = json.dumps(tokenizer.get_vocab(), sort_keys=True, ensure_ascii=False)
60
+ actual_vocab = hashlib.sha256(serialized.encode("utf-8")).hexdigest()
61
+ require(actual_vocab == VOCAB_SHA256, "Local tokenizer vocabulary differs from native MKA")
62
+ require(all(bool((ids >= 0).all()) and bool((ids < len(tokenizer)).all())
63
+ for ids in chunks), "Native cache contains out-of-vocabulary IDs")
64
+ tokenizer_verified = True
65
+
66
+ inputs_hash, masks_hash = hashlib.sha256(), hashlib.sha256()
67
+ batches = []
68
+ for chunk in chunks:
69
+ ids = chunk.contiguous().unsqueeze(0)
70
+ mask = torch.ones_like(ids)
71
+ inputs_hash.update(ids.numpy().astype("<i8").tobytes())
72
+ masks_hash.update(mask.numpy().astype("<i8").tobytes())
73
+ batches.append({"input_ids": ids, "attention_mask": mask})
74
+ require(inputs_hash.hexdigest() == INPUT_SHA256, "Native calibration token checksum mismatch")
75
+
76
+ args.output.mkdir(parents=True, exist_ok=True)
77
+ selection_path = args.output / "selection.pt"
78
+ metadata_path = args.output / "selection.json"
79
+ if selection_path.exists() or metadata_path.exists():
80
+ raise FileExistsError("Refusing to overwrite an existing selection.pt or selection.json")
81
+ torch.save(batches, selection_path)
82
+ selection_metadata = dict(metadata)
83
+ selection_metadata.update({
84
+ "source": {
85
+ "repo_id": "LJYAI/paper_revision", "revision": SOURCE_REVISION,
86
+ "path_in_repo": SOURCE_PREFIX + "/calibration_ids.pt",
87
+ "local_path": str(args.source.resolve()), "file_sha256": raw_hash,
88
+ },
89
+ "input_ids_sha256": inputs_hash.hexdigest(),
90
+ "attention_mask_sha256": masks_hash.hexdigest(),
91
+ "sequences": len(batches), "batch_size": 1,
92
+ "selection_file_sha256": hashlib.sha256(selection_path.read_bytes()).hexdigest(),
93
+ "local_tokenizer_vocabulary_verified": tokenizer_verified,
94
+ "resampled": False,
95
+ "validation": "Immutable source file, tokenizer metadata, all native token IDs and masks verified",
96
+ })
97
+ metadata_path.write_text(json.dumps(selection_metadata, indent=2) + "\n", encoding="utf-8")
98
+ print(json.dumps({
99
+ "verified": True, "sequences": len(batches), "sequence_length": 512,
100
+ "input_ids_sha256": inputs_hash.hexdigest(),
101
+ "attention_mask_sha256": masks_hash.hexdigest(),
102
+ "source_file_sha256": raw_hash, "selection_path": str(selection_path),
103
+ "local_tokenizer_vocabulary_verified": tokenizer_verified, "resampled": False,
104
+ }), flush=True)
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/prepare_offline_ppl_cache.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Export the warmed WikiText dataset once; never contact the Hub here."""
2
+ import os
3
+ for key in ('HF_HUB_OFFLINE', 'HF_DATASETS_OFFLINE', 'TRANSFORMERS_OFFLINE'):
4
+ os.environ[key] = '1'
5
+
6
+ import json
7
+ from pathlib import Path
8
+ import sys
9
+ from datasets import load_dataset, load_from_disk
10
+
11
+ root = Path(sys.argv[1])
12
+ source = load_dataset('Salesforce/wikitext', 'wikitext-2-raw-v1')
13
+ cache = root / 'wikitext2_cache'
14
+ if not cache.exists():
15
+ temporary = root / f'wikitext2_cache_partial_{os.getpid()}'
16
+ source.save_to_disk(str(temporary))
17
+ temporary.rename(cache)
18
+ restored = load_from_disk(str(cache))
19
+ assert set(source) == set(restored)
20
+ assert all(source[k].data.table.equals(restored[k].data.table) for k in source)
21
+ policy = {'wikitext_cache': str(cache), 'dataset': 'Salesforce/wikitext',
22
+ 'config': 'wikitext-2-raw-v1', 'splits': {k: len(v) for k,v in restored.items()},
23
+ 'fingerprints': {k: v._fingerprint for k,v in source.items()}}
24
+ for family in ('base', 'instruct'):
25
+ target = root / 'full' / family / 'offline_eval.json'
26
+ target.parent.mkdir(parents=True, exist_ok=True)
27
+ temporary = target.with_suffix('.json.partial')
28
+ temporary.write_text(json.dumps(policy, indent=2) + '\n')
29
+ temporary.replace(target)
30
+ print('OFFLINE_PPL_CACHE_EXACT_ROWS_VERIFIED', policy['splits'], flush=True)
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/project_commit.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 6c06f07df04803cf7c885440ea82761817744f56
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/run_external_abprune_instruct_order.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run the transport-enabled ABPrune entrypoint with SlimOrca record data.
3
+
4
+ The transport implementation currently lives in the external repository's
5
+ ``src`` tree, while its instruction-only tree does not contain the transport
6
+ patch. This adapter keeps the transport implementation unchanged and swaps
7
+ only the calibration/distillation record loader to the established SlimOrca
8
+ first-turn protocol.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import os
15
+ import sys
16
+ from typing import Dict, List, Optional
17
+
18
+ import torch
19
+
20
+
21
+ external_src = os.environ.get("ABPRUNE_EXTERNAL_SRC", "").strip()
22
+ if not external_src:
23
+ raise SystemExit("Set ABPRUNE_EXTERNAL_SRC to the external ABPrune src directory")
24
+ sys.path.insert(0, external_src)
25
+
26
+ import fuse_layers as base # noqa: E402
27
+ import fuse_layers_data as data # noqa: E402
28
+
29
+
30
+ def _messages_text(messages: List[Dict[str, str]]) -> str:
31
+ return "\n\n".join(
32
+ f"{str(message.get('role', '')).strip().title() or 'User'}: "
33
+ f"{str(message.get('content', '')).strip()}"
34
+ for message in messages
35
+ if str(message.get("content", "")).strip()
36
+ )
37
+
38
+
39
+ def _slimorca_record(row: Dict[str, object]) -> Optional[Dict[str, object]]:
40
+ conversations = row.get("conversations")
41
+ if not isinstance(conversations, list) or len(conversations) < 2:
42
+ return None
43
+ start = 0 if str(conversations[0].get("from", "")).lower() == "human" else 1
44
+ if start + 1 >= len(conversations):
45
+ return None
46
+ user = conversations[start]
47
+ assistant = conversations[start + 1]
48
+ if str(user.get("from", "")).lower() != "human":
49
+ return None
50
+ if str(assistant.get("from", "")).lower() != "gpt":
51
+ return None
52
+ user_text = str(user.get("value", "")).strip()
53
+ assistant_text = str(assistant.get("value", "")).strip()
54
+ if not user_text or not assistant_text:
55
+ return None
56
+ messages = [
57
+ {"role": "user", "content": user_text},
58
+ {"role": "assistant", "content": assistant_text},
59
+ ]
60
+ return {"messages": messages, "text": _messages_text(messages)}
61
+
62
+
63
+ def load_slimorca_records(
64
+ args: argparse.Namespace,
65
+ num_samples: int,
66
+ manifest_env_var: str = "ABPRUNE_DATA_INDICES_FILE",
67
+ ) -> List[Dict[str, object]]:
68
+ if args.instruction_dataset != "Open-Orca/SlimOrca":
69
+ raise SystemExit(
70
+ "The instruction transport adapter requires Open-Orca/SlimOrca"
71
+ )
72
+ dataset = data.load_dataset(**data._instruction_dataset_kwargs(args))
73
+ rows = (
74
+ data._sample_dataset_rows(dataset, num_samples, args.seed, manifest_env_var)
75
+ if num_samples > 0
76
+ else dataset
77
+ )
78
+ records: List[Dict[str, object]] = []
79
+ for row in rows:
80
+ if not isinstance(row, dict):
81
+ continue
82
+ record = _slimorca_record(row)
83
+ if record is not None:
84
+ records.append(record)
85
+ return records
86
+
87
+
88
+ def build_instruction_calibration(args: argparse.Namespace, tokenizer):
89
+ records = load_slimorca_records(
90
+ args, args.num_samples, "ABPRUNE_CALIB_DATA_INDICES_FILE"
91
+ )
92
+ if not records:
93
+ raise SystemExit("No SlimOrca instruction calibration records were built")
94
+ dataset = base.FixedSeqDataset(records, tokenizer, args.seq_len)
95
+ chunks = [dataset[index][0] for index in range(len(dataset))]
96
+ masks = [dataset[index][1] for index in range(len(dataset))]
97
+ loader = torch.utils.data.DataLoader(
98
+ torch.utils.data.TensorDataset(torch.stack(chunks), torch.stack(masks)),
99
+ batch_size=args.batch_size,
100
+ shuffle=False,
101
+ )
102
+ return [], chunks, loader
103
+
104
+
105
+ original_parse_args = base.parse_args
106
+
107
+
108
+ def parse_args() -> argparse.Namespace:
109
+ args = original_parse_args()
110
+ args.instruction_format = "slimorca"
111
+ args.calibration_source = "instruction"
112
+ return args
113
+
114
+
115
+ base.parse_args = parse_args
116
+ base.load_instruction_records = load_slimorca_records
117
+ base.build_calibration_dataloader = build_instruction_calibration
118
+ data.load_instruction_records = load_slimorca_records
119
+
120
+ original_prepare_distillation_data = base.prepare_distillation_data
121
+
122
+
123
+ def prepare_instruction_distillation(args, tokenizer, include_instruction=True):
124
+ # The generic LM entrypoint deliberately suppresses instruction records for
125
+ # reparameterization and enables them only for LoRA. This adapter is the
126
+ # instruction-model entrypoint, so both calibration and reparameterization
127
+ # must consume the requested SlimOrca records.
128
+ del include_instruction
129
+ return original_prepare_distillation_data(
130
+ args, tokenizer, include_instruction=True
131
+ )
132
+
133
+
134
+ base.prepare_distillation_data = prepare_instruction_distillation
135
+
136
+ import fuse_layers_order as ordered # noqa: E402
137
+
138
+
139
+ if __name__ == "__main__":
140
+ ordered.main()
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/run_llama31_base_fit_ablation.py ADDED
@@ -0,0 +1,869 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Non-Fisher initialization controls on the historical additive-U FiT engine.
3
+
4
+ Wa/Wb/average use the fixed anchor. MKA uses the corrected, committed MKA
5
+ selector; --fit-mka-mlp freezes its merged attention and anchor norms while
6
+ fitting only the three MLP weights. The existing default MKA scope is unchanged.
7
+ The opt-in fixed-span-merge-only mode instead retains our selection/transport,
8
+ replaces just the three MLP initializers, and freezes anchor attention/norms.
9
+ No fake Fisher tensor is used to derive initialization; empty placeholders
10
+ only satisfy the unmodified engine's call signature. Audits mark this clearly.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import hashlib
16
+ import json
17
+ import math
18
+ import os
19
+ import sys
20
+ import time
21
+ from pathlib import Path
22
+
23
+
24
+ def install_exact_layer(distill, torch, state):
25
+ original = distill.ReparamMergedLayer
26
+
27
+ class ExactInitializationLayer(original):
28
+ def __init__(self, layer_a, layer_b, targets, **kwargs):
29
+ assert kwargs.get("additive_u"), "Controls require additive-U"
30
+ assert not kwargs.get("tensor_rho")
31
+ super().__init__(layer_a, layer_b, targets, **kwargs)
32
+ self.exact_lambda = float(state["lambda"])
33
+ self.initialization_errors = {}
34
+ self.fit_attention = bool(state.get("fit_attention", False))
35
+ self.fit_full_block = bool(state.get("fit_full_block", False))
36
+ self.fit_come_mlp = bool(state.get("fit_come_mlp", False))
37
+ self.fit_come_attention = bool(state.get("fit_come_attention", False))
38
+ self.fit_mka_mlp = bool(state.get("fit_mka_mlp", False))
39
+ fixed_merge_only = bool(state.get("fixed_span_merge_only", False))
40
+ fixed_initial = None
41
+ if fixed_merge_only:
42
+ from fusegpt.fixed_span_merge_init import MLP_NAMES, build_initialization
43
+ assert set(self._name_map) == set(MLP_NAMES), self._name_map
44
+ assert state.get("transport_completed"), "Initialize only after transport"
45
+ fixed_initial, fixed_audit = build_initialization(
46
+ layer_a, layer_b, state["initializer"], state["merge_payload"])
47
+ if ((state["initializer"] == "mka" and not fixed_merge_only) or
48
+ self.fit_attention or self.fit_come_attention):
49
+ from fusegpt.fit_ablation_mka import PROJECTION_WEIGHTS
50
+ for name, safe in list(self._name_map.items()):
51
+ if name not in PROJECTION_WEIGHTS:
52
+ del self._name_map[name]
53
+ del self.u[safe]
54
+ del self.gates[safe]
55
+ mka_frozen_initial = {}
56
+ if self.fit_mka_mlp:
57
+ assert state["initializer"] == "mka" and not fixed_merge_only
58
+ assert len(self._name_map) == 3 and all(n.startswith("mlp.") for n in self._name_map)
59
+ # Native MKA merges all seven projections in FP32, rounds into
60
+ # the model dtype, and leaves both RMSNorms at the left anchor.
61
+ # A narrower FiT scope must still materialize that attention merge.
62
+ for name, param in layer_a.named_parameters():
63
+ if name in self._name_map:
64
+ continue
65
+ projection_weight = name in PROJECTION_WEIGHTS
66
+ projection_bias = name.endswith(".bias") and name[:-4] + "weight" in PROJECTION_WEIGHTS
67
+ initial = (torch.lerp(layer_b.get_parameter(name).detach().float(),
68
+ param.detach().float(), self.exact_lambda)
69
+ if projection_weight or projection_bias else param.detach().clone())
70
+ initial = initial.to(param.dtype)
71
+ mka_frozen_initial[name] = initial.detach().clone()
72
+ self.register_buffer("frozen_initial__" + name.replace(".", "__"),
73
+ initial.detach().clone(), persistent=False)
74
+ if (self.fit_come_mlp or self.fit_come_attention) and not fixed_merge_only:
75
+ assert len(self._name_map) == (7 if self.fit_come_attention else 3)
76
+ if self.fit_come_mlp:
77
+ assert all(n.startswith("mlp.") for n in self._name_map)
78
+ for name, initial in state["come_initial"].items():
79
+ if name not in self._name_map:
80
+ self.register_buffer("frozen_initial__" + name.replace(".", "__"),
81
+ initial.to(layer_a.get_parameter(name).device).clone(), persistent=False)
82
+ with torch.no_grad():
83
+ for name, safe in self._name_map.items():
84
+ a = layer_a.get_parameter(name).detach().float()
85
+ b = layer_b.get_parameter(name).detach().float()
86
+ # This is a fitting-scope ablation, not an attention merge.
87
+ # Keep anchor attention exactly; only MLP uses Wa/Wb lambda.
88
+ ratio = 1. if self.fit_attention and name.startswith("self_attn.") else self.exact_lambda
89
+ if fixed_merge_only:
90
+ initial = fixed_initial[name].to(a.device).clone()
91
+ elif state["initializer"] == "come":
92
+ initial = state["come_initial"][name].to(a.device).clone()
93
+ elif ratio == 1:
94
+ initial = a.clone()
95
+ elif ratio == 0:
96
+ initial = b.clone()
97
+ else:
98
+ initial = torch.lerp(b, a, ratio)
99
+ self.register_buffer("initial__" + safe, initial, persistent=False)
100
+ self.u[safe].zero_()
101
+ assert torch.isfinite(initial).all(), name
102
+ self.initialization_errors[name] = 0.0
103
+ state["initialization_audit"] = {
104
+ "lambda": self.exact_lambda, "endpoint_clamping": False,
105
+ "initial_u_nonzero": 0, "merged_parameters": list(self._name_map),
106
+ "parameterization": "W_initial + U_add", "fisher_computed": False,
107
+ "fit_scope": "full_block_including_norms" if self.fit_full_block else (
108
+ "attention_and_mlp" if self.fit_attention or self.fit_come_attention else "mlp"),
109
+ "attention_initialization": "CoMe_channel_merge" if state["initializer"] == "come" else (
110
+ "anchor_Wa" if self.fit_attention else (
111
+ "MKA_merge" if state["initializer"] == "mka" else "anchor_Wa")
112
+ ),
113
+ }
114
+ if fixed_merge_only:
115
+ state["initialization_audit"].update({"fixed_span_merge_only": True,
116
+ "attention_initialization": "anchor_Wa", "norm_initialization": "anchor_Wa",
117
+ "norms_trainable": False, "initialized_parameters": list(self._name_map),
118
+ "selection_policy": state.get("selection_policy", "fixed_anchor21_remove_original_22_30"),
119
+ "merge_rule_audit": fixed_audit})
120
+ state.pop("merge_payload")
121
+ elif state["initializer"] == "come":
122
+ assert len(state["come_initial"]) == 9, "Pinned Llama block has7 projections and2 norms"
123
+ if self.fit_full_block:
124
+ assert set(self._name_map) == set(state["come_initial"]), "All block parameters must have U"
125
+ state["initialization_audit"].update({"lambda": None, "norm_initialization": "CoMe_pair_mean",
126
+ "CoMe": state["come_audit"], "norms_trainable": self.fit_full_block,
127
+ "initialized_parameters": list(state["come_initial"]),
128
+ "frozen_CoMe_parameters": [n for n in state["come_initial"] if n not in self._name_map]})
129
+ if self.fit_come_attention:
130
+ state["initialization_audit"]["frozen_norm_expected_sha256"] = {
131
+ n: hashlib.sha256(initial.to(dtype=layer_a.get_parameter(n).dtype).cpu().contiguous()
132
+ .view(torch.uint8).numpy().tobytes()).hexdigest()
133
+ for n, initial in state["come_initial"].items() if n not in self._name_map
134
+ }
135
+ assert len(state["initialization_audit"]["frozen_norm_expected_sha256"]) == 2
136
+ state.pop("come_initial")
137
+ elif self.fit_mka_mlp:
138
+ hashes = {n: hashlib.sha256(p.cpu().contiguous().view(torch.uint8).numpy().tobytes()).hexdigest()
139
+ for n, p in mka_frozen_initial.items()}
140
+ actual = self._merged_params()
141
+ measured = {n: hashlib.sha256(actual[n].detach().cpu().contiguous()
142
+ .view(torch.uint8).numpy().tobytes()).hexdigest() for n in hashes}
143
+ assert measured == hashes, "MKA frozen initialization does not match native merge"
144
+ state["initialization_audit"].update({
145
+ "fit_scope": "mlp", "attention_initialization": "MKA_merge",
146
+ "norm_initialization": "anchor_Wa", "norms_trainable": False,
147
+ "frozen_MKA_parameters": list(mka_frozen_initial),
148
+ "frozen_attention_norm_expected_sha256": hashes,
149
+ "frozen_attention_norm_before_sha256": measured,
150
+ })
151
+
152
+ def gate_lambdas(self):
153
+ return {name: torch.tensor(
154
+ 1. if self.fit_attention and name.startswith("self_attn.") else self.exact_lambda,
155
+ device=self.u[safe].device)
156
+ for name, safe in self._name_map.items()}
157
+
158
+ def _merged_params(self):
159
+ result = {}
160
+ for name, param in self.layer_a.named_parameters():
161
+ safe = self._name_map.get(name)
162
+ frozen = getattr(self, "frozen_initial__" + name.replace(".", "__"), param.detach())
163
+ result[name] = (frozen.to(param.dtype) if safe is None else
164
+ (getattr(self, "initial__" + safe) + self.u[safe]).to(param.dtype))
165
+ return result
166
+
167
+ def materialize_into_layer_a(self):
168
+ with torch.no_grad():
169
+ for name, param in self.layer_a.named_parameters():
170
+ frozen = getattr(self, "frozen_initial__" + name.replace(".", "__"), None)
171
+ if frozen is not None:
172
+ param.copy_(frozen.to(param.dtype))
173
+ for name, safe in self._name_map.items():
174
+ param = self.layer_a.get_parameter(name)
175
+ param.copy_((getattr(self, "initial__" + safe) + self.u[safe]).to(param.dtype))
176
+ return len(self._name_map)
177
+
178
+ distill.ReparamMergedLayer = ExactInitializationLayer
179
+ # The old diagnostic names its reference "Fisher displacement". That is
180
+ # not the reference direction in these controls, so do not emit it.
181
+ distill._sequential_u_fisher_orthogonality = lambda layer: {}
182
+ return ExactInitializationLayer
183
+
184
+
185
+ def algebra_test(torch, distill):
186
+ class Layer(torch.nn.Module):
187
+ def __init__(self):
188
+ super().__init__()
189
+ self.mlp = torch.nn.Module()
190
+ self.mlp.up_proj = torch.nn.Linear(4, 5, bias=False)
191
+
192
+ torch.manual_seed(42)
193
+ state = {"initializer": "average", "lambda": .5}
194
+ cls = install_exact_layer(distill, torch, state)
195
+ a, b = Layer(), Layer()
196
+ for ratio in (0., .5, 1.):
197
+ state["lambda"] = ratio
198
+ layer = cls(a, b, {"mlp.up_proj.weight": ratio},
199
+ param_subset="mlp", additive_u=True)
200
+ actual = layer._merged_params()["mlp.up_proj.weight"]
201
+ expected = a.mlp.up_proj.weight if ratio == 1 else (
202
+ b.mlp.up_proj.weight if ratio == 0 else
203
+ torch.lerp(b.mlp.up_proj.weight, a.mlp.up_proj.weight, ratio))
204
+ expected = expected.detach().clone()
205
+ assert torch.equal(actual, expected)
206
+ actual.sum().backward()
207
+ u = layer.u["mlp__up_proj__weight"]
208
+ assert torch.equal(u.grad, torch.ones_like(u)), "Average must not mask FiT gradients"
209
+ with torch.no_grad():
210
+ u.add_(.01)
211
+ layer.materialize_into_layer_a()
212
+ assert torch.equal(a.mlp.up_proj.weight, expected + .01)
213
+ print("EXACT_INITIALIZATION_AND_AVERAGE_U_GRADIENT_OK", flush=True)
214
+
215
+
216
+ def attention_algebra_test(torch, distill):
217
+ class Layer(torch.nn.Module):
218
+ def __init__(self):
219
+ super().__init__()
220
+ self.self_attn = torch.nn.Module()
221
+ self.mlp = torch.nn.Module()
222
+ for name in ("q_proj", "k_proj", "v_proj", "o_proj"):
223
+ setattr(self.self_attn, name, torch.nn.Linear(4, 4, bias=False))
224
+ for name in ("gate_proj", "up_proj", "down_proj"):
225
+ setattr(self.mlp, name, torch.nn.Linear(4, 4, bias=False))
226
+ self.input_layernorm = torch.nn.LayerNorm(4)
227
+
228
+ state = {"initializer": "wa", "lambda": 1., "fit_attention": True}
229
+ cls = install_exact_layer(distill, torch, state)
230
+ for ratio in (0., 1.):
231
+ state["lambda"] = ratio
232
+ a, b = Layer(), Layer()
233
+ targets = {name: ratio for name, _ in a.named_parameters()}
234
+ layer = cls(a, b, targets, param_subset="all", additive_u=True)
235
+ assert len(layer._name_map) == 7
236
+ merged = layer._merged_params()
237
+ for name, safe in layer._name_map.items():
238
+ expected = (a if name.startswith("self_attn.") or ratio == 1 else b).get_parameter(name)
239
+ assert torch.equal(merged[name], expected.detach()), name
240
+ assert torch.equal(merged["input_layernorm.weight"], a.input_layernorm.weight)
241
+ sum(merged[name].sum() for name in layer._name_map).backward()
242
+ assert all(torch.equal(u.grad, torch.ones_like(u)) for u in layer.u.values())
243
+ print("ATTENTION_FIT_EXACT_ANCHOR_ATTENTION_MLP_ENDPOINTS_7_U_GRADIENTS_OK", flush=True)
244
+
245
+
246
+ def come_algebra_test(torch, distill, mlp_only=False, attention_and_mlp=False):
247
+ from types import SimpleNamespace
248
+ from fusegpt import come
249
+
250
+ class Layer(torch.nn.Module):
251
+ def __init__(self):
252
+ super().__init__()
253
+ self.self_attn = torch.nn.Module()
254
+ self.self_attn.config = SimpleNamespace(num_attention_heads=2, num_key_value_heads=2)
255
+ self.self_attn.head_dim = 2
256
+ for n in ("q_proj", "k_proj", "v_proj", "o_proj"):
257
+ setattr(self.self_attn, n, torch.nn.Linear(4, 4, bias=False))
258
+ self.mlp = torch.nn.Module()
259
+ self.mlp.gate_proj = torch.nn.Linear(4, 6, bias=False)
260
+ self.mlp.up_proj = torch.nn.Linear(4, 6, bias=False)
261
+ self.mlp.down_proj = torch.nn.Linear(6, 4, bias=False)
262
+ self.input_layernorm = torch.nn.RMSNorm(4)
263
+ self.post_attention_layernorm = torch.nn.RMSNorm(4)
264
+
265
+ import copy
266
+ a, b = Layer(), Layer()
267
+ with torch.no_grad():
268
+ a.input_layernorm.weight.fill_(2)
269
+ b.input_layernorm.weight.fill_(4)
270
+ untouched = {n: p.detach().clone() for n, p in a.named_parameters()}
271
+ pair = [copy.deepcopy(a), copy.deepcopy(b)]
272
+ come.merge_attention(pair, [.5, .5], [torch.tensor([0., 1.]), torch.tensor([1., 0.])])
273
+ come.merge_mlp(pair, [.5, .5], [torch.arange(6.), torch.arange(6.).flip(0)])
274
+ come.merge_norms(pair)
275
+ expected = {n: p.detach().clone() for n, p in pair[0].named_parameters()}
276
+ state = {"initializer": "come", "lambda": 1., "fit_full_block": not (mlp_only or attention_and_mlp),
277
+ "fit_come_mlp": mlp_only,
278
+ "fit_come_attention": attention_and_mlp,
279
+ "come_initial": expected, "come_audit": {"self_test": True}}
280
+ cls = install_exact_layer(distill, torch, state)
281
+ layer = cls(a, b, {n: 1. for n in expected}, param_subset="mlp" if mlp_only else "all", additive_u=True)
282
+ merged = layer._merged_params()
283
+ assert len(layer._name_map) == (3 if mlp_only else (7 if attention_and_mlp else 9))
284
+ assert all(torch.equal(merged[n], expected[n]) for n in expected)
285
+ assert all(torch.equal(p, untouched[n]) for n, p in a.named_parameters())
286
+ assert bool((merged["input_layernorm.weight"] == 3).all())
287
+ sum(v.sum() for v in merged.values()).backward()
288
+ assert all(torch.equal(u.grad, torch.ones_like(u)) for u in layer.u.values())
289
+ assert state["initialization_audit"]["attention_initialization"] == "CoMe_channel_merge"
290
+ if mlp_only or attention_and_mlp:
291
+ assert not state["initialization_audit"]["norms_trainable"]
292
+ assert len(state["initialization_audit"]["frozen_CoMe_parameters"]) == (2 if attention_and_mlp else 6)
293
+ with torch.no_grad():
294
+ for u in layer.u.values():
295
+ u.add_(.01)
296
+ layer.materialize_into_layer_a()
297
+ for n, p in a.named_parameters():
298
+ trainable = n in layer._name_map
299
+ assert torch.equal(p, expected[n] + .01 if trainable else expected[n]), n
300
+ print("COME_NATIVE_MERGE_MLP3_U_FROZEN_ATTN_NORMS_OK" if mlp_only else (
301
+ "COME_NATIVE_MERGE_ATTN4_MLP3_U_FROZEN_NORMS_TEACHER_UNCHANGED_OK" if attention_and_mlp else
302
+ "COME_NATIVE_MERGE_9_U_GRADIENTS_NORMS_TEACHER_UNCHANGED_OK"), flush=True)
303
+
304
+
305
+ def mka_algebra_test(torch, distill, mlp_only=False):
306
+ """Compare with the real native merger, including BF16 rounding and frozen attention."""
307
+ import copy
308
+ from types import SimpleNamespace
309
+ from fusegpt import fit_ablation_mka as mka
310
+ original = distill.ReparamMergedLayer
311
+
312
+ class Layer(torch.nn.Module):
313
+ def __init__(self):
314
+ super().__init__()
315
+ self.self_attn = torch.nn.Module()
316
+ self.mlp = torch.nn.Module()
317
+ for name in ("q_proj", "k_proj", "v_proj", "o_proj"):
318
+ setattr(self.self_attn, name, torch.nn.Linear(4, 4, bias=False))
319
+ for name in ("gate_proj", "up_proj", "down_proj"):
320
+ setattr(self.mlp, name, torch.nn.Linear(4, 4, bias=False))
321
+ self.input_layernorm = torch.nn.RMSNorm(4)
322
+ self.post_attention_layernorm = torch.nn.RMSNorm(4)
323
+
324
+ for dtype in (torch.float32, torch.bfloat16):
325
+ for ratio in (0., .623, 1.):
326
+ a, b = Layer().to(dtype), Layer().to(dtype)
327
+ with torch.no_grad():
328
+ a.input_layernorm.weight.fill_(2)
329
+ b.input_layernorm.weight.fill_(4)
330
+ a.post_attention_layernorm.weight.fill_(3)
331
+ b.post_attention_layernorm.weight.fill_(5)
332
+ teacher = [{n: p.detach().clone() for n, p in layer.named_parameters()} for layer in (a, b)]
333
+ model = torch.nn.Module()
334
+ model.config = SimpleNamespace(num_hidden_layers=2)
335
+ model.model = torch.nn.Module()
336
+ model.model.config = model.config
337
+ model.model.layers = torch.nn.ModuleList([copy.deepcopy(a), copy.deepcopy(b)])
338
+ mka.merge_pair(model, 0, ratio)
339
+ expected = {n: p.detach().clone() for n, p in model.model.layers[0].named_parameters()}
340
+ state = {"initializer": "mka", "lambda": ratio, "fit_mka_mlp": mlp_only}
341
+ distill.ReparamMergedLayer = original
342
+ cls = install_exact_layer(distill, torch, state)
343
+ layer = cls(a, b, {n: ratio for n, _ in a.named_parameters()},
344
+ param_subset="mlp" if mlp_only else "all", additive_u=True)
345
+ merged = layer._merged_params()
346
+ assert len(layer._name_map) == (3 if mlp_only else 7)
347
+ assert all(torch.equal(merged[n], expected[n]) for n in expected)
348
+ assert all(torch.equal(p, saved[n]) for source, saved in zip((a, b), teacher)
349
+ for n, p in source.named_parameters()), "Initialization mutated the teacher"
350
+ sum(merged[n].float().sum() for n in layer._name_map).backward()
351
+ assert all(u.grad is not None and torch.equal(u.grad, torch.ones_like(u)) for u in layer.u.values())
352
+ with torch.no_grad():
353
+ for u in layer.u.values():
354
+ u.add_(.01)
355
+ layer.materialize_into_layer_a()
356
+ for n, p in a.named_parameters():
357
+ after = (expected[n].float() + .01).to(dtype) if n in layer._name_map else expected[n]
358
+ # Trainable BF16 native initialization keeps its unrounded FP32
359
+ # weighted sum until materialization, as in the existing engine.
360
+ if n in layer._name_map:
361
+ initial = torch.lerp(teacher[1][n].float(), teacher[0][n].float(), ratio)
362
+ after = (initial + .01).to(dtype)
363
+ assert torch.equal(p, after), n
364
+ if mlp_only:
365
+ audit = state["initialization_audit"]
366
+ assert len(audit["frozen_attention_norm_expected_sha256"]) == 6
367
+ assert audit["frozen_attention_norm_before_sha256"] == audit["frozen_attention_norm_expected_sha256"]
368
+ assert not audit["norms_trainable"] and audit["attention_initialization"] == "MKA_merge"
369
+ # Historical MKA uses a seven-projection map but the external
370
+ # fitter trains only MLP U (reparam_train_subset=mlp). Confirm
371
+ # narrowing the map preserves that initialization and update.
372
+ old_a, old_b = Layer().to(dtype), Layer().to(dtype)
373
+ old_a.load_state_dict(teacher[0])
374
+ old_b.load_state_dict(teacher[1])
375
+ distill.ReparamMergedLayer = original
376
+ old_cls = install_exact_layer(distill, torch, {"initializer": "mka", "lambda": ratio})
377
+ old = old_cls(old_a, old_b, {n: ratio for n, _ in old_a.named_parameters()},
378
+ param_subset="all", additive_u=True)
379
+ assert len(old._name_map) == 7
380
+ for name, safe in old._name_map.items():
381
+ u = old.u[safe]
382
+ u.requires_grad_(name.startswith("mlp."))
383
+ if name.startswith("mlp."):
384
+ with torch.no_grad():
385
+ u.add_(.01)
386
+ old.materialize_into_layer_a()
387
+ assert all(torch.equal(p, old_a.get_parameter(n)) for n, p in a.named_parameters()), (
388
+ "New three-MLP map differs from historical seven-map/MLP-only-update MKA")
389
+ distill.ReparamMergedLayer = original
390
+ print("MKA_NATIVE_MERGE_MLP3_U_FROZEN_ATTN_NORMS_TEACHER_UNCHANGED_OK" if mlp_only else
391
+ "MKA_NATIVE_MERGE_DEFAULT7_U_REGRESSION_OK", flush=True)
392
+
393
+
394
+ def main():
395
+ parser = argparse.ArgumentParser(allow_abbrev=False)
396
+ parser.add_argument("--external-root", type=Path, required=True)
397
+ parser.add_argument("--initializer", choices=("wa", "wb", "average", "mka", "come"), required=True)
398
+ parser.add_argument("--fixed-anchor", type=int, default=21)
399
+ parser.add_argument("--original-layers", type=int, default=32,
400
+ help="Original decoder depth; defaults preserve the Llama controls")
401
+ parser.add_argument("--audit-root", type=Path, required=True)
402
+ parser.add_argument("--mka-data", type=Path)
403
+ parser.add_argument("--selection-data", type=Path,
404
+ help="Frozen native calibration batches; separate from FiT inputs")
405
+ parser.add_argument("--selection-hash",
406
+ help="Required input_ids SHA256 for frozen selection batches")
407
+ parser.add_argument("--record-fit-runtime", action="store_true")
408
+ parser.add_argument("--mka-samples", type=int, default=100)
409
+ parser.add_argument("--self-test", action="store_true")
410
+ parser.add_argument("--model-id", default="meta-llama/Llama-3.1-8B")
411
+ parser.add_argument("--base-revision", default="d04e592bb4f6aa9cfee91e2e20afa771667e1d4b")
412
+ parser.add_argument("--instruction-data", action="store_true")
413
+ parser.add_argument("--fit-attention", action="store_true",
414
+ help="Train seven projection U tensors; initialize attention from anchor Wa")
415
+ parser.add_argument("--fit-full-block", action="store_true",
416
+ help="CoMe initialization; train all9 block weights including both norms")
417
+ parser.add_argument("--fit-come-mlp", action="store_true",
418
+ help="CoMe initializes all9 weights; fit only3 MLP weights, freeze merged attention/norms")
419
+ parser.add_argument("--fit-come-attention", action="store_true",
420
+ help="CoMe initializes all9 weights; fit7 attention/MLP projections, freeze merged norms")
421
+ parser.add_argument("--fit-mka-mlp", action="store_true",
422
+ help="Native dynamic MKA initializes7 projections; fit3 MLP weights, freeze merged attention/anchor norms")
423
+ parser.add_argument("--fixed-span-merge-only", action="store_true",
424
+ help="Fixed our span, transport ON, replace ONLY3 MLP initial weights with CoMe/MKA")
425
+ parser.add_argument("--come-minimum-retention", type=float, default=.97)
426
+ parser.add_argument("--come-power", type=float, default=1.)
427
+ parser.add_argument("--one-shot", type=int, default=1,
428
+ help="Absorb this many blocks in a single cycle (Wa only).")
429
+ opt, forwarded = parser.parse_known_args()
430
+ if opt.fit_attention:
431
+ assert opt.initializer in ("wa", "wb") and opt.one_shot == 1
432
+ if opt.fit_mka_mlp:
433
+ assert opt.initializer == "mka" and not opt.fixed_span_merge_only and opt.one_shot == 1
434
+ assert not (opt.fit_attention or opt.fit_full_block or opt.fit_come_mlp or opt.fit_come_attention)
435
+ assert "--source_feature_transport" not in forwarded
436
+ if not opt.self_test:
437
+ assert opt.selection_data or opt.mka_data, "MLP-only MKA requires explicitly saved native geometry inputs"
438
+ assert opt.selection_hash, "MLP-only MKA requires a native geometry input hash"
439
+ for key in ("--reparam_param_subset", "--reparam_train_subset"):
440
+ assert forwarded[forwarded.index(key) + 1] == "mlp"
441
+ assert sum((opt.fit_full_block, opt.fit_come_mlp, opt.fit_come_attention)) == int(
442
+ opt.initializer == "come" and not opt.fixed_span_merge_only)
443
+ if opt.fixed_span_merge_only:
444
+ assert opt.initializer in ("come", "mka") and opt.one_shot == 1
445
+ count = int(forwarded[forwarded.index("--num_progressive") + 1])
446
+ assert opt.original_layers > 1 and 0 <= opt.fixed_anchor < opt.original_layers - 1
447
+ assert 1 <= count <= opt.original_layers - opt.fixed_anchor - 1
448
+ assert int(forwarded[forwarded.index("--layer") + 1]) == opt.fixed_anchor
449
+ assert not (opt.fit_attention or opt.fit_full_block or opt.fit_come_mlp or opt.fit_come_attention or opt.self_test)
450
+ assert "--source_feature_transport" in forwarded
451
+ for key in ("--reparam_param_subset", "--reparam_train_subset"):
452
+ assert forwarded[forwarded.index(key) + 1] == "mlp"
453
+ elif opt.initializer == "come":
454
+ assert not opt.fit_attention and opt.one_shot == 1
455
+ assert "--source_feature_transport" not in forwarded
456
+ if not opt.self_test:
457
+ subset = "mlp" if opt.fit_come_mlp else "all"
458
+ assert forwarded[forwarded.index("--reparam_param_subset") + 1] == subset
459
+ assert forwarded[forwarded.index("--reparam_train_subset") + 1] == subset
460
+ if opt.one_shot != 1:
461
+ assert opt.initializer == "wa" and opt.one_shot == 8
462
+ assert forwarded[forwarded.index("--num_progressive") + 1] == "1"
463
+ assert forwarded[forwarded.index("--redistrib_teacher_source") + 1] == "base_model"
464
+ assert forwarded[forwarded.index("--reparam_absorb_count") + 1] == "8"
465
+ assert "--source_feature_transport" not in forwarded
466
+ sys.path.insert(0, str(opt.external_root / "src"))
467
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
468
+ import torch
469
+ import fuse_layers as base
470
+ import fuse_layers_distill as distill
471
+ if opt.self_test:
472
+ if opt.initializer == "come":
473
+ come_algebra_test(torch, distill, mlp_only=opt.fit_come_mlp,
474
+ attention_and_mlp=opt.fit_come_attention)
475
+ elif opt.initializer == "mka":
476
+ mka_algebra_test(torch, distill, mlp_only=opt.fit_mka_mlp)
477
+ else:
478
+ (attention_algebra_test if opt.fit_attention else algebra_test)(torch, distill)
479
+ return
480
+ if opt.instruction_data:
481
+ assert opt.model_id in ("meta-llama/Llama-3.1-8B-Instruct", "Qwen/Qwen3-8B")
482
+ os.environ["ABPRUNE_EXTERNAL_SRC"] = str(opt.external_root / "src")
483
+ import run_external_abprune_instruct_order as instruction
484
+
485
+ opt.audit_root.mkdir(parents=True, exist_ok=True)
486
+ selection_batches = None
487
+ if opt.selection_data:
488
+ if opt.initializer not in ("come", "mka") or opt.fixed_span_merge_only:
489
+ raise ValueError("Frozen selection inputs require native CoMe or MKA")
490
+ selection_batches = torch.load(opt.selection_data, weights_only=True, map_location="cpu")
491
+ checksum = hashlib.sha256()
492
+ count = 0
493
+ for batch in selection_batches:
494
+ ids, mask = batch["input_ids"], batch["attention_mask"]
495
+ if ids.ndim != 2 or ids.shape != mask.shape or not bool(mask.bool().any(dim=1).all()):
496
+ raise ValueError("Frozen native inputs require matching nonempty valid-token masks")
497
+ if opt.initializer == "come" and not bool(mask.all()):
498
+ raise ValueError("Frozen native CoMe inputs must be unpadded matrices")
499
+ checksum.update(ids.numpy().astype("<i8").tobytes())
500
+ count += ids.shape[0]
501
+ measured = checksum.hexdigest()
502
+ if not opt.selection_hash or measured != opt.selection_hash:
503
+ raise ValueError("Frozen native calibration hash mismatch")
504
+ (opt.audit_root / "selection_inputs.json").write_text(json.dumps({
505
+ "input_ids_sha256": measured, "sequences": count,
506
+ "source": str(opt.selection_data), "independent_of_fit_loader": True,
507
+ }, indent=2) + "\n")
508
+ if opt.fit_mka_mlp:
509
+ source = opt.selection_data or opt.mka_data
510
+ if selection_batches is None:
511
+ if not source.is_file():
512
+ raise FileNotFoundError("Saved native MKA geometry is required; do not resample: " + str(source))
513
+ selection_batches = torch.load(source, weights_only=True, map_location="cpu")
514
+ ids_hash, mask_hash = hashlib.sha256(), hashlib.sha256()
515
+ count = valid_tokens = 0
516
+ for batch in selection_batches:
517
+ ids, mask = batch["input_ids"], batch["attention_mask"]
518
+ if ids.ndim != 2 or ids.shape != mask.shape or ids.shape[1] != 512:
519
+ raise ValueError("Native saved MKA geometry requires 512-token matrices, not CoMe packed windows")
520
+ if not bool(((mask == 0) | (mask == 1)).all()) or not bool(mask.bool().any(dim=1).all()):
521
+ raise ValueError("Native MKA geometry has invalid/empty attention masks")
522
+ ids_hash.update(ids.cpu().numpy().astype("<i8").tobytes())
523
+ mask_hash.update(mask.cpu().numpy().astype("<i8").tobytes())
524
+ count += ids.shape[0]
525
+ valid_tokens += int(mask.sum())
526
+ if count != opt.mka_samples or ids_hash.hexdigest() != opt.selection_hash:
527
+ raise ValueError("Saved native MKA geometry sample count or input SHA256 mismatch")
528
+ (opt.audit_root / "selection_inputs.json").write_text(json.dumps({
529
+ "input_ids_sha256": ids_hash.hexdigest(), "attention_mask_sha256": mask_hash.hexdigest(),
530
+ "sequences": count, "sequence_length": 512, "valid_tokens": valid_tokens,
531
+ "source": str(source), "independent_of_fit_loader": True,
532
+ "selection_protocol": "native_MKA_saved_geometry_dynamic_NPIB",
533
+ }, indent=2) + "\n")
534
+ state = {"initializer": opt.initializer, "fit_attention": opt.fit_attention,
535
+ "fixed_span_merge_only": opt.fixed_span_merge_only,
536
+ "fit_full_block": opt.fit_full_block,
537
+ "fit_come_mlp": opt.fit_come_mlp,
538
+ "fit_come_attention": opt.fit_come_attention,
539
+ "fit_mka_mlp": opt.fit_mka_mlp,
540
+ "lambda": {"wa": 1., "wb": 0., "average": .5, "mka": .5, "come": 1.}[opt.initializer],
541
+ "records": [], "active": list(range(opt.original_layers)),
542
+ "lineage": [[i] for i in range(opt.original_layers)],
543
+ "selection_policy": f"fixed_anchor{opt.fixed_anchor}_remove_original_{opt.fixed_anchor + 1}_{opt.fixed_anchor + 1 + int(forwarded[forwarded.index('--num_progressive') + 1])}"}
544
+ install_exact_layer(distill, torch, state)
545
+
546
+ def no_fisher(*args, **kwargs):
547
+ print("[fit-ablation] Fisher bypassed: non-Fisher initializer", flush=True)
548
+ return ({}, {}), 0, ({}, {})
549
+
550
+ def no_contextual_fisher(**kwargs):
551
+ values = no_fisher()
552
+ return (*values, {"computed": False, "reason": "non-Fisher initializer",
553
+ "anchor_candidate_mean_nll": 0., "transported_source_candidate_mean_nll": 0.})
554
+
555
+ def priors(**kwargs):
556
+ a, b = kwargs["layer_a"], dict(kwargs["layer_b"].named_parameters())
557
+ return {name: state["lambda"] for name, param in a.named_parameters()
558
+ if name in b and param.shape == b[name].shape}
559
+
560
+ base.compute_fisher = no_fisher
561
+ base.compute_same_anchor_contextual_fisher = no_contextual_fisher
562
+ base.compute_fisher_gate_priors = priors
563
+ base.summarize_fisher_gate_prior_inputs = lambda **kw: {
564
+ "computed": False, "initializer": opt.initializer, "prior_mean": state["lambda"]}
565
+ if opt.fixed_span_merge_only:
566
+ original_transport = base.fit_and_apply_source_feature_transport
567
+
568
+ def tracked_transport(**kwargs):
569
+ from fusegpt.fixed_span_merge_init import MLP_NAMES, tensor_hash
570
+ before = {n: tensor_hash(kwargs["layer_b"].get_parameter(n)) for n in MLP_NAMES}
571
+ result = original_transport(**kwargs)
572
+ after = {n: tensor_hash(kwargs["layer_b"].get_parameter(n)) for n in MLP_NAMES}
573
+ state["transport_completed"] = True
574
+ state["transport_operands"] = {"before": before, "after": after,
575
+ "changed": [n for n in MLP_NAMES if before[n] != after[n]]}
576
+ return result
577
+
578
+ base.fit_and_apply_source_feature_transport = tracked_transport
579
+
580
+ original_prepare = base.prepare_all_data
581
+
582
+ def prepare(*args, **kwargs):
583
+ if opt.instruction_data:
584
+ config = args[0]
585
+ assert not config.dataset and config.target_tokens == 0
586
+ assert config.instruction_dataset == "Open-Orca/SlimOrca"
587
+ data = original_prepare(*args, **kwargs)
588
+ fingerprints = {}
589
+ for name in ("calib_loader", "distill_loader"):
590
+ loader = getattr(data, name)
591
+ checksum = hashlib.sha256()
592
+ mask_checksum = hashlib.sha256()
593
+ valid_tokens = 0
594
+ for item in loader.dataset:
595
+ ids = item[0] if isinstance(item, (tuple, list)) else item["input_ids"]
596
+ mask = item[1] if isinstance(item, (tuple, list)) else item["attention_mask"]
597
+ checksum.update(ids.cpu().numpy().astype("<i8").tobytes())
598
+ mask_checksum.update(mask.cpu().numpy().astype("<i8").tobytes())
599
+ valid_tokens += int(mask.sum())
600
+ fingerprints[name] = {"sequences": len(loader.dataset), "sha256": checksum.hexdigest(),
601
+ "attention_mask_sha256": mask_checksum.hexdigest(), "valid_tokens": valid_tokens}
602
+ (opt.audit_root / "data_fingerprints.json").write_text(json.dumps(fingerprints, indent=2) + "\n")
603
+ if opt.fit_attention or opt.initializer == "come" or opt.fixed_span_merge_only or opt.fit_mka_mlp:
604
+ size = fingerprints["distill_loader"]["sequences"]
605
+ if opt.model_id == "meta-llama/Llama-3.1-8B" and size == 512:
606
+ assert fingerprints["calib_loader"]["sha256"] == "fa4a6219f7a7b17364eef6b5b7771533b57a407f1d26db1d483bbd955814ce38"
607
+ assert fingerprints["distill_loader"]["sha256"] == "2b2d044c8c040f67891817ecc110f0fa0de2f469db4c6731114ff7816bbf1cd0"
608
+ elif opt.model_id == "meta-llama/Llama-3.1-8B-Instruct" and opt.instruction_data and size == 500:
609
+ assert fingerprints["calib_loader"]["sha256"] == "98ff6481a347ebc9444154a51f379c5c71746abe3b417b47186d9f61cbedeeb2"
610
+ assert fingerprints["distill_loader"]["sha256"] == "c75cb58ff76dce06a57127e87633f2fbad04d7d7c9c824e5150c14fd8556cda3"
611
+ assert fingerprints["distill_loader"]["attention_mask_sha256"] == "1e9ccfe6387a9565982ab4ee99f2a3b8c54afebe957ab11ef16e2097c4b8f825"
612
+ elif opt.model_id == "Qwen/Qwen3-8B" and opt.instruction_data:
613
+ assert fingerprints["calib_loader"]["sha256"] == "0d438c8d712c08b428287c97ff2422cc63c99cc0564a27ec53afcae788f042bb"
614
+ assert fingerprints["calib_loader"]["attention_mask_sha256"] == "fdcd61583ffdd02ccfd992f92343facc38a41d794a316746d9b9b7836ebb65b5"
615
+ if size == 500:
616
+ assert fingerprints["distill_loader"]["sha256"] == "b9885f1464a0b145f1c59bc60190bfa73ad388902cbd245e532aa082044a61e7"
617
+ assert fingerprints["distill_loader"]["attention_mask_sha256"] == "f5380885dd835321800a18abd00245d32d60aef9c78ea43a1f16effc26457718"
618
+ print("ATTENTION_FIT_DATA_FINGERPRINTS_CHECKED_BEFORE_TRAINING", flush=True)
619
+ if opt.one_shot > 1 and fingerprints["distill_loader"]["sequences"] == 512:
620
+ assert fingerprints["calib_loader"]["sha256"] == "fa4a6219f7a7b17364eef6b5b7771533b57a407f1d26db1d483bbd955814ce38"
621
+ assert fingerprints["distill_loader"]["sha256"] == "2b2d044c8c040f67891817ecc110f0fa0de2f469db4c6731114ff7816bbf1cd0"
622
+ print("ONE_SHOT_DATA_MATCHES_PREVIOUS_PROGRESSIVE", flush=True)
623
+ return data
624
+
625
+ base.prepare_all_data = prepare
626
+ geometry_batches = None
627
+
628
+ def select(args, model, layers, dataloader, cosine_loader, scores, start, excluded):
629
+ nonlocal geometry_batches
630
+ if opt.fixed_span_merge_only:
631
+ from fusegpt.fit_ablation_come import valid_calibration_batches
632
+ index = opt.fixed_anchor
633
+ assert state["active"][index] == opt.fixed_anchor
634
+ assert state["active"][index + 1] == opt.fixed_anchor + 1 + len(state["records"])
635
+ state["transport_completed"] = False
636
+ batches = valid_calibration_batches(dataloader)
637
+ if opt.initializer == "come":
638
+ from fusegpt import come
639
+ measured = come.collect_calibration_scores(model, batches, sbi_metric="angular_last")
640
+ leaves = len(state["lineage"][index]) + len(state["lineage"][index + 1])
641
+ minimum = opt.come_minimum_retention ** (1 / (leaves - 1))
642
+ ratios = come.compute_retention_ratios(
643
+ measured.block_importance[index:index+2], power=opt.come_power, minimum=minimum)
644
+ state["merge_payload"] = {"ratios": ratios,
645
+ "neuron_scores": measured.mlp_neurons[index:index+2]}
646
+ extra = {"minimum_retention": opt.come_minimum_retention,
647
+ "adjusted_minimum": minimum, "power": opt.come_power,
648
+ "retention_ratios": ratios, "block_importance": measured.block_importance[index:index+2]}
649
+ del measured
650
+ else:
651
+ from fusegpt import fit_ablation_mka as mka
652
+ config = mka.GeometryConfig()
653
+ assert len(batches) >= 64, "MKA geometry requires the matched64-record calibration view"
654
+ features = mka.collect_features(model, batches, pooling=config.pooling)
655
+ manifolds = [mka.diffusion_embedding(x, config) for x in features]
656
+ del features
657
+ matrix, entropies = mka.npib_matrix([x[0] for x in manifolds], config)
658
+ state["lambda"] = mka.upstream_lambda(matrix, index, index+1, config.beta)
659
+ state["merge_payload"] = {"lambda_left": state["lambda"]}
660
+ extra = {"npib_matrix": matrix.tolist(), "entropies": entropies,
661
+ "row_means": matrix.mean(1).tolist(), "geometry_samples": len(batches),
662
+ "geometry_sequence_length": int(batches[0]["input_ids"].shape[1])}
663
+ del manifolds, matrix
664
+ extra.update({"selection_policy": f"fixed_anchor{opt.fixed_anchor}", "source_lineage":
665
+ [state["lineage"][index][:], state["lineage"][index+1][:]],
666
+ "score_data": "same_calib_loader_as_transport", "data_seed": 42,
667
+ "mka_mi_seed": 0 if opt.initializer == "mka" else None,
668
+ "initializer_weights_after_transport": True})
669
+ del batches
670
+ elif opt.initializer == "come":
671
+ from fusegpt.fit_ablation_come import select_and_initialize
672
+ index, initial, extra = select_and_initialize(
673
+ model, selection_batches if selection_batches is not None else dataloader, state["lineage"],
674
+ minimum=opt.come_minimum_retention, power=opt.come_power)
675
+ state["come_initial"] = initial
676
+ state["come_audit"] = extra
677
+ elif opt.initializer == "mka":
678
+ from fusegpt import fit_ablation_mka as mka
679
+ if geometry_batches is None:
680
+ if selection_batches is not None:
681
+ geometry_batches = selection_batches
682
+ elif opt.mka_data and opt.mka_data.is_file():
683
+ geometry_batches = torch.load(opt.mka_data, weights_only=True)
684
+ else:
685
+ from transformers import AutoTokenizer
686
+ tokenizer = AutoTokenizer.from_pretrained(args.model)
687
+ if opt.instruction_data:
688
+ import copy
689
+ geometry_args = copy.copy(args)
690
+ geometry_args.seed = 0
691
+ records = instruction.load_slimorca_records(geometry_args, opt.mka_samples,
692
+ "ABPRUNE_MKA_DATA_INDICES_FILE")
693
+ dataset = base.FixedSeqDataset(records, tokenizer, 512)
694
+ geometry_batches = [{"input_ids": ids[None, :], "attention_mask": mask[None, :]}
695
+ for ids, mask in dataset]
696
+ assert len(geometry_batches) == opt.mka_samples
697
+ checksum = hashlib.sha256()
698
+ for batch in geometry_batches:
699
+ checksum.update(batch["input_ids"].numpy().astype("<i8").tobytes())
700
+ metadata = {"dataset": "Open-Orca/SlimOrca", "revision": os.environ["ABPRUNE_DATASET_REVISION"],
701
+ "samples": len(records), "sequence_length": 512, "seed": 0,
702
+ "format": "first user-assistant turn; model chat template; right padding masked",
703
+ "input_ids_sha256": checksum.hexdigest()}
704
+ else:
705
+ geometry_batches, metadata = mka.sample_slimpajama(
706
+ tokenizer, samples=opt.mka_samples, sequence_length=512, seed=0)
707
+ if opt.mka_data:
708
+ opt.mka_data.parent.mkdir(parents=True, exist_ok=True)
709
+ torch.save(geometry_batches, opt.mka_data)
710
+ opt.mka_data.with_suffix(".json").write_text(json.dumps(metadata, indent=2) + "\n")
711
+ config = mka.GeometryConfig()
712
+ print(f"[fit-ablation] MKA geometry: {len(layers)} layers", flush=True)
713
+ features = mka.collect_features(model, geometry_batches)
714
+ manifold = [mka.diffusion_embedding(x, config) for x in features]
715
+ del features
716
+ matrix, entropies = mka.npib_matrix([x[0] for x in manifold], config)
717
+ index = mka.select_pair(matrix)
718
+ state["lambda"] = mka.upstream_lambda(matrix, index, index + 1, config.beta)
719
+ extra = {"npib_matrix": matrix.tolist(), "entropies": entropies,
720
+ "pair_npib": float(matrix[index, index+1]),
721
+ "source_lineage": [state["lineage"][index][:], state["lineage"][index+1][:]]}
722
+ if opt.fit_mka_mlp:
723
+ extra.update({"geometry_samples": sum(b["input_ids"].shape[0] for b in geometry_batches),
724
+ "geometry_sequence_length": 512,
725
+ "geometry_input_ids_sha256": opt.selection_hash,
726
+ "selection_policy": "native_dynamic_adjacent_NPIB",
727
+ "score_data": "saved_native_MKA_geometry_not_CoMe_calibration"})
728
+ else:
729
+ index, extra = opt.fixed_anchor, {}
730
+ assert len(layers) == len(state["active"])
731
+ record = {"cycle": len(state["records"]) + 1, "pair_index": index,
732
+ "initializer": opt.initializer,
733
+ "lambda_left": None if opt.initializer == "come" else state["lambda"],
734
+ "recipient_original_layer": state["active"][index], "recipient_side": "left",
735
+ "removed_original_layer": state["active"][index+1], **extra}
736
+ state["records"].append(record)
737
+ record["removed_original_layers"] = state["active"][index+1:index+1+opt.one_shot]
738
+ for _ in range(opt.one_shot):
739
+ state["active"].pop(index+1)
740
+ state["lineage"][index] += state["lineage"].pop(index+1)
741
+ record["active_original_layers"] = state["active"][:]
742
+ (opt.audit_root / "selection.json").write_text(json.dumps(state["records"], indent=2) + "\n")
743
+ print("[fit-ablation] selection " + json.dumps({k:v for k,v in record.items() if k != "npib_matrix"}), flush=True)
744
+ return index, None, {"method": opt.initializer, "fisher_computed": False}
745
+
746
+ base.resolve_layer_idx = select
747
+ original_fit = base.distill_reparam_merge
748
+
749
+ def fit(**kwargs):
750
+ if opt.fixed_span_merge_only:
751
+ from fusegpt.fixed_span_merge_init import frozen_hashes
752
+ anchor_layer = kwargs["student_layers"][kwargs["layer_idx"]]
753
+ frozen_before = frozen_hashes(anchor_layer)
754
+ if opt.one_shot > 1:
755
+ assert len(kwargs["teacher_layers"]) == 32
756
+ assert len(kwargs["student_layers"]) == 32
757
+ assert kwargs["layer_idx"] == 21 and kwargs["absorb_count"] == 8
758
+ print("ONE_SHOT_FIXED_DENSE_TEACHER_BOUNDARY=29 STUDENT_BOUNDARY=21 DROP=22:30", flush=True)
759
+ if opt.record_fit_runtime:
760
+ forward_shapes = {}
761
+ hooks = []
762
+ def trace_forward(label):
763
+ def capture(module, positional, named):
764
+ ids = named.get("input_ids")
765
+ if ids is None and positional:
766
+ ids = positional[0]
767
+ if torch.is_tensor(ids):
768
+ key = label + ":" + "x".join(str(v) for v in ids.shape)
769
+ forward_shapes[key] = forward_shapes.get(key, 0) + 1
770
+ return capture
771
+ for label in ("student", "teacher"):
772
+ hooks.append(kwargs[label + "_model"].register_forward_pre_hook(
773
+ trace_forward(label), with_kwargs=True))
774
+ torch.cuda.synchronize()
775
+ torch.cuda.reset_peak_memory_stats()
776
+ fit_started = time.perf_counter()
777
+ try:
778
+ merged, gates, stats = original_fit(**kwargs)
779
+ finally:
780
+ if opt.record_fit_runtime:
781
+ for hook in hooks:
782
+ hook.remove()
783
+ if opt.record_fit_runtime:
784
+ torch.cuda.synchronize()
785
+ elapsed = time.perf_counter() - fit_started
786
+ loader = kwargs["dataloader"]
787
+ tokens = sum(int(item[1].sum()) for item in loader.dataset)
788
+ stats["runtime"] = {
789
+ "seconds": elapsed, "dataset_tokens": tokens,
790
+ "tokens_per_second": tokens * float(kwargs["args"].distill_epochs) / elapsed,
791
+ "batch_size": int(kwargs["args"].distill_batch_size),
792
+ "batches_per_epoch": len(loader),
793
+ "grad_accumulation": int(kwargs["args"].distill_grad_accum_steps),
794
+ "peak_allocated_bytes": torch.cuda.max_memory_allocated(),
795
+ "peak_reserved_bytes": torch.cuda.max_memory_reserved(),
796
+ "gpu_total_bytes": torch.cuda.get_device_properties(0).total_memory,
797
+ "actual_forward_shapes": forward_shapes,
798
+ }
799
+ if opt.fit_come_attention:
800
+ layer = kwargs["student_layers"][kwargs["layer_idx"]]
801
+ expected = state["initialization_audit"]["frozen_norm_expected_sha256"]
802
+ measured = {n: hashlib.sha256(layer.get_parameter(n).detach().cpu().contiguous()
803
+ .view(torch.uint8).numpy().tobytes()).hexdigest() for n in expected}
804
+ assert measured == expected, "CoMe-initialized norms changed during attention+MLP FiT"
805
+ state["initialization_audit"]["frozen_norm_after_sha256"] = measured
806
+ state["initialization_audit"]["frozen_norms_unchanged"] = True
807
+ if opt.fit_mka_mlp:
808
+ layer = kwargs["student_layers"][kwargs["layer_idx"]]
809
+ expected = state["initialization_audit"]["frozen_attention_norm_expected_sha256"]
810
+ measured = {n: hashlib.sha256(layer.get_parameter(n).detach().cpu().contiguous()
811
+ .view(torch.uint8).numpy().tobytes()).hexdigest() for n in expected}
812
+ assert measured == expected, "Native MKA merged attention/anchor norms changed during MLP-only FiT"
813
+ state["initialization_audit"]["frozen_attention_norm_after_sha256"] = measured
814
+ state["initialization_audit"]["frozen_attention_norm_unchanged"] = True
815
+ if opt.fixed_span_merge_only:
816
+ frozen_after = frozen_hashes(anchor_layer)
817
+ assert frozen_after == frozen_before, "Attention/norm changed during MLP-only FiT"
818
+ audit = state["initialization_audit"]["merge_rule_audit"]
819
+ assert audit["transported_source_mlp_sha256"] == state["transport_operands"]["after"]
820
+ state["initialization_audit"].update({"frozen_attention_norm_unchanged": True,
821
+ "transport_operands": state["transport_operands"]})
822
+ stats["ablation"] = {**state["initialization_audit"],
823
+ "source_feature_transport": bool(kwargs["args"].source_feature_transport),
824
+ "initializer": opt.initializer,
825
+ "removed_count_per_cycle": opt.one_shot,
826
+ "teacher_boundary_current_layer": kwargs["layer_idx"] + opt.one_shot,
827
+ "teacher_boundary_original_layer": state["records"][-1]["removed_original_layers"][-1]}
828
+ (opt.audit_root / f"cycle_{kwargs['progressive_cycle']:02d}_fit.json").write_text(
829
+ json.dumps(stats, indent=2) + "\n")
830
+ return merged, gates, stats
831
+
832
+ base.distill_reparam_merge = fit
833
+ sys.argv = [sys.argv[0], *forwarded]
834
+ base.main()
835
+ # Correct legacy Fisher-specific labels and add reconstructible topology.
836
+ output = Path(forwarded[forwarded.index("--output_dir") + 1])
837
+ for record in state["records"]:
838
+ path = output / f"cycle_{record['cycle']}" / "cycle_metadata.json"
839
+ data = json.loads(path.read_text())
840
+ data.update({k: record[k] for k in ("recipient_original_layer", "removed_original_layer", "recipient_side", "active_original_layers")})
841
+ data["fisher_computed"] = False
842
+ data["merge_initializer"] = opt.initializer
843
+ data["fixed_span_merge_only"] = opt.fixed_span_merge_only
844
+ data["removed_original_layers"] = record["removed_original_layers"]
845
+ data["same_anchor_contextual_fisher"] = {"computed": False}
846
+ if data.get("source_feature_transport"):
847
+ data["source_feature_transport"]["fisher_order"] = "source transport; non-Fisher initialization; additive-U FiT"
848
+ reparam = data.get("distill", {}).get("reparam_stats")
849
+ if reparam:
850
+ reparam["lambda_init"] = opt.initializer
851
+ path.write_text(json.dumps(data, indent=2) + "\n")
852
+ if opt.one_shot > 1:
853
+ import subprocess
854
+ subprocess.run([sys.executable, str(Path(__file__).with_name("package_qwen3_1_7b_one_shot_compact.py")),
855
+ "--run-root", str(output), "--output-root", str(opt.audit_root.parent / "compact"),
856
+ "--model", opt.model_id, "--base-revision", opt.base_revision,
857
+ "--run-id", "llama31_base_wa_oneshot_8block", "--anchor", str(opt.fixed_anchor),
858
+ "--removed-count", str(opt.one_shot)], check=True)
859
+ else:
860
+ from fusegpt.abprune_compact import package
861
+ package(argparse.Namespace(run_root=output, output_root=opt.audit_root.parent / "compact",
862
+ model=opt.model_id, base_revision=opt.base_revision,
863
+ run_id=f"{opt.model_id.split('/')[-1].lower().replace('-', '_')}_fit_{opt.initializer}_{'fixed_span_transport_mlp_' if opt.fixed_span_merge_only else ('full_block_' if opt.fit_full_block else ('attn_mlp_' if opt.fit_attention or opt.fit_come_attention else ('mlp_' if opt.fit_mka_mlp else '')))}{len(state['records'])}block", cycles=len(state["records"]),
864
+ start_cycle=1, layer_order=" ".join(str(r["pair_index"]) for r in state["records"])))
865
+ (opt.audit_root.parent / "TRAIN_COMPLETE").touch()
866
+
867
+
868
+ if __name__ == "__main__":
869
+ main()
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/run_llama31_come_fit_arm.sh ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ project="$1"; external="$2"; root="$3"; model="$4"; family="$5"; gpu="$6"; mode="${7:-full}"
4
+ scope="${8:-full}"; subset=all; fit=(--fit-full-block)
5
+ if [[ "$scope" == mlp ]]; then subset=mlp; fit=(--fit-come-mlp); elif [[ "$scope" != full ]]; then exit 2; fi
6
+ export CUDA_VISIBLE_DEVICES="$gpu" HF_HOME=/workspace/.hf_home HF_TOKEN_PATH=/root/.cache/huggingface/token
7
+ export HF_DATASETS_CACHE=/workspace/.hf_datasets36 HF_DATASETS_TRUST_REMOTE_CODE=1
8
+ export HF_HUB_OFFLINE=1 HF_DATASETS_OFFLINE=1
9
+ export PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false OMP_NUM_THREADS=4
10
+ export PYTHONPATH="$external/src:$project/src${PYTHONPATH:+:$PYTHONPATH}"
11
+ mkdir -p "$root/logs" "$root/audit" "$root/run"
12
+ cycles=8; records=500; calib=64; tokens=524288
13
+ if [[ "$mode" == smoke ]]; then cycles=2; records=20; calib=4; tokens=20480; fi
14
+ if [[ "$family" == instruct ]]; then
15
+ export ABPRUNE_DATASET_REVISION=ce9ed009ef3292bac33d3520afaf5ec804066120
16
+ wrapper=(--model-id meta-llama/Llama-3.1-8B-Instruct --base-revision 0e9e39f249a16976918f6564b8830bc894c89659 --instruction-data)
17
+ data=(--target_tokens 0 --distill_calib_samples 0 --instruction_dataset Open-Orca/SlimOrca
18
+ --instruction_config none --instruction_split train --distill_inst_samples "$records")
19
+ elif [[ "$family" == base ]]; then
20
+ export ABPRUNE_DATASET_REVISION=b5f90f419b7489cdba26fdbc8c022fcb5562f968
21
+ wrapper=(--model-id meta-llama/Llama-3.1-8B --base-revision d04e592bb4f6aa9cfee91e2e20afa771667e1d4b)
22
+ data=(--dataset slimpajama --dataset_config none --target_tokens "$tokens")
23
+ else exit 2; fi
24
+ python "$project/scripts/run_llama31_base_fit_ablation.py" \
25
+ --external-root "$external" --initializer come "${fit[@]}" --audit-root "$root/audit" \
26
+ --come-minimum-retention .97 --come-power 1 "${wrapper[@]}" --model "$model" --output_dir "$root/run" \
27
+ --layer 21 --num_progressive "$cycles" "${data[@]}" --num_samples "$calib" \
28
+ --seq_len 1024 --batch_size 2 --distill_seq_len 1024 --distill_batch_size 1 \
29
+ --distill_epochs 1 --distill_lr 1e-4 --distill_weight_decay 0 --distill_max_grad_norm 1 \
30
+ --distill_grad_accum_steps 1 --distill_kl_weight .02 --distill_kl_temp 4 \
31
+ --distill_hidden_mse_weight 1 --distill_mlp_mse_weight 1 --distill_attn_mse_weight 0 \
32
+ --reparam_eta 0 --reparam_gamma 0 --reparam_param_subset "$subset" \
33
+ --reparam_fisher_init_subset same --reparam_train_subset "$subset" --reparam_rho_objective none \
34
+ --reparam_additive_u --redistrib_teacher_source previous_cycle --fisher_mode param --eps 0 \
35
+ --no_head_permute_merge --no_head_permute_select --dtype bfloat16 --eval_dtype bfloat16 \
36
+ --lora_epochs 0 --skip_eval --skip_final_model_save --distill_log_steps 20 --seed 42 \
37
+ >> "$root/logs/train.log" 2>&1
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/run_mka_batch_arm.sh ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ project="$1"; external="$2"; root="$3"; model="$4"; selection="$5"; batch="$6"; gpu="$7"
4
+ cycles="${8:-8}"; tokens="${9:-524288}"; selection_hash="${10:?frozen MKA input hash required}"
5
+ export CUDA_VISIBLE_DEVICES="$gpu" HF_HOME=/workspace/.hf_home HF_TOKEN_PATH=/root/.cache/huggingface/token
6
+ export HF_DATASETS_CACHE=/workspace/.hf_datasets36 HF_DATASETS_TRUST_REMOTE_CODE=1
7
+ export HF_HUB_OFFLINE=1 HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1
8
+ export PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false OMP_NUM_THREADS=4
9
+ export PYTHONPATH="$external/src:$project/src${PYTHONPATH:+:$PYTHONPATH}"
10
+ export ABPRUNE_DATASET_REVISION=b5f90f419b7489cdba26fdbc8c022fcb5562f968
11
+ [[ -s "$selection" ]] || { echo 'Frozen historical MKA inputs are required; no resampling'; exit 1; }
12
+ mkdir -p "$root/logs" "$root/audit" "$root/run"
13
+ python "$project/scripts/run_llama31_base_fit_ablation.py" \
14
+ --external-root "$external" --initializer mka --fit-mka-mlp --audit-root "$root/audit" \
15
+ --mka-data "$selection" --selection-hash "$selection_hash" --mka-samples 100 --record-fit-runtime \
16
+ --model-id meta-llama/Llama-3.1-8B --base-revision d04e592bb4f6aa9cfee91e2e20afa771667e1d4b \
17
+ --model "$model" --output_dir "$root/run" --layer 21 --num_progressive "$cycles" \
18
+ --dataset slimpajama --dataset_config none --target_tokens "$tokens" \
19
+ --num_samples 64 --seq_len 1024 --batch_size 2 \
20
+ --distill_seq_len 1024 --distill_batch_size "$batch" --distill_epochs 1 --distill_lr 1e-4 \
21
+ --distill_weight_decay 0 --distill_max_grad_norm 1 --distill_grad_accum_steps 1 \
22
+ --distill_kl_weight .02 --distill_kl_temp 4 --distill_hidden_mse_weight 1 \
23
+ --distill_mlp_mse_weight 1 --distill_attn_mse_weight 0 --reparam_eta 0 --reparam_gamma 0 \
24
+ --reparam_param_subset mlp --reparam_fisher_init_subset same --reparam_train_subset mlp \
25
+ --reparam_rho_objective none --reparam_additive_u --redistrib_teacher_source previous_cycle \
26
+ --fisher_mode param --eps 0 --no_head_permute_merge --no_head_permute_select \
27
+ --dtype bfloat16 --eval_dtype bfloat16 --lora_epochs 0 --skip_eval --skip_final_model_save \
28
+ --distill_log_steps 10 --seed 42 >> "$root/logs/train.log" 2>&1
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/source_feature_transport.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage-local source MLP transport into the anchor MLP input coordinate.
2
+
3
+ The fitted map ``T`` satisfies ``X_anchor @ T ~= X_source``. For linear
4
+ input projections stored as ``W`` (PyTorch convention ``y = x @ W.T``), the
5
+ equivalent source projection in the anchor coordinate is ``W @ T.T``.
6
+
7
+ This module intentionally transports only ``gate_proj`` and ``up_proj``.
8
+ ``down_proj`` consumes the SwiGLU intermediate representation rather than the
9
+ decoder hidden coordinate and is therefore left unchanged.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import math
15
+ from typing import Dict, List, Tuple
16
+
17
+ import torch
18
+
19
+
20
+ class _StopAfterSource(RuntimeError):
21
+ """Abort a model forward once both MLP inputs have been captured."""
22
+
23
+
24
+ def _capture_mlp_inputs(model, layer_a, layer_b, input_ids, attention_mask=None):
25
+ captured: Dict[str, torch.Tensor] = {}
26
+
27
+ def capture_anchor(_module, inputs):
28
+ captured["anchor"] = inputs[0].detach()
29
+
30
+ def capture_source(_module, inputs):
31
+ captured["source"] = inputs[0].detach()
32
+ raise _StopAfterSource()
33
+
34
+ handles = (
35
+ layer_a.mlp.register_forward_pre_hook(capture_anchor),
36
+ layer_b.mlp.register_forward_pre_hook(capture_source),
37
+ )
38
+ try:
39
+ kwargs = {"input_ids": input_ids, "use_cache": False}
40
+ if attention_mask is not None:
41
+ kwargs["attention_mask"] = attention_mask
42
+ try:
43
+ model(**kwargs)
44
+ except _StopAfterSource:
45
+ pass
46
+ finally:
47
+ for handle in handles:
48
+ handle.remove()
49
+
50
+ if set(captured) != {"anchor", "source"}:
51
+ raise RuntimeError(
52
+ "Failed to capture anchor/source MLP inputs; "
53
+ f"captured={sorted(captured)}"
54
+ )
55
+ return captured["anchor"], captured["source"]
56
+
57
+
58
+ def solve_transport_from_statistics(
59
+ gram_sum: torch.Tensor,
60
+ cross_sum: torch.Tensor,
61
+ source_sq_sum: float,
62
+ token_count: int,
63
+ ridge_relative: float,
64
+ ) -> Tuple[torch.Tensor, Dict[str, float]]:
65
+ """Solve ridge OLS and return its calibration-set reconstruction metrics."""
66
+ if token_count <= 0:
67
+ raise ValueError("token_count must be positive")
68
+ if ridge_relative < 0.0:
69
+ raise ValueError("ridge_relative must be non-negative")
70
+
71
+ gram = gram_sum / float(token_count)
72
+ cross = cross_sum / float(token_count)
73
+ target_sq = float(source_sq_sum) / float(token_count)
74
+ mean_diagonal = float(torch.diagonal(gram).mean().item())
75
+ ridge = float(ridge_relative) * mean_diagonal
76
+ regularized = gram.clone()
77
+ regularized.diagonal().add_(ridge)
78
+ chol, info = torch.linalg.cholesky_ex(regularized)
79
+ if int(info.max().item()) != 0:
80
+ raise RuntimeError(
81
+ "Source-feature transport Cholesky failed: "
82
+ f"info={int(info.max().item())}"
83
+ )
84
+ solution = torch.cholesky_solve(cross, chol)
85
+
86
+ # Since (G + ridge I) T = C, tr(T' G T) can be computed without another
87
+ # O(d^3) multiply as <T,C> - ridge ||T||^2.
88
+ dot = float((solution.double() * cross.double()).sum().item())
89
+ solution_sq = float(solution.double().square().sum().item())
90
+ predicted_sq = max(0.0, dot - ridge * solution_sq)
91
+ error_sq = max(0.0, target_sq + predicted_sq - 2.0 * dot)
92
+ denominator = math.sqrt(max(predicted_sq, 0.0) * max(target_sq, 0.0))
93
+ identity = torch.eye(
94
+ solution.shape[0], dtype=solution.dtype, device=solution.device
95
+ )
96
+ relative_identity_distance = float(
97
+ torch.linalg.vector_norm((solution - identity).float()).item()
98
+ / math.sqrt(float(solution.shape[0]))
99
+ )
100
+ del identity
101
+
102
+ stats = {
103
+ "tokens": int(token_count),
104
+ "ridge_relative": float(ridge_relative),
105
+ "ridge_absolute": ridge,
106
+ "gram_mean_diagonal": mean_diagonal,
107
+ "calibration_nmse": error_sq / target_sq if target_sq > 0.0 else float("nan"),
108
+ "calibration_cosine": dot / denominator if denominator > 0.0 else float("nan"),
109
+ "calibration_norm_ratio": (
110
+ math.sqrt(predicted_sq / target_sq) if target_sq > 0.0 else float("nan")
111
+ ),
112
+ "transport_relative_identity_distance": relative_identity_distance,
113
+ }
114
+ return solution, stats
115
+
116
+
117
+ def _apply_transport_to_source_mlp(source_mlp, solution, row_chunk: int) -> None:
118
+ if row_chunk <= 0:
119
+ raise ValueError("row_chunk must be positive")
120
+ with torch.no_grad():
121
+ for projection_name in ("gate_proj", "up_proj"):
122
+ projection = getattr(source_mlp, projection_name)
123
+ original = projection.weight.detach().clone()
124
+ if original.ndim != 2 or original.shape[1] != solution.shape[0]:
125
+ raise ValueError(
126
+ f"Unexpected {projection_name} shape {tuple(original.shape)} "
127
+ f"for transport {tuple(solution.shape)}"
128
+ )
129
+ for start in range(0, original.shape[0], row_chunk):
130
+ end = min(start + row_chunk, original.shape[0])
131
+ transported = original[start:end].float() @ solution.transpose(0, 1)
132
+ projection.weight[start:end].copy_(transported.to(projection.weight.dtype))
133
+ del original
134
+
135
+
136
+ def fit_and_apply_source_feature_transport(
137
+ model,
138
+ layer_a,
139
+ layer_b,
140
+ dataloader,
141
+ device: str,
142
+ ridge_relative: float = 1e-3,
143
+ max_batches: int = 0,
144
+ row_chunk: int = 128,
145
+ ) -> Dict[str, object]:
146
+ """Fit ``X_a T ~= X_b`` and rewrite source MLP input projections."""
147
+ if dataloader is None:
148
+ raise ValueError("Source-feature transport requires a dataloader")
149
+
150
+ previous_training = model.training
151
+ model.eval()
152
+ gram_sum = None
153
+ cross_sum = None
154
+ source_sq_sum = 0.0
155
+ token_count = 0
156
+ batches = 0
157
+ try:
158
+ with torch.no_grad():
159
+ for batch in dataloader:
160
+ if max_batches > 0 and batches >= max_batches:
161
+ break
162
+ input_ids = batch[0].to(device, non_blocking=True)
163
+ attention_mask = (
164
+ batch[1].to(device, non_blocking=True) if len(batch) > 1 else None
165
+ )
166
+ x_a, x_b = _capture_mlp_inputs(
167
+ model, layer_a, layer_b, input_ids, attention_mask
168
+ )
169
+ x_a = x_a.reshape(-1, x_a.shape[-1]).float()
170
+ x_b = x_b.reshape(-1, x_b.shape[-1]).float()
171
+ if attention_mask is not None:
172
+ valid = attention_mask.reshape(-1).to(dtype=torch.bool)
173
+ if valid.numel() != x_a.shape[0]:
174
+ raise RuntimeError(
175
+ "Attention mask does not align with captured MLP inputs"
176
+ )
177
+ x_a = x_a[valid]
178
+ x_b = x_b[valid]
179
+ if gram_sum is None:
180
+ width = x_a.shape[-1]
181
+ gram_sum = torch.zeros(
182
+ (width, width), dtype=torch.float32, device=x_a.device
183
+ )
184
+ cross_sum = torch.zeros_like(gram_sum)
185
+ gram_sum.addmm_(x_a.transpose(0, 1), x_a)
186
+ cross_sum.addmm_(x_a.transpose(0, 1), x_b)
187
+ source_sq_sum += float(x_b.double().square().sum().item())
188
+ token_count += int(x_a.shape[0])
189
+ batches += 1
190
+ finally:
191
+ model.train(previous_training)
192
+
193
+ if gram_sum is None or cross_sum is None or batches == 0:
194
+ raise RuntimeError("No batches were processed for source-feature transport")
195
+ solution, stats = solve_transport_from_statistics(
196
+ gram_sum,
197
+ cross_sum,
198
+ source_sq_sum,
199
+ token_count,
200
+ ridge_relative,
201
+ )
202
+ _apply_transport_to_source_mlp(layer_b.mlp, solution, row_chunk=row_chunk)
203
+ stats.update(
204
+ {
205
+ "enabled": True,
206
+ "batches": int(batches),
207
+ "coordinate_fit": "X_anchor @ T ~= X_source",
208
+ "weight_rewrite": [
209
+ "mlp.gate_proj.weight <- W_source @ T.T",
210
+ "mlp.up_proj.weight <- W_source @ T.T",
211
+ ],
212
+ "down_proj_transported": False,
213
+ }
214
+ )
215
+ del solution, gram_sum, cross_sum
216
+ if torch.cuda.is_available():
217
+ torch.cuda.empty_cache()
218
+ return stats
219
+
220
+
221
+ def _drop_container_layer(container, index: int):
222
+ if isinstance(container, torch.nn.ModuleList):
223
+ return torch.nn.ModuleList(
224
+ [layer for layer_index, layer in enumerate(container) if layer_index != index]
225
+ )
226
+ if isinstance(container, list):
227
+ return [layer for layer_index, layer in enumerate(container) if layer_index != index]
228
+ raise TypeError(f"Unsupported layer container: {type(container)}")
229
+
230
+
231
+ def compute_same_anchor_contextual_fisher(
232
+ model,
233
+ parent,
234
+ layer_attr: str,
235
+ container,
236
+ layer_idx: int,
237
+ layer_a,
238
+ layer_b,
239
+ dataloader,
240
+ device: str,
241
+ fisher_mode: str,
242
+ ) -> Tuple[List[Dict[str, object]], int, List[Dict[str, int]], Dict[str, float]]:
243
+ """Measure both candidate MLPs in the same post-pruning anchor topology.
244
+
245
+ The source MLP must already be feature-transported. Two virtual pruned
246
+ models are evaluated on every calibration batch: one uses the native
247
+ anchor MLP and one replaces it with the transported source MLP. The source
248
+ decoder block is absent in both arms, so the gradients describe the actual
249
+ deployment coordinate/topology rather than the source's old depth.
250
+ """
251
+ if fisher_mode != "param":
252
+ raise ValueError("Same-anchor contextual Fisher currently requires fisher_mode=param")
253
+
254
+ anchor_mlp = layer_a.mlp
255
+ source_mlp = layer_b.mlp
256
+ previous_container = container
257
+ pruned_container = _drop_container_layer(container, layer_idx + 1)
258
+ previous_training = model.training
259
+
260
+ names_a = dict(layer_a.named_parameters())
261
+ names_b = dict(layer_b.named_parameters())
262
+ fisher_a: Dict[str, object] = {}
263
+ fisher_b: Dict[str, object] = {}
264
+ numels_a: Dict[str, int] = {}
265
+ numels_b: Dict[str, int] = {}
266
+ for name, parameter in names_a.items():
267
+ if name.startswith("mlp."):
268
+ fisher_a[name] = torch.zeros_like(parameter, dtype=torch.float32, device="cpu")
269
+ else:
270
+ fisher_a[name] = 0.0
271
+ numels_a[name] = int(parameter.numel())
272
+ for name, parameter in names_b.items():
273
+ if name.startswith("mlp."):
274
+ fisher_b[name] = torch.zeros_like(parameter, dtype=torch.float32, device="cpu")
275
+ else:
276
+ fisher_b[name] = 0.0
277
+ numels_b[name] = int(parameter.numel())
278
+
279
+ for parameter in model.parameters():
280
+ parameter.requires_grad_(False)
281
+
282
+ anchor_loss_sum = 0.0
283
+ source_loss_sum = 0.0
284
+ num_batches = 0
285
+
286
+ def run_arm(candidate_mlp, fisher_target, input_ids, attention_mask):
287
+ layer_a.mlp = candidate_mlp
288
+ for parameter in candidate_mlp.parameters():
289
+ parameter.requires_grad_(True)
290
+ model.zero_grad(set_to_none=True)
291
+ labels = input_ids
292
+ if attention_mask is not None:
293
+ labels = input_ids.masked_fill(attention_mask == 0, -100)
294
+ kwargs = {"input_ids": input_ids, "labels": labels, "use_cache": False}
295
+ if attention_mask is not None:
296
+ kwargs["attention_mask"] = attention_mask
297
+ output = model(**kwargs)
298
+ output.loss.backward()
299
+ for local_name, parameter in candidate_mlp.named_parameters():
300
+ full_name = f"mlp.{local_name}"
301
+ if parameter.grad is not None:
302
+ fisher_target[full_name] += parameter.grad.detach().float().square().cpu()
303
+ loss = float(output.loss.detach().item())
304
+ model.zero_grad(set_to_none=True)
305
+ for parameter in candidate_mlp.parameters():
306
+ parameter.requires_grad_(False)
307
+ return loss
308
+
309
+ try:
310
+ setattr(parent, layer_attr, pruned_container)
311
+ model.eval()
312
+ for batch in dataloader:
313
+ input_ids = batch[0].to(device, non_blocking=True)
314
+ attention_mask = (
315
+ batch[1].to(device, non_blocking=True) if len(batch) > 1 else None
316
+ )
317
+ anchor_loss_sum += run_arm(
318
+ anchor_mlp, fisher_a, input_ids, attention_mask
319
+ )
320
+ source_loss_sum += run_arm(
321
+ source_mlp, fisher_b, input_ids, attention_mask
322
+ )
323
+ num_batches += 1
324
+ finally:
325
+ layer_a.mlp = anchor_mlp
326
+ setattr(parent, layer_attr, previous_container)
327
+ model.train(previous_training)
328
+
329
+ if num_batches == 0:
330
+ raise RuntimeError("No batches were processed for same-anchor contextual Fisher")
331
+ stats = {
332
+ "num_batches": int(num_batches),
333
+ "anchor_candidate_mean_nll": anchor_loss_sum / float(num_batches),
334
+ "transported_source_candidate_mean_nll": source_loss_sum / float(num_batches),
335
+ "source_minus_anchor_mean_nll": (
336
+ source_loss_sum - anchor_loss_sum
337
+ ) / float(num_batches),
338
+ "topology": "source block dropped; candidate MLP evaluated at anchor slot",
339
+ "shared_input_coordinate": True,
340
+ "scope": "mlp gate/up/down diagonal empirical Fisher",
341
+ }
342
+ return [fisher_a, fisher_b], num_batches, [numels_a, numels_b], stats
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/validate_mka_first_selection.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare the pre-FiT MKA selection against its immutable historical reference."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+
6
+
7
+ def main():
8
+ p = argparse.ArgumentParser(description=__doc__)
9
+ p.add_argument("--reference", type=Path, required=True)
10
+ p.add_argument("--selection", type=Path, required=True)
11
+ p.add_argument("--output", type=Path, required=True)
12
+ p.add_argument("--historical-reference", type=Path,
13
+ help="Preserve cross-environment historical differences separately from the native implementation gate")
14
+ p.add_argument("--atol", type=float, default=1e-6)
15
+ p.add_argument("--rtol", type=float, default=1e-5)
16
+ a = p.parse_args()
17
+ source = json.loads(a.reference.read_text())
18
+ ref = source["merges"][0] if "merges" in source else source
19
+ observed = json.loads(a.selection.read_text())[0]
20
+ left, right = ref["npib_matrix"], observed["npib_matrix"]
21
+ assert len(left) == len(right) == 32
22
+ assert all(len(x) == len(y) == 32 for x, y in zip(left, right))
23
+ differences = [abs(x - y) for xs, ys in zip(left, right) for x, y in zip(xs, ys)]
24
+ close = all(abs(x - y) <= a.atol + a.rtol * abs(x)
25
+ for xs, ys in zip(left, right) for x, y in zip(xs, ys))
26
+ ratio_close = abs(ref["lambda_left"] - observed["lambda_left"]) <= a.atol
27
+ reference_index = ref.get("left_index", ref.get("pair_index"))
28
+ source_lineage = ref.get("source_layers", [[reference_index], [reference_index + 1]])
29
+ passed = (reference_index == observed["pair_index"] and close and ratio_close
30
+ and source_lineage == observed["source_lineage"])
31
+ result = {"passed": passed, "validation_scope": "first pre-FiT selection only; no eight-stage replay claimed",
32
+ "atol": a.atol, "rtol": a.rtol, "matrix_allclose": close,
33
+ "matrix_max_absolute_difference": max(differences),
34
+ "reference_path": str(a.reference),
35
+ "reference_implementation": source.get("implementation", "historical native MKA"),
36
+ "expected_pair_index": reference_index, "observed_pair_index": observed["pair_index"],
37
+ "expected_lambda": ref["lambda_left"], "observed_lambda": observed["lambda_left"],
38
+ "expected_pair_npib": ref["pair_npib"], "observed_pair_npib": observed["pair_npib"]}
39
+ if a.historical_reference:
40
+ old = json.loads(a.historical_reference.read_text())["merges"][0]
41
+ result["historical_reference_comparison"] = {
42
+ "path": str(a.historical_reference),
43
+ "pair_agrees": old["left_index"] == observed["pair_index"],
44
+ "expected_lambda": old["lambda_left"], "observed_lambda": observed["lambda_left"],
45
+ "matrix_max_absolute_difference": max(abs(x-y) for xs, ys in zip(old["npib_matrix"], right)
46
+ for x, y in zip(xs, ys)),
47
+ "exact_historical_reproduction_claimed": False,
48
+ "qualification": "Same frozen tokens and native algorithm; historical execution environment differs. Current runtime native implementation is validated independently."}
49
+ a.output.parent.mkdir(parents=True, exist_ok=True)
50
+ a.output.write_text(json.dumps(result, indent=2) + "\n")
51
+ print(json.dumps(result, indent=2))
52
+ if not passed:
53
+ raise SystemExit("Native reference differs; inspect runtime/input fidelity before production")
54
+
55
+
56
+ if __name__ == "__main__":
57
+ main()
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/code/validate_mka_runtime_geometry.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Split native MKA activation collection from CPU geometry for runtime diagnosis.
2
+
3
+ Pooled feature caches are private diagnostic artifacts, never public payloads.
4
+ No model weights or calibration tokens are written by this script.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ from dataclasses import asdict
10
+ import hashlib
11
+ import importlib.metadata
12
+ import json
13
+ from pathlib import Path
14
+ import platform
15
+ import sys
16
+ import time
17
+
18
+
19
+ def versions():
20
+ result = {"python": platform.python_version()}
21
+ for name in ("torch", "transformers", "numpy", "scipy", "scikit-learn"):
22
+ try:
23
+ result[name] = importlib.metadata.version(name)
24
+ except importlib.metadata.PackageNotFoundError:
25
+ result[name] = None
26
+ return result
27
+
28
+
29
+ def file_hash(path):
30
+ digest = hashlib.sha256()
31
+ with path.open("rb") as stream:
32
+ for chunk in iter(lambda: stream.read(8 << 20), b""):
33
+ digest.update(chunk)
34
+ return digest.hexdigest()
35
+
36
+
37
+ def first_reference(path):
38
+ item = json.loads(path.read_text())
39
+ if isinstance(item, list):
40
+ return item[0]
41
+ if "merges" in item:
42
+ return item["merges"][0]
43
+ return item
44
+
45
+
46
+ def main():
47
+ p = argparse.ArgumentParser(description=__doc__)
48
+ p.add_argument("--model", help="Local dense model directory; not needed with --features-input")
49
+ p.add_argument("--selection", type=Path, help="Frozen native MKA100x512 list of input/mask dictionaries")
50
+ p.add_argument("--output", type=Path, required=True)
51
+ p.add_argument("--features-output", type=Path)
52
+ p.add_argument("--features-input", type=Path)
53
+ p.add_argument("--features-only", action="store_true")
54
+ p.add_argument("--reference", type=Path)
55
+ p.add_argument("--implementation", choices=("native", "fit"), default="native",
56
+ help="Independent native implementation or the FiT selector helper")
57
+ p.add_argument("--device", default="cuda:0")
58
+ p.add_argument("--attn-implementation", default="sdpa", choices=("sdpa", "eager", "flash_attention_2"))
59
+ p.add_argument("--atol", type=float, default=1e-6)
60
+ p.add_argument("--rtol", type=float, default=1e-5)
61
+ a = p.parse_args()
62
+ if a.features_only and (not a.features_output or a.features_input):
63
+ p.error("--features-only requires --features-output and collects new model features")
64
+ if not a.features_input and (not a.model or not a.selection):
65
+ p.error("Collecting features requires both --model and --selection")
66
+
67
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
68
+ import numpy as np
69
+ import torch
70
+ if a.implementation == "native":
71
+ from fusegpt import mka
72
+ else:
73
+ from fusegpt import fit_ablation_mka as mka
74
+
75
+ started = time.monotonic()
76
+ config = mka.GeometryConfig()
77
+ result = {"runtime_versions": versions(), "geometry_config": asdict(config),
78
+ "implementation": a.implementation, "implementation_module": str(Path(mka.__file__).resolve()),
79
+ "implementation_source_sha256": file_hash(Path(mka.__file__)),
80
+ "private_feature_cache": True, "public_upload_allowed": False,
81
+ "validation_scope": "dense original model, first pre-FiT MKA geometry only"}
82
+ if a.features_input:
83
+ features = np.load(a.features_input, allow_pickle=False)
84
+ result["features_source"] = str(a.features_input)
85
+ result["features_sha256"] = file_hash(a.features_input)
86
+ sidecar = a.features_input.with_suffix(a.features_input.suffix + ".json")
87
+ if sidecar.is_file():
88
+ result["feature_collection_provenance"] = json.loads(sidecar.read_text())
89
+ else:
90
+ from transformers import AutoModelForCausalLM
91
+
92
+ batches = torch.load(a.selection, weights_only=True, map_location="cpu")
93
+ if len(batches) != 100:
94
+ raise ValueError("Expected the frozen native100x512 MKA geometry")
95
+ ids_hash, masks_hash = hashlib.sha256(), hashlib.sha256()
96
+ for batch in batches:
97
+ ids, mask = batch["input_ids"], batch["attention_mask"]
98
+ if tuple(ids.shape) != (1, 512) or mask.shape != ids.shape:
99
+ raise ValueError("Native MKA input shape must be1x512")
100
+ if not bool(((mask == 0) | (mask == 1)).all()) or not bool(mask.any()):
101
+ raise ValueError("Invalid native attention mask")
102
+ ids_hash.update(ids.numpy().astype("<i8").tobytes())
103
+ masks_hash.update(mask.numpy().astype("<i8").tobytes())
104
+ torch.manual_seed(config.seed)
105
+ model = AutoModelForCausalLM.from_pretrained(
106
+ a.model, torch_dtype=torch.bfloat16, attn_implementation=a.attn_implementation,
107
+ local_files_only=True).to(a.device)
108
+ model.eval()
109
+ features = np.stack(mka.collect_features(model, batches, pooling=config.pooling))
110
+ result.update({"model": a.model, "selection": str(a.selection),
111
+ "selection_input_ids_sha256": ids_hash.hexdigest(),
112
+ "selection_attention_mask_sha256": masks_hash.hexdigest(),
113
+ "model_class": type(model).__name__, "model_dtype": str(next(model.parameters()).dtype),
114
+ "requested_attn_implementation": a.attn_implementation,
115
+ "actual_attn_implementation": getattr(model.config, "_attn_implementation", None),
116
+ "cuda_version": torch.version.cuda,
117
+ "allow_tf32_matmul": torch.backends.cuda.matmul.allow_tf32,
118
+ "allow_tf32_cudnn": torch.backends.cudnn.allow_tf32})
119
+ del model
120
+ if torch.cuda.is_available():
121
+ torch.cuda.empty_cache()
122
+ if features.ndim != 3 or tuple(features.shape[:2]) != (32, 100) or not np.isfinite(features).all():
123
+ raise ValueError("Expected finite pooled features shaped [32,100,hidden_size]")
124
+ result["features_shape"] = list(features.shape)
125
+ result["features_dtype"] = str(features.dtype)
126
+ result["features_bytes_sha256"] = hashlib.sha256(features.tobytes()).hexdigest()
127
+ result["feature_phase_seconds"] = time.monotonic() - started
128
+ if a.features_output:
129
+ a.features_output.parent.mkdir(parents=True, exist_ok=True)
130
+ if a.features_output.exists():
131
+ raise FileExistsError("Refusing to overwrite diagnostic features: " + str(a.features_output))
132
+ with a.features_output.open("wb") as stream:
133
+ np.save(stream, features, allow_pickle=False)
134
+ result["features_output"] = str(a.features_output)
135
+ result["features_sha256"] = file_hash(a.features_output)
136
+ a.features_output.with_suffix(a.features_output.suffix + ".json").write_text(
137
+ json.dumps(result, indent=2) + "\n")
138
+ if not a.features_only:
139
+ geo_started = time.monotonic()
140
+ manifolds = [mka.diffusion_embedding(x, config) for x in features]
141
+ matrix, entropies = mka.npib_matrix([x[0] for x in manifolds], config)
142
+ pair = mka.select_pair(matrix)
143
+ ratio = mka.upstream_lambda(matrix, pair, pair + 1, config.beta)
144
+ result.update({"pair_index": pair, "lambda_left": ratio,
145
+ "pair_npib": float(matrix[pair, pair + 1]), "npib_matrix": matrix.tolist(),
146
+ "entropies": entropies, "row_means": matrix.mean(1).tolist(),
147
+ "manifolds": [x[1] for x in manifolds],
148
+ "geometry_seconds": time.monotonic() - geo_started})
149
+ if a.reference:
150
+ ref = first_reference(a.reference)
151
+ expected = np.asarray(ref["npib_matrix"], dtype=np.float64)
152
+ if expected.shape != matrix.shape:
153
+ raise ValueError("Reference NPIB matrix shape differs")
154
+ ref_pair = ref.get("left_index", ref.get("pair_index"))
155
+ close = bool(np.allclose(matrix, expected, atol=a.atol, rtol=a.rtol))
156
+ ratio_close = bool(abs(ratio - ref["lambda_left"]) <= a.atol)
157
+ result["reference_comparison"] = {
158
+ "reference": str(a.reference), "matrix_allclose": close,
159
+ "matrix_max_absolute_difference": float(np.max(np.abs(matrix - expected))),
160
+ "expected_pair_index": ref_pair, "observed_pair_index": pair,
161
+ "expected_lambda": ref["lambda_left"], "observed_lambda": ratio,
162
+ "expected_pair_npib": ref.get("pair_npib"),
163
+ "observed_pair_npib": float(matrix[pair, pair + 1]),
164
+ "atol": a.atol, "rtol": a.rtol,
165
+ "passed": bool(close and ratio_close and pair == ref_pair)}
166
+ result["wall_seconds"] = time.monotonic() - started
167
+ a.output.parent.mkdir(parents=True, exist_ok=True)
168
+ a.output.write_text(json.dumps(result, indent=2) + "\n")
169
+ print(json.dumps({k: result[k] for k in ("runtime_versions", "features_shape", "pair_index", "lambda_left",
170
+ "pair_npib", "reference_comparison", "wall_seconds") if k in result}, indent=2))
171
+
172
+
173
+ if __name__ == "__main__":
174
+ main()
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/compact/stage_08/layer_original_0010.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0b64e37f0d706432ccf53b7b1cc9cf0d6ae3a188e0962f51bc3d8969083ac004
3
+ size 436228357
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/compact/stage_08/layer_original_0018.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2608c0699b195a3f9c613c2a9087b36532baec8e2c7e2ec3582b1b5a108c239a
3
+ size 436228357
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/compact/stage_08/layer_original_0021.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:560d0886d59065b0f0697b34fd2961c3867411f0d73fb068991225940bc5ba3b
3
+ size 436228357
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/compact/stage_08/layer_original_0023.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:328d67c97caa91430e09f4671723816beb09747afd7402a9f10c2a3a132d756a
3
+ size 436228357
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/compact/stage_08/layer_original_0026.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77dd379060028e10323ac2198335c47ae288707bdd01337f24cfe33c22bbad04
3
+ size 436228357
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/compact/stage_08/metadata.json ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format": "abprune_compact_stage_v2",
3
+ "model": "meta-llama/Llama-3.1-8B",
4
+ "base_model_revision": "d04e592bb4f6aa9cfee91e2e20afa771667e1d4b",
5
+ "run_id": "llama_3.1_8b_fit_mka_mlp_8block",
6
+ "target_prune_count": 8,
7
+ "stage": 8,
8
+ "removed_count": 8,
9
+ "original_layer_count": 32,
10
+ "layer_order": [
11
+ 21,
12
+ 18,
13
+ 21,
14
+ 24,
15
+ 10,
16
+ 17,
17
+ 21,
18
+ 19
19
+ ],
20
+ "latest_pair_index": 19,
21
+ "latest_recipient_side": "left",
22
+ "latest_recipient_original_layer": 23,
23
+ "latest_removed_original_layer": 25,
24
+ "removed_original_layers": [
25
+ 11,
26
+ 19,
27
+ 20,
28
+ 22,
29
+ 24,
30
+ 25,
31
+ 27,
32
+ 28
33
+ ],
34
+ "active_original_layers": [
35
+ 0,
36
+ 1,
37
+ 2,
38
+ 3,
39
+ 4,
40
+ 5,
41
+ 6,
42
+ 7,
43
+ 8,
44
+ 9,
45
+ 10,
46
+ 12,
47
+ 13,
48
+ 14,
49
+ 15,
50
+ 16,
51
+ 17,
52
+ 18,
53
+ 21,
54
+ 23,
55
+ 26,
56
+ 29,
57
+ 30,
58
+ 31
59
+ ],
60
+ "retained_layer_states": [
61
+ {
62
+ "original_layer": 10,
63
+ "state_file": "layer_original_0010.pt",
64
+ "sha256": "0b64e37f0d706432ccf53b7b1cc9cf0d6ae3a188e0962f51bc3d8969083ac004",
65
+ "source_cycle": 5,
66
+ "recipient_side": "left"
67
+ },
68
+ {
69
+ "original_layer": 18,
70
+ "state_file": "layer_original_0018.pt",
71
+ "sha256": "2608c0699b195a3f9c613c2a9087b36532baec8e2c7e2ec3582b1b5a108c239a",
72
+ "source_cycle": 6,
73
+ "recipient_side": "left"
74
+ },
75
+ {
76
+ "original_layer": 21,
77
+ "state_file": "layer_original_0021.pt",
78
+ "sha256": "560d0886d59065b0f0697b34fd2961c3867411f0d73fb068991225940bc5ba3b",
79
+ "source_cycle": 1,
80
+ "recipient_side": "left"
81
+ },
82
+ {
83
+ "original_layer": 23,
84
+ "state_file": "layer_original_0023.pt",
85
+ "sha256": "328d67c97caa91430e09f4671723816beb09747afd7402a9f10c2a3a132d756a",
86
+ "source_cycle": 8,
87
+ "recipient_side": "left"
88
+ },
89
+ {
90
+ "original_layer": 26,
91
+ "state_file": "layer_original_0026.pt",
92
+ "sha256": "77dd379060028e10323ac2198335c47ae288707bdd01337f24cfe33c22bbad04",
93
+ "source_cycle": 7,
94
+ "recipient_side": "left"
95
+ }
96
+ ],
97
+ "source_cycle": "cycle_8"
98
+ }
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/eval/final_14bench.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "task_scores": {
3
+ "race_high": 0.24042309891366495,
4
+ "race_middle": 0.2841225626740947,
5
+ "c3": 0.4876712328767123,
6
+ "cmnli": 0.33363287313128015,
7
+ "chid": 0.39603960396039606,
8
+ "piqa": 0.6789989118607181,
9
+ "winogrande": 0.6661404893449092,
10
+ "hellaswag": 0.5370444134634534,
11
+ "arc_challenge": 0.3378839590443686,
12
+ "arc_easy": 0.5315656565656566,
13
+ "openbookqa": 0.302,
14
+ "sciq": 0.824,
15
+ "mmlu": 0.36020509898874803,
16
+ "cmmlu": 0.32395095838369886
17
+ },
18
+ "macro_mean_14": 0.45026277565769296,
19
+ "tasks": [
20
+ "race_high",
21
+ "race_middle",
22
+ "c3",
23
+ "cmnli",
24
+ "chid",
25
+ "piqa",
26
+ "winogrande",
27
+ "hellaswag",
28
+ "arc_challenge",
29
+ "arc_easy",
30
+ "openbookqa",
31
+ "sciq",
32
+ "mmlu",
33
+ "cmmlu"
34
+ ],
35
+ "opencompass_protocol": "OpenCompass 0.5.4 canonical PPL prompts; full-prompt mean CE; lowest PPL",
36
+ "lm_eval_num_fewshot": 0
37
+ }
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/eval/final_lmeval9.json ADDED
@@ -0,0 +1,1402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "/workspace/models/llama31-base-d04e592",
3
+ "revision": "d04e592bb4f6aa9cfee91e2e20afa771667e1d4b",
4
+ "compact_stage": "/workspace/mka-fit-batch-20261126/full/batch1/compact/stage_08",
5
+ "cycle": 8,
6
+ "anchor": 21,
7
+ "tasks": [
8
+ "piqa",
9
+ "winogrande",
10
+ "hellaswag",
11
+ "arc_challenge",
12
+ "arc_easy",
13
+ "openbookqa",
14
+ "sciq",
15
+ "mmlu",
16
+ "cmmlu"
17
+ ],
18
+ "num_fewshot": 0,
19
+ "batch_size": "auto:4",
20
+ "limit": null,
21
+ "dataset_cache": "/workspace/come-attn-fit-20261126/lmeval_cache",
22
+ "preferred_metrics": {
23
+ "piqa": "acc_norm,none",
24
+ "winogrande": "acc,none",
25
+ "hellaswag": "acc_norm,none",
26
+ "arc_challenge": "acc_norm,none",
27
+ "arc_easy": "acc_norm,none",
28
+ "openbookqa": "acc_norm,none",
29
+ "sciq": "acc_norm,none",
30
+ "mmlu": "acc,none",
31
+ "cmmlu": "acc,none"
32
+ },
33
+ "task_scores": {
34
+ "piqa": 0.6789989118607181,
35
+ "winogrande": 0.6661404893449092,
36
+ "hellaswag": 0.5370444134634534,
37
+ "arc_challenge": 0.3378839590443686,
38
+ "arc_easy": 0.5315656565656566,
39
+ "openbookqa": 0.302,
40
+ "sciq": 0.824,
41
+ "mmlu": 0.36020509898874803,
42
+ "cmmlu": 0.32395095838369886
43
+ },
44
+ "macro_mean_all_rows": 0.5068654986279504,
45
+ "lm_eval_results": {
46
+ "piqa": {
47
+ "name": "piqa",
48
+ "alias": "piqa",
49
+ "sample_len": 1838,
50
+ "acc,none": 0.661588683351469,
51
+ "acc_stderr,none": "N/A",
52
+ "acc_norm,none": 0.6789989118607181,
53
+ "acc_norm_stderr,none": "N/A"
54
+ },
55
+ "winogrande": {
56
+ "name": "winogrande",
57
+ "alias": "winogrande",
58
+ "sample_len": 1267,
59
+ "acc,none": 0.6661404893449092,
60
+ "acc_stderr,none": "N/A"
61
+ },
62
+ "hellaswag": {
63
+ "name": "hellaswag",
64
+ "alias": "hellaswag",
65
+ "sample_len": 10042,
66
+ "acc,none": 0.3921529575781717,
67
+ "acc_stderr,none": "N/A",
68
+ "acc_norm,none": 0.5370444134634534,
69
+ "acc_norm_stderr,none": "N/A"
70
+ },
71
+ "arc_challenge": {
72
+ "name": "arc_challenge",
73
+ "alias": "arc_challenge",
74
+ "sample_len": 1172,
75
+ "acc,none": 0.29436860068259385,
76
+ "acc_stderr,none": "N/A",
77
+ "acc_norm,none": 0.3378839590443686,
78
+ "acc_norm_stderr,none": "N/A"
79
+ },
80
+ "arc_easy": {
81
+ "name": "arc_easy",
82
+ "alias": "arc_easy",
83
+ "sample_len": 2376,
84
+ "acc,none": 0.5601851851851852,
85
+ "acc_stderr,none": "N/A",
86
+ "acc_norm,none": 0.5315656565656566,
87
+ "acc_norm_stderr,none": "N/A"
88
+ },
89
+ "openbookqa": {
90
+ "name": "openbookqa",
91
+ "alias": "openbookqa",
92
+ "sample_len": 500,
93
+ "acc,none": 0.184,
94
+ "acc_stderr,none": "N/A",
95
+ "acc_norm,none": 0.302,
96
+ "acc_norm_stderr,none": "N/A"
97
+ },
98
+ "sciq": {
99
+ "name": "sciq",
100
+ "alias": "sciq",
101
+ "sample_len": 1000,
102
+ "acc,none": 0.844,
103
+ "acc_stderr,none": "N/A",
104
+ "acc_norm,none": 0.824,
105
+ "acc_norm_stderr,none": "N/A"
106
+ },
107
+ "mmlu_abstract_algebra": {
108
+ "name": "mmlu_abstract_algebra",
109
+ "alias": "abstract_algebra",
110
+ "sample_len": 100,
111
+ "acc,none": 0.28,
112
+ "acc_stderr,none": "N/A"
113
+ },
114
+ "mmlu_anatomy": {
115
+ "name": "mmlu_anatomy",
116
+ "alias": "anatomy",
117
+ "sample_len": 135,
118
+ "acc,none": 0.4074074074074074,
119
+ "acc_stderr,none": "N/A"
120
+ },
121
+ "mmlu_astronomy": {
122
+ "name": "mmlu_astronomy",
123
+ "alias": "astronomy",
124
+ "sample_len": 152,
125
+ "acc,none": 0.3618421052631579,
126
+ "acc_stderr,none": "N/A"
127
+ },
128
+ "mmlu_college_biology": {
129
+ "name": "mmlu_college_biology",
130
+ "alias": "college_biology",
131
+ "sample_len": 144,
132
+ "acc,none": 0.4930555555555556,
133
+ "acc_stderr,none": "N/A"
134
+ },
135
+ "mmlu_college_chemistry": {
136
+ "name": "mmlu_college_chemistry",
137
+ "alias": "college_chemistry",
138
+ "sample_len": 100,
139
+ "acc,none": 0.31,
140
+ "acc_stderr,none": "N/A"
141
+ },
142
+ "mmlu_college_computer_science": {
143
+ "name": "mmlu_college_computer_science",
144
+ "alias": "college_computer_science",
145
+ "sample_len": 100,
146
+ "acc,none": 0.39,
147
+ "acc_stderr,none": "N/A"
148
+ },
149
+ "mmlu_college_mathematics": {
150
+ "name": "mmlu_college_mathematics",
151
+ "alias": "college_mathematics",
152
+ "sample_len": 100,
153
+ "acc,none": 0.31,
154
+ "acc_stderr,none": "N/A"
155
+ },
156
+ "mmlu_college_physics": {
157
+ "name": "mmlu_college_physics",
158
+ "alias": "college_physics",
159
+ "sample_len": 102,
160
+ "acc,none": 0.29411764705882354,
161
+ "acc_stderr,none": "N/A"
162
+ },
163
+ "mmlu_computer_security": {
164
+ "name": "mmlu_computer_security",
165
+ "alias": "computer_security",
166
+ "sample_len": 100,
167
+ "acc,none": 0.48,
168
+ "acc_stderr,none": "N/A"
169
+ },
170
+ "mmlu_conceptual_physics": {
171
+ "name": "mmlu_conceptual_physics",
172
+ "alias": "conceptual_physics",
173
+ "sample_len": 235,
174
+ "acc,none": 0.37872340425531914,
175
+ "acc_stderr,none": "N/A"
176
+ },
177
+ "mmlu_electrical_engineering": {
178
+ "name": "mmlu_electrical_engineering",
179
+ "alias": "electrical_engineering",
180
+ "sample_len": 145,
181
+ "acc,none": 0.30344827586206896,
182
+ "acc_stderr,none": "N/A"
183
+ },
184
+ "mmlu_elementary_mathematics": {
185
+ "name": "mmlu_elementary_mathematics",
186
+ "alias": "elementary_mathematics",
187
+ "sample_len": 378,
188
+ "acc,none": 0.23809523809523808,
189
+ "acc_stderr,none": "N/A"
190
+ },
191
+ "mmlu_high_school_biology": {
192
+ "name": "mmlu_high_school_biology",
193
+ "alias": "high_school_biology",
194
+ "sample_len": 310,
195
+ "acc,none": 0.41935483870967744,
196
+ "acc_stderr,none": "N/A"
197
+ },
198
+ "mmlu_high_school_chemistry": {
199
+ "name": "mmlu_high_school_chemistry",
200
+ "alias": "high_school_chemistry",
201
+ "sample_len": 203,
202
+ "acc,none": 0.2955665024630542,
203
+ "acc_stderr,none": "N/A"
204
+ },
205
+ "mmlu_high_school_computer_science": {
206
+ "name": "mmlu_high_school_computer_science",
207
+ "alias": "high_school_computer_science",
208
+ "sample_len": 100,
209
+ "acc,none": 0.32,
210
+ "acc_stderr,none": "N/A"
211
+ },
212
+ "mmlu_high_school_mathematics": {
213
+ "name": "mmlu_high_school_mathematics",
214
+ "alias": "high_school_mathematics",
215
+ "sample_len": 270,
216
+ "acc,none": 0.24444444444444444,
217
+ "acc_stderr,none": "N/A"
218
+ },
219
+ "mmlu_high_school_physics": {
220
+ "name": "mmlu_high_school_physics",
221
+ "alias": "high_school_physics",
222
+ "sample_len": 151,
223
+ "acc,none": 0.2119205298013245,
224
+ "acc_stderr,none": "N/A"
225
+ },
226
+ "mmlu_high_school_statistics": {
227
+ "name": "mmlu_high_school_statistics",
228
+ "alias": "high_school_statistics",
229
+ "sample_len": 216,
230
+ "acc,none": 0.19444444444444445,
231
+ "acc_stderr,none": "N/A"
232
+ },
233
+ "mmlu_machine_learning": {
234
+ "name": "mmlu_machine_learning",
235
+ "alias": "machine_learning",
236
+ "sample_len": 112,
237
+ "acc,none": 0.35714285714285715,
238
+ "acc_stderr,none": "N/A"
239
+ },
240
+ "mmlu_business_ethics": {
241
+ "name": "mmlu_business_ethics",
242
+ "alias": "business_ethics",
243
+ "sample_len": 100,
244
+ "acc,none": 0.48,
245
+ "acc_stderr,none": "N/A"
246
+ },
247
+ "mmlu_clinical_knowledge": {
248
+ "name": "mmlu_clinical_knowledge",
249
+ "alias": "clinical_knowledge",
250
+ "sample_len": 265,
251
+ "acc,none": 0.32075471698113206,
252
+ "acc_stderr,none": "N/A"
253
+ },
254
+ "mmlu_college_medicine": {
255
+ "name": "mmlu_college_medicine",
256
+ "alias": "college_medicine",
257
+ "sample_len": 173,
258
+ "acc,none": 0.3236994219653179,
259
+ "acc_stderr,none": "N/A"
260
+ },
261
+ "mmlu_global_facts": {
262
+ "name": "mmlu_global_facts",
263
+ "alias": "global_facts",
264
+ "sample_len": 100,
265
+ "acc,none": 0.2,
266
+ "acc_stderr,none": "N/A"
267
+ },
268
+ "mmlu_human_aging": {
269
+ "name": "mmlu_human_aging",
270
+ "alias": "human_aging",
271
+ "sample_len": 223,
272
+ "acc,none": 0.43946188340807174,
273
+ "acc_stderr,none": "N/A"
274
+ },
275
+ "mmlu_management": {
276
+ "name": "mmlu_management",
277
+ "alias": "management",
278
+ "sample_len": 103,
279
+ "acc,none": 0.44660194174757284,
280
+ "acc_stderr,none": "N/A"
281
+ },
282
+ "mmlu_marketing": {
283
+ "name": "mmlu_marketing",
284
+ "alias": "marketing",
285
+ "sample_len": 234,
286
+ "acc,none": 0.5341880341880342,
287
+ "acc_stderr,none": "N/A"
288
+ },
289
+ "mmlu_medical_genetics": {
290
+ "name": "mmlu_medical_genetics",
291
+ "alias": "medical_genetics",
292
+ "sample_len": 100,
293
+ "acc,none": 0.54,
294
+ "acc_stderr,none": "N/A"
295
+ },
296
+ "mmlu_miscellaneous": {
297
+ "name": "mmlu_miscellaneous",
298
+ "alias": "miscellaneous",
299
+ "sample_len": 783,
300
+ "acc,none": 0.5504469987228607,
301
+ "acc_stderr,none": "N/A"
302
+ },
303
+ "mmlu_nutrition": {
304
+ "name": "mmlu_nutrition",
305
+ "alias": "nutrition",
306
+ "sample_len": 306,
307
+ "acc,none": 0.3562091503267974,
308
+ "acc_stderr,none": "N/A"
309
+ },
310
+ "mmlu_professional_accounting": {
311
+ "name": "mmlu_professional_accounting",
312
+ "alias": "professional_accounting",
313
+ "sample_len": 282,
314
+ "acc,none": 0.2872340425531915,
315
+ "acc_stderr,none": "N/A"
316
+ },
317
+ "mmlu_professional_medicine": {
318
+ "name": "mmlu_professional_medicine",
319
+ "alias": "professional_medicine",
320
+ "sample_len": 272,
321
+ "acc,none": 0.3088235294117647,
322
+ "acc_stderr,none": "N/A"
323
+ },
324
+ "mmlu_virology": {
325
+ "name": "mmlu_virology",
326
+ "alias": "virology",
327
+ "sample_len": 166,
328
+ "acc,none": 0.3493975903614458,
329
+ "acc_stderr,none": "N/A"
330
+ },
331
+ "mmlu_econometrics": {
332
+ "name": "mmlu_econometrics",
333
+ "alias": "econometrics",
334
+ "sample_len": 114,
335
+ "acc,none": 0.2982456140350877,
336
+ "acc_stderr,none": "N/A"
337
+ },
338
+ "mmlu_high_school_geography": {
339
+ "name": "mmlu_high_school_geography",
340
+ "alias": "high_school_geography",
341
+ "sample_len": 198,
342
+ "acc,none": 0.40404040404040403,
343
+ "acc_stderr,none": "N/A"
344
+ },
345
+ "mmlu_high_school_government_and_politics": {
346
+ "name": "mmlu_high_school_government_and_politics",
347
+ "alias": "high_school_government_and_politics",
348
+ "sample_len": 193,
349
+ "acc,none": 0.46632124352331605,
350
+ "acc_stderr,none": "N/A"
351
+ },
352
+ "mmlu_high_school_macroeconomics": {
353
+ "name": "mmlu_high_school_macroeconomics",
354
+ "alias": "high_school_macroeconomics",
355
+ "sample_len": 390,
356
+ "acc,none": 0.28205128205128205,
357
+ "acc_stderr,none": "N/A"
358
+ },
359
+ "mmlu_high_school_microeconomics": {
360
+ "name": "mmlu_high_school_microeconomics",
361
+ "alias": "high_school_microeconomics",
362
+ "sample_len": 238,
363
+ "acc,none": 0.31092436974789917,
364
+ "acc_stderr,none": "N/A"
365
+ },
366
+ "mmlu_high_school_psychology": {
367
+ "name": "mmlu_high_school_psychology",
368
+ "alias": "high_school_psychology",
369
+ "sample_len": 545,
370
+ "acc,none": 0.5064220183486239,
371
+ "acc_stderr,none": "N/A"
372
+ },
373
+ "mmlu_human_sexuality": {
374
+ "name": "mmlu_human_sexuality",
375
+ "alias": "human_sexuality",
376
+ "sample_len": 131,
377
+ "acc,none": 0.45038167938931295,
378
+ "acc_stderr,none": "N/A"
379
+ },
380
+ "mmlu_professional_psychology": {
381
+ "name": "mmlu_professional_psychology",
382
+ "alias": "professional_psychology",
383
+ "sample_len": 612,
384
+ "acc,none": 0.3954248366013072,
385
+ "acc_stderr,none": "N/A"
386
+ },
387
+ "mmlu_public_relations": {
388
+ "name": "mmlu_public_relations",
389
+ "alias": "public_relations",
390
+ "sample_len": 110,
391
+ "acc,none": 0.36363636363636365,
392
+ "acc_stderr,none": "N/A"
393
+ },
394
+ "mmlu_security_studies": {
395
+ "name": "mmlu_security_studies",
396
+ "alias": "security_studies",
397
+ "sample_len": 245,
398
+ "acc,none": 0.24897959183673468,
399
+ "acc_stderr,none": "N/A"
400
+ },
401
+ "mmlu_sociology": {
402
+ "name": "mmlu_sociology",
403
+ "alias": "sociology",
404
+ "sample_len": 201,
405
+ "acc,none": 0.4427860696517413,
406
+ "acc_stderr,none": "N/A"
407
+ },
408
+ "mmlu_us_foreign_policy": {
409
+ "name": "mmlu_us_foreign_policy",
410
+ "alias": "us_foreign_policy",
411
+ "sample_len": 100,
412
+ "acc,none": 0.49,
413
+ "acc_stderr,none": "N/A"
414
+ },
415
+ "mmlu_formal_logic": {
416
+ "name": "mmlu_formal_logic",
417
+ "alias": "formal_logic",
418
+ "sample_len": 126,
419
+ "acc,none": 0.29365079365079366,
420
+ "acc_stderr,none": "N/A"
421
+ },
422
+ "mmlu_high_school_european_history": {
423
+ "name": "mmlu_high_school_european_history",
424
+ "alias": "high_school_european_history",
425
+ "sample_len": 165,
426
+ "acc,none": 0.509090909090909,
427
+ "acc_stderr,none": "N/A"
428
+ },
429
+ "mmlu_high_school_us_history": {
430
+ "name": "mmlu_high_school_us_history",
431
+ "alias": "high_school_us_history",
432
+ "sample_len": 204,
433
+ "acc,none": 0.4215686274509804,
434
+ "acc_stderr,none": "N/A"
435
+ },
436
+ "mmlu_high_school_world_history": {
437
+ "name": "mmlu_high_school_world_history",
438
+ "alias": "high_school_world_history",
439
+ "sample_len": 237,
440
+ "acc,none": 0.48945147679324896,
441
+ "acc_stderr,none": "N/A"
442
+ },
443
+ "mmlu_international_law": {
444
+ "name": "mmlu_international_law",
445
+ "alias": "international_law",
446
+ "sample_len": 121,
447
+ "acc,none": 0.3884297520661157,
448
+ "acc_stderr,none": "N/A"
449
+ },
450
+ "mmlu_jurisprudence": {
451
+ "name": "mmlu_jurisprudence",
452
+ "alias": "jurisprudence",
453
+ "sample_len": 108,
454
+ "acc,none": 0.37962962962962965,
455
+ "acc_stderr,none": "N/A"
456
+ },
457
+ "mmlu_logical_fallacies": {
458
+ "name": "mmlu_logical_fallacies",
459
+ "alias": "logical_fallacies",
460
+ "sample_len": 163,
461
+ "acc,none": 0.3128834355828221,
462
+ "acc_stderr,none": "N/A"
463
+ },
464
+ "mmlu_moral_disputes": {
465
+ "name": "mmlu_moral_disputes",
466
+ "alias": "moral_disputes",
467
+ "sample_len": 346,
468
+ "acc,none": 0.36416184971098264,
469
+ "acc_stderr,none": "N/A"
470
+ },
471
+ "mmlu_moral_scenarios": {
472
+ "name": "mmlu_moral_scenarios",
473
+ "alias": "moral_scenarios",
474
+ "sample_len": 895,
475
+ "acc,none": 0.23798882681564246,
476
+ "acc_stderr,none": "N/A"
477
+ },
478
+ "mmlu_philosophy": {
479
+ "name": "mmlu_philosophy",
480
+ "alias": "philosophy",
481
+ "sample_len": 311,
482
+ "acc,none": 0.36977491961414793,
483
+ "acc_stderr,none": "N/A"
484
+ },
485
+ "mmlu_prehistory": {
486
+ "name": "mmlu_prehistory",
487
+ "alias": "prehistory",
488
+ "sample_len": 324,
489
+ "acc,none": 0.3333333333333333,
490
+ "acc_stderr,none": "N/A"
491
+ },
492
+ "mmlu_professional_law": {
493
+ "name": "mmlu_professional_law",
494
+ "alias": "professional_law",
495
+ "sample_len": 1534,
496
+ "acc,none": 0.27053455019556716,
497
+ "acc_stderr,none": "N/A"
498
+ },
499
+ "mmlu_world_religions": {
500
+ "name": "mmlu_world_religions",
501
+ "alias": "world_religions",
502
+ "sample_len": 171,
503
+ "acc,none": 0.6257309941520468,
504
+ "acc_stderr,none": "N/A"
505
+ },
506
+ "cmmlu_agronomy": {
507
+ "name": "cmmlu_agronomy",
508
+ "alias": "cmmlu_agronomy",
509
+ "sample_len": 169,
510
+ "acc,none": 0.3136094674556213,
511
+ "acc_stderr,none": "N/A",
512
+ "acc_norm,none": 0.3136094674556213,
513
+ "acc_norm_stderr,none": "N/A"
514
+ },
515
+ "cmmlu_anatomy": {
516
+ "name": "cmmlu_anatomy",
517
+ "alias": "cmmlu_anatomy",
518
+ "sample_len": 148,
519
+ "acc,none": 0.25675675675675674,
520
+ "acc_stderr,none": "N/A",
521
+ "acc_norm,none": 0.25675675675675674,
522
+ "acc_norm_stderr,none": "N/A"
523
+ },
524
+ "cmmlu_ancient_chinese": {
525
+ "name": "cmmlu_ancient_chinese",
526
+ "alias": "cmmlu_ancient_chinese",
527
+ "sample_len": 164,
528
+ "acc,none": 0.25,
529
+ "acc_stderr,none": "N/A",
530
+ "acc_norm,none": 0.25,
531
+ "acc_norm_stderr,none": "N/A"
532
+ },
533
+ "cmmlu_arts": {
534
+ "name": "cmmlu_arts",
535
+ "alias": "cmmlu_arts",
536
+ "sample_len": 160,
537
+ "acc,none": 0.33125,
538
+ "acc_stderr,none": "N/A",
539
+ "acc_norm,none": 0.33125,
540
+ "acc_norm_stderr,none": "N/A"
541
+ },
542
+ "cmmlu_astronomy": {
543
+ "name": "cmmlu_astronomy",
544
+ "alias": "cmmlu_astronomy",
545
+ "sample_len": 165,
546
+ "acc,none": 0.28484848484848485,
547
+ "acc_stderr,none": "N/A",
548
+ "acc_norm,none": 0.28484848484848485,
549
+ "acc_norm_stderr,none": "N/A"
550
+ },
551
+ "cmmlu_business_ethics": {
552
+ "name": "cmmlu_business_ethics",
553
+ "alias": "cmmlu_business_ethics",
554
+ "sample_len": 209,
555
+ "acc,none": 0.39712918660287083,
556
+ "acc_stderr,none": "N/A",
557
+ "acc_norm,none": 0.39712918660287083,
558
+ "acc_norm_stderr,none": "N/A"
559
+ },
560
+ "cmmlu_chinese_civil_service_exam": {
561
+ "name": "cmmlu_chinese_civil_service_exam",
562
+ "alias": "cmmlu_chinese_civil_service_exam",
563
+ "sample_len": 160,
564
+ "acc,none": 0.26875,
565
+ "acc_stderr,none": "N/A",
566
+ "acc_norm,none": 0.26875,
567
+ "acc_norm_stderr,none": "N/A"
568
+ },
569
+ "cmmlu_chinese_driving_rule": {
570
+ "name": "cmmlu_chinese_driving_rule",
571
+ "alias": "cmmlu_chinese_driving_rule",
572
+ "sample_len": 131,
573
+ "acc,none": 0.32061068702290074,
574
+ "acc_stderr,none": "N/A",
575
+ "acc_norm,none": 0.32061068702290074,
576
+ "acc_norm_stderr,none": "N/A"
577
+ },
578
+ "cmmlu_chinese_food_culture": {
579
+ "name": "cmmlu_chinese_food_culture",
580
+ "alias": "cmmlu_chinese_food_culture",
581
+ "sample_len": 136,
582
+ "acc,none": 0.27205882352941174,
583
+ "acc_stderr,none": "N/A",
584
+ "acc_norm,none": 0.27205882352941174,
585
+ "acc_norm_stderr,none": "N/A"
586
+ },
587
+ "cmmlu_chinese_foreign_policy": {
588
+ "name": "cmmlu_chinese_foreign_policy",
589
+ "alias": "cmmlu_chinese_foreign_policy",
590
+ "sample_len": 107,
591
+ "acc,none": 0.32710280373831774,
592
+ "acc_stderr,none": "N/A",
593
+ "acc_norm,none": 0.32710280373831774,
594
+ "acc_norm_stderr,none": "N/A"
595
+ },
596
+ "cmmlu_chinese_history": {
597
+ "name": "cmmlu_chinese_history",
598
+ "alias": "cmmlu_chinese_history",
599
+ "sample_len": 323,
600
+ "acc,none": 0.35294117647058826,
601
+ "acc_stderr,none": "N/A",
602
+ "acc_norm,none": 0.35294117647058826,
603
+ "acc_norm_stderr,none": "N/A"
604
+ },
605
+ "cmmlu_chinese_literature": {
606
+ "name": "cmmlu_chinese_literature",
607
+ "alias": "cmmlu_chinese_literature",
608
+ "sample_len": 204,
609
+ "acc,none": 0.2647058823529412,
610
+ "acc_stderr,none": "N/A",
611
+ "acc_norm,none": 0.2647058823529412,
612
+ "acc_norm_stderr,none": "N/A"
613
+ },
614
+ "cmmlu_chinese_teacher_qualification": {
615
+ "name": "cmmlu_chinese_teacher_qualification",
616
+ "alias": "cmmlu_chinese_teacher_qualification",
617
+ "sample_len": 179,
618
+ "acc,none": 0.3743016759776536,
619
+ "acc_stderr,none": "N/A",
620
+ "acc_norm,none": 0.3743016759776536,
621
+ "acc_norm_stderr,none": "N/A"
622
+ },
623
+ "cmmlu_clinical_knowledge": {
624
+ "name": "cmmlu_clinical_knowledge",
625
+ "alias": "cmmlu_clinical_knowledge",
626
+ "sample_len": 237,
627
+ "acc,none": 0.2742616033755274,
628
+ "acc_stderr,none": "N/A",
629
+ "acc_norm,none": 0.2742616033755274,
630
+ "acc_norm_stderr,none": "N/A"
631
+ },
632
+ "cmmlu_college_actuarial_science": {
633
+ "name": "cmmlu_college_actuarial_science",
634
+ "alias": "cmmlu_college_actuarial_science",
635
+ "sample_len": 106,
636
+ "acc,none": 0.2169811320754717,
637
+ "acc_stderr,none": "N/A",
638
+ "acc_norm,none": 0.2169811320754717,
639
+ "acc_norm_stderr,none": "N/A"
640
+ },
641
+ "cmmlu_college_education": {
642
+ "name": "cmmlu_college_education",
643
+ "alias": "cmmlu_college_education",
644
+ "sample_len": 107,
645
+ "acc,none": 0.4485981308411215,
646
+ "acc_stderr,none": "N/A",
647
+ "acc_norm,none": 0.4485981308411215,
648
+ "acc_norm_stderr,none": "N/A"
649
+ },
650
+ "cmmlu_college_engineering_hydrology": {
651
+ "name": "cmmlu_college_engineering_hydrology",
652
+ "alias": "cmmlu_college_engineering_hydrology",
653
+ "sample_len": 106,
654
+ "acc,none": 0.330188679245283,
655
+ "acc_stderr,none": "N/A",
656
+ "acc_norm,none": 0.330188679245283,
657
+ "acc_norm_stderr,none": "N/A"
658
+ },
659
+ "cmmlu_college_law": {
660
+ "name": "cmmlu_college_law",
661
+ "alias": "cmmlu_college_law",
662
+ "sample_len": 108,
663
+ "acc,none": 0.25925925925925924,
664
+ "acc_stderr,none": "N/A",
665
+ "acc_norm,none": 0.25925925925925924,
666
+ "acc_norm_stderr,none": "N/A"
667
+ },
668
+ "cmmlu_college_mathematics": {
669
+ "name": "cmmlu_college_mathematics",
670
+ "alias": "cmmlu_college_mathematics",
671
+ "sample_len": 105,
672
+ "acc,none": 0.2761904761904762,
673
+ "acc_stderr,none": "N/A",
674
+ "acc_norm,none": 0.2761904761904762,
675
+ "acc_norm_stderr,none": "N/A"
676
+ },
677
+ "cmmlu_college_medical_statistics": {
678
+ "name": "cmmlu_college_medical_statistics",
679
+ "alias": "cmmlu_college_medical_statistics",
680
+ "sample_len": 106,
681
+ "acc,none": 0.32075471698113206,
682
+ "acc_stderr,none": "N/A",
683
+ "acc_norm,none": 0.32075471698113206,
684
+ "acc_norm_stderr,none": "N/A"
685
+ },
686
+ "cmmlu_college_medicine": {
687
+ "name": "cmmlu_college_medicine",
688
+ "alias": "cmmlu_college_medicine",
689
+ "sample_len": 273,
690
+ "acc,none": 0.31135531135531136,
691
+ "acc_stderr,none": "N/A",
692
+ "acc_norm,none": 0.31135531135531136,
693
+ "acc_norm_stderr,none": "N/A"
694
+ },
695
+ "cmmlu_computer_science": {
696
+ "name": "cmmlu_computer_science",
697
+ "alias": "cmmlu_computer_science",
698
+ "sample_len": 204,
699
+ "acc,none": 0.3627450980392157,
700
+ "acc_stderr,none": "N/A",
701
+ "acc_norm,none": 0.3627450980392157,
702
+ "acc_norm_stderr,none": "N/A"
703
+ },
704
+ "cmmlu_computer_security": {
705
+ "name": "cmmlu_computer_security",
706
+ "alias": "cmmlu_computer_security",
707
+ "sample_len": 171,
708
+ "acc,none": 0.39766081871345027,
709
+ "acc_stderr,none": "N/A",
710
+ "acc_norm,none": 0.39766081871345027,
711
+ "acc_norm_stderr,none": "N/A"
712
+ },
713
+ "cmmlu_conceptual_physics": {
714
+ "name": "cmmlu_conceptual_physics",
715
+ "alias": "cmmlu_conceptual_physics",
716
+ "sample_len": 147,
717
+ "acc,none": 0.2653061224489796,
718
+ "acc_stderr,none": "N/A",
719
+ "acc_norm,none": 0.2653061224489796,
720
+ "acc_norm_stderr,none": "N/A"
721
+ },
722
+ "cmmlu_construction_project_management": {
723
+ "name": "cmmlu_construction_project_management",
724
+ "alias": "cmmlu_construction_project_management",
725
+ "sample_len": 139,
726
+ "acc,none": 0.3381294964028777,
727
+ "acc_stderr,none": "N/A",
728
+ "acc_norm,none": 0.3381294964028777,
729
+ "acc_norm_stderr,none": "N/A"
730
+ },
731
+ "cmmlu_economics": {
732
+ "name": "cmmlu_economics",
733
+ "alias": "cmmlu_economics",
734
+ "sample_len": 159,
735
+ "acc,none": 0.3710691823899371,
736
+ "acc_stderr,none": "N/A",
737
+ "acc_norm,none": 0.3710691823899371,
738
+ "acc_norm_stderr,none": "N/A"
739
+ },
740
+ "cmmlu_education": {
741
+ "name": "cmmlu_education",
742
+ "alias": "cmmlu_education",
743
+ "sample_len": 163,
744
+ "acc,none": 0.32515337423312884,
745
+ "acc_stderr,none": "N/A",
746
+ "acc_norm,none": 0.32515337423312884,
747
+ "acc_norm_stderr,none": "N/A"
748
+ },
749
+ "cmmlu_electrical_engineering": {
750
+ "name": "cmmlu_electrical_engineering",
751
+ "alias": "cmmlu_electrical_engineering",
752
+ "sample_len": 172,
753
+ "acc,none": 0.31976744186046513,
754
+ "acc_stderr,none": "N/A",
755
+ "acc_norm,none": 0.31976744186046513,
756
+ "acc_norm_stderr,none": "N/A"
757
+ },
758
+ "cmmlu_elementary_chinese": {
759
+ "name": "cmmlu_elementary_chinese",
760
+ "alias": "cmmlu_elementary_chinese",
761
+ "sample_len": 252,
762
+ "acc,none": 0.30952380952380953,
763
+ "acc_stderr,none": "N/A",
764
+ "acc_norm,none": 0.30952380952380953,
765
+ "acc_norm_stderr,none": "N/A"
766
+ },
767
+ "cmmlu_elementary_commonsense": {
768
+ "name": "cmmlu_elementary_commonsense",
769
+ "alias": "cmmlu_elementary_commonsense",
770
+ "sample_len": 198,
771
+ "acc,none": 0.2828282828282828,
772
+ "acc_stderr,none": "N/A",
773
+ "acc_norm,none": 0.2828282828282828,
774
+ "acc_norm_stderr,none": "N/A"
775
+ },
776
+ "cmmlu_elementary_information_and_technology": {
777
+ "name": "cmmlu_elementary_information_and_technology",
778
+ "alias": "cmmlu_elementary_information_and_technology",
779
+ "sample_len": 238,
780
+ "acc,none": 0.4327731092436975,
781
+ "acc_stderr,none": "N/A",
782
+ "acc_norm,none": 0.4327731092436975,
783
+ "acc_norm_stderr,none": "N/A"
784
+ },
785
+ "cmmlu_elementary_mathematics": {
786
+ "name": "cmmlu_elementary_mathematics",
787
+ "alias": "cmmlu_elementary_mathematics",
788
+ "sample_len": 230,
789
+ "acc,none": 0.30434782608695654,
790
+ "acc_stderr,none": "N/A",
791
+ "acc_norm,none": 0.30434782608695654,
792
+ "acc_norm_stderr,none": "N/A"
793
+ },
794
+ "cmmlu_ethnology": {
795
+ "name": "cmmlu_ethnology",
796
+ "alias": "cmmlu_ethnology",
797
+ "sample_len": 135,
798
+ "acc,none": 0.3333333333333333,
799
+ "acc_stderr,none": "N/A",
800
+ "acc_norm,none": 0.3333333333333333,
801
+ "acc_norm_stderr,none": "N/A"
802
+ },
803
+ "cmmlu_food_science": {
804
+ "name": "cmmlu_food_science",
805
+ "alias": "cmmlu_food_science",
806
+ "sample_len": 143,
807
+ "acc,none": 0.3076923076923077,
808
+ "acc_stderr,none": "N/A",
809
+ "acc_norm,none": 0.3076923076923077,
810
+ "acc_norm_stderr,none": "N/A"
811
+ },
812
+ "cmmlu_genetics": {
813
+ "name": "cmmlu_genetics",
814
+ "alias": "cmmlu_genetics",
815
+ "sample_len": 176,
816
+ "acc,none": 0.2556818181818182,
817
+ "acc_stderr,none": "N/A",
818
+ "acc_norm,none": 0.2556818181818182,
819
+ "acc_norm_stderr,none": "N/A"
820
+ },
821
+ "cmmlu_global_facts": {
822
+ "name": "cmmlu_global_facts",
823
+ "alias": "cmmlu_global_facts",
824
+ "sample_len": 149,
825
+ "acc,none": 0.3288590604026846,
826
+ "acc_stderr,none": "N/A",
827
+ "acc_norm,none": 0.3288590604026846,
828
+ "acc_norm_stderr,none": "N/A"
829
+ },
830
+ "cmmlu_high_school_biology": {
831
+ "name": "cmmlu_high_school_biology",
832
+ "alias": "cmmlu_high_school_biology",
833
+ "sample_len": 169,
834
+ "acc,none": 0.27218934911242604,
835
+ "acc_stderr,none": "N/A",
836
+ "acc_norm,none": 0.27218934911242604,
837
+ "acc_norm_stderr,none": "N/A"
838
+ },
839
+ "cmmlu_high_school_chemistry": {
840
+ "name": "cmmlu_high_school_chemistry",
841
+ "alias": "cmmlu_high_school_chemistry",
842
+ "sample_len": 132,
843
+ "acc,none": 0.26515151515151514,
844
+ "acc_stderr,none": "N/A",
845
+ "acc_norm,none": 0.26515151515151514,
846
+ "acc_norm_stderr,none": "N/A"
847
+ },
848
+ "cmmlu_high_school_geography": {
849
+ "name": "cmmlu_high_school_geography",
850
+ "alias": "cmmlu_high_school_geography",
851
+ "sample_len": 118,
852
+ "acc,none": 0.3220338983050847,
853
+ "acc_stderr,none": "N/A",
854
+ "acc_norm,none": 0.3220338983050847,
855
+ "acc_norm_stderr,none": "N/A"
856
+ },
857
+ "cmmlu_high_school_mathematics": {
858
+ "name": "cmmlu_high_school_mathematics",
859
+ "alias": "cmmlu_high_school_mathematics",
860
+ "sample_len": 164,
861
+ "acc,none": 0.24390243902439024,
862
+ "acc_stderr,none": "N/A",
863
+ "acc_norm,none": 0.24390243902439024,
864
+ "acc_norm_stderr,none": "N/A"
865
+ },
866
+ "cmmlu_high_school_physics": {
867
+ "name": "cmmlu_high_school_physics",
868
+ "alias": "cmmlu_high_school_physics",
869
+ "sample_len": 110,
870
+ "acc,none": 0.2727272727272727,
871
+ "acc_stderr,none": "N/A",
872
+ "acc_norm,none": 0.2727272727272727,
873
+ "acc_norm_stderr,none": "N/A"
874
+ },
875
+ "cmmlu_high_school_politics": {
876
+ "name": "cmmlu_high_school_politics",
877
+ "alias": "cmmlu_high_school_politics",
878
+ "sample_len": 143,
879
+ "acc,none": 0.3006993006993007,
880
+ "acc_stderr,none": "N/A",
881
+ "acc_norm,none": 0.3006993006993007,
882
+ "acc_norm_stderr,none": "N/A"
883
+ },
884
+ "cmmlu_human_sexuality": {
885
+ "name": "cmmlu_human_sexuality",
886
+ "alias": "cmmlu_human_sexuality",
887
+ "sample_len": 126,
888
+ "acc,none": 0.35714285714285715,
889
+ "acc_stderr,none": "N/A",
890
+ "acc_norm,none": 0.35714285714285715,
891
+ "acc_norm_stderr,none": "N/A"
892
+ },
893
+ "cmmlu_international_law": {
894
+ "name": "cmmlu_international_law",
895
+ "alias": "cmmlu_international_law",
896
+ "sample_len": 185,
897
+ "acc,none": 0.3081081081081081,
898
+ "acc_stderr,none": "N/A",
899
+ "acc_norm,none": 0.3081081081081081,
900
+ "acc_norm_stderr,none": "N/A"
901
+ },
902
+ "cmmlu_journalism": {
903
+ "name": "cmmlu_journalism",
904
+ "alias": "cmmlu_journalism",
905
+ "sample_len": 172,
906
+ "acc,none": 0.36046511627906974,
907
+ "acc_stderr,none": "N/A",
908
+ "acc_norm,none": 0.36046511627906974,
909
+ "acc_norm_stderr,none": "N/A"
910
+ },
911
+ "cmmlu_jurisprudence": {
912
+ "name": "cmmlu_jurisprudence",
913
+ "alias": "cmmlu_jurisprudence",
914
+ "sample_len": 411,
915
+ "acc,none": 0.30656934306569344,
916
+ "acc_stderr,none": "N/A",
917
+ "acc_norm,none": 0.30656934306569344,
918
+ "acc_norm_stderr,none": "N/A"
919
+ },
920
+ "cmmlu_legal_and_moral_basis": {
921
+ "name": "cmmlu_legal_and_moral_basis",
922
+ "alias": "cmmlu_legal_and_moral_basis",
923
+ "sample_len": 214,
924
+ "acc,none": 0.5280373831775701,
925
+ "acc_stderr,none": "N/A",
926
+ "acc_norm,none": 0.5280373831775701,
927
+ "acc_norm_stderr,none": "N/A"
928
+ },
929
+ "cmmlu_logical": {
930
+ "name": "cmmlu_logical",
931
+ "alias": "cmmlu_logical",
932
+ "sample_len": 123,
933
+ "acc,none": 0.2926829268292683,
934
+ "acc_stderr,none": "N/A",
935
+ "acc_norm,none": 0.2926829268292683,
936
+ "acc_norm_stderr,none": "N/A"
937
+ },
938
+ "cmmlu_machine_learning": {
939
+ "name": "cmmlu_machine_learning",
940
+ "alias": "cmmlu_machine_learning",
941
+ "sample_len": 122,
942
+ "acc,none": 0.3114754098360656,
943
+ "acc_stderr,none": "N/A",
944
+ "acc_norm,none": 0.3114754098360656,
945
+ "acc_norm_stderr,none": "N/A"
946
+ },
947
+ "cmmlu_management": {
948
+ "name": "cmmlu_management",
949
+ "alias": "cmmlu_management",
950
+ "sample_len": 210,
951
+ "acc,none": 0.3142857142857143,
952
+ "acc_stderr,none": "N/A",
953
+ "acc_norm,none": 0.3142857142857143,
954
+ "acc_norm_stderr,none": "N/A"
955
+ },
956
+ "cmmlu_marketing": {
957
+ "name": "cmmlu_marketing",
958
+ "alias": "cmmlu_marketing",
959
+ "sample_len": 180,
960
+ "acc,none": 0.37222222222222223,
961
+ "acc_stderr,none": "N/A",
962
+ "acc_norm,none": 0.37222222222222223,
963
+ "acc_norm_stderr,none": "N/A"
964
+ },
965
+ "cmmlu_marxist_theory": {
966
+ "name": "cmmlu_marxist_theory",
967
+ "alias": "cmmlu_marxist_theory",
968
+ "sample_len": 189,
969
+ "acc,none": 0.4126984126984127,
970
+ "acc_stderr,none": "N/A",
971
+ "acc_norm,none": 0.4126984126984127,
972
+ "acc_norm_stderr,none": "N/A"
973
+ },
974
+ "cmmlu_modern_chinese": {
975
+ "name": "cmmlu_modern_chinese",
976
+ "alias": "cmmlu_modern_chinese",
977
+ "sample_len": 116,
978
+ "acc,none": 0.27586206896551724,
979
+ "acc_stderr,none": "N/A",
980
+ "acc_norm,none": 0.27586206896551724,
981
+ "acc_norm_stderr,none": "N/A"
982
+ },
983
+ "cmmlu_nutrition": {
984
+ "name": "cmmlu_nutrition",
985
+ "alias": "cmmlu_nutrition",
986
+ "sample_len": 145,
987
+ "acc,none": 0.31724137931034485,
988
+ "acc_stderr,none": "N/A",
989
+ "acc_norm,none": 0.31724137931034485,
990
+ "acc_norm_stderr,none": "N/A"
991
+ },
992
+ "cmmlu_philosophy": {
993
+ "name": "cmmlu_philosophy",
994
+ "alias": "cmmlu_philosophy",
995
+ "sample_len": 105,
996
+ "acc,none": 0.3142857142857143,
997
+ "acc_stderr,none": "N/A",
998
+ "acc_norm,none": 0.3142857142857143,
999
+ "acc_norm_stderr,none": "N/A"
1000
+ },
1001
+ "cmmlu_professional_accounting": {
1002
+ "name": "cmmlu_professional_accounting",
1003
+ "alias": "cmmlu_professional_accounting",
1004
+ "sample_len": 175,
1005
+ "acc,none": 0.3314285714285714,
1006
+ "acc_stderr,none": "N/A",
1007
+ "acc_norm,none": 0.3314285714285714,
1008
+ "acc_norm_stderr,none": "N/A"
1009
+ },
1010
+ "cmmlu_professional_law": {
1011
+ "name": "cmmlu_professional_law",
1012
+ "alias": "cmmlu_professional_law",
1013
+ "sample_len": 211,
1014
+ "acc,none": 0.26066350710900477,
1015
+ "acc_stderr,none": "N/A",
1016
+ "acc_norm,none": 0.26066350710900477,
1017
+ "acc_norm_stderr,none": "N/A"
1018
+ },
1019
+ "cmmlu_professional_medicine": {
1020
+ "name": "cmmlu_professional_medicine",
1021
+ "alias": "cmmlu_professional_medicine",
1022
+ "sample_len": 376,
1023
+ "acc,none": 0.3058510638297872,
1024
+ "acc_stderr,none": "N/A",
1025
+ "acc_norm,none": 0.3058510638297872,
1026
+ "acc_norm_stderr,none": "N/A"
1027
+ },
1028
+ "cmmlu_professional_psychology": {
1029
+ "name": "cmmlu_professional_psychology",
1030
+ "alias": "cmmlu_professional_psychology",
1031
+ "sample_len": 232,
1032
+ "acc,none": 0.3577586206896552,
1033
+ "acc_stderr,none": "N/A",
1034
+ "acc_norm,none": 0.3577586206896552,
1035
+ "acc_norm_stderr,none": "N/A"
1036
+ },
1037
+ "cmmlu_public_relations": {
1038
+ "name": "cmmlu_public_relations",
1039
+ "alias": "cmmlu_public_relations",
1040
+ "sample_len": 174,
1041
+ "acc,none": 0.40229885057471265,
1042
+ "acc_stderr,none": "N/A",
1043
+ "acc_norm,none": 0.40229885057471265,
1044
+ "acc_norm_stderr,none": "N/A"
1045
+ },
1046
+ "cmmlu_security_study": {
1047
+ "name": "cmmlu_security_study",
1048
+ "alias": "cmmlu_security_study",
1049
+ "sample_len": 135,
1050
+ "acc,none": 0.3333333333333333,
1051
+ "acc_stderr,none": "N/A",
1052
+ "acc_norm,none": 0.3333333333333333,
1053
+ "acc_norm_stderr,none": "N/A"
1054
+ },
1055
+ "cmmlu_sociology": {
1056
+ "name": "cmmlu_sociology",
1057
+ "alias": "cmmlu_sociology",
1058
+ "sample_len": 226,
1059
+ "acc,none": 0.3053097345132743,
1060
+ "acc_stderr,none": "N/A",
1061
+ "acc_norm,none": 0.3053097345132743,
1062
+ "acc_norm_stderr,none": "N/A"
1063
+ },
1064
+ "cmmlu_sports_science": {
1065
+ "name": "cmmlu_sports_science",
1066
+ "alias": "cmmlu_sports_science",
1067
+ "sample_len": 165,
1068
+ "acc,none": 0.3151515151515151,
1069
+ "acc_stderr,none": "N/A",
1070
+ "acc_norm,none": 0.3151515151515151,
1071
+ "acc_norm_stderr,none": "N/A"
1072
+ },
1073
+ "cmmlu_traditional_chinese_medicine": {
1074
+ "name": "cmmlu_traditional_chinese_medicine",
1075
+ "alias": "cmmlu_traditional_chinese_medicine",
1076
+ "sample_len": 185,
1077
+ "acc,none": 0.2864864864864865,
1078
+ "acc_stderr,none": "N/A",
1079
+ "acc_norm,none": 0.2864864864864865,
1080
+ "acc_norm_stderr,none": "N/A"
1081
+ },
1082
+ "cmmlu_virology": {
1083
+ "name": "cmmlu_virology",
1084
+ "alias": "cmmlu_virology",
1085
+ "sample_len": 169,
1086
+ "acc,none": 0.3609467455621302,
1087
+ "acc_stderr,none": "N/A",
1088
+ "acc_norm,none": 0.3609467455621302,
1089
+ "acc_norm_stderr,none": "N/A"
1090
+ },
1091
+ "cmmlu_world_history": {
1092
+ "name": "cmmlu_world_history",
1093
+ "alias": "cmmlu_world_history",
1094
+ "sample_len": 161,
1095
+ "acc,none": 0.33540372670807456,
1096
+ "acc_stderr,none": "N/A",
1097
+ "acc_norm,none": 0.33540372670807456,
1098
+ "acc_norm_stderr,none": "N/A"
1099
+ },
1100
+ "cmmlu_world_religions": {
1101
+ "name": "cmmlu_world_religions",
1102
+ "alias": "cmmlu_world_religions",
1103
+ "sample_len": 160,
1104
+ "acc,none": 0.41875,
1105
+ "acc_stderr,none": "N/A",
1106
+ "acc_norm,none": 0.41875,
1107
+ "acc_norm_stderr,none": "N/A"
1108
+ },
1109
+ "mmlu_stem": {
1110
+ "alias": "stem",
1111
+ "name": "mmlu_stem",
1112
+ "sample_len": 3153,
1113
+ "acc,none": 0.3212813193783698,
1114
+ "acc_stderr,none": "N/A",
1115
+ "sample_count": {
1116
+ "acc,none": 3153
1117
+ }
1118
+ },
1119
+ "mmlu_other": {
1120
+ "alias": "other",
1121
+ "name": "mmlu_other",
1122
+ "sample_len": 3107,
1123
+ "acc,none": 0.416800772449308,
1124
+ "acc_stderr,none": "N/A",
1125
+ "sample_count": {
1126
+ "acc,none": 3107
1127
+ }
1128
+ },
1129
+ "mmlu_social_sciences": {
1130
+ "alias": "social sciences",
1131
+ "name": "mmlu_social_sciences",
1132
+ "sample_len": 3077,
1133
+ "acc,none": 0.3912902177445564,
1134
+ "acc_stderr,none": "N/A",
1135
+ "sample_count": {
1136
+ "acc,none": 3077
1137
+ }
1138
+ },
1139
+ "mmlu_humanities": {
1140
+ "alias": "humanities",
1141
+ "name": "mmlu_humanities",
1142
+ "sample_len": 4705,
1143
+ "acc,none": 0.328586609989373,
1144
+ "acc_stderr,none": "N/A",
1145
+ "sample_count": {
1146
+ "acc,none": 4705
1147
+ }
1148
+ },
1149
+ "mmlu": {
1150
+ "alias": "mmlu",
1151
+ "name": "mmlu",
1152
+ "sample_len": 14042,
1153
+ "acc,none": 0.36020509898874803,
1154
+ "acc_stderr,none": "N/A",
1155
+ "sample_count": {
1156
+ "acc,none": 14042
1157
+ }
1158
+ },
1159
+ "cmmlu": {
1160
+ "alias": "cmmlu",
1161
+ "name": "cmmlu",
1162
+ "sample_len": 11582,
1163
+ "acc,none": 0.32395095838369886,
1164
+ "acc_stderr,none": "N/A",
1165
+ "acc_norm,none": 0.32395095838369886,
1166
+ "acc_norm_stderr,none": "N/A",
1167
+ "sample_count": {
1168
+ "acc,none": 11582,
1169
+ "acc_norm,none": 11582
1170
+ }
1171
+ }
1172
+ },
1173
+ "lm_eval_groups": {
1174
+ "mmlu_stem": {
1175
+ "alias": "stem",
1176
+ "name": "mmlu_stem",
1177
+ "sample_len": 3153,
1178
+ "acc,none": 0.3212813193783698,
1179
+ "acc_stderr,none": "N/A",
1180
+ "sample_count": {
1181
+ "acc,none": 3153
1182
+ }
1183
+ },
1184
+ "mmlu_other": {
1185
+ "alias": "other",
1186
+ "name": "mmlu_other",
1187
+ "sample_len": 3107,
1188
+ "acc,none": 0.416800772449308,
1189
+ "acc_stderr,none": "N/A",
1190
+ "sample_count": {
1191
+ "acc,none": 3107
1192
+ }
1193
+ },
1194
+ "mmlu_social_sciences": {
1195
+ "alias": "social sciences",
1196
+ "name": "mmlu_social_sciences",
1197
+ "sample_len": 3077,
1198
+ "acc,none": 0.3912902177445564,
1199
+ "acc_stderr,none": "N/A",
1200
+ "sample_count": {
1201
+ "acc,none": 3077
1202
+ }
1203
+ },
1204
+ "mmlu_humanities": {
1205
+ "alias": "humanities",
1206
+ "name": "mmlu_humanities",
1207
+ "sample_len": 4705,
1208
+ "acc,none": 0.328586609989373,
1209
+ "acc_stderr,none": "N/A",
1210
+ "sample_count": {
1211
+ "acc,none": 4705
1212
+ }
1213
+ },
1214
+ "mmlu": {
1215
+ "alias": "mmlu",
1216
+ "name": "mmlu",
1217
+ "sample_len": 14042,
1218
+ "acc,none": 0.36020509898874803,
1219
+ "acc_stderr,none": "N/A",
1220
+ "sample_count": {
1221
+ "acc,none": 14042
1222
+ }
1223
+ },
1224
+ "cmmlu": {
1225
+ "alias": "cmmlu",
1226
+ "name": "cmmlu",
1227
+ "sample_len": 11582,
1228
+ "acc,none": 0.32395095838369886,
1229
+ "acc_stderr,none": "N/A",
1230
+ "acc_norm,none": 0.32395095838369886,
1231
+ "acc_norm_stderr,none": "N/A",
1232
+ "sample_count": {
1233
+ "acc,none": 11582,
1234
+ "acc_norm,none": 11582
1235
+ }
1236
+ }
1237
+ },
1238
+ "lm_eval_versions": {
1239
+ "arc_challenge": 1.0,
1240
+ "arc_easy": 1.0,
1241
+ "cmmlu": "1.0",
1242
+ "cmmlu_agronomy": 1.0,
1243
+ "cmmlu_anatomy": 1.0,
1244
+ "cmmlu_ancient_chinese": 1.0,
1245
+ "cmmlu_arts": 1.0,
1246
+ "cmmlu_astronomy": 1.0,
1247
+ "cmmlu_business_ethics": 1.0,
1248
+ "cmmlu_chinese_civil_service_exam": 1.0,
1249
+ "cmmlu_chinese_driving_rule": 1.0,
1250
+ "cmmlu_chinese_food_culture": 1.0,
1251
+ "cmmlu_chinese_foreign_policy": 1.0,
1252
+ "cmmlu_chinese_history": 1.0,
1253
+ "cmmlu_chinese_literature": 1.0,
1254
+ "cmmlu_chinese_teacher_qualification": 1.0,
1255
+ "cmmlu_clinical_knowledge": 1.0,
1256
+ "cmmlu_college_actuarial_science": 1.0,
1257
+ "cmmlu_college_education": 1.0,
1258
+ "cmmlu_college_engineering_hydrology": 1.0,
1259
+ "cmmlu_college_law": 1.0,
1260
+ "cmmlu_college_mathematics": 1.0,
1261
+ "cmmlu_college_medical_statistics": 1.0,
1262
+ "cmmlu_college_medicine": 1.0,
1263
+ "cmmlu_computer_science": 1.0,
1264
+ "cmmlu_computer_security": 1.0,
1265
+ "cmmlu_conceptual_physics": 1.0,
1266
+ "cmmlu_construction_project_management": 1.0,
1267
+ "cmmlu_economics": 1.0,
1268
+ "cmmlu_education": 1.0,
1269
+ "cmmlu_electrical_engineering": 1.0,
1270
+ "cmmlu_elementary_chinese": 1.0,
1271
+ "cmmlu_elementary_commonsense": 1.0,
1272
+ "cmmlu_elementary_information_and_technology": 1.0,
1273
+ "cmmlu_elementary_mathematics": 1.0,
1274
+ "cmmlu_ethnology": 1.0,
1275
+ "cmmlu_food_science": 1.0,
1276
+ "cmmlu_genetics": 1.0,
1277
+ "cmmlu_global_facts": 1.0,
1278
+ "cmmlu_high_school_biology": 1.0,
1279
+ "cmmlu_high_school_chemistry": 1.0,
1280
+ "cmmlu_high_school_geography": 1.0,
1281
+ "cmmlu_high_school_mathematics": 1.0,
1282
+ "cmmlu_high_school_physics": 1.0,
1283
+ "cmmlu_high_school_politics": 1.0,
1284
+ "cmmlu_human_sexuality": 1.0,
1285
+ "cmmlu_international_law": 1.0,
1286
+ "cmmlu_journalism": 1.0,
1287
+ "cmmlu_jurisprudence": 1.0,
1288
+ "cmmlu_legal_and_moral_basis": 1.0,
1289
+ "cmmlu_logical": 1.0,
1290
+ "cmmlu_machine_learning": 1.0,
1291
+ "cmmlu_management": 1.0,
1292
+ "cmmlu_marketing": 1.0,
1293
+ "cmmlu_marxist_theory": 1.0,
1294
+ "cmmlu_modern_chinese": 1.0,
1295
+ "cmmlu_nutrition": 1.0,
1296
+ "cmmlu_philosophy": 1.0,
1297
+ "cmmlu_professional_accounting": 1.0,
1298
+ "cmmlu_professional_law": 1.0,
1299
+ "cmmlu_professional_medicine": 1.0,
1300
+ "cmmlu_professional_psychology": 1.0,
1301
+ "cmmlu_public_relations": 1.0,
1302
+ "cmmlu_security_study": 1.0,
1303
+ "cmmlu_sociology": 1.0,
1304
+ "cmmlu_sports_science": 1.0,
1305
+ "cmmlu_traditional_chinese_medicine": 1.0,
1306
+ "cmmlu_virology": 1.0,
1307
+ "cmmlu_world_history": 1.0,
1308
+ "cmmlu_world_religions": 1.0,
1309
+ "hellaswag": 1.0,
1310
+ "mmlu": "2",
1311
+ "mmlu_abstract_algebra": 1.0,
1312
+ "mmlu_anatomy": 1.0,
1313
+ "mmlu_astronomy": 1.0,
1314
+ "mmlu_business_ethics": 1.0,
1315
+ "mmlu_clinical_knowledge": 1.0,
1316
+ "mmlu_college_biology": 1.0,
1317
+ "mmlu_college_chemistry": 1.0,
1318
+ "mmlu_college_computer_science": 1.0,
1319
+ "mmlu_college_mathematics": 1.0,
1320
+ "mmlu_college_medicine": 1.0,
1321
+ "mmlu_college_physics": 1.0,
1322
+ "mmlu_computer_security": 1.0,
1323
+ "mmlu_conceptual_physics": 1.0,
1324
+ "mmlu_econometrics": 1.0,
1325
+ "mmlu_electrical_engineering": 1.0,
1326
+ "mmlu_elementary_mathematics": 1.0,
1327
+ "mmlu_formal_logic": 1.0,
1328
+ "mmlu_global_facts": 1.0,
1329
+ "mmlu_high_school_biology": 1.0,
1330
+ "mmlu_high_school_chemistry": 1.0,
1331
+ "mmlu_high_school_computer_science": 1.0,
1332
+ "mmlu_high_school_european_history": 1.0,
1333
+ "mmlu_high_school_geography": 1.0,
1334
+ "mmlu_high_school_government_and_politics": 1.0,
1335
+ "mmlu_high_school_macroeconomics": 1.0,
1336
+ "mmlu_high_school_mathematics": 1.0,
1337
+ "mmlu_high_school_microeconomics": 1.0,
1338
+ "mmlu_high_school_physics": 1.0,
1339
+ "mmlu_high_school_psychology": 1.0,
1340
+ "mmlu_high_school_statistics": 1.0,
1341
+ "mmlu_high_school_us_history": 1.0,
1342
+ "mmlu_high_school_world_history": 1.0,
1343
+ "mmlu_human_aging": 1.0,
1344
+ "mmlu_human_sexuality": 1.0,
1345
+ "mmlu_humanities": "2",
1346
+ "mmlu_international_law": 1.0,
1347
+ "mmlu_jurisprudence": 1.0,
1348
+ "mmlu_logical_fallacies": 1.0,
1349
+ "mmlu_machine_learning": 1.0,
1350
+ "mmlu_management": 1.0,
1351
+ "mmlu_marketing": 1.0,
1352
+ "mmlu_medical_genetics": 1.0,
1353
+ "mmlu_miscellaneous": 1.0,
1354
+ "mmlu_moral_disputes": 1.0,
1355
+ "mmlu_moral_scenarios": 1.0,
1356
+ "mmlu_nutrition": 1.0,
1357
+ "mmlu_other": "2",
1358
+ "mmlu_philosophy": 1.0,
1359
+ "mmlu_prehistory": 1.0,
1360
+ "mmlu_professional_accounting": 1.0,
1361
+ "mmlu_professional_law": 1.0,
1362
+ "mmlu_professional_medicine": 1.0,
1363
+ "mmlu_professional_psychology": 1.0,
1364
+ "mmlu_public_relations": 1.0,
1365
+ "mmlu_security_studies": 1.0,
1366
+ "mmlu_social_sciences": "2",
1367
+ "mmlu_sociology": 1.0,
1368
+ "mmlu_stem": "2",
1369
+ "mmlu_us_foreign_policy": 1.0,
1370
+ "mmlu_virology": 1.0,
1371
+ "mmlu_world_religions": 1.0,
1372
+ "openbookqa": 1.0,
1373
+ "piqa": 1.0,
1374
+ "sciq": 1.0,
1375
+ "winogrande": 1.0
1376
+ },
1377
+ "lm_eval_config": {
1378
+ "model": "/workspace/models/llama31-base-d04e592",
1379
+ "model_args": null,
1380
+ "model_num_parameters": 6285365248,
1381
+ "model_dtype": "torch.bfloat16",
1382
+ "model_revision": "main",
1383
+ "model_sha": "",
1384
+ "batch_size": "auto:4",
1385
+ "batch_sizes": [
1386
+ 64,
1387
+ 64,
1388
+ 64,
1389
+ 64,
1390
+ 64
1391
+ ],
1392
+ "device": null,
1393
+ "use_cache": null,
1394
+ "limit": null,
1395
+ "bootstrap_iters": 0,
1396
+ "gen_kwargs": null,
1397
+ "random_seed": 0,
1398
+ "numpy_seed": 1234,
1399
+ "torch_seed": 1234,
1400
+ "fewshot_seed": 1234
1401
+ }
1402
+ }
runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch1/eval/final_opencompass5.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "/workspace/models/llama31-base-d04e592",
3
+ "revision": "d04e592bb4f6aa9cfee91e2e20afa771667e1d4b",
4
+ "compact_stage": "/workspace/mka-fit-batch-20261126/full/batch1/compact/stage_08",
5
+ "cycle": 8,
6
+ "anchor": 21,
7
+ "tokenizer": "/workspace/models/llama31-base-d04e592",
8
+ "protocol": "OpenCompass 0.5.4 canonical PPL prompts; full-prompt mean CE; lowest PPL",
9
+ "max_batch": 32,
10
+ "token_budget": 8192,
11
+ "limit": null,
12
+ "results": {
13
+ "race-middle": {
14
+ "accuracy": 0.2841225626740947,
15
+ "correct": 408,
16
+ "samples": 1436,
17
+ "choices": 5744
18
+ },
19
+ "race-high": {
20
+ "accuracy": 0.24042309891366495,
21
+ "correct": 841,
22
+ "samples": 3498,
23
+ "choices": 13992
24
+ },
25
+ "C3": {
26
+ "accuracy": 0.4876712328767123,
27
+ "correct": 890,
28
+ "samples": 1825,
29
+ "choices": 7300
30
+ },
31
+ "cmnli": {
32
+ "accuracy": 0.33363287313128015,
33
+ "correct": 4084,
34
+ "samples": 12241,
35
+ "choices": 36723
36
+ },
37
+ "chid-dev": {
38
+ "accuracy": 0.39603960396039606,
39
+ "correct": 80,
40
+ "samples": 202,
41
+ "choices": 1414
42
+ }
43
+ }
44
+ }