diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_01_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_01_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..2cb5b07f60bd75ebca1294d276c824120947e729 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_01_fit.json @@ -0,0 +1,256 @@ +{ + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6240300536155701, + "std": 0.0, + "min": 0.6240300536155701, + "max": 0.6240300536155701, + "mean_abs_from_0_5": 0.12403005361557007, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6240300536155701, + "std": 0.0, + "min": 0.6240300536155701, + "max": 0.6240300536155701, + "mean_abs_from_0_5": 0.12403005361557007 + }, + "mlp.up_proj.weight": { + "mean": 0.6240300536155701, + "std": 0.0, + "min": 0.6240300536155701, + "max": 0.6240300536155701, + "mean_abs_from_0_5": 0.12403005361557007 + }, + "mlp.down_proj.weight": { + "mean": 0.6240300536155701, + "std": 0.0, + "min": 0.6240300536155701, + "max": 0.6240300536155701, + "mean_abs_from_0_5": 0.12403005361557007 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6240301132202148, + "std": 0.00011399101194493286, + "min": 0.6240301132202148, + "max": 0.6240301132202148, + "mean_abs_from_0_5": 0.12403011322021484, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6240301132202148, + "std": 0.00011399101194493286, + "min": 0.6240301132202148, + "max": 0.6240301132202148, + "mean_abs_from_0_5": 0.12403011322021484 + }, + "mlp.up_proj.weight": { + "mean": 0.6240301132202148, + "std": 0.00011399101194493286, + "min": 0.6240301132202148, + "max": 0.6240301132202148, + "mean_abs_from_0_5": 0.12403011322021484 + }, + "mlp.down_proj.weight": { + "mean": 0.6240301132202148, + "std": 0.00011399101194493286, + "min": 0.6240301132202148, + "max": 0.6240301132202148, + "mean_abs_from_0_5": 0.12403011322021484 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.028465702459520677, + "mean_abs": 1.2423996893284355e-06, + "max_abs": 0.00069427490234375 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": 2.854910684661826e-06, + "std": 0.0009041833972203849, + "rms": 0.0009041879043229973, + "mean_abs": 0.0007286663610665571, + "min": -0.006496109068393707, + "max": 0.006071228068321943, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 8.477651655474411e-06, + "std": 0.0009155867578784959, + "rms": 0.0009156260054083475, + "mean_abs": 0.000737509091517755, + "min": -0.00588262639939785, + "max": 0.006071228068321943 + }, + "mlp.up_proj.weight": { + "mean": 1.699711284735323e-07, + "std": 0.0008917679378926515, + "rms": 0.000891767954090915, + "mean_abs": 0.0007192332829747881, + "min": -0.00567873427644372, + "max": 0.0057873912155628204 + }, + "mlp.down_proj.weight": { + "mean": -8.289072996246563e-08, + "std": 0.0009050117272044737, + "rms": 0.000905011731000487, + "mean_abs": 0.0007292567087071282, + "min": -0.006496109068393707, + "max": 0.0059011755511164665 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 173.79743414744735, + "dataset_tokens": 524288, + "tokens_per_second": 3016.6613366409156, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 64399123456, + "peak_reserved_bytes": 76701237248, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6240301169976673, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "4a1304ccf61920a97636331ade2fa8e57952e2592a59a3923abf20b5a1575c49", + "self_attn.k_proj.weight": "6710bf5362c49a99451481e33e0b3ce5e9cd9181d086d75a866e7f16b338c1e3", + "self_attn.v_proj.weight": "30b51dc5274bf74b3e6d4820f1b58e4aa9e2fe144a998c9fb9a5326d746d4e2f", + "self_attn.o_proj.weight": "d438bc8a8906f12fc134841c45241cf5847136143ba1f871b06c29b6eead7d34", + "input_layernorm.weight": "f856da6761e60707e41aac347e76b1e89f061b141683614d6d181ca7940c638c", + "post_attention_layernorm.weight": "392084c4b287c1be3dc86b898f84579f8145d981ccc71d02c85ae14a40da0e3f" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "4a1304ccf61920a97636331ade2fa8e57952e2592a59a3923abf20b5a1575c49", + "self_attn.k_proj.weight": "6710bf5362c49a99451481e33e0b3ce5e9cd9181d086d75a866e7f16b338c1e3", + "self_attn.v_proj.weight": "30b51dc5274bf74b3e6d4820f1b58e4aa9e2fe144a998c9fb9a5326d746d4e2f", + "self_attn.o_proj.weight": "d438bc8a8906f12fc134841c45241cf5847136143ba1f871b06c29b6eead7d34", + "input_layernorm.weight": "f856da6761e60707e41aac347e76b1e89f061b141683614d6d181ca7940c638c", + "post_attention_layernorm.weight": "392084c4b287c1be3dc86b898f84579f8145d981ccc71d02c85ae14a40da0e3f" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "4a1304ccf61920a97636331ade2fa8e57952e2592a59a3923abf20b5a1575c49", + "self_attn.k_proj.weight": "6710bf5362c49a99451481e33e0b3ce5e9cd9181d086d75a866e7f16b338c1e3", + "self_attn.v_proj.weight": "30b51dc5274bf74b3e6d4820f1b58e4aa9e2fe144a998c9fb9a5326d746d4e2f", + "self_attn.o_proj.weight": "d438bc8a8906f12fc134841c45241cf5847136143ba1f871b06c29b6eead7d34", + "input_layernorm.weight": "f856da6761e60707e41aac347e76b1e89f061b141683614d6d181ca7940c638c", + "post_attention_layernorm.weight": "392084c4b287c1be3dc86b898f84579f8145d981ccc71d02c85ae14a40da0e3f" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 22, + "teacher_boundary_original_layer": 22 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_02_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_02_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..6cd72865f1cd2913b132e3d72ba5fee1859b0be9 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_02_fit.json @@ -0,0 +1,256 @@ +{ + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6243720054626465, + "std": 0.0, + "min": 0.6243720054626465, + "max": 0.6243720054626465, + "mean_abs_from_0_5": 0.12437200546264648, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6243720054626465, + "std": 0.0, + "min": 0.6243720054626465, + "max": 0.6243720054626465, + "mean_abs_from_0_5": 0.12437200546264648 + }, + "mlp.up_proj.weight": { + "mean": 0.6243720054626465, + "std": 0.0, + "min": 0.6243720054626465, + "max": 0.6243720054626465, + "mean_abs_from_0_5": 0.12437200546264648 + }, + "mlp.down_proj.weight": { + "mean": 0.6243720054626465, + "std": 0.0, + "min": 0.6243720054626465, + "max": 0.6243720054626465, + "mean_abs_from_0_5": 0.12437200546264648 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6243720650672913, + "std": 8.960509203140518e-05, + "min": 0.6243720650672913, + "max": 0.6243720650672913, + "mean_abs_from_0_5": 0.12437206506729126, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6243720650672913, + "std": 8.960509203140518e-05, + "min": 0.6243720650672913, + "max": 0.6243720650672913, + "mean_abs_from_0_5": 0.12437206506729126 + }, + "mlp.up_proj.weight": { + "mean": 0.6243720650672913, + "std": 8.960509203140518e-05, + "min": 0.6243720650672913, + "max": 0.6243720650672913, + "mean_abs_from_0_5": 0.12437206506729126 + }, + "mlp.down_proj.weight": { + "mean": 0.6243720650672913, + "std": 8.960509203140518e-05, + "min": 0.6243720650672913, + "max": 0.6243720650672913, + "mean_abs_from_0_5": 0.12437206506729126 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.015569758067493491, + "mean_abs": 4.0223484834963787e-07, + "max_abs": 0.0023882389068603516 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": 4.247186996595008e-07, + "std": 0.0008837740109772068, + "rms": 0.0008837741130315563, + "mean_abs": 0.0007097784296742507, + "min": -0.006343320943415165, + "max": 0.00642724335193634, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.45962336059061e-06, + "std": 0.0009102086850955709, + "rms": 0.0009102098554310225, + "mean_abs": 0.0007322642819157668, + "min": -0.006002224050462246, + "max": 0.0061955866403877735 + }, + "mlp.up_proj.weight": { + "mean": -2.081775554480763e-07, + "std": 0.000854396591693673, + "rms": 0.0008543966170553695, + "mean_abs": 0.000685555993446282, + "min": -0.005236032418906689, + "max": 0.005667621269822121 + }, + "mlp.down_proj.weight": { + "mean": 2.2710293835968643e-08, + "std": 0.0008858298301135282, + "rms": 0.0008858298304046437, + "mean_abs": 0.0007115150136607033, + "min": -0.006343320943415165, + "max": 0.00642724335193634 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 168.2695588967763, + "dataset_tokens": 524288, + "tokens_per_second": 3115.7626099300624, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 65810608640, + "peak_reserved_bytes": 80729866240, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6243720763232038, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "6ea5e8782ac8684cc9bd9908f56e75b8947761a05a07420b37900ebba9bbbd06", + "self_attn.k_proj.weight": "915f27233c34e236f5bc3876c4e58174724759412dae919fffe0b0df7317bc47", + "self_attn.v_proj.weight": "2ffe3627c44e10d14be66a5ab2c7546c7173a8d4aa07788f1c2aafab18e8f7af", + "self_attn.o_proj.weight": "d9f7a05b16eea939da003c3fc5f8bd01175179a04eea9d49aeaa2686c3a00386", + "input_layernorm.weight": "2e51ae768cf6bf12d1903474b16741c383154686c8da264bfb44713bacaa0621", + "post_attention_layernorm.weight": "b3191d2dd3776ffff6f3dc74aebe2ddd40c82210ceba22c221eff83b1aeb1f95" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "6ea5e8782ac8684cc9bd9908f56e75b8947761a05a07420b37900ebba9bbbd06", + "self_attn.k_proj.weight": "915f27233c34e236f5bc3876c4e58174724759412dae919fffe0b0df7317bc47", + "self_attn.v_proj.weight": "2ffe3627c44e10d14be66a5ab2c7546c7173a8d4aa07788f1c2aafab18e8f7af", + "self_attn.o_proj.weight": "d9f7a05b16eea939da003c3fc5f8bd01175179a04eea9d49aeaa2686c3a00386", + "input_layernorm.weight": "2e51ae768cf6bf12d1903474b16741c383154686c8da264bfb44713bacaa0621", + "post_attention_layernorm.weight": "b3191d2dd3776ffff6f3dc74aebe2ddd40c82210ceba22c221eff83b1aeb1f95" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "6ea5e8782ac8684cc9bd9908f56e75b8947761a05a07420b37900ebba9bbbd06", + "self_attn.k_proj.weight": "915f27233c34e236f5bc3876c4e58174724759412dae919fffe0b0df7317bc47", + "self_attn.v_proj.weight": "2ffe3627c44e10d14be66a5ab2c7546c7173a8d4aa07788f1c2aafab18e8f7af", + "self_attn.o_proj.weight": "d9f7a05b16eea939da003c3fc5f8bd01175179a04eea9d49aeaa2686c3a00386", + "input_layernorm.weight": "2e51ae768cf6bf12d1903474b16741c383154686c8da264bfb44713bacaa0621", + "post_attention_layernorm.weight": "b3191d2dd3776ffff6f3dc74aebe2ddd40c82210ceba22c221eff83b1aeb1f95" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 19, + "teacher_boundary_original_layer": 19 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_03_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_03_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..518378dac8e175ddc9dddf3185a0dc98c99d3607 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_03_fit.json @@ -0,0 +1,256 @@ +{ + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145 + }, + "mlp.up_proj.weight": { + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145 + }, + "mlp.down_proj.weight": { + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145 + }, + "mlp.up_proj.weight": { + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145 + }, + "mlp.down_proj.weight": { + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.030293374457000595, + "mean_abs": 7.845224315263164e-07, + "max_abs": 0.0031156539916992188 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": 1.8650639470067853e-06, + "std": 0.0007761889496868795, + "rms": 0.0007761911904160905, + "mean_abs": 0.0006255472877195903, + "min": -0.006375117227435112, + "max": 0.006123701576143503, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 5.739701529299575e-06, + "std": 0.0007743511574451851, + "rms": 0.0007743724292679481, + "mean_abs": 0.0006252706183918885, + "min": -0.005891299806535244, + "max": 0.005949811544269323 + }, + "mlp.up_proj.weight": { + "mean": 3.181370849298608e-08, + "std": 0.0007656183632133441, + "rms": 0.000765618363874321, + "mean_abs": 0.000617578426109893, + "min": -0.006375117227435112, + "max": 0.005850381217896938 + }, + "mlp.down_proj.weight": { + "mean": -1.7632339677220443e-07, + "std": 0.0007884124065720728, + "rms": 0.0007884124262888732, + "mean_abs": 0.0006337928186569895, + "min": -0.00629733270034194, + "max": 0.006123701576143503 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 166.4453473757021, + "dataset_tokens": 524288, + "tokens_per_second": 3149.9108161706185, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 60370297344, + "peak_reserved_bytes": 83724599296, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6243202778643895, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "15ddc12b47e73aac3a13f47c90907b9b3ad9d2c2f3b6d92d18150d67a1177b91", + "self_attn.k_proj.weight": "25df896e1d40135244874d105e9d045ad3f36869bad85dac0c3fd644dac8e15d", + "self_attn.v_proj.weight": "8c132171150a34123ce0fe518880c3cbdf0ef21f50997cece69eccc1e61f9856", + "self_attn.o_proj.weight": "fc2860fcbdf78eec3494d3529ad628872ad3c6de62ed63c9c6a3f1d6f1a6d55a", + "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7", + "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "15ddc12b47e73aac3a13f47c90907b9b3ad9d2c2f3b6d92d18150d67a1177b91", + "self_attn.k_proj.weight": "25df896e1d40135244874d105e9d045ad3f36869bad85dac0c3fd644dac8e15d", + "self_attn.v_proj.weight": "8c132171150a34123ce0fe518880c3cbdf0ef21f50997cece69eccc1e61f9856", + "self_attn.o_proj.weight": "fc2860fcbdf78eec3494d3529ad628872ad3c6de62ed63c9c6a3f1d6f1a6d55a", + "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7", + "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "15ddc12b47e73aac3a13f47c90907b9b3ad9d2c2f3b6d92d18150d67a1177b91", + "self_attn.k_proj.weight": "25df896e1d40135244874d105e9d045ad3f36869bad85dac0c3fd644dac8e15d", + "self_attn.v_proj.weight": "8c132171150a34123ce0fe518880c3cbdf0ef21f50997cece69eccc1e61f9856", + "self_attn.o_proj.weight": "fc2860fcbdf78eec3494d3529ad628872ad3c6de62ed63c9c6a3f1d6f1a6d55a", + "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7", + "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 22, + "teacher_boundary_original_layer": 24 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_04_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_04_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..0d4737da5572322e5d4cf01cd08679dc770e50f7 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_04_fit.json @@ -0,0 +1,256 @@ +{ + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6214288473129272, + "std": 4.7565402832764544e-05, + "min": 0.6214288473129272, + "max": 0.6214288473129272, + "mean_abs_from_0_5": 0.12142884731292725, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6214288473129272, + "std": 4.7565402832764544e-05, + "min": 0.6214288473129272, + "max": 0.6214288473129272, + "mean_abs_from_0_5": 0.12142884731292725 + }, + "mlp.up_proj.weight": { + "mean": 0.6214288473129272, + "std": 4.7565402832764544e-05, + "min": 0.6214288473129272, + "max": 0.6214288473129272, + "mean_abs_from_0_5": 0.12142884731292725 + }, + "mlp.down_proj.weight": { + "mean": 0.6214288473129272, + "std": 4.7565402832764544e-05, + "min": 0.6214288473129272, + "max": 0.6214288473129272, + "mean_abs_from_0_5": 0.12142884731292725 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6214287877082825, + "std": 0.0, + "min": 0.6214287877082825, + "max": 0.6214287877082825, + "mean_abs_from_0_5": 0.12142878770828247, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6214287877082825, + "std": 0.0, + "min": 0.6214287877082825, + "max": 0.6214287877082825, + "mean_abs_from_0_5": 0.12142878770828247 + }, + "mlp.up_proj.weight": { + "mean": 0.6214287877082825, + "std": 0.0, + "min": 0.6214287877082825, + "max": 0.6214287877082825, + "mean_abs_from_0_5": 0.12142878770828247 + }, + "mlp.down_proj.weight": { + "mean": 0.6214287877082825, + "std": 0.0, + "min": 0.6214287877082825, + "max": 0.6214287877082825, + "mean_abs_from_0_5": 0.12142878770828247 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.06622738011610237, + "mean_abs": 1.1644387671237512e-06, + "max_abs": 0.010463714599609375 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": 3.683162882831918e-07, + "std": 0.0009767218954390667, + "rms": 0.0009767219648840562, + "mean_abs": 0.0007777905446432886, + "min": -0.0063410247676074505, + "max": 0.00635013822466135, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 9.061984980819813e-07, + "std": 0.0009685778717330229, + "rms": 0.0009685782956512034, + "mean_abs": 0.0007752220013311931, + "min": -0.006030924152582884, + "max": 0.005831782706081867 + }, + "mlp.up_proj.weight": { + "mean": 6.8289247272852145e-09, + "std": 0.0009665684278061907, + "rms": 0.0009665684278303143, + "mean_abs": 0.0007696717179247311, + "min": -0.00573101406916976, + "max": 0.005574765615165234 + }, + "mlp.down_proj.weight": { + "mean": 1.9192144204030877e-07, + "std": 0.0009947657577249627, + "rms": 0.0009947657762387882, + "mean_abs": 0.0007884779146739415, + "min": -0.0063410247676074505, + "max": 0.00635013822466135 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 164.69223202904686, + "dataset_tokens": 524288, + "tokens_per_second": 3183.440976788335, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 54929986048, + "peak_reserved_bytes": 78104231936, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6214287991453509, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "1483e52e20992c5b6111f4478ebc1b2701dbd0b645ccc86c234d6b4c54629bd7", + "self_attn.k_proj.weight": "4167b5b9d247abe59a84bbfc92234908c05f6680322139947a977d62b7a8de8c", + "self_attn.v_proj.weight": "18087bf6d3c06bf1d8233b679c2e146cc82b47e1dbfa85181da20197557b4f27", + "self_attn.o_proj.weight": "2bb782a492fa69fc1555d9d4d878be31196c4627e38a2b3228674c2fb19f059a", + "input_layernorm.weight": "442962ef4923e31f331597e007c41301c88b9cf34900e9e6c9570fba7b887f6d", + "post_attention_layernorm.weight": "16325c0e3226964c4e7ec0b20cd2a522cbd0380ec694f34d9aede17cc217b462" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "1483e52e20992c5b6111f4478ebc1b2701dbd0b645ccc86c234d6b4c54629bd7", + "self_attn.k_proj.weight": "4167b5b9d247abe59a84bbfc92234908c05f6680322139947a977d62b7a8de8c", + "self_attn.v_proj.weight": "18087bf6d3c06bf1d8233b679c2e146cc82b47e1dbfa85181da20197557b4f27", + "self_attn.o_proj.weight": "2bb782a492fa69fc1555d9d4d878be31196c4627e38a2b3228674c2fb19f059a", + "input_layernorm.weight": "442962ef4923e31f331597e007c41301c88b9cf34900e9e6c9570fba7b887f6d", + "post_attention_layernorm.weight": "16325c0e3226964c4e7ec0b20cd2a522cbd0380ec694f34d9aede17cc217b462" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "1483e52e20992c5b6111f4478ebc1b2701dbd0b645ccc86c234d6b4c54629bd7", + "self_attn.k_proj.weight": "4167b5b9d247abe59a84bbfc92234908c05f6680322139947a977d62b7a8de8c", + "self_attn.v_proj.weight": "18087bf6d3c06bf1d8233b679c2e146cc82b47e1dbfa85181da20197557b4f27", + "self_attn.o_proj.weight": "2bb782a492fa69fc1555d9d4d878be31196c4627e38a2b3228674c2fb19f059a", + "input_layernorm.weight": "442962ef4923e31f331597e007c41301c88b9cf34900e9e6c9570fba7b887f6d", + "post_attention_layernorm.weight": "16325c0e3226964c4e7ec0b20cd2a522cbd0380ec694f34d9aede17cc217b462" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 25, + "teacher_boundary_original_layer": 28 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_05_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_05_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..9d41a6cb77ba288491b8ddd13328ded8bbbeacc4 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_05_fit.json @@ -0,0 +1,256 @@ +{ + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6221969723701477, + "std": 0.0, + "min": 0.6221969723701477, + "max": 0.6221969723701477, + "mean_abs_from_0_5": 0.1221969723701477, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6221969723701477, + "std": 0.0, + "min": 0.6221969723701477, + "max": 0.6221969723701477, + "mean_abs_from_0_5": 0.1221969723701477 + }, + "mlp.up_proj.weight": { + "mean": 0.6221969723701477, + "std": 0.0, + "min": 0.6221969723701477, + "max": 0.6221969723701477, + "mean_abs_from_0_5": 0.1221969723701477 + }, + "mlp.down_proj.weight": { + "mean": 0.6221969723701477, + "std": 0.0, + "min": 0.6221969723701477, + "max": 0.6221969723701477, + "mean_abs_from_0_5": 0.1221969723701477 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6221970319747925, + "std": 0.00010575140668483164, + "min": 0.6221970319747925, + "max": 0.6221970319747925, + "mean_abs_from_0_5": 0.12219703197479248, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6221970319747925, + "std": 0.00010575140668483164, + "min": 0.6221970319747925, + "max": 0.6221970319747925, + "mean_abs_from_0_5": 0.12219703197479248 + }, + "mlp.up_proj.weight": { + "mean": 0.6221970319747925, + "std": 0.00010575140668483164, + "min": 0.6221970319747925, + "max": 0.6221970319747925, + "mean_abs_from_0_5": 0.12219703197479248 + }, + "mlp.down_proj.weight": { + "mean": 0.6221970319747925, + "std": 0.00010575140668483164, + "min": 0.6221970319747925, + "max": 0.6221970319747925, + "mean_abs_from_0_5": 0.12219703197479248 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.017244738186102816, + "mean_abs": 5.998026067356391e-07, + "max_abs": 0.0014104843139648438 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": -5.122936548624628e-07, + "std": 0.0008861497273292803, + "rms": 0.0008861498754107833, + "mean_abs": 0.0007082510163031873, + "min": -0.00636459281668067, + "max": 0.006377923768013716, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": -1.5799352175755693e-06, + "std": 0.0008790690587729167, + "rms": 0.000879070478566533, + "mean_abs": 0.0007048696944756168, + "min": -0.00636459281668067, + "max": 0.00579824997112155 + }, + "mlp.up_proj.weight": { + "mean": 2.075030839218276e-08, + "std": 0.000904259461657283, + "rms": 0.0009042594618953648, + "mean_abs": 0.0007221191855413574, + "min": -0.006330917589366436, + "max": 0.005814752075821161 + }, + "mlp.down_proj.weight": { + "mean": 2.2303944595997953e-08, + "std": 0.0008748341121948127, + "rms": 0.0008748341124791328, + "mean_abs": 0.000697764168892588, + "min": -0.006065336987376213, + "max": 0.006377923768013716 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 158.20467386068776, + "dataset_tokens": 524288, + "tokens_per_second": 3313.9855302990527, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 56341469696, + "peak_reserved_bytes": 78932606976, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6221970199569331, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "43c71ff851719b981a17d39c96e58134600d702b67809ffe7e1367354f171f3a", + "self_attn.k_proj.weight": "029697bf31182f605dbe4470fd363c0f4da9b3e774c865e3b502102379acf6fa", + "self_attn.v_proj.weight": "bee45b937525908cad83825ef000c48c65c36c9b42a86342481c8d09f7c8b031", + "self_attn.o_proj.weight": "a7c625ad20b47e2ae39637b93e46fd03ac09ca50d199deb5baf6ae1b60479926", + "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7", + "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "43c71ff851719b981a17d39c96e58134600d702b67809ffe7e1367354f171f3a", + "self_attn.k_proj.weight": "029697bf31182f605dbe4470fd363c0f4da9b3e774c865e3b502102379acf6fa", + "self_attn.v_proj.weight": "bee45b937525908cad83825ef000c48c65c36c9b42a86342481c8d09f7c8b031", + "self_attn.o_proj.weight": "a7c625ad20b47e2ae39637b93e46fd03ac09ca50d199deb5baf6ae1b60479926", + "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7", + "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "43c71ff851719b981a17d39c96e58134600d702b67809ffe7e1367354f171f3a", + "self_attn.k_proj.weight": "029697bf31182f605dbe4470fd363c0f4da9b3e774c865e3b502102379acf6fa", + "self_attn.v_proj.weight": "bee45b937525908cad83825ef000c48c65c36c9b42a86342481c8d09f7c8b031", + "self_attn.o_proj.weight": "a7c625ad20b47e2ae39637b93e46fd03ac09ca50d199deb5baf6ae1b60479926", + "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7", + "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 22, + "teacher_boundary_original_layer": 25 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_06_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_06_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..9515caf43437d7577ea1f47347e317c3e8ffb92d --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_06_fit.json @@ -0,0 +1,256 @@ +{ + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668 + }, + "mlp.up_proj.weight": { + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668 + }, + "mlp.down_proj.weight": { + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668 + }, + "mlp.up_proj.weight": { + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668 + }, + "mlp.down_proj.weight": { + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.015325511073016893, + "mean_abs": 5.175094256195561e-07, + "max_abs": 0.00034111738204956055 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": -9.499538943405891e-07, + "std": 0.0007645287922128008, + "rms": 0.0007645293823881233, + "mean_abs": 0.0006120525123108001, + "min": -0.004902039188891649, + "max": 0.004761568270623684, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": -2.76329176683378e-06, + "std": 0.0008060499610024697, + "rms": 0.0008060546975320421, + "mean_abs": 0.0006482953737889018, + "min": -0.004902039188891649, + "max": 0.004761568270623684 + }, + "mlp.up_proj.weight": { + "mean": -7.554790824672506e-08, + "std": 0.0007344616429140787, + "rms": 0.0007344616467995685, + "mean_abs": 0.0005870084943515914, + "min": -0.004594889469444752, + "max": 0.004446103703230619 + }, + "mlp.down_proj.weight": { + "mean": -1.1022007941262148e-08, + "std": 0.0007512372750668098, + "rms": 0.0007512372751476662, + "mean_abs": 0.0006008536687919072, + "min": -0.004617602098733187, + "max": 0.004696824587881565 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 147.67390455212444, + "dataset_tokens": 524288, + "tokens_per_second": 3550.3090514881196, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 66888679936, + "peak_reserved_bytes": 79958114304, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6211211480841742, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "53e37683daf2b4f755fef4ee6d24b20c07885de290d559e9bd8d0e13a1ad8f81", + "self_attn.k_proj.weight": "7f367d9f19a459039e3a17afefb6c6874147e8a3b60ecd58789c65e8e0cbafb8", + "self_attn.v_proj.weight": "3d69c8dff42f94ffec329af9af7d844de8350c2bbb7da8558e34dc6c186f5f7d", + "self_attn.o_proj.weight": "2015d40b1bcb9a7c46f362a2901ba4b6636f34b496426df97ee99d910e912eed", + "input_layernorm.weight": "215a4054b42dffd42acdc2d290049db92fba6920b1d5cc1e6bdb9d5a2cb4ed6c", + "post_attention_layernorm.weight": "880bfd813c0b0ae9ab6deed30a3dd1aef4ebf2b1fb8604921beb732a83deaf0b" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "53e37683daf2b4f755fef4ee6d24b20c07885de290d559e9bd8d0e13a1ad8f81", + "self_attn.k_proj.weight": "7f367d9f19a459039e3a17afefb6c6874147e8a3b60ecd58789c65e8e0cbafb8", + "self_attn.v_proj.weight": "3d69c8dff42f94ffec329af9af7d844de8350c2bbb7da8558e34dc6c186f5f7d", + "self_attn.o_proj.weight": "2015d40b1bcb9a7c46f362a2901ba4b6636f34b496426df97ee99d910e912eed", + "input_layernorm.weight": "215a4054b42dffd42acdc2d290049db92fba6920b1d5cc1e6bdb9d5a2cb4ed6c", + "post_attention_layernorm.weight": "880bfd813c0b0ae9ab6deed30a3dd1aef4ebf2b1fb8604921beb732a83deaf0b" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "53e37683daf2b4f755fef4ee6d24b20c07885de290d559e9bd8d0e13a1ad8f81", + "self_attn.k_proj.weight": "7f367d9f19a459039e3a17afefb6c6874147e8a3b60ecd58789c65e8e0cbafb8", + "self_attn.v_proj.weight": "3d69c8dff42f94ffec329af9af7d844de8350c2bbb7da8558e34dc6c186f5f7d", + "self_attn.o_proj.weight": "2015d40b1bcb9a7c46f362a2901ba4b6636f34b496426df97ee99d910e912eed", + "input_layernorm.weight": "215a4054b42dffd42acdc2d290049db92fba6920b1d5cc1e6bdb9d5a2cb4ed6c", + "post_attention_layernorm.weight": "880bfd813c0b0ae9ab6deed30a3dd1aef4ebf2b1fb8604921beb732a83deaf0b" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 11, + "teacher_boundary_original_layer": 11 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_07_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_07_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..f09074a33217295f159cb232e74ab76966c3910c --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_07_fit.json @@ -0,0 +1,256 @@ +{ + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218 + }, + "mlp.up_proj.weight": { + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218 + }, + "mlp.down_proj.weight": { + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218 + }, + "mlp.up_proj.weight": { + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218 + }, + "mlp.down_proj.weight": { + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.009353721000454441, + "mean_abs": 2.8153123193554903e-07, + "max_abs": 0.001277327537536621 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": 1.5348852977175348e-06, + "std": 0.0008906192953409906, + "rms": 0.0008906206179437796, + "mean_abs": 0.0007133157036843754, + "min": -0.006191921886056662, + "max": 0.0069657727144658566, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 4.687837125467402e-06, + "std": 0.0009487456182395482, + "rms": 0.0009487571996805385, + "mean_abs": 0.0007639551934387003, + "min": -0.005632347427308559, + "max": 0.0049436092376708984 + }, + "mlp.up_proj.weight": { + "mean": -2.580860609668889e-07, + "std": 0.000862742007209576, + "rms": 0.0008627420458123176, + "mean_abs": 0.0006906303710171155, + "min": -0.004639971535652876, + "max": 0.0049757156521081924 + }, + "mlp.down_proj.weight": { + "mean": 1.7490482865209094e-07, + "std": 0.000857409565592722, + "rms": 0.0008574095834323287, + "mean_abs": 0.0006853615465973105, + "min": -0.006191921886056662, + "max": 0.0069657727144658566 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 148.01820804690942, + "dataset_tokens": 524288, + "tokens_per_second": 3542.050717394474, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 58022471168, + "peak_reserved_bytes": 79513518080, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6229176202047336, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "f1a38d57cf5ef9ca4d1eb5a1f85ff7f3b0e48ca3108da13f083a7eb33304963d", + "self_attn.k_proj.weight": "64e044d1d4c42bdd8ca349d5aa091363741c62366b4097b9bf93f636de401d35", + "self_attn.v_proj.weight": "8ed75a50876602d6bf3c9a28561afab66ee8afa9e161a43048ae5c09211ad6db", + "self_attn.o_proj.weight": "349a7fb4bf47cacf9a61d82e86c1977787bc15eae2c6a148bee210df37b5f0e6", + "input_layernorm.weight": "3136ce06cd326def67ac994dc995f04f4d8677a7c624d2992d3f489e52036507", + "post_attention_layernorm.weight": "cfd7949654b781ca46277155f18c3f381fbfe9ed6d3863ac6953f30f3ea697aa" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "f1a38d57cf5ef9ca4d1eb5a1f85ff7f3b0e48ca3108da13f083a7eb33304963d", + "self_attn.k_proj.weight": "64e044d1d4c42bdd8ca349d5aa091363741c62366b4097b9bf93f636de401d35", + "self_attn.v_proj.weight": "8ed75a50876602d6bf3c9a28561afab66ee8afa9e161a43048ae5c09211ad6db", + "self_attn.o_proj.weight": "349a7fb4bf47cacf9a61d82e86c1977787bc15eae2c6a148bee210df37b5f0e6", + "input_layernorm.weight": "3136ce06cd326def67ac994dc995f04f4d8677a7c624d2992d3f489e52036507", + "post_attention_layernorm.weight": "cfd7949654b781ca46277155f18c3f381fbfe9ed6d3863ac6953f30f3ea697aa" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "f1a38d57cf5ef9ca4d1eb5a1f85ff7f3b0e48ca3108da13f083a7eb33304963d", + "self_attn.k_proj.weight": "64e044d1d4c42bdd8ca349d5aa091363741c62366b4097b9bf93f636de401d35", + "self_attn.v_proj.weight": "8ed75a50876602d6bf3c9a28561afab66ee8afa9e161a43048ae5c09211ad6db", + "self_attn.o_proj.weight": "349a7fb4bf47cacf9a61d82e86c1977787bc15eae2c6a148bee210df37b5f0e6", + "input_layernorm.weight": "3136ce06cd326def67ac994dc995f04f4d8677a7c624d2992d3f489e52036507", + "post_attention_layernorm.weight": "cfd7949654b781ca46277155f18c3f381fbfe9ed6d3863ac6953f30f3ea697aa" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 17, + "teacher_boundary_original_layer": 18 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_08_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_08_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..f1632b19e8227f32c829a77221779381a93a7ecd --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/cycle_08_fit.json @@ -0,0 +1,256 @@ +{ + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862 + }, + "mlp.up_proj.weight": { + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862 + }, + "mlp.down_proj.weight": { + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862 + }, + "mlp.up_proj.weight": { + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862 + }, + "mlp.down_proj.weight": { + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.009576967976147916, + "mean_abs": 2.923745363486454e-07, + "max_abs": 0.0009045600891113281 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": 1.0223904117386458e-06, + "std": 0.0009100702131976495, + "rms": 0.0009100707874840118, + "mean_abs": 0.0007217294270438808, + "min": -0.005950410384684801, + "max": 0.006033126264810562, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 3.1802483135834336e-06, + "std": 0.0009605824510155752, + "rms": 0.0009605877155046415, + "mean_abs": 0.000767326115497521, + "min": -0.005950410384684801, + "max": 0.006033126264810562 + }, + "mlp.up_proj.weight": { + "mean": -2.316466764438831e-07, + "std": 0.0009094989642336212, + "rms": 0.00090949899373348, + "mean_abs": 0.000719951931387186, + "min": -0.005685383919626474, + "max": 0.005684840492904186 + }, + "mlp.down_proj.weight": { + "mean": 1.1856959807638695e-07, + "std": 0.0008571868651909685, + "rms": 0.0008571868733914847, + "mean_abs": 0.0006779102342469352, + "min": -0.005608192179352045, + "max": 0.005835949908941984 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 144.06955006718636, + "dataset_tokens": 524288, + "tokens_per_second": 3639.1312373468236, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 56008057344, + "peak_reserved_bytes": 77118570496, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6223904334015297, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "c2d269beae16d485167c22a3e390eb1009f2f29db5a15ccf6608b3e152183b0e", + "self_attn.k_proj.weight": "2eddd8dce925c09c5aae054e0abd9de0f49d179db37a2eba7d63d205fe9f2736", + "self_attn.v_proj.weight": "48a7a8be43dddd6b910a909a30dd1b2949c3b9c63ac97a37e894f5bfd1fd6787", + "self_attn.o_proj.weight": "7fd00db7930f63d6d9ea5ae7887847bbdbbd2012a69e4510211048d000d29005", + "input_layernorm.weight": "3136ce06cd326def67ac994dc995f04f4d8677a7c624d2992d3f489e52036507", + "post_attention_layernorm.weight": "cfd7949654b781ca46277155f18c3f381fbfe9ed6d3863ac6953f30f3ea697aa" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "c2d269beae16d485167c22a3e390eb1009f2f29db5a15ccf6608b3e152183b0e", + "self_attn.k_proj.weight": "2eddd8dce925c09c5aae054e0abd9de0f49d179db37a2eba7d63d205fe9f2736", + "self_attn.v_proj.weight": "48a7a8be43dddd6b910a909a30dd1b2949c3b9c63ac97a37e894f5bfd1fd6787", + "self_attn.o_proj.weight": "7fd00db7930f63d6d9ea5ae7887847bbdbbd2012a69e4510211048d000d29005", + "input_layernorm.weight": "3136ce06cd326def67ac994dc995f04f4d8677a7c624d2992d3f489e52036507", + "post_attention_layernorm.weight": "cfd7949654b781ca46277155f18c3f381fbfe9ed6d3863ac6953f30f3ea697aa" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "c2d269beae16d485167c22a3e390eb1009f2f29db5a15ccf6608b3e152183b0e", + "self_attn.k_proj.weight": "2eddd8dce925c09c5aae054e0abd9de0f49d179db37a2eba7d63d205fe9f2736", + "self_attn.v_proj.weight": "48a7a8be43dddd6b910a909a30dd1b2949c3b9c63ac97a37e894f5bfd1fd6787", + "self_attn.o_proj.weight": "7fd00db7930f63d6d9ea5ae7887847bbdbbd2012a69e4510211048d000d29005", + "input_layernorm.weight": "3136ce06cd326def67ac994dc995f04f4d8677a7c624d2992d3f489e52036507", + "post_attention_layernorm.weight": "cfd7949654b781ca46277155f18c3f381fbfe9ed6d3863ac6953f30f3ea697aa" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 17, + "teacher_boundary_original_layer": 20 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/data_fingerprints.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/data_fingerprints.json new file mode 100644 index 0000000000000000000000000000000000000000..2786003446bc0efdd2631166f7017f4beeab263b --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/data_fingerprints.json @@ -0,0 +1,14 @@ +{ + "calib_loader": { + "sequences": 64, + "sha256": "fa4a6219f7a7b17364eef6b5b7771533b57a407f1d26db1d483bbd955814ce38", + "attention_mask_sha256": "b1476de1907209012e63fa502715fd97db26e595352faa808d8c10433a1472a4", + "valid_tokens": 65536 + }, + "distill_loader": { + "sequences": 512, + "sha256": "2b2d044c8c040f67891817ecc110f0fa0de2f469db4c6731114ff7816bbf1cd0", + "attention_mask_sha256": "c8e7f8e30cd532b82e6af4b98d596bc7106f29f9fb2b398b44355e624898a30d", + "valid_tokens": 524288 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/selection.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/selection.json new file mode 100644 index 0000000000000000000000000000000000000000..45f7115a7c3ec9f08cb39145859b95e9cf79d5d4 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/selection.json @@ -0,0 +1,7706 @@ +[ + { + "cycle": 1, + "pair_index": 21, + "initializer": "mka", + "lambda_left": 0.6240301169976673, + "recipient_original_layer": 21, + "recipient_side": "left", + "removed_original_layer": 22, + "npib_matrix": [ + [ + 2.3598368318150484, + 0.3443452304720188, + 0.9511127221245259, + 0.6904843093120027, + 0.6690162505343388, + 0.6512097574296891, + 0.631399187420879, + 0.5855134762308328, + 0.6074206194778445, + 0.6555240534054558, + 0.49958804122731876, + 0.6371923983001465, + 0.4417405635438939, + 0.5458261478339751, + 0.5147575575305561, + 0.5456280200378638, + 0.5119727444468924, + 0.4906904475143589, + 0.49686980422873356, + 0.5007548737037725, + 0.4909326049611054, + 0.41671024690974307, + 0.4387471977747883, + 0.39685065206404935, + 0.43174035090641505, + 0.4322034766073971, + 0.500242508592751, + 0.481475617859331, + 0.44658150792035717, + 0.5508606965071854, + 0.6514947846794727, + 0.39482596703050005 + ], + [ + 0.3443452304720188, + 2.391816699157234, + 0.6105530658931005, + 0.4443044467140416, + 0.4158723960081373, + 0.40098832660997547, + 0.35615130217538943, + 0.43519508514758576, + 0.3503926486536749, + 0.33321429661265745, + 0.33267757715099683, + 0.37623434210878476, + 0.32133205919801977, + 0.3490059585089323, + 0.3660249748943472, + 0.3114854567755884, + 0.2663593264561916, + 0.2697431210006974, + 0.23969181081364918, + 0.20237086665596765, + 0.22902198478287483, + 0.22188175667574367, + 0.22098790332254636, + 0.23390728366569083, + 0.2560451048255479, + 0.2680148119306393, + 0.28035639827742287, + 0.30750722863409474, + 0.28784943246013434, + 0.32759881757054604, + 0.37074971141649987, + 0.3293382174223876 + ], + [ + 0.9511127221245259, + 0.6105530658931005, + 2.4034261954132092, + 1.172988635221176, + 0.9543480188379591, + 0.8217904224586922, + 0.805130531492367, + 0.8220121195811046, + 0.7808879677224255, + 0.7198356581526952, + 0.6651786755142716, + 0.7394256448693735, + 0.5932303151559802, + 0.6590574115563346, + 0.5715370352061608, + 0.6433894891957147, + 0.6561537291529483, + 0.5636594465267478, + 0.4960923859903253, + 0.4504579792228191, + 0.503964847276733, + 0.4818954454181723, + 0.47437967935982867, + 0.4422984249053836, + 0.4578287650549084, + 0.4703924079149479, + 0.4198416250207986, + 0.46747794648653784, + 0.4235432814471379, + 0.5423763435477104, + 0.6124439821104768, + 0.49988283736870626 + ], + [ + 0.6904843093120027, + 0.4443044467140416, + 1.172988635221176, + 2.3196693821091636, + 1.4078769588470965, + 1.183936344408245, + 1.1082009322507629, + 0.9869828327866518, + 0.9597145887539139, + 0.8597942447782176, + 0.8324508551527933, + 0.905095248097947, + 0.6673620409811332, + 0.5916311920292769, + 0.5334841931361148, + 0.7273803335574809, + 0.7331561725301285, + 0.634557790255331, + 0.5933998637935438, + 0.5456125833358797, + 0.5818430579093835, + 0.5181523059977853, + 0.4757999158509575, + 0.4055742836599909, + 0.42106474256647436, + 0.4252603030372225, + 0.36087259606458394, + 0.39713352919186096, + 0.3682254385912048, + 0.5155635647736617, + 0.558499014278503, + 0.40115530415785605 + ], + [ + 0.6690162505343388, + 0.4158723960081373, + 0.9543480188379591, + 1.4078769588470965, + 2.2720808664678995, + 1.485803190155229, + 1.327137744734443, + 0.9471235684848248, + 1.041610642885693, + 0.9573001564339423, + 0.9696052598995775, + 1.007237442000292, + 0.7128891436386944, + 0.6222556937347655, + 0.568017177630325, + 0.8534056937268815, + 0.8583181137894533, + 0.7680260770400199, + 0.62131871323841, + 0.6217868869928156, + 0.6111352783152795, + 0.5395096885019625, + 0.5145518880086186, + 0.4366874358328202, + 0.4601208200988597, + 0.46021490180546626, + 0.39833060299545137, + 0.4125271325788956, + 0.41447218245834994, + 0.5664972167009787, + 0.6180715847107823, + 0.35951647159338135 + ], + [ + 0.6512097574296891, + 0.40098832660997547, + 0.8217904224586922, + 1.183936344408245, + 1.485803190155229, + 2.2967483552546537, + 1.2091134623365896, + 0.8585350462054803, + 1.0042500648005865, + 1.0018474416582548, + 0.9933762252232546, + 0.9621227995153653, + 0.696909302382986, + 0.6173209992447204, + 0.584492383082575, + 0.9417926684185647, + 0.9804920771997399, + 0.8654061944230085, + 0.7360931751284087, + 0.7221598881518954, + 0.7223459997169059, + 0.6156795213393015, + 0.5468737586504832, + 0.45825086860279507, + 0.4799151930560324, + 0.4767380978545758, + 0.40466452279346693, + 0.4568184952230524, + 0.5045926674997778, + 0.58435645849721, + 0.6256388458718639, + 0.31967495199986407 + ], + [ + 0.631399187420879, + 0.35615130217538943, + 0.805130531492367, + 1.1082009322507629, + 1.327137744734443, + 1.2091134623365896, + 2.3477764543003454, + 1.3226532341597808, + 1.391330620637103, + 1.1491906635237006, + 1.330624622598439, + 1.2899779542933039, + 0.9812795935011823, + 0.8137354257801147, + 0.7128203622741097, + 1.0943587368970968, + 0.9169852285979067, + 0.7489303132311632, + 0.5957700393761652, + 0.5772984839799916, + 0.5728788366708345, + 0.522146633389984, + 0.5108383850179606, + 0.4511957005788042, + 0.4455230063974084, + 0.4830623854063782, + 0.40709548726126416, + 0.4655207218266681, + 0.45957553340504287, + 0.543734117746918, + 0.6158380671576326, + 0.3550066549521344 + ], + [ + 0.5855134762308328, + 0.43519508514758576, + 0.8220121195811046, + 0.9869828327866518, + 0.9471235684848248, + 0.8585350462054803, + 1.3226532341597808, + 2.4645174274691333, + 1.5029144393235752, + 0.9573721322151795, + 1.2301516083629374, + 1.2305852484401933, + 1.1399072532624648, + 0.9239914450556869, + 0.8093851963034749, + 0.9379028784095761, + 0.731517385991915, + 0.6448813877703499, + 0.5379667729294401, + 0.5294864880277178, + 0.5079667389303936, + 0.5245803699416272, + 0.4744845202580027, + 0.4327224542434812, + 0.44834531875717765, + 0.43254923506795145, + 0.368549686861022, + 0.4126745519742891, + 0.39345964030083375, + 0.45211889834829105, + 0.49528232901619434, + 0.4126838584327378 + ], + [ + 0.6074206194778445, + 0.3503926486536749, + 0.7808879677224255, + 0.9597145887539139, + 1.041610642885693, + 1.0042500648005865, + 1.391330620637103, + 1.5029144393235752, + 2.4052196230162677, + 1.2619624752451808, + 1.6629277581695627, + 1.4891374132962578, + 1.0460814411649866, + 0.8646820523019201, + 0.8616511378320537, + 1.0424249204378506, + 0.8597179961702175, + 0.6853907014738974, + 0.5306082981407941, + 0.5436825114832436, + 0.5639931871899226, + 0.52980676925778, + 0.49248867468811364, + 0.473341002455841, + 0.480735575990032, + 0.4484756313777117, + 0.3556208623890435, + 0.4326442045787333, + 0.42869715692477955, + 0.5122915143876665, + 0.536795980355824, + 0.3913663687079706 + ], + [ + 0.6555240534054558, + 0.33321429661265745, + 0.7198356581526952, + 0.8597942447782176, + 0.9573001564339423, + 1.0018474416582548, + 1.1491906635237006, + 0.9573721322151795, + 1.2619624752451808, + 2.4560572801455933, + 1.483543481961692, + 1.3405276365717165, + 0.873279151443917, + 0.7367176797293109, + 0.7671022375573167, + 0.9327855360635636, + 1.0918270331754372, + 0.8987631835322829, + 0.7411743452192853, + 0.678290115979759, + 0.7157675345161907, + 0.6224539967309892, + 0.5907158321563325, + 0.4757131277143376, + 0.5357051886846795, + 0.5834946353512401, + 0.5022765077438472, + 0.5295977082224858, + 0.5383664811130305, + 0.6285712649266708, + 0.6979284053832475, + 0.3940685939911559 + ], + [ + 0.49958804122731876, + 0.33267757715099683, + 0.6651786755142716, + 0.8324508551527933, + 0.9696052598995775, + 0.9933762252232546, + 1.330624622598439, + 1.2301516083629374, + 1.6629277581695627, + 1.483543481961692, + 2.4914126330956137, + 1.6929237795968073, + 1.0771191337248727, + 0.8883623835176718, + 0.8878595069664904, + 1.1132836387670426, + 1.032671214420258, + 0.8192048616297526, + 0.6034947248735233, + 0.5700481723700193, + 0.5774935292201491, + 0.583770828800659, + 0.5388271795933294, + 0.4698853943900148, + 0.49620617590182514, + 0.47235331136426406, + 0.37845442673241386, + 0.432039302776271, + 0.46846035830225224, + 0.521121567590533, + 0.5466094111102114, + 0.3690309990865931 + ], + [ + 0.6371923983001465, + 0.37623434210878476, + 0.7394256448693735, + 0.905095248097947, + 1.007237442000292, + 0.9621227995153653, + 1.2899779542933039, + 1.2305852484401933, + 1.4891374132962578, + 1.3405276365717165, + 1.6929237795968073, + 2.510786418656704, + 1.105015632231669, + 0.9460946269422356, + 0.9918068018658639, + 1.1470943292218765, + 1.0083643873866202, + 0.8081600544791975, + 0.6278828228343547, + 0.6054836053118589, + 0.6255044767875986, + 0.5900823552660293, + 0.5414767167058885, + 0.4479253362313485, + 0.49692362744848345, + 0.5113580137489129, + 0.4471429184397226, + 0.4867092136241807, + 0.5024785251683773, + 0.5464054321823507, + 0.584632351047142, + 0.4216823412541298 + ], + [ + 0.4417405635438939, + 0.32133205919801977, + 0.5932303151559802, + 0.6673620409811332, + 0.7128891436386944, + 0.696909302382986, + 0.9812795935011823, + 1.1399072532624648, + 1.0460814411649866, + 0.873279151443917, + 1.0771191337248727, + 1.105015632231669, + 2.4424500948199106, + 1.2331711378465116, + 0.9869157393394576, + 0.9785032314839748, + 0.6539071204830524, + 0.5355085539514636, + 0.5089888208180045, + 0.48279766211029607, + 0.4703556965468468, + 0.49414077600156814, + 0.4288636618234584, + 0.3872519631929014, + 0.39628148652610834, + 0.4151450648944335, + 0.30457255176326703, + 0.3523815030275264, + 0.41326208695582894, + 0.41955856650584505, + 0.49659899187849804, + 0.3839089053761638 + ], + [ + 0.5458261478339751, + 0.3490059585089323, + 0.6590574115563346, + 0.5916311920292769, + 0.6222556937347655, + 0.6173209992447204, + 0.8137354257801147, + 0.9239914450556869, + 0.8646820523019201, + 0.7367176797293109, + 0.8883623835176718, + 0.9460946269422356, + 1.2331711378465116, + 2.4086109155702577, + 1.1621077679013359, + 0.8982730203378348, + 0.6927039380229185, + 0.6290895770560241, + 0.593551381925273, + 0.5543999780243056, + 0.5728756049449134, + 0.5798883340256388, + 0.4893338307676691, + 0.435936337703488, + 0.47641661565960836, + 0.5003655228731798, + 0.4490379530139086, + 0.4153813004697292, + 0.4628492628331043, + 0.46845416226985, + 0.5107506481678791, + 0.4239956465214684 + ], + [ + 0.5147575575305561, + 0.3660249748943472, + 0.5715370352061608, + 0.5334841931361148, + 0.568017177630325, + 0.584492383082575, + 0.7128203622741097, + 0.8093851963034749, + 0.8616511378320537, + 0.7671022375573167, + 0.8878595069664904, + 0.9918068018658639, + 0.9869157393394576, + 1.1621077679013359, + 2.4712107267688586, + 0.8577210081001834, + 0.674081272784002, + 0.5751414578932731, + 0.5355574777097107, + 0.5178368856962178, + 0.5401823826449512, + 0.5230943313115047, + 0.4863531830990153, + 0.44152176715232216, + 0.4590583351476515, + 0.4855642576483593, + 0.41789850817829466, + 0.4175032010527429, + 0.46237204976690616, + 0.45043312286605597, + 0.514917149889001, + 0.5373022221316843 + ], + [ + 0.5456280200378638, + 0.3114854567755884, + 0.6433894891957147, + 0.7273803335574809, + 0.8534056937268815, + 0.9417926684185647, + 1.0943587368970968, + 0.9379028784095761, + 1.0424249204378506, + 0.9327855360635636, + 1.1132836387670426, + 1.1470943292218765, + 0.9785032314839748, + 0.8982730203378348, + 0.8577210081001834, + 2.35422460389475, + 1.1181007818213686, + 0.8714307710618016, + 0.7187184547841231, + 0.6883113128284807, + 0.6502884814966043, + 0.5963153732456243, + 0.529745985691747, + 0.5092733281430033, + 0.5119474481678267, + 0.5450628734731863, + 0.45712508829694054, + 0.47026310358054507, + 0.49142077024067776, + 0.5056598815070166, + 0.5771570490994211, + 0.3124591887208858 + ], + [ + 0.5119727444468924, + 0.2663593264561916, + 0.6561537291529483, + 0.7331561725301285, + 0.8583181137894533, + 0.9804920771997399, + 0.9169852285979067, + 0.731517385991915, + 0.8597179961702175, + 1.0918270331754372, + 1.032671214420258, + 1.0083643873866202, + 0.6539071204830524, + 0.6927039380229185, + 0.674081272784002, + 1.1181007818213686, + 2.364160616417643, + 1.406379212095852, + 1.066597488922481, + 0.9713519524329484, + 0.9853070600751667, + 0.7883326850034772, + 0.7277145459739254, + 0.6161355430225458, + 0.6525965187640944, + 0.643997055502672, + 0.5334950150985914, + 0.601092110423163, + 0.6144073509761494, + 0.7409705031559474, + 0.7685763630116533, + 0.2810645082871226 + ], + [ + 0.4906904475143589, + 0.2697431210006974, + 0.5636594465267478, + 0.634557790255331, + 0.7680260770400199, + 0.8654061944230085, + 0.7489303132311632, + 0.6448813877703499, + 0.6853907014738974, + 0.8987631835322829, + 0.8192048616297526, + 0.8081600544791975, + 0.5355085539514636, + 0.6290895770560241, + 0.5751414578932731, + 0.8714307710618016, + 1.406379212095852, + 2.375249320052241, + 1.3307167716858816, + 1.2188380316969656, + 1.2921693180252614, + 0.9813781213863277, + 0.8675050326619157, + 0.6789747704775959, + 0.7487689844432894, + 0.66732757693249, + 0.6491084666761803, + 0.7298290629474359, + 0.6962626153942411, + 0.8603765679867883, + 0.8552138662399789, + 0.27081192736622073 + ], + [ + 0.49686980422873356, + 0.23969181081364918, + 0.4960923859903253, + 0.5933998637935438, + 0.62131871323841, + 0.7360931751284087, + 0.5957700393761652, + 0.5379667729294401, + 0.5306082981407941, + 0.7411743452192853, + 0.6034947248735233, + 0.6278828228343547, + 0.5089888208180045, + 0.593551381925273, + 0.5355574777097107, + 0.7187184547841231, + 1.066597488922481, + 1.3307167716858816, + 2.554491403562512, + 1.8411160089685985, + 1.9021849031385998, + 1.409127822506441, + 1.227421274532488, + 1.0045338814331073, + 1.0102281393269974, + 0.9065874256586741, + 0.820341302932184, + 0.9204273034826517, + 0.9444737117502111, + 1.0538450230996865, + 0.983390346847638, + 0.35259660481292165 + ], + [ + 0.5007548737037725, + 0.20237086665596765, + 0.4504579792228191, + 0.5456125833358797, + 0.6217868869928156, + 0.7221598881518954, + 0.5772984839799916, + 0.5294864880277178, + 0.5436825114832436, + 0.678290115979759, + 0.5700481723700193, + 0.6054836053118589, + 0.48279766211029607, + 0.5543999780243056, + 0.5178368856962178, + 0.6883113128284807, + 0.9713519524329484, + 1.2188380316969656, + 1.8411160089685985, + 2.5553993179009056, + 1.7502012123430974, + 1.5689423676484757, + 1.3581492365840062, + 1.1112474856123096, + 1.0782459803923432, + 0.9244614543234807, + 0.8277944467571421, + 0.9258866126200027, + 0.9325043069692235, + 1.0081108631780855, + 0.9187726410370608, + 0.3443873796467296 + ], + [ + 0.4909326049611054, + 0.22902198478287483, + 0.503964847276733, + 0.5818430579093835, + 0.6111352783152795, + 0.7223459997169059, + 0.5728788366708345, + 0.5079667389303936, + 0.5639931871899226, + 0.7157675345161907, + 0.5774935292201491, + 0.6255044767875986, + 0.4703556965468468, + 0.5728756049449134, + 0.5401823826449512, + 0.6502884814966043, + 0.9853070600751667, + 1.2921693180252614, + 1.9021849031385998, + 1.7502012123430974, + 2.5317678160262354, + 1.4062434844826273, + 1.2243459751269488, + 0.9797280801221611, + 1.0386664534760275, + 0.9279992553042722, + 0.8669036379159782, + 0.9886587043107198, + 1.0204477500009674, + 1.1690476205954352, + 1.060093979897247, + 0.37387602129746506 + ], + [ + 0.41671024690974307, + 0.22188175667574367, + 0.4818954454181723, + 0.5181523059977853, + 0.5395096885019625, + 0.6156795213393015, + 0.522146633389984, + 0.5245803699416272, + 0.52980676925778, + 0.6224539967309892, + 0.583770828800659, + 0.5900823552660293, + 0.49414077600156814, + 0.5798883340256388, + 0.5230943313115047, + 0.5963153732456243, + 0.7883326850034772, + 0.9813781213863277, + 1.409127822506441, + 1.5689423676484757, + 1.4062434844826273, + 2.612521802223467, + 1.928525358648791, + 1.517284160205908, + 1.4123471963993008, + 1.1304092517080433, + 0.957029492064757, + 1.025258266883139, + 1.0481234957139045, + 1.0276080698511403, + 0.9127447106731977, + 0.3931592331427885 + ], + [ + 0.4387471977747883, + 0.22098790332254636, + 0.47437967935982867, + 0.4757999158509575, + 0.5145518880086186, + 0.5468737586504832, + 0.5108383850179606, + 0.4744845202580027, + 0.49248867468811364, + 0.5907158321563325, + 0.5388271795933294, + 0.5414767167058885, + 0.4288636618234584, + 0.4893338307676691, + 0.4863531830990153, + 0.529745985691747, + 0.7277145459739254, + 0.8675050326619157, + 1.227421274532488, + 1.3581492365840062, + 1.2243459751269488, + 1.928525358648791, + 2.5215636053431267, + 1.6967282931685714, + 1.6214021765846605, + 1.2560859315321182, + 1.0468561590304648, + 1.098644182553855, + 1.1036843223663502, + 1.0300426646320324, + 0.8815651988002146, + 0.38244786921348634 + ], + [ + 0.39685065206404935, + 0.23390728366569083, + 0.4422984249053836, + 0.4055742836599909, + 0.4366874358328202, + 0.45825086860279507, + 0.4511957005788042, + 0.4327224542434812, + 0.473341002455841, + 0.4757131277143376, + 0.4698853943900148, + 0.4479253362313485, + 0.3872519631929014, + 0.435936337703488, + 0.44152176715232216, + 0.5092733281430033, + 0.6161355430225458, + 0.6789747704775959, + 1.0045338814331073, + 1.1112474856123096, + 0.9797280801221611, + 1.517284160205908, + 1.6967282931685714, + 2.5452477219845417, + 1.7691084743004584, + 1.3333116669465275, + 1.0713190430324606, + 1.0498036675108549, + 1.0454719784431084, + 0.9285289360144396, + 0.8129164819514269, + 0.4147811281532504 + ], + [ + 0.43174035090641505, + 0.2560451048255479, + 0.4578287650549084, + 0.42106474256647436, + 0.4601208200988597, + 0.4799151930560324, + 0.4455230063974084, + 0.44834531875717765, + 0.480735575990032, + 0.5357051886846795, + 0.49620617590182514, + 0.49692362744848345, + 0.39628148652610834, + 0.47641661565960836, + 0.4590583351476515, + 0.5119474481678267, + 0.6525965187640944, + 0.7487689844432894, + 1.0102281393269974, + 1.0782459803923432, + 1.0386664534760275, + 1.4123471963993008, + 1.6214021765846605, + 1.7691084743004584, + 2.4762545854541904, + 1.6661606141271548, + 1.2233109656584273, + 1.2264565574723074, + 1.199297006208594, + 1.0714015077948558, + 0.8371357399329575, + 0.4329284583907527 + ], + [ + 0.4322034766073971, + 0.2680148119306393, + 0.4703924079149479, + 0.4252603030372225, + 0.46021490180546626, + 0.4767380978545758, + 0.4830623854063782, + 0.43254923506795145, + 0.4484756313777117, + 0.5834946353512401, + 0.47235331136426406, + 0.5113580137489129, + 0.4151450648944335, + 0.5003655228731798, + 0.4855642576483593, + 0.5450628734731863, + 0.643997055502672, + 0.66732757693249, + 0.9065874256586741, + 0.9244614543234807, + 0.9279992553042722, + 1.1304092517080433, + 1.2560859315321182, + 1.3333116669465275, + 1.6661606141271548, + 2.3495556464839207, + 1.3543646166225316, + 1.420862758304908, + 1.410002017466233, + 1.1685869444873658, + 0.861714400281723, + 0.4320710520570215 + ], + [ + 0.500242508592751, + 0.28035639827742287, + 0.4198416250207986, + 0.36087259606458394, + 0.39833060299545137, + 0.40466452279346693, + 0.40709548726126416, + 0.368549686861022, + 0.3556208623890435, + 0.5022765077438472, + 0.37845442673241386, + 0.4471429184397226, + 0.30457255176326703, + 0.4490379530139086, + 0.41789850817829466, + 0.45712508829694054, + 0.5334950150985914, + 0.6491084666761803, + 0.820341302932184, + 0.8277944467571421, + 0.8669036379159782, + 0.957029492064757, + 1.0468561590304648, + 1.0713190430324606, + 1.2233109656584273, + 1.3543646166225316, + 2.494595543705533, + 1.5336951404235857, + 1.3765187561907508, + 1.2017909959100128, + 0.8593463653761192, + 0.37335736107989964 + ], + [ + 0.481475617859331, + 0.30750722863409474, + 0.46747794648653784, + 0.39713352919186096, + 0.4125271325788956, + 0.4568184952230524, + 0.4655207218266681, + 0.4126745519742891, + 0.4326442045787333, + 0.5295977082224858, + 0.432039302776271, + 0.4867092136241807, + 0.3523815030275264, + 0.4153813004697292, + 0.4175032010527429, + 0.47026310358054507, + 0.601092110423163, + 0.7298290629474359, + 0.9204273034826517, + 0.9258866126200027, + 0.9886587043107198, + 1.025258266883139, + 1.098644182553855, + 1.0498036675108549, + 1.2264565574723074, + 1.420862758304908, + 1.5336951404235857, + 2.425739729275032, + 1.9045005494769904, + 1.5017977357556944, + 0.9975537728050332, + 0.4151471273153199 + ], + [ + 0.44658150792035717, + 0.28784943246013434, + 0.4235432814471379, + 0.3682254385912048, + 0.41447218245834994, + 0.5045926674997778, + 0.45957553340504287, + 0.39345964030083375, + 0.42869715692477955, + 0.5383664811130305, + 0.46846035830225224, + 0.5024785251683773, + 0.41326208695582894, + 0.4628492628331043, + 0.46237204976690616, + 0.49142077024067776, + 0.6144073509761494, + 0.6962626153942411, + 0.9444737117502111, + 0.9325043069692235, + 1.0204477500009674, + 1.0481234957139045, + 1.1036843223663502, + 1.0454719784431084, + 1.199297006208594, + 1.410002017466233, + 1.3765187561907508, + 1.9045005494769904, + 2.416587692763311, + 1.4764802942245, + 0.9996880525868025, + 0.4878069800099702 + ], + [ + 0.5508606965071854, + 0.32759881757054604, + 0.5423763435477104, + 0.5155635647736617, + 0.5664972167009787, + 0.58435645849721, + 0.543734117746918, + 0.45211889834829105, + 0.5122915143876665, + 0.6285712649266708, + 0.521121567590533, + 0.5464054321823507, + 0.41955856650584505, + 0.46845416226985, + 0.45043312286605597, + 0.5056598815070166, + 0.7409705031559474, + 0.8603765679867883, + 1.0538450230996865, + 1.0081108631780855, + 1.1690476205954352, + 1.0276080698511403, + 1.0300426646320324, + 0.9285289360144396, + 1.0714015077948558, + 1.1685869444873658, + 1.2017909959100128, + 1.5017977357556944, + 1.4764802942245, + 2.507491965186489, + 1.3964967937608386, + 0.45955548911576516 + ], + [ + 0.6514947846794727, + 0.37074971141649987, + 0.6124439821104768, + 0.558499014278503, + 0.6180715847107823, + 0.6256388458718639, + 0.6158380671576326, + 0.49528232901619434, + 0.536795980355824, + 0.6979284053832475, + 0.5466094111102114, + 0.584632351047142, + 0.49659899187849804, + 0.5107506481678791, + 0.514917149889001, + 0.5771570490994211, + 0.7685763630116533, + 0.8552138662399789, + 0.983390346847638, + 0.9187726410370608, + 1.060093979897247, + 0.9127447106731977, + 0.8815651988002146, + 0.8129164819514269, + 0.8371357399329575, + 0.861714400281723, + 0.8593463653761192, + 0.9975537728050332, + 0.9996880525868025, + 1.3964967937608386, + 2.3285008150321787, + 0.4715462196109566 + ], + [ + 0.39482596703050005, + 0.3293382174223876, + 0.49988283736870626, + 0.40115530415785605, + 0.35951647159338135, + 0.31967495199986407, + 0.3550066549521344, + 0.4126838584327378, + 0.3913663687079706, + 0.3940685939911559, + 0.3690309990865931, + 0.4216823412541298, + 0.3839089053761638, + 0.4239956465214684, + 0.5373022221316843, + 0.3124591887208858, + 0.2810645082871226, + 0.27081192736622073, + 0.35259660481292165, + 0.3443873796467296, + 0.37387602129746506, + 0.3931592331427885, + 0.38244786921348634, + 0.4147811281532504, + 0.4329284583907527, + 0.4320710520570215, + 0.37335736107989964, + 0.4151471273153199, + 0.4878069800099702, + 0.45955548911576516, + 0.4715462196109566, + 2.3789146738766314 + ] + ], + "entropies": [ + -0.6315610607587784, + -0.627416009583068, + -0.5861614941870391, + -0.6016038763611488, + -0.6130674217530055, + -0.6121981385094227, + -0.6033131501980972, + -0.5924187613341422, + -0.6069171484092294, + -0.6132380808987886, + -0.5909367743402253, + -0.590407987771964, + -0.5917503747664402, + -0.5967832540390615, + -0.6130424939063307, + -0.5930475051215599, + -0.6093573556090445, + -0.5989470593654461, + -0.5676289381777201, + -0.5608694521216201, + -0.5743625477527975, + -0.5557850271201213, + -0.5616113594268438, + -0.5596460325149003, + -0.5734106113048131, + -0.5980103347467473, + -0.585848842395306, + -0.6006940220260183, + -0.6040359784607082, + -0.596804905704757, + -0.6565548704092264, + -0.6440389208735767 + ], + "pair_npib": 1.928525358648791, + "source_lineage": [ + [ + 21 + ], + [ + 22 + ] + ], + "geometry_samples": 100, + "geometry_sequence_length": 512, + "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", + "selection_policy": "native_dynamic_adjacent_NPIB", + "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", + "removed_original_layers": [ + 22 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31 + ] + }, + { + "cycle": 2, + "pair_index": 18, + "initializer": "mka", + "lambda_left": 0.6243720763232038, + "recipient_original_layer": 18, + "recipient_side": "left", + "removed_original_layer": 19, + "npib_matrix": [ + [ + 2.3598368318150484, + 0.3443452304720188, + 0.9511127221245259, + 0.6904843093120027, + 0.6690162505343388, + 0.6512097574296891, + 0.631399187420879, + 0.5855134762308328, + 0.6074206194778445, + 0.6555240534054558, + 0.49958804122731876, + 0.6371923983001465, + 0.4417405635438939, + 0.5458261478339751, + 0.5147575575305561, + 0.5456280200378638, + 0.5119727444468924, + 0.4906904475143589, + 0.49686980422873356, + 0.5007548737037725, + 0.4909326049611054, + 0.44812252343672704, + 0.4303933265324181, + 0.4489823414661812, + 0.4067367055982065, + 0.48814193671369643, + 0.508729666484104, + 0.4862661741259329, + 0.5391690351435269, + 0.69407562303068, + 0.37686918844984935 + ], + [ + 0.3443452304720188, + 2.391816699157234, + 0.6105530658931005, + 0.4443044467140416, + 0.4158723960081373, + 0.40098832660997547, + 0.35615130217538943, + 0.43519508514758576, + 0.3503926486536749, + 0.33321429661265745, + 0.33267757715099683, + 0.37623434210878476, + 0.32133205919801977, + 0.3490059585089323, + 0.3660249748943472, + 0.3114854567755884, + 0.2663593264561916, + 0.2697431210006974, + 0.23969181081364918, + 0.20237086665596765, + 0.22902198478287483, + 0.2378853126583987, + 0.21488357238667533, + 0.2835220223552374, + 0.3175987454670357, + 0.32291141709831583, + 0.3415784816830714, + 0.3654726433991152, + 0.3418765301087253, + 0.41832210376266754, + 0.3007024470865242 + ], + [ + 0.9511127221245259, + 0.6105530658931005, + 2.4034261954132092, + 1.172988635221176, + 0.9543480188379591, + 0.8217904224586922, + 0.805130531492367, + 0.8220121195811046, + 0.7808879677224255, + 0.7198356581526952, + 0.6651786755142716, + 0.7394256448693735, + 0.5932303151559802, + 0.6590574115563346, + 0.5715370352061608, + 0.6433894891957147, + 0.6561537291529483, + 0.5636594465267478, + 0.4960923859903253, + 0.4504579792228191, + 0.503964847276733, + 0.4384295230882143, + 0.4334338635990655, + 0.4374528133098268, + 0.4296248068181768, + 0.46513519382697804, + 0.4447264083059988, + 0.4633641986234235, + 0.5092209212271238, + 0.6591341318279818, + 0.4709404014542207 + ], + [ + 0.6904843093120027, + 0.4443044467140416, + 1.172988635221176, + 2.3196693821091636, + 1.4078769588470965, + 1.183936344408245, + 1.1082009322507629, + 0.9869828327866518, + 0.9597145887539139, + 0.8597942447782176, + 0.8324508551527933, + 0.905095248097947, + 0.6673620409811332, + 0.5916311920292769, + 0.5334841931361148, + 0.7273803335574809, + 0.7331561725301285, + 0.634557790255331, + 0.5933998637935438, + 0.5456125833358797, + 0.5818430579093835, + 0.4578215583477836, + 0.44231481345996515, + 0.41708827847754665, + 0.3954820454358807, + 0.37257838951696237, + 0.34264042173632975, + 0.37157926170053285, + 0.4674483111914456, + 0.5928922014392551, + 0.38383911582455815 + ], + [ + 0.6690162505343388, + 0.4158723960081373, + 0.9543480188379591, + 1.4078769588470965, + 2.2720808664678995, + 1.485803190155229, + 1.327137744734443, + 0.9471235684848248, + 1.041610642885693, + 0.9573001564339423, + 0.9696052598995775, + 1.007237442000292, + 0.7128891436386944, + 0.6222556937347655, + 0.568017177630325, + 0.8534056937268815, + 0.8583181137894533, + 0.7680260770400199, + 0.62131871323841, + 0.6217868869928156, + 0.6111352783152795, + 0.517594163880571, + 0.45898032506158865, + 0.4222027257552709, + 0.38021418045488015, + 0.39754889794925813, + 0.39478259864876236, + 0.3925078147807659, + 0.5339298647737573, + 0.6255692221222743, + 0.3391088758415887 + ], + [ + 0.6512097574296891, + 0.40098832660997547, + 0.8217904224586922, + 1.183936344408245, + 1.485803190155229, + 2.2967483552546537, + 1.2091134623365896, + 0.8585350462054803, + 1.0042500648005865, + 1.0018474416582548, + 0.9933762252232546, + 0.9621227995153653, + 0.696909302382986, + 0.6173209992447204, + 0.584492383082575, + 0.9417926684185647, + 0.9804920771997399, + 0.8654061944230085, + 0.7360931751284087, + 0.7221598881518954, + 0.7223459997169059, + 0.5169397278946233, + 0.4609300423721312, + 0.41695492143409296, + 0.44609037429796167, + 0.42260401663266467, + 0.4453477813716776, + 0.4287572735494411, + 0.5987665017609344, + 0.6694274902493748, + 0.2955670795032907 + ], + [ + 0.631399187420879, + 0.35615130217538943, + 0.805130531492367, + 1.1082009322507629, + 1.327137744734443, + 1.2091134623365896, + 2.3477764543003454, + 1.3226532341597808, + 1.391330620637103, + 1.1491906635237006, + 1.330624622598439, + 1.2899779542933039, + 0.9812795935011823, + 0.8137354257801147, + 0.7128203622741097, + 1.0943587368970968, + 0.9169852285979067, + 0.7489303132311632, + 0.5957700393761652, + 0.5772984839799916, + 0.5728788366708345, + 0.5132513676072861, + 0.44510003594984315, + 0.4248310515378361, + 0.44172994779289615, + 0.3989823266116706, + 0.4627025308280699, + 0.44537209061055866, + 0.5207458254274734, + 0.5936140353419367, + 0.3169621613356411 + ], + [ + 0.5855134762308328, + 0.43519508514758576, + 0.8220121195811046, + 0.9869828327866518, + 0.9471235684848248, + 0.8585350462054803, + 1.3226532341597808, + 2.4645174274691333, + 1.5029144393235752, + 0.9573721322151795, + 1.2301516083629374, + 1.2305852484401933, + 1.1399072532624648, + 0.9239914450556869, + 0.8093851963034749, + 0.9379028784095761, + 0.731517385991915, + 0.6448813877703499, + 0.5379667729294401, + 0.5294864880277178, + 0.5079667389303936, + 0.4775736768036259, + 0.4245908167754744, + 0.3970837250551835, + 0.4266053326901856, + 0.37208791683425024, + 0.3813589331178204, + 0.44953919713912627, + 0.4248174141010847, + 0.5084520332911227, + 0.40528775686626656 + ], + [ + 0.6074206194778445, + 0.3503926486536749, + 0.7808879677224255, + 0.9597145887539139, + 1.041610642885693, + 1.0042500648005865, + 1.391330620637103, + 1.5029144393235752, + 2.4052196230162677, + 1.2619624752451808, + 1.6629277581695627, + 1.4891374132962578, + 1.0460814411649866, + 0.8646820523019201, + 0.8616511378320537, + 1.0424249204378506, + 0.8597179961702175, + 0.6853907014738974, + 0.5306082981407941, + 0.5436825114832436, + 0.5639931871899226, + 0.49024059956717025, + 0.4345060328377167, + 0.42587699002858814, + 0.4486941362179286, + 0.3733044829623987, + 0.4348647785567718, + 0.42436100666087956, + 0.5147117350907365, + 0.5590142945473258, + 0.35542852834636296 + ], + [ + 0.6555240534054558, + 0.33321429661265745, + 0.7198356581526952, + 0.8597942447782176, + 0.9573001564339423, + 1.0018474416582548, + 1.1491906635237006, + 0.9573721322151795, + 1.2619624752451808, + 2.4560572801455933, + 1.483543481961692, + 1.3405276365717165, + 0.873279151443917, + 0.7367176797293109, + 0.7671022375573167, + 0.9327855360635636, + 1.0918270331754372, + 0.8987631835322829, + 0.7411743452192853, + 0.678290115979759, + 0.7157675345161907, + 0.5920078400945115, + 0.5828628310210722, + 0.5160041505677119, + 0.531505678355514, + 0.5139759012271491, + 0.5175840676628899, + 0.5198085117451912, + 0.6484288104775807, + 0.6770675599328052, + 0.3902523538319553 + ], + [ + 0.49958804122731876, + 0.33267757715099683, + 0.6651786755142716, + 0.8324508551527933, + 0.9696052598995775, + 0.9933762252232546, + 1.330624622598439, + 1.2301516083629374, + 1.6629277581695627, + 1.483543481961692, + 2.4914126330956137, + 1.6929237795968073, + 1.0771191337248727, + 0.8883623835176718, + 0.8878595069664904, + 1.1132836387670426, + 1.032671214420258, + 0.8192048616297526, + 0.6034947248735233, + 0.5700481723700193, + 0.5774935292201491, + 0.5400331083694989, + 0.4501951802874655, + 0.4152883353841564, + 0.45116114511979793, + 0.3864026698270076, + 0.45357120505657933, + 0.4516089376084809, + 0.5019929122330061, + 0.5950233432094136, + 0.3647693300217755 + ], + [ + 0.6371923983001465, + 0.37623434210878476, + 0.7394256448693735, + 0.905095248097947, + 1.007237442000292, + 0.9621227995153653, + 1.2899779542933039, + 1.2305852484401933, + 1.4891374132962578, + 1.3405276365717165, + 1.6929237795968073, + 2.510786418656704, + 1.105015632231669, + 0.9460946269422356, + 0.9918068018658639, + 1.1470943292218765, + 1.0083643873866202, + 0.8081600544791975, + 0.6278828228343547, + 0.6054836053118589, + 0.6255044767875986, + 0.5439111818319826, + 0.49762812826143743, + 0.4811619858893614, + 0.48863642976119576, + 0.4415799552158163, + 0.46531570400617395, + 0.47714392820539175, + 0.5704473370106038, + 0.6185877808124107, + 0.37746940132482537 + ], + [ + 0.4417405635438939, + 0.32133205919801977, + 0.5932303151559802, + 0.6673620409811332, + 0.7128891436386944, + 0.696909302382986, + 0.9812795935011823, + 1.1399072532624648, + 1.0460814411649866, + 0.873279151443917, + 1.0771191337248727, + 1.105015632231669, + 2.4424500948199106, + 1.2331711378465116, + 0.9869157393394576, + 0.9785032314839748, + 0.6539071204830524, + 0.5355085539514636, + 0.5089888208180045, + 0.48279766211029607, + 0.4703556965468468, + 0.41492572206251227, + 0.39507203953838355, + 0.3645569298276436, + 0.3729726244417347, + 0.3565332389806202, + 0.3709069341848774, + 0.42996900340750044, + 0.48195889876444364, + 0.5086661446708327, + 0.3737460095572829 + ], + [ + 0.5458261478339751, + 0.3490059585089323, + 0.6590574115563346, + 0.5916311920292769, + 0.6222556937347655, + 0.6173209992447204, + 0.8137354257801147, + 0.9239914450556869, + 0.8646820523019201, + 0.7367176797293109, + 0.8883623835176718, + 0.9460946269422356, + 1.2331711378465116, + 2.4086109155702577, + 1.1621077679013359, + 0.8982730203378348, + 0.6927039380229185, + 0.6290895770560241, + 0.593551381925273, + 0.5543999780243056, + 0.5728756049449134, + 0.5082417240150763, + 0.5045050300328607, + 0.4488239623113525, + 0.48051380930961507, + 0.5038216339318167, + 0.4841009968749123, + 0.5143922610965156, + 0.49844839706233063, + 0.5489797133630117, + 0.36621590101895635 + ], + [ + 0.5147575575305561, + 0.3660249748943472, + 0.5715370352061608, + 0.5334841931361148, + 0.568017177630325, + 0.584492383082575, + 0.7128203622741097, + 0.8093851963034749, + 0.8616511378320537, + 0.7671022375573167, + 0.8878595069664904, + 0.9918068018658639, + 0.9869157393394576, + 1.1621077679013359, + 2.4712107267688586, + 0.8577210081001834, + 0.674081272784002, + 0.5751414578932731, + 0.5355574777097107, + 0.5178368856962178, + 0.5401823826449512, + 0.4839903417715451, + 0.47193496690665454, + 0.44066011412897094, + 0.46477102314322877, + 0.47745052106476993, + 0.46225143303087635, + 0.5218438417231736, + 0.478328005740566, + 0.5801512397197011, + 0.4849744477034098 + ], + [ + 0.5456280200378638, + 0.3114854567755884, + 0.6433894891957147, + 0.7273803335574809, + 0.8534056937268815, + 0.9417926684185647, + 1.0943587368970968, + 0.9379028784095761, + 1.0424249204378506, + 0.9327855360635636, + 1.1132836387670426, + 1.1470943292218765, + 0.9785032314839748, + 0.8982730203378348, + 0.8577210081001834, + 2.35422460389475, + 1.1181007818213686, + 0.8714307710618016, + 0.7187184547841231, + 0.6883113128284807, + 0.6502884814966043, + 0.5818582034940311, + 0.49753859234238434, + 0.460424588331168, + 0.5064934008960987, + 0.43569560826644044, + 0.48354596667251615, + 0.517256807089013, + 0.527722777128293, + 0.6227444558183268, + 0.26865222038048103 + ], + [ + 0.5119727444468924, + 0.2663593264561916, + 0.6561537291529483, + 0.7331561725301285, + 0.8583181137894533, + 0.9804920771997399, + 0.9169852285979067, + 0.731517385991915, + 0.8597179961702175, + 1.0918270331754372, + 1.032671214420258, + 1.0083643873866202, + 0.6539071204830524, + 0.6927039380229185, + 0.674081272784002, + 1.1181007818213686, + 2.364160616417643, + 1.406379212095852, + 1.066597488922481, + 0.9713519524329484, + 0.9853070600751667, + 0.7413712661952219, + 0.6854214168428368, + 0.6174774086091552, + 0.5946949591954577, + 0.5453355558090447, + 0.5863671160781438, + 0.5563330836729167, + 0.7401916871368269, + 0.7915410225404914, + 0.23396036139653456 + ], + [ + 0.4906904475143589, + 0.2697431210006974, + 0.5636594465267478, + 0.634557790255331, + 0.7680260770400199, + 0.8654061944230085, + 0.7489303132311632, + 0.6448813877703499, + 0.6853907014738974, + 0.8987631835322829, + 0.8192048616297526, + 0.8081600544791975, + 0.5355085539514636, + 0.6290895770560241, + 0.5751414578932731, + 0.8714307710618016, + 1.406379212095852, + 2.375249320052241, + 1.3307167716858816, + 1.2188380316969656, + 1.2921693180252614, + 0.9167759052115636, + 0.792474489348373, + 0.7111307251147, + 0.6398773679784637, + 0.6043340919478172, + 0.7026048231231676, + 0.627030968893774, + 0.8096201061756071, + 0.8449971749218934, + 0.19383626675362675 + ], + [ + 0.49686980422873356, + 0.23969181081364918, + 0.4960923859903253, + 0.5933998637935438, + 0.62131871323841, + 0.7360931751284087, + 0.5957700393761652, + 0.5379667729294401, + 0.5306082981407941, + 0.7411743452192853, + 0.6034947248735233, + 0.6278828228343547, + 0.5089888208180045, + 0.593551381925273, + 0.5355574777097107, + 0.7187184547841231, + 1.066597488922481, + 1.3307167716858816, + 2.554491403562512, + 1.8411160089685985, + 1.9021849031385998, + 1.2695470386327201, + 1.0836063921947772, + 0.926398877067255, + 0.8463447811140492, + 0.8239043077624073, + 0.8665347557642402, + 0.7925564236279239, + 0.9940813014638915, + 0.9594607628026728, + 0.3406595466838304 + ], + [ + 0.5007548737037725, + 0.20237086665596765, + 0.4504579792228191, + 0.5456125833358797, + 0.6217868869928156, + 0.7221598881518954, + 0.5772984839799916, + 0.5294864880277178, + 0.5436825114832436, + 0.678290115979759, + 0.5700481723700193, + 0.6054836053118589, + 0.48279766211029607, + 0.5543999780243056, + 0.5178368856962178, + 0.6883113128284807, + 0.9713519524329484, + 1.2188380316969656, + 1.8411160089685985, + 2.5553993179009056, + 1.7502012123430974, + 1.2692934735268153, + 1.0986456017649637, + 0.9293557578908243, + 0.8683235766733857, + 0.8449856029788099, + 0.8744627854157484, + 0.782551125965279, + 0.9350077279170363, + 0.8630354077584944, + 0.3234279861929802 + ], + [ + 0.4909326049611054, + 0.22902198478287483, + 0.503964847276733, + 0.5818430579093835, + 0.6111352783152795, + 0.7223459997169059, + 0.5728788366708345, + 0.5079667389303936, + 0.5639931871899226, + 0.7157675345161907, + 0.5774935292201491, + 0.6255044767875986, + 0.4703556965468468, + 0.5728756049449134, + 0.5401823826449512, + 0.6502884814966043, + 0.9853070600751667, + 1.2921693180252614, + 1.9021849031385998, + 1.7502012123430974, + 2.5317678160262354, + 1.3302840778035987, + 1.103539110691206, + 0.9520272855674701, + 0.9079439050011602, + 0.8500905458081266, + 0.9213876394025102, + 0.8469019603570608, + 1.0666559255667682, + 1.036046577394678, + 0.3117257992527307 + ], + [ + 0.44812252343672704, + 0.2378853126583987, + 0.4384295230882143, + 0.4578215583477836, + 0.517594163880571, + 0.5169397278946233, + 0.5132513676072861, + 0.4775736768036259, + 0.49024059956717025, + 0.5920078400945115, + 0.5400331083694989, + 0.5439111818319826, + 0.41492572206251227, + 0.5082417240150763, + 0.4839903417715451, + 0.5818582034940311, + 0.7413712661952219, + 0.9167759052115636, + 1.2695470386327201, + 1.2692934735268153, + 1.3302840778035987, + 2.4780772485833844, + 1.6419802272015402, + 1.3789257148030214, + 1.2779049643604752, + 1.1224916112837222, + 1.1226498135355771, + 0.936459272123645, + 1.1288382922820734, + 0.939277939135362, + 0.4197443832943667 + ], + [ + 0.4303933265324181, + 0.21488357238667533, + 0.4334338635990655, + 0.44231481345996515, + 0.45898032506158865, + 0.4609300423721312, + 0.44510003594984315, + 0.4245908167754744, + 0.4345060328377167, + 0.5828628310210722, + 0.4501951802874655, + 0.49762812826143743, + 0.39507203953838355, + 0.5045050300328607, + 0.47193496690665454, + 0.49753859234238434, + 0.6854214168428368, + 0.792474489348373, + 1.0836063921947772, + 1.0986456017649637, + 1.103539110691206, + 1.6419802272015402, + 2.4653622233800743, + 1.6967338550739395, + 1.458672990750323, + 1.191492656652394, + 1.150589004812641, + 1.0754531794628786, + 1.0926148622147287, + 0.8835006765878411, + 0.43334699973360874 + ], + [ + 0.4489823414661812, + 0.2835220223552374, + 0.4374528133098268, + 0.41708827847754665, + 0.4222027257552709, + 0.41695492143409296, + 0.4248310515378361, + 0.3970837250551835, + 0.42587699002858814, + 0.5160041505677119, + 0.4152883353841564, + 0.4811619858893614, + 0.3645569298276436, + 0.4488239623113525, + 0.44066011412897094, + 0.460424588331168, + 0.6174774086091552, + 0.7111307251147, + 0.926398877067255, + 0.9293557578908243, + 0.9520272855674701, + 1.3789257148030214, + 1.6967338550739395, + 2.437217589172306, + 1.801880522331393, + 1.4247835684785237, + 1.3632496945142552, + 1.2386867021298822, + 1.143295003132412, + 0.9201816885699067, + 0.4389547360471068 + ], + [ + 0.4067367055982065, + 0.3175987454670357, + 0.4296248068181768, + 0.3954820454358807, + 0.38021418045488015, + 0.44609037429796167, + 0.44172994779289615, + 0.4266053326901856, + 0.4486941362179286, + 0.531505678355514, + 0.45116114511979793, + 0.48863642976119576, + 0.3729726244417347, + 0.48051380930961507, + 0.46477102314322877, + 0.5064934008960987, + 0.5946949591954577, + 0.6398773679784637, + 0.8463447811140492, + 0.8683235766733857, + 0.9079439050011602, + 1.2779049643604752, + 1.458672990750323, + 1.801880522331393, + 2.313788742926064, + 1.4690559690442293, + 1.4393057465180432, + 1.3216152659331615, + 1.204721357451594, + 0.8886472003608102, + 0.4281967192049599 + ], + [ + 0.48814193671369643, + 0.32291141709831583, + 0.46513519382697804, + 0.37257838951696237, + 0.39754889794925813, + 0.42260401663266467, + 0.3989823266116706, + 0.37208791683425024, + 0.3733044829623987, + 0.5139759012271491, + 0.3864026698270076, + 0.4415799552158163, + 0.3565332389806202, + 0.5038216339318167, + 0.47745052106476993, + 0.43569560826644044, + 0.5453355558090447, + 0.6043340919478172, + 0.8239043077624073, + 0.8449856029788099, + 0.8500905458081266, + 1.1224916112837222, + 1.191492656652394, + 1.4247835684785237, + 1.4690559690442293, + 2.394540869605081, + 1.5388871342426367, + 1.3684559181628084, + 1.2247105995018992, + 0.8739819757837416, + 0.40673004083535363 + ], + [ + 0.508729666484104, + 0.3415784816830714, + 0.4447264083059988, + 0.34264042173632975, + 0.39478259864876236, + 0.4453477813716776, + 0.4627025308280699, + 0.3813589331178204, + 0.4348647785567718, + 0.5175840676628899, + 0.45357120505657933, + 0.46531570400617395, + 0.3709069341848774, + 0.4841009968749123, + 0.46225143303087635, + 0.48354596667251615, + 0.5863671160781438, + 0.7026048231231676, + 0.8665347557642402, + 0.8744627854157484, + 0.9213876394025102, + 1.1226498135355771, + 1.150589004812641, + 1.3632496945142552, + 1.4393057465180432, + 1.5388871342426367, + 2.33513518014129, + 1.5674920045282656, + 1.4973835953129904, + 1.0086624045429424, + 0.41358608143296866 + ], + [ + 0.4862661741259329, + 0.3654726433991152, + 0.4633641986234235, + 0.37157926170053285, + 0.3925078147807659, + 0.4287572735494411, + 0.44537209061055866, + 0.44953919713912627, + 0.42436100666087956, + 0.5198085117451912, + 0.4516089376084809, + 0.47714392820539175, + 0.42996900340750044, + 0.5143922610965156, + 0.5218438417231736, + 0.517256807089013, + 0.5563330836729167, + 0.627030968893774, + 0.7925564236279239, + 0.782551125965279, + 0.8469019603570608, + 0.936459272123645, + 1.0754531794628786, + 1.2386867021298822, + 1.3216152659331615, + 1.3684559181628084, + 1.5674920045282656, + 2.2765867406886535, + 1.295328483598044, + 0.9096136539089765, + 0.4659352213518139 + ], + [ + 0.5391690351435269, + 0.3418765301087253, + 0.5092209212271238, + 0.4674483111914456, + 0.5339298647737573, + 0.5987665017609344, + 0.5207458254274734, + 0.4248174141010847, + 0.5147117350907365, + 0.6484288104775807, + 0.5019929122330061, + 0.5704473370106038, + 0.48195889876444364, + 0.49844839706233063, + 0.478328005740566, + 0.527722777128293, + 0.7401916871368269, + 0.8096201061756071, + 0.9940813014638915, + 0.9350077279170363, + 1.0666559255667682, + 1.1288382922820734, + 1.0926148622147287, + 1.143295003132412, + 1.204721357451594, + 1.2247105995018992, + 1.4973835953129904, + 1.295328483598044, + 2.4312798638120423, + 1.3093376563854953, + 0.4164377351239836 + ], + [ + 0.69407562303068, + 0.41832210376266754, + 0.6591341318279818, + 0.5928922014392551, + 0.6255692221222743, + 0.6694274902493748, + 0.5936140353419367, + 0.5084520332911227, + 0.5590142945473258, + 0.6770675599328052, + 0.5950233432094136, + 0.6185877808124107, + 0.5086661446708327, + 0.5489797133630117, + 0.5801512397197011, + 0.6227444558183268, + 0.7915410225404914, + 0.8449971749218934, + 0.9594607628026728, + 0.8630354077584944, + 1.036046577394678, + 0.939277939135362, + 0.8835006765878411, + 0.9201816885699067, + 0.8886472003608102, + 0.8739819757837416, + 1.0086624045429424, + 0.9096136539089765, + 1.3093376563854953, + 2.318418604395567, + 0.4373806240017924 + ], + [ + 0.37686918844984935, + 0.3007024470865242, + 0.4709404014542207, + 0.38383911582455815, + 0.3391088758415887, + 0.2955670795032907, + 0.3169621613356411, + 0.40528775686626656, + 0.35542852834636296, + 0.3902523538319553, + 0.3647693300217755, + 0.37746940132482537, + 0.3737460095572829, + 0.36621590101895635, + 0.4849744477034098, + 0.26865222038048103, + 0.23396036139653456, + 0.19383626675362675, + 0.3406595466838304, + 0.3234279861929802, + 0.3117257992527307, + 0.4197443832943667, + 0.43334699973360874, + 0.4389547360471068, + 0.4281967192049599, + 0.40673004083535363, + 0.41358608143296866, + 0.4659352213518139, + 0.4164377351239836, + 0.4373806240017924, + 2.3065769089635246 + ] + ], + "entropies": [ + -0.6315610607587784, + -0.627416009583068, + -0.5861614941870391, + -0.6016038763611488, + -0.6130674217530055, + -0.6121981385094227, + -0.6033131501980972, + -0.5924187613341422, + -0.6069171484092294, + -0.6132380808987886, + -0.5909367743402253, + -0.590407987771964, + -0.5917503747664402, + -0.5967832540390615, + -0.6130424939063307, + -0.5930475051215599, + -0.6093573556090445, + -0.5989470593654461, + -0.5676289381777201, + -0.5608694521216201, + -0.5743625477527975, + -0.5758816773281742, + -0.5801409806126402, + -0.5913668641359654, + -0.6097472828545235, + -0.6083570027802482, + -0.6274904600708421, + -0.6306152827921306, + -0.6120070175682731, + -0.6667256627105463, + -0.6619341659869157 + ], + "pair_npib": 1.8411160089685985, + "source_lineage": [ + [ + 18 + ], + [ + 19 + ] + ], + "geometry_samples": 100, + "geometry_sequence_length": 512, + "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", + "selection_policy": "native_dynamic_adjacent_NPIB", + "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", + "removed_original_layers": [ + 19 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 20, + 21, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31 + ] + }, + { + "cycle": 3, + "pair_index": 21, + "initializer": "mka", + "lambda_left": 0.6243202778643895, + "recipient_original_layer": 23, + "recipient_side": "left", + "removed_original_layer": 24, + "npib_matrix": [ + [ + 2.3598368318150484, + 0.3443452304720188, + 0.9511127221245259, + 0.6904843093120027, + 0.6690162505343388, + 0.6512097574296891, + 0.631399187420879, + 0.5855134762308328, + 0.6074206194778445, + 0.6555240534054558, + 0.49958804122731876, + 0.6371923983001465, + 0.4417405635438939, + 0.5458261478339751, + 0.5147575575305561, + 0.5456280200378638, + 0.5119727444468924, + 0.4906904475143589, + 0.5069969467582512, + 0.509695920091663, + 0.49398628694295066, + 0.44039189220553704, + 0.4630697844314841, + 0.4952713656174089, + 0.48683988503594894, + 0.49254374837871395, + 0.5419461075789854, + 0.5448813381544559, + 0.7082692938719349, + 0.5284220919846891 + ], + [ + 0.3443452304720188, + 2.391816699157234, + 0.6105530658931005, + 0.4443044467140416, + 0.4158723960081373, + 0.40098832660997547, + 0.35615130217538943, + 0.43519508514758576, + 0.3503926486536749, + 0.33321429661265745, + 0.33267757715099683, + 0.37623434210878476, + 0.32133205919801977, + 0.3490059585089323, + 0.3660249748943472, + 0.3114854567755884, + 0.2663593264561916, + 0.2697431210006974, + 0.2708607670334084, + 0.2636171211243358, + 0.2870144728303516, + 0.3147558579459343, + 0.3072655491341674, + 0.3291930289953316, + 0.3493593847882676, + 0.37627200728488314, + 0.4062637166624044, + 0.35382385610187517, + 0.4718635050401223, + 0.38927201404253525 + ], + [ + 0.9511127221245259, + 0.6105530658931005, + 2.4034261954132092, + 1.172988635221176, + 0.9543480188379591, + 0.8217904224586922, + 0.805130531492367, + 0.8220121195811046, + 0.7808879677224255, + 0.7198356581526952, + 0.6651786755142716, + 0.7394256448693735, + 0.5932303151559802, + 0.6590574115563346, + 0.5715370352061608, + 0.6433894891957147, + 0.6561537291529483, + 0.5636594465267478, + 0.5470659748216011, + 0.4820355727830177, + 0.42359644388184126, + 0.41950122438440324, + 0.4543048240459809, + 0.43984099529676157, + 0.4636276823638565, + 0.45076184698976207, + 0.5111704918748468, + 0.5533524510921555, + 0.7065706801055288, + 0.5986043764842145 + ], + [ + 0.6904843093120027, + 0.4443044467140416, + 1.172988635221176, + 2.3196693821091636, + 1.4078769588470965, + 1.183936344408245, + 1.1082009322507629, + 0.9869828327866518, + 0.9597145887539139, + 0.8597942447782176, + 0.8324508551527933, + 0.905095248097947, + 0.6673620409811332, + 0.5916311920292769, + 0.5334841931361148, + 0.7273803335574809, + 0.7331561725301285, + 0.634557790255331, + 0.5878535143099074, + 0.5458337816977792, + 0.4799224486802803, + 0.4678856049693605, + 0.4395961020071838, + 0.41872916052589604, + 0.4338609750690056, + 0.4216963717213181, + 0.43381033477450065, + 0.5314811991734427, + 0.6141193851733041, + 0.5531694824668841 + ], + [ + 0.6690162505343388, + 0.4158723960081373, + 0.9543480188379591, + 1.4078769588470965, + 2.2720808664678995, + 1.485803190155229, + 1.327137744734443, + 0.9471235684848248, + 1.041610642885693, + 0.9573001564339423, + 0.9696052598995775, + 1.007237442000292, + 0.7128891436386944, + 0.6222556937347655, + 0.568017177630325, + 0.8534056937268815, + 0.8583181137894533, + 0.7680260770400199, + 0.6696025604235553, + 0.6137087253643312, + 0.4869978469188338, + 0.46005107151896657, + 0.4217948345916569, + 0.41488302609356215, + 0.45892954608478187, + 0.45611724663114955, + 0.45157849103520004, + 0.5939175896062586, + 0.6428018504106864, + 0.49925363211471374 + ], + [ + 0.6512097574296891, + 0.40098832660997547, + 0.8217904224586922, + 1.183936344408245, + 1.485803190155229, + 2.2967483552546537, + 1.2091134623365896, + 0.8585350462054803, + 1.0042500648005865, + 1.0018474416582548, + 0.9933762252232546, + 0.9621227995153653, + 0.696909302382986, + 0.6173209992447204, + 0.584492383082575, + 0.9417926684185647, + 0.9804920771997399, + 0.8654061944230085, + 0.7982915952136304, + 0.693551712150731, + 0.49463228081020266, + 0.4468140223082248, + 0.42093827212310797, + 0.40981747647501837, + 0.46175117904826973, + 0.4878657456903686, + 0.5087951832069553, + 0.6016582147715859, + 0.6567745940178692, + 0.49453095367900496 + ], + [ + 0.631399187420879, + 0.35615130217538943, + 0.805130531492367, + 1.1082009322507629, + 1.327137744734443, + 1.2091134623365896, + 2.3477764543003454, + 1.3226532341597808, + 1.391330620637103, + 1.1491906635237006, + 1.330624622598439, + 1.2899779542933039, + 0.9812795935011823, + 0.8137354257801147, + 0.7128203622741097, + 1.0943587368970968, + 0.9169852285979067, + 0.7489303132311632, + 0.6594020787989971, + 0.5682074043438511, + 0.5056922134447404, + 0.4524684733974224, + 0.42536624449229615, + 0.43150873471501905, + 0.46522594137718604, + 0.4347833894180766, + 0.509929983934642, + 0.5745343884606358, + 0.6415942511035096, + 0.4979195970551139 + ], + [ + 0.5855134762308328, + 0.43519508514758576, + 0.8220121195811046, + 0.9869828327866518, + 0.9471235684848248, + 0.8585350462054803, + 1.3226532341597808, + 2.4645174274691333, + 1.5029144393235752, + 0.9573721322151795, + 1.2301516083629374, + 1.2305852484401933, + 1.1399072532624648, + 0.9239914450556869, + 0.8093851963034749, + 0.9379028784095761, + 0.731517385991915, + 0.6448813877703499, + 0.5717717424334022, + 0.4714663961826335, + 0.45551041034889256, + 0.4160111543411354, + 0.3781657957944654, + 0.3905069587982822, + 0.41935785336497833, + 0.44810070794021567, + 0.4550701725525005, + 0.5108747792343451, + 0.5260050815661209, + 0.5382422302923919 + ], + [ + 0.6074206194778445, + 0.3503926486536749, + 0.7808879677224255, + 0.9597145887539139, + 1.041610642885693, + 1.0042500648005865, + 1.391330620637103, + 1.5029144393235752, + 2.4052196230162677, + 1.2619624752451808, + 1.6629277581695627, + 1.4891374132962578, + 1.0460814411649866, + 0.8646820523019201, + 0.8616511378320537, + 1.0424249204378506, + 0.8597179961702175, + 0.6853907014738974, + 0.5940671202652917, + 0.5110226758298415, + 0.45984362316260796, + 0.4176464240398986, + 0.37844195980454054, + 0.41110858647762294, + 0.40959452678286, + 0.4446041288048262, + 0.4717583188011383, + 0.5443867058440028, + 0.5469841739116845, + 0.4834450023856785 + ], + [ + 0.6555240534054558, + 0.33321429661265745, + 0.7198356581526952, + 0.8597942447782176, + 0.9573001564339423, + 1.0018474416582548, + 1.1491906635237006, + 0.9573721322151795, + 1.2619624752451808, + 2.4560572801455933, + 1.483543481961692, + 1.3405276365717165, + 0.873279151443917, + 0.7367176797293109, + 0.7671022375573167, + 0.9327855360635636, + 1.0918270331754372, + 0.8987631835322829, + 0.803533839199152, + 0.7387411852170389, + 0.592435898640002, + 0.5183354825011868, + 0.4718849219659738, + 0.5667018422733502, + 0.5472211753611604, + 0.5705250043333447, + 0.6058934267183888, + 0.7155460145206461, + 0.7382443490538002, + 0.548849766120485 + ], + [ + 0.49958804122731876, + 0.33267757715099683, + 0.6651786755142716, + 0.8324508551527933, + 0.9696052598995775, + 0.9933762252232546, + 1.330624622598439, + 1.2301516083629374, + 1.6629277581695627, + 1.483543481961692, + 2.4914126330956137, + 1.6929237795968073, + 1.0771191337248727, + 0.8883623835176718, + 0.8878595069664904, + 1.1132836387670426, + 1.032671214420258, + 0.8192048616297526, + 0.662358373020083, + 0.6048540019320288, + 0.49502227461357323, + 0.44649562903539675, + 0.4084417095199685, + 0.4869030668239273, + 0.4974789348873178, + 0.4720000450776102, + 0.5099371325089435, + 0.5210749810072831, + 0.6408567167035579, + 0.5143911248012927 + ], + [ + 0.6371923983001465, + 0.37623434210878476, + 0.7394256448693735, + 0.905095248097947, + 1.007237442000292, + 0.9621227995153653, + 1.2899779542933039, + 1.2305852484401933, + 1.4891374132962578, + 1.3405276365717165, + 1.6929237795968073, + 2.510786418656704, + 1.105015632231669, + 0.9460946269422356, + 0.9918068018658639, + 1.1470943292218765, + 1.0083643873866202, + 0.8081600544791975, + 0.6716363352631979, + 0.581883479435235, + 0.503975827793527, + 0.4438136512293106, + 0.41729433957347817, + 0.510645998551254, + 0.48271898617765824, + 0.4878856636725931, + 0.5359242775847267, + 0.6060127137677928, + 0.6753910460760023, + 0.5012428406632976 + ], + [ + 0.4417405635438939, + 0.32133205919801977, + 0.5932303151559802, + 0.6673620409811332, + 0.7128891436386944, + 0.696909302382986, + 0.9812795935011823, + 1.1399072532624648, + 1.0460814411649866, + 0.873279151443917, + 1.0771191337248727, + 1.105015632231669, + 2.4424500948199106, + 1.2331711378465116, + 0.9869157393394576, + 0.9785032314839748, + 0.6539071204830524, + 0.5355085539514636, + 0.5056950225437449, + 0.45024533594856087, + 0.4264009212176895, + 0.35315141341839135, + 0.3119429743086256, + 0.3865311416967606, + 0.35704751066545815, + 0.4108360627315002, + 0.4289220164340592, + 0.5084113016249782, + 0.522384104991249, + 0.541432627112468 + ], + [ + 0.5458261478339751, + 0.3490059585089323, + 0.6590574115563346, + 0.5916311920292769, + 0.6222556937347655, + 0.6173209992447204, + 0.8137354257801147, + 0.9239914450556869, + 0.8646820523019201, + 0.7367176797293109, + 0.8883623835176718, + 0.9460946269422356, + 1.2331711378465116, + 2.4086109155702577, + 1.1621077679013359, + 0.8982730203378348, + 0.6927039380229185, + 0.6290895770560241, + 0.5843147569474538, + 0.5794452186493381, + 0.5525000392692625, + 0.4474630064221762, + 0.4295758294540093, + 0.47341264824954005, + 0.4454340363875005, + 0.4810572265796396, + 0.5215846627986294, + 0.5578195927503444, + 0.613684095808701, + 0.5027762837269726 + ], + [ + 0.5147575575305561, + 0.3660249748943472, + 0.5715370352061608, + 0.5334841931361148, + 0.568017177630325, + 0.584492383082575, + 0.7128203622741097, + 0.8093851963034749, + 0.8616511378320537, + 0.7671022375573167, + 0.8878595069664904, + 0.9918068018658639, + 0.9869157393394576, + 1.1621077679013359, + 2.4712107267688586, + 0.8577210081001834, + 0.674081272784002, + 0.5751414578932731, + 0.5478054716933916, + 0.49815395164947046, + 0.5288598664301039, + 0.4133860360198412, + 0.41657258515979506, + 0.4581566170823173, + 0.4506670041360416, + 0.5083722191785629, + 0.5251208011695117, + 0.5475720541959053, + 0.6205935639295819, + 0.5102434973222952 + ], + [ + 0.5456280200378638, + 0.3114854567755884, + 0.6433894891957147, + 0.7273803335574809, + 0.8534056937268815, + 0.9417926684185647, + 1.0943587368970968, + 0.9379028784095761, + 1.0424249204378506, + 0.9327855360635636, + 1.1132836387670426, + 1.1470943292218765, + 0.9785032314839748, + 0.8982730203378348, + 0.8577210081001834, + 2.35422460389475, + 1.1181007818213686, + 0.8714307710618016, + 0.7381816659115783, + 0.6476494026609263, + 0.49557930786416166, + 0.48701526168433446, + 0.4449370612328448, + 0.45597306820240674, + 0.43870229378281633, + 0.4492039681299209, + 0.501691455841653, + 0.5917369367185793, + 0.6306431136532828, + 0.4126889144083468 + ], + [ + 0.5119727444468924, + 0.2663593264561916, + 0.6561537291529483, + 0.7331561725301285, + 0.8583181137894533, + 0.9804920771997399, + 0.9169852285979067, + 0.731517385991915, + 0.8597179961702175, + 1.0918270331754372, + 1.032671214420258, + 1.0083643873866202, + 0.6539071204830524, + 0.6927039380229185, + 0.674081272784002, + 1.1181007818213686, + 2.364160616417643, + 1.406379212095852, + 1.1413088181770794, + 0.9802747268836863, + 0.6601521103275246, + 0.579143186116225, + 0.5330772708812382, + 0.5640069657302249, + 0.5875438892494699, + 0.5838886150977082, + 0.6162231695617352, + 0.766009563973229, + 0.7891979351791285, + 0.3587424683125375 + ], + [ + 0.4906904475143589, + 0.2697431210006974, + 0.5636594465267478, + 0.634557790255331, + 0.7680260770400199, + 0.8654061944230085, + 0.7489303132311632, + 0.6448813877703499, + 0.6853907014738974, + 0.8987631835322829, + 0.8192048616297526, + 0.8081600544791975, + 0.5355085539514636, + 0.6290895770560241, + 0.5751414578932731, + 0.8714307710618016, + 1.406379212095852, + 2.375249320052241, + 1.5460048798765922, + 1.1211371830440595, + 0.826251932506181, + 0.7148260213449106, + 0.6422414531376828, + 0.6520824931873268, + 0.6504234477088661, + 0.6806447128285997, + 0.7313139728617817, + 0.8798777645538979, + 0.7822303528835381, + 0.41007789038203785 + ], + [ + 0.5069969467582512, + 0.2708607670334084, + 0.5470659748216011, + 0.5878535143099074, + 0.6696025604235553, + 0.7982915952136304, + 0.6594020787989971, + 0.5717717424334022, + 0.5940671202652917, + 0.803533839199152, + 0.662358373020083, + 0.6716363352631979, + 0.5056950225437449, + 0.5843147569474538, + 0.5478054716933916, + 0.7381816659115783, + 1.1413088181770794, + 1.5460048798765922, + 2.3972158331560505, + 1.3129963258733297, + 1.0338351357632705, + 0.8643212187462258, + 0.7815115154715061, + 0.7753357752170268, + 0.7910196677264854, + 0.8194553585411691, + 0.8331135042667799, + 0.9549443168409868, + 0.8588174054553845, + 0.44416923247823553 + ], + [ + 0.509695920091663, + 0.2636171211243358, + 0.4820355727830177, + 0.5458337816977792, + 0.6137087253643312, + 0.693551712150731, + 0.5682074043438511, + 0.4714663961826335, + 0.5110226758298415, + 0.7387411852170389, + 0.6048540019320288, + 0.581883479435235, + 0.45024533594856087, + 0.5794452186493381, + 0.49815395164947046, + 0.6476494026609263, + 0.9802747268836863, + 1.1211371830440595, + 1.3129963258733297, + 2.423024856913207, + 1.2237360183481807, + 0.9510468915401579, + 0.8539167148734343, + 0.9044252569656039, + 0.9020152203578425, + 0.9733254909743332, + 0.9247060494138263, + 1.0948773073189908, + 0.9484503912344027, + 0.42838663993978265 + ], + [ + 0.49398628694295066, + 0.2870144728303516, + 0.42359644388184126, + 0.4799224486802803, + 0.4869978469188338, + 0.49463228081020266, + 0.5056922134447404, + 0.45551041034889256, + 0.45984362316260796, + 0.592435898640002, + 0.49502227461357323, + 0.503975827793527, + 0.4264009212176895, + 0.5525000392692625, + 0.5288598664301039, + 0.49557930786416166, + 0.6601521103275246, + 0.826251932506181, + 1.0338351357632705, + 1.2237360183481807, + 2.563849009889373, + 1.5581765312977485, + 1.363434725232547, + 1.369621585369866, + 1.3000780466849735, + 1.3101342323072245, + 1.228045758480594, + 1.1530302824792655, + 0.9357180492997906, + 0.4906659612773393 + ], + [ + 0.44039189220553704, + 0.3147558579459343, + 0.41950122438440324, + 0.4678856049693605, + 0.46005107151896657, + 0.4468140223082248, + 0.4524684733974224, + 0.4160111543411354, + 0.4176464240398986, + 0.5183354825011868, + 0.44649562903539675, + 0.4438136512293106, + 0.35315141341839135, + 0.4474630064221762, + 0.4133860360198412, + 0.48701526168433446, + 0.579143186116225, + 0.7148260213449106, + 0.8643212187462258, + 0.9510468915401579, + 1.5581765312977485, + 2.530381448911574, + 1.8433488761948427, + 1.6198438991030204, + 1.469028935353149, + 1.2540118692355817, + 1.2312674881005565, + 1.0006859692067058, + 0.8170672906086645, + 0.4651581479279038 + ], + [ + 0.4630697844314841, + 0.3072655491341674, + 0.4543048240459809, + 0.4395961020071838, + 0.4217948345916569, + 0.42093827212310797, + 0.42536624449229615, + 0.3781657957944654, + 0.37844195980454054, + 0.4718849219659738, + 0.4084417095199685, + 0.41729433957347817, + 0.3119429743086256, + 0.4295758294540093, + 0.41657258515979506, + 0.4449370612328448, + 0.5330772708812382, + 0.6422414531376828, + 0.7815115154715061, + 0.8539167148734343, + 1.363434725232547, + 1.8433488761948427, + 2.451584496490092, + 1.6912730333622856, + 1.5603223720525863, + 1.2525797685440578, + 1.247613734288332, + 1.009582285512618, + 0.8377551018098485, + 0.441473272379803 + ], + [ + 0.4952713656174089, + 0.3291930289953316, + 0.43984099529676157, + 0.41872916052589604, + 0.41488302609356215, + 0.40981747647501837, + 0.43150873471501905, + 0.3905069587982822, + 0.41110858647762294, + 0.5667018422733502, + 0.4869030668239273, + 0.510645998551254, + 0.3865311416967606, + 0.47341264824954005, + 0.4581566170823173, + 0.45597306820240674, + 0.5640069657302249, + 0.6520824931873268, + 0.7753357752170268, + 0.9044252569656039, + 1.369621585369866, + 1.6198438991030204, + 1.6912730333622856, + 2.4786561800878815, + 1.7209630972026655, + 1.4726071098830118, + 1.4834851517696888, + 1.157192088676768, + 0.8723949980437518, + 0.4165182416091546 + ], + [ + 0.48683988503594894, + 0.3493593847882676, + 0.4636276823638565, + 0.4338609750690056, + 0.45892954608478187, + 0.46175117904826973, + 0.46522594137718604, + 0.41935785336497833, + 0.40959452678286, + 0.5472211753611604, + 0.4974789348873178, + 0.48271898617765824, + 0.35704751066545815, + 0.4454340363875005, + 0.4506670041360416, + 0.43870229378281633, + 0.5875438892494699, + 0.6504234477088661, + 0.7910196677264854, + 0.9020152203578425, + 1.3000780466849735, + 1.469028935353149, + 1.5603223720525863, + 1.7209630972026655, + 2.415094302495011, + 1.5244351638054063, + 1.5080740789202105, + 1.1755307149887646, + 0.9000782457992295, + 0.413339467482769 + ], + [ + 0.49254374837871395, + 0.37627200728488314, + 0.45076184698976207, + 0.4216963717213181, + 0.45611724663114955, + 0.4878657456903686, + 0.4347833894180766, + 0.44810070794021567, + 0.4446041288048262, + 0.5705250043333447, + 0.4720000450776102, + 0.4878856636725931, + 0.4108360627315002, + 0.4810572265796396, + 0.5083722191785629, + 0.4492039681299209, + 0.5838886150977082, + 0.6806447128285997, + 0.8194553585411691, + 0.9733254909743332, + 1.3101342323072245, + 1.2540118692355817, + 1.2525797685440578, + 1.4726071098830118, + 1.5244351638054063, + 2.3495773434314646, + 1.8135381035155922, + 1.3777793293106462, + 0.9685114957980427, + 0.46644574416296614 + ], + [ + 0.5419461075789854, + 0.4062637166624044, + 0.5111704918748468, + 0.43381033477450065, + 0.45157849103520004, + 0.5087951832069553, + 0.509929983934642, + 0.4550701725525005, + 0.4717583188011383, + 0.6058934267183888, + 0.5099371325089435, + 0.5359242775847267, + 0.4289220164340592, + 0.5215846627986294, + 0.5251208011695117, + 0.501691455841653, + 0.6162231695617352, + 0.7313139728617817, + 0.8331135042667799, + 0.9247060494138263, + 1.228045758480594, + 1.2312674881005565, + 1.247613734288332, + 1.4834851517696888, + 1.5080740789202105, + 1.8135381035155922, + 2.4518351221472297, + 1.3649971081561127, + 0.9918424746471816, + 0.5074805884856376 + ], + [ + 0.5448813381544559, + 0.35382385610187517, + 0.5533524510921555, + 0.5314811991734427, + 0.5939175896062586, + 0.6016582147715859, + 0.5745343884606358, + 0.5108747792343451, + 0.5443867058440028, + 0.7155460145206461, + 0.5210749810072831, + 0.6060127137677928, + 0.5084113016249782, + 0.5578195927503444, + 0.5475720541959053, + 0.5917369367185793, + 0.766009563973229, + 0.8798777645538979, + 0.9549443168409868, + 1.0948773073189908, + 1.1530302824792655, + 1.0006859692067058, + 1.009582285512618, + 1.157192088676768, + 1.1755307149887646, + 1.3777793293106462, + 1.3649971081561127, + 2.3680333610957596, + 1.2405862327395574, + 0.5003068240647341 + ], + [ + 0.7082692938719349, + 0.4718635050401223, + 0.7065706801055288, + 0.6141193851733041, + 0.6428018504106864, + 0.6567745940178692, + 0.6415942511035096, + 0.5260050815661209, + 0.5469841739116845, + 0.7382443490538002, + 0.6408567167035579, + 0.6753910460760023, + 0.522384104991249, + 0.613684095808701, + 0.6205935639295819, + 0.6306431136532828, + 0.7891979351791285, + 0.7822303528835381, + 0.8588174054553845, + 0.9484503912344027, + 0.9357180492997906, + 0.8170672906086645, + 0.8377551018098485, + 0.8723949980437518, + 0.9000782457992295, + 0.9685114957980427, + 0.9918424746471816, + 1.2405862327395574, + 2.3863905818174085, + 0.5881759230668384 + ], + [ + 0.5284220919846891, + 0.38927201404253525, + 0.5986043764842145, + 0.5531694824668841, + 0.49925363211471374, + 0.49453095367900496, + 0.4979195970551139, + 0.5382422302923919, + 0.4834450023856785, + 0.548849766120485, + 0.5143911248012927, + 0.5012428406632976, + 0.541432627112468, + 0.5027762837269726, + 0.5102434973222952, + 0.4126889144083468, + 0.3587424683125375, + 0.41007789038203785, + 0.44416923247823553, + 0.42838663993978265, + 0.4906659612773393, + 0.4651581479279038, + 0.441473272379803, + 0.4165182416091546, + 0.413339467482769, + 0.46644574416296614, + 0.5074805884856376, + 0.5003068240647341, + 0.5881759230668384, + 2.5311037419803406 + ] + ], + "entropies": [ + -0.6315610607587784, + -0.627416009583068, + -0.5861614941870391, + -0.6016038763611488, + -0.6130674217530055, + -0.6121981385094227, + -0.6033131501980972, + -0.5924187613341422, + -0.6069171484092294, + -0.6132380808987886, + -0.5909367743402253, + -0.590407987771964, + -0.5917503747664402, + -0.5967832540390615, + -0.6130424939063307, + -0.5930475051215599, + -0.6093573556090445, + -0.5989470593654461, + -0.5845659494901442, + -0.6006742712305501, + -0.5705183361386409, + -0.5802214835165794, + -0.5813144789491883, + -0.5945462750297424, + -0.6060665316489774, + -0.6338224312205408, + -0.6133413857874385, + -0.6456504390068377, + -0.6696087275441559, + -0.6286190472747107 + ], + "pair_npib": 1.8433488761948427, + "source_lineage": [ + [ + 23 + ], + [ + 24 + ] + ], + "geometry_samples": 100, + "geometry_sequence_length": 512, + "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", + "selection_policy": "native_dynamic_adjacent_NPIB", + "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", + "removed_original_layers": [ + 24 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 20, + 21, + 23, + 25, + 26, + 27, + 28, + 29, + 30, + 31 + ] + }, + { + "cycle": 4, + "pair_index": 24, + "initializer": "mka", + "lambda_left": 0.6214287991453509, + "recipient_original_layer": 27, + "recipient_side": "left", + "removed_original_layer": 28, + "npib_matrix": [ + [ + 2.3598368318150484, + 0.3443452304720188, + 0.9511127221245259, + 0.6904843093120027, + 0.6690162505343388, + 0.6512097574296891, + 0.631399187420879, + 0.5855134762308328, + 0.6074206194778445, + 0.6555240534054558, + 0.49958804122731876, + 0.6371923983001465, + 0.4417405635438939, + 0.5458261478339751, + 0.5147575575305561, + 0.5456280200378638, + 0.5119727444468924, + 0.4906904475143589, + 0.5069969467582512, + 0.509695920091663, + 0.49398628694295066, + 0.4777223980170616, + 0.4483855704677067, + 0.49889753614881016, + 0.5544097476036024, + 0.5899085981382183, + 0.6065855130415095, + 0.7619975068059607, + 0.6603751948219921 + ], + [ + 0.3443452304720188, + 2.391816699157234, + 0.6105530658931005, + 0.4443044467140416, + 0.4158723960081373, + 0.40098832660997547, + 0.35615130217538943, + 0.43519508514758576, + 0.3503926486536749, + 0.33321429661265745, + 0.33267757715099683, + 0.37623434210878476, + 0.32133205919801977, + 0.3490059585089323, + 0.3660249748943472, + 0.3114854567755884, + 0.2663593264561916, + 0.2697431210006974, + 0.2708607670334084, + 0.2636171211243358, + 0.2870144728303516, + 0.3150619224401865, + 0.32457032664387564, + 0.37736365348917367, + 0.36566606236565885, + 0.3385276943010031, + 0.39586035516225865, + 0.4497313141819099, + 0.3810434251268655 + ], + [ + 0.9511127221245259, + 0.6105530658931005, + 2.4034261954132092, + 1.172988635221176, + 0.9543480188379591, + 0.8217904224586922, + 0.805130531492367, + 0.8220121195811046, + 0.7808879677224255, + 0.7198356581526952, + 0.6651786755142716, + 0.7394256448693735, + 0.5932303151559802, + 0.6590574115563346, + 0.5715370352061608, + 0.6433894891957147, + 0.6561537291529483, + 0.5636594465267478, + 0.5470659748216011, + 0.4820355727830177, + 0.42359644388184126, + 0.4290130649925284, + 0.48633978571767406, + 0.5306666992435854, + 0.5585118509719904, + 0.541394970071984, + 0.6277604572852876, + 0.7593678065259454, + 0.6866671568777142 + ], + [ + 0.6904843093120027, + 0.4443044467140416, + 1.172988635221176, + 2.3196693821091636, + 1.4078769588470965, + 1.183936344408245, + 1.1082009322507629, + 0.9869828327866518, + 0.9597145887539139, + 0.8597942447782176, + 0.8324508551527933, + 0.905095248097947, + 0.6673620409811332, + 0.5916311920292769, + 0.5334841931361148, + 0.7273803335574809, + 0.7331561725301285, + 0.634557790255331, + 0.5878535143099074, + 0.5458337816977792, + 0.4799224486802803, + 0.44754294544947126, + 0.42912129947190836, + 0.47784591951956373, + 0.48835222100251724, + 0.49644723883219316, + 0.6307491837540473, + 0.6800550797531838, + 0.6193262698160626 + ], + [ + 0.6690162505343388, + 0.4158723960081373, + 0.9543480188379591, + 1.4078769588470965, + 2.2720808664678995, + 1.485803190155229, + 1.327137744734443, + 0.9471235684848248, + 1.041610642885693, + 0.9573001564339423, + 0.9696052598995775, + 1.007237442000292, + 0.7128891436386944, + 0.6222556937347655, + 0.568017177630325, + 0.8534056937268815, + 0.8583181137894533, + 0.7680260770400199, + 0.6696025604235553, + 0.6137087253643312, + 0.4869978469188338, + 0.45971006974425616, + 0.4342588806481867, + 0.47317993670947534, + 0.4841336167643895, + 0.48649844232124384, + 0.6163900033604423, + 0.6747334933449406, + 0.550592065461312 + ], + [ + 0.6512097574296891, + 0.40098832660997547, + 0.8217904224586922, + 1.183936344408245, + 1.485803190155229, + 2.2967483552546537, + 1.2091134623365896, + 0.8585350462054803, + 1.0042500648005865, + 1.0018474416582548, + 0.9933762252232546, + 0.9621227995153653, + 0.696909302382986, + 0.6173209992447204, + 0.584492383082575, + 0.9417926684185647, + 0.9804920771997399, + 0.8654061944230085, + 0.7982915952136304, + 0.693551712150731, + 0.49463228081020266, + 0.45137225107331364, + 0.43990946794546165, + 0.4617217454735904, + 0.5269775367404087, + 0.494876155330237, + 0.6821079656295619, + 0.7029352378078818, + 0.5105530223891046 + ], + [ + 0.631399187420879, + 0.35615130217538943, + 0.805130531492367, + 1.1082009322507629, + 1.327137744734443, + 1.2091134623365896, + 2.3477764543003454, + 1.3226532341597808, + 1.391330620637103, + 1.1491906635237006, + 1.330624622598439, + 1.2899779542933039, + 0.9812795935011823, + 0.8137354257801147, + 0.7128203622741097, + 1.0943587368970968, + 0.9169852285979067, + 0.7489303132311632, + 0.6594020787989971, + 0.5682074043438511, + 0.5056922134447404, + 0.4160543269307774, + 0.4227857302717014, + 0.47646466167056034, + 0.4681948928953218, + 0.5189919844162934, + 0.6166428799523332, + 0.6819074978263693, + 0.5423080095526123 + ], + [ + 0.5855134762308328, + 0.43519508514758576, + 0.8220121195811046, + 0.9869828327866518, + 0.9471235684848248, + 0.8585350462054803, + 1.3226532341597808, + 2.4645174274691333, + 1.5029144393235752, + 0.9573721322151795, + 1.2301516083629374, + 1.2305852484401933, + 1.1399072532624648, + 0.9239914450556869, + 0.8093851963034749, + 0.9379028784095761, + 0.731517385991915, + 0.6448813877703499, + 0.5717717424334022, + 0.4714663961826335, + 0.45551041034889256, + 0.3919586756643936, + 0.3754624904030411, + 0.3884244698755106, + 0.3931704655154562, + 0.43566594861417557, + 0.564792540961827, + 0.5800074144253207, + 0.568141767376776 + ], + [ + 0.6074206194778445, + 0.3503926486536749, + 0.7808879677224255, + 0.9597145887539139, + 1.041610642885693, + 1.0042500648005865, + 1.391330620637103, + 1.5029144393235752, + 2.4052196230162677, + 1.2619624752451808, + 1.6629277581695627, + 1.4891374132962578, + 1.0460814411649866, + 0.8646820523019201, + 0.8616511378320537, + 1.0424249204378506, + 0.8597179961702175, + 0.6853907014738974, + 0.5940671202652917, + 0.5110226758298415, + 0.45984362316260796, + 0.3978230277118285, + 0.38853240489800867, + 0.41111756199119454, + 0.4526571066492106, + 0.43479741985352593, + 0.5888168646206028, + 0.5927429548820353, + 0.5621755108816642 + ], + [ + 0.6555240534054558, + 0.33321429661265745, + 0.7198356581526952, + 0.8597942447782176, + 0.9573001564339423, + 1.0018474416582548, + 1.1491906635237006, + 0.9573721322151795, + 1.2619624752451808, + 2.4560572801455933, + 1.483543481961692, + 1.3405276365717165, + 0.873279151443917, + 0.7367176797293109, + 0.7671022375573167, + 0.9327855360635636, + 1.0918270331754372, + 0.8987631835322829, + 0.803533839199152, + 0.7387411852170389, + 0.592435898640002, + 0.4946397590464865, + 0.4818822757302268, + 0.5451054029788187, + 0.6052415377616155, + 0.6188126366725923, + 0.7274854301795741, + 0.7888779843663815, + 0.5756575681804428 + ], + [ + 0.49958804122731876, + 0.33267757715099683, + 0.6651786755142716, + 0.8324508551527933, + 0.9696052598995775, + 0.9933762252232546, + 1.330624622598439, + 1.2301516083629374, + 1.6629277581695627, + 1.483543481961692, + 2.4914126330956137, + 1.6929237795968073, + 1.0771191337248727, + 0.8883623835176718, + 0.8878595069664904, + 1.1132836387670426, + 1.032671214420258, + 0.8192048616297526, + 0.662358373020083, + 0.6048540019320288, + 0.49502227461357323, + 0.40292790905984166, + 0.42632241050557057, + 0.46845061285433875, + 0.45322862891787485, + 0.4578253898988515, + 0.5953437196389184, + 0.6547181024506887, + 0.528902482610194 + ], + [ + 0.6371923983001465, + 0.37623434210878476, + 0.7394256448693735, + 0.905095248097947, + 1.007237442000292, + 0.9621227995153653, + 1.2899779542933039, + 1.2305852484401933, + 1.4891374132962578, + 1.3405276365717165, + 1.6929237795968073, + 2.510786418656704, + 1.105015632231669, + 0.9460946269422356, + 0.9918068018658639, + 1.1470943292218765, + 1.0083643873866202, + 0.8081600544791975, + 0.6716363352631979, + 0.581883479435235, + 0.503975827793527, + 0.46109022615033257, + 0.44639271265800956, + 0.479131893195918, + 0.5241625887117312, + 0.570362117396969, + 0.6596876512780077, + 0.7333204404497603, + 0.5695334203481488 + ], + [ + 0.4417405635438939, + 0.32133205919801977, + 0.5932303151559802, + 0.6673620409811332, + 0.7128891436386944, + 0.696909302382986, + 0.9812795935011823, + 1.1399072532624648, + 1.0460814411649866, + 0.873279151443917, + 1.0771191337248727, + 1.105015632231669, + 2.4424500948199106, + 1.2331711378465116, + 0.9869157393394576, + 0.9785032314839748, + 0.6539071204830524, + 0.5355085539514636, + 0.5056950225437449, + 0.45024533594856087, + 0.4264009212176895, + 0.32904911111956586, + 0.3539963832603928, + 0.36767176666680723, + 0.4314820128267822, + 0.46748906072650054, + 0.5834104363175144, + 0.582678544821444, + 0.5306267809937362 + ], + [ + 0.5458261478339751, + 0.3490059585089323, + 0.6590574115563346, + 0.5916311920292769, + 0.6222556937347655, + 0.6173209992447204, + 0.8137354257801147, + 0.9239914450556869, + 0.8646820523019201, + 0.7367176797293109, + 0.8883623835176718, + 0.9460946269422356, + 1.2331711378465116, + 2.4086109155702577, + 1.1621077679013359, + 0.8982730203378348, + 0.6927039380229185, + 0.6290895770560241, + 0.5843147569474538, + 0.5794452186493381, + 0.5525000392692625, + 0.4738953439605773, + 0.4732384296504443, + 0.4543980498410436, + 0.5306544427030813, + 0.5631202661591924, + 0.5590855461305394, + 0.6417454173824407, + 0.5457402885420086 + ], + [ + 0.5147575575305561, + 0.3660249748943472, + 0.5715370352061608, + 0.5334841931361148, + 0.568017177630325, + 0.584492383082575, + 0.7128203622741097, + 0.8093851963034749, + 0.8616511378320537, + 0.7671022375573167, + 0.8878595069664904, + 0.9918068018658639, + 0.9869157393394576, + 1.1621077679013359, + 2.4712107267688586, + 0.8577210081001834, + 0.674081272784002, + 0.5751414578932731, + 0.5478054716933916, + 0.49815395164947046, + 0.5288598664301039, + 0.46018996158776276, + 0.4583655895097408, + 0.438774791031295, + 0.48618633507458764, + 0.4857666297496164, + 0.5740404906861404, + 0.6853101130562791, + 0.5751501331031035 + ], + [ + 0.5456280200378638, + 0.3114854567755884, + 0.6433894891957147, + 0.7273803335574809, + 0.8534056937268815, + 0.9417926684185647, + 1.0943587368970968, + 0.9379028784095761, + 1.0424249204378506, + 0.9327855360635636, + 1.1132836387670426, + 1.1470943292218765, + 0.9785032314839748, + 0.8982730203378348, + 0.8577210081001834, + 2.35422460389475, + 1.1181007818213686, + 0.8714307710618016, + 0.7381816659115783, + 0.6476494026609263, + 0.49557930786416166, + 0.45058225966369114, + 0.43894389179458343, + 0.4768540183730887, + 0.5249334898584487, + 0.5515671294938511, + 0.6244974548374118, + 0.7031810032366932, + 0.47233775530598293 + ], + [ + 0.5119727444468924, + 0.2663593264561916, + 0.6561537291529483, + 0.7331561725301285, + 0.8583181137894533, + 0.9804920771997399, + 0.9169852285979067, + 0.731517385991915, + 0.8597179961702175, + 1.0918270331754372, + 1.032671214420258, + 1.0083643873866202, + 0.6539071204830524, + 0.6927039380229185, + 0.674081272784002, + 1.1181007818213686, + 2.364160616417643, + 1.406379212095852, + 1.1413088181770794, + 0.9802747268836863, + 0.6601521103275246, + 0.5627223639863541, + 0.5643169982060225, + 0.6382812072503347, + 0.6572336055484409, + 0.7183087189994398, + 0.8760863469922743, + 0.8191896114136177, + 0.3961464947498511 + ], + [ + 0.4906904475143589, + 0.2697431210006974, + 0.5636594465267478, + 0.634557790255331, + 0.7680260770400199, + 0.8654061944230085, + 0.7489303132311632, + 0.6448813877703499, + 0.6853907014738974, + 0.8987631835322829, + 0.8192048616297526, + 0.8081600544791975, + 0.5355085539514636, + 0.6290895770560241, + 0.5751414578932731, + 0.8714307710618016, + 1.406379212095852, + 2.375249320052241, + 1.5460048798765922, + 1.1211371830440595, + 0.826251932506181, + 0.7053121266212709, + 0.648007332201699, + 0.6859282462142468, + 0.7516644576091708, + 0.7729497919055347, + 0.8928200903205241, + 0.7666833940248412, + 0.41700726431869956 + ], + [ + 0.5069969467582512, + 0.2708607670334084, + 0.5470659748216011, + 0.5878535143099074, + 0.6696025604235553, + 0.7982915952136304, + 0.6594020787989971, + 0.5717717424334022, + 0.5940671202652917, + 0.803533839199152, + 0.662358373020083, + 0.6716363352631979, + 0.5056950225437449, + 0.5843147569474538, + 0.5478054716933916, + 0.7381816659115783, + 1.1413088181770794, + 1.5460048798765922, + 2.3972158331560505, + 1.3129963258733297, + 1.0338351357632705, + 0.8176128556002724, + 0.7682947359500265, + 0.7982393095183105, + 0.890338390632563, + 0.9456453663880567, + 0.9800948140914871, + 0.8260223728285291, + 0.46285422860794995 + ], + [ + 0.509695920091663, + 0.2636171211243358, + 0.4820355727830177, + 0.5458337816977792, + 0.6137087253643312, + 0.693551712150731, + 0.5682074043438511, + 0.4714663961826335, + 0.5110226758298415, + 0.7387411852170389, + 0.6048540019320288, + 0.581883479435235, + 0.45024533594856087, + 0.5794452186493381, + 0.49815395164947046, + 0.6476494026609263, + 0.9802747268836863, + 1.1211371830440595, + 1.3129963258733297, + 2.423024856913207, + 1.2237360183481807, + 0.9275915012223467, + 0.9736963815916483, + 1.0590363622629884, + 1.102406271576372, + 1.1733691300359488, + 1.0799160915818709, + 0.9177346783311634, + 0.49184154027871335 + ], + [ + 0.49398628694295066, + 0.2870144728303516, + 0.42359644388184126, + 0.4799224486802803, + 0.4869978469188338, + 0.49463228081020266, + 0.5056922134447404, + 0.45551041034889256, + 0.45984362316260796, + 0.592435898640002, + 0.49502227461357323, + 0.503975827793527, + 0.4264009212176895, + 0.5525000392692625, + 0.5288598664301039, + 0.49557930786416166, + 0.6601521103275246, + 0.826251932506181, + 1.0338351357632705, + 1.2237360183481807, + 2.563849009889373, + 1.6053637306718178, + 1.4287044617237288, + 1.3459008519221531, + 1.2783280619530364, + 1.2859095711473054, + 0.9802142577739286, + 0.8860271278713211, + 0.5235956788369126 + ], + [ + 0.4777223980170616, + 0.3150619224401865, + 0.4290130649925284, + 0.44754294544947126, + 0.45971006974425616, + 0.45137225107331364, + 0.4160543269307774, + 0.3919586756643936, + 0.3978230277118285, + 0.4946397590464865, + 0.40292790905984166, + 0.46109022615033257, + 0.32904911111956586, + 0.4738953439605773, + 0.46018996158776276, + 0.45058225966369114, + 0.5627223639863541, + 0.7053121266212709, + 0.8176128556002724, + 0.9275915012223467, + 1.6053637306718178, + 2.5518011860560654, + 1.7846382378202132, + 1.5651474492987432, + 1.2255427556233986, + 1.2072638526989938, + 0.9075578601130548, + 0.8274974047918999, + 0.5203899162775607 + ], + [ + 0.4483855704677067, + 0.32457032664387564, + 0.48633978571767406, + 0.42912129947190836, + 0.4342588806481867, + 0.43990946794546165, + 0.4227857302717014, + 0.3754624904030411, + 0.38853240489800867, + 0.4818822757302268, + 0.42632241050557057, + 0.44639271265800956, + 0.3539963832603928, + 0.4732384296504443, + 0.4583655895097408, + 0.43894389179458343, + 0.5643169982060225, + 0.648007332201699, + 0.7682947359500265, + 0.9736963815916483, + 1.4287044617237288, + 1.7846382378202132, + 2.509965443030394, + 1.7510576906084423, + 1.3775982877620547, + 1.318766874073593, + 0.9995123935405109, + 0.8569719192909191, + 0.45699483617404196 + ], + [ + 0.49889753614881016, + 0.37736365348917367, + 0.5306666992435854, + 0.47784591951956373, + 0.47317993670947534, + 0.4617217454735904, + 0.47646466167056034, + 0.3884244698755106, + 0.41111756199119454, + 0.5451054029788187, + 0.46845061285433875, + 0.479131893195918, + 0.36767176666680723, + 0.4543980498410436, + 0.438774791031295, + 0.4768540183730887, + 0.6382812072503347, + 0.6859282462142468, + 0.7982393095183105, + 1.0590363622629884, + 1.3459008519221531, + 1.5651474492987432, + 1.7510576906084423, + 2.401240529626188, + 1.5401428646279158, + 1.490082688784796, + 1.1058716197554594, + 0.9109250442210471, + 0.4892857763678062 + ], + [ + 0.5544097476036024, + 0.36566606236565885, + 0.5585118509719904, + 0.48835222100251724, + 0.4841336167643895, + 0.5269775367404087, + 0.4681948928953218, + 0.3931704655154562, + 0.4526571066492106, + 0.6052415377616155, + 0.45322862891787485, + 0.5241625887117312, + 0.4314820128267822, + 0.5306544427030813, + 0.48618633507458764, + 0.5249334898584487, + 0.6572336055484409, + 0.7516644576091708, + 0.890338390632563, + 1.102406271576372, + 1.2783280619530364, + 1.2255427556233986, + 1.3775982877620547, + 1.5401428646279158, + 2.425179730140971, + 1.79552158793285, + 1.290926226336089, + 0.9787881708892342, + 0.5173733469762901 + ], + [ + 0.5899085981382183, + 0.3385276943010031, + 0.541394970071984, + 0.49644723883219316, + 0.48649844232124384, + 0.494876155330237, + 0.5189919844162934, + 0.43566594861417557, + 0.43479741985352593, + 0.6188126366725923, + 0.4578253898988515, + 0.570362117396969, + 0.46748906072650054, + 0.5631202661591924, + 0.4857666297496164, + 0.5515671294938511, + 0.7183087189994398, + 0.7729497919055347, + 0.9456453663880567, + 1.1733691300359488, + 1.2859095711473054, + 1.2072638526989938, + 1.318766874073593, + 1.490082688784796, + 1.79552158793285, + 2.3850461051755043, + 1.343587301242696, + 1.0437870921145342, + 0.5655114899970136 + ], + [ + 0.6065855130415095, + 0.39586035516225865, + 0.6277604572852876, + 0.6307491837540473, + 0.6163900033604423, + 0.6821079656295619, + 0.6166428799523332, + 0.564792540961827, + 0.5888168646206028, + 0.7274854301795741, + 0.5953437196389184, + 0.6596876512780077, + 0.5834104363175144, + 0.5590855461305394, + 0.5740404906861404, + 0.6244974548374118, + 0.8760863469922743, + 0.8928200903205241, + 0.9800948140914871, + 1.0799160915818709, + 0.9802142577739286, + 0.9075578601130548, + 0.9995123935405109, + 1.1058716197554594, + 1.290926226336089, + 1.343587301242696, + 2.283481888251667, + 1.3699617962066117, + 0.5987736284527644 + ], + [ + 0.7619975068059607, + 0.4497313141819099, + 0.7593678065259454, + 0.6800550797531838, + 0.6747334933449406, + 0.7029352378078818, + 0.6819074978263693, + 0.5800074144253207, + 0.5927429548820353, + 0.7888779843663815, + 0.6547181024506887, + 0.7333204404497603, + 0.582678544821444, + 0.6417454173824407, + 0.6853101130562791, + 0.7031810032366932, + 0.8191896114136177, + 0.7666833940248412, + 0.8260223728285291, + 0.9177346783311634, + 0.8860271278713211, + 0.8274974047918999, + 0.8569719192909191, + 0.9109250442210471, + 0.9787881708892342, + 1.0437870921145342, + 1.3699617962066117, + 2.5438750829873813, + 0.7333136427865427 + ], + [ + 0.6603751948219921, + 0.3810434251268655, + 0.6866671568777142, + 0.6193262698160626, + 0.550592065461312, + 0.5105530223891046, + 0.5423080095526123, + 0.568141767376776, + 0.5621755108816642, + 0.5756575681804428, + 0.528902482610194, + 0.5695334203481488, + 0.5306267809937362, + 0.5457402885420086, + 0.5751501331031035, + 0.47233775530598293, + 0.3961464947498511, + 0.41700726431869956, + 0.46285422860794995, + 0.49184154027871335, + 0.5235956788369126, + 0.5203899162775607, + 0.45699483617404196, + 0.4892857763678062, + 0.5173733469762901, + 0.5655114899970136, + 0.5987736284527644, + 0.7333136427865427, + 2.583327109890292 + ] + ], + "entropies": [ + -0.6315610607587784, + -0.627416009583068, + -0.5861614941870391, + -0.6016038763611488, + -0.6130674217530055, + -0.6121981385094227, + -0.6033131501980972, + -0.5924187613341422, + -0.6069171484092294, + -0.6132380808987886, + -0.5909367743402253, + -0.590407987771964, + -0.5917503747664402, + -0.5967832540390615, + -0.6130424939063307, + -0.5930475051215599, + -0.6093573556090445, + -0.5989470593654461, + -0.5845659494901442, + -0.6006742712305501, + -0.5705183361386409, + -0.566425003102157, + -0.5875409475739463, + -0.6165914355649426, + -0.6481007302498619, + -0.6388713218255503, + -0.6641428062353042, + -0.6250859027743988, + -0.6166829740327132 + ], + "pair_npib": 1.79552158793285, + "source_lineage": [ + [ + 27 + ], + [ + 28 + ] + ], + "geometry_samples": 100, + "geometry_sequence_length": 512, + "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", + "selection_policy": "native_dynamic_adjacent_NPIB", + "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", + "removed_original_layers": [ + 28 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 20, + 21, + 23, + 25, + 26, + 27, + 29, + 30, + 31 + ] + }, + { + "cycle": 5, + "pair_index": 21, + "initializer": "mka", + "lambda_left": 0.6221970199569331, + "recipient_original_layer": 23, + "recipient_side": "left", + "removed_original_layer": 25, + "npib_matrix": [ + [ + 2.3598368318150484, + 0.3443452304720188, + 0.9511127221245259, + 0.6904843093120027, + 0.6690162505343388, + 0.6512097574296891, + 0.631399187420879, + 0.5855134762308328, + 0.6074206194778445, + 0.6555240534054558, + 0.49958804122731876, + 0.6371923983001465, + 0.4417405635438939, + 0.5458261478339751, + 0.5147575575305561, + 0.5456280200378638, + 0.5119727444468924, + 0.4906904475143589, + 0.5069969467582512, + 0.509695920091663, + 0.49398628694295066, + 0.4777223980170616, + 0.4483855704677067, + 0.49889753614881016, + 0.5794776539454732, + 0.6703168987807457, + 0.7899735437392195, + 0.8221502726118711 + ], + [ + 0.3443452304720188, + 2.391816699157234, + 0.6105530658931005, + 0.4443044467140416, + 0.4158723960081373, + 0.40098832660997547, + 0.35615130217538943, + 0.43519508514758576, + 0.3503926486536749, + 0.33321429661265745, + 0.33267757715099683, + 0.37623434210878476, + 0.32133205919801977, + 0.3490059585089323, + 0.3660249748943472, + 0.3114854567755884, + 0.2663593264561916, + 0.2697431210006974, + 0.2708607670334084, + 0.2636171211243358, + 0.2870144728303516, + 0.3150619224401865, + 0.32457032664387564, + 0.37736365348917367, + 0.34805218453661785, + 0.4174593559400913, + 0.47956318979672663, + 0.42986351468781164 + ], + [ + 0.9511127221245259, + 0.6105530658931005, + 2.4034261954132092, + 1.172988635221176, + 0.9543480188379591, + 0.8217904224586922, + 0.805130531492367, + 0.8220121195811046, + 0.7808879677224255, + 0.7198356581526952, + 0.6651786755142716, + 0.7394256448693735, + 0.5932303151559802, + 0.6590574115563346, + 0.5715370352061608, + 0.6433894891957147, + 0.6561537291529483, + 0.5636594465267478, + 0.5470659748216011, + 0.4820355727830177, + 0.42359644388184126, + 0.4290130649925284, + 0.48633978571767406, + 0.5306666992435854, + 0.5543464953014086, + 0.6592011885387397, + 0.7791423632616443, + 0.8075482555761011 + ], + [ + 0.6904843093120027, + 0.4443044467140416, + 1.172988635221176, + 2.3196693821091636, + 1.4078769588470965, + 1.183936344408245, + 1.1082009322507629, + 0.9869828327866518, + 0.9597145887539139, + 0.8597942447782176, + 0.8324508551527933, + 0.905095248097947, + 0.6673620409811332, + 0.5916311920292769, + 0.5334841931361148, + 0.7273803335574809, + 0.7331561725301285, + 0.634557790255331, + 0.5878535143099074, + 0.5458337816977792, + 0.4799224486802803, + 0.44754294544947126, + 0.42912129947190836, + 0.47784591951956373, + 0.5093809784458568, + 0.6366790259204592, + 0.6621333392667872, + 0.6443837154801703 + ], + [ + 0.6690162505343388, + 0.4158723960081373, + 0.9543480188379591, + 1.4078769588470965, + 2.2720808664678995, + 1.485803190155229, + 1.327137744734443, + 0.9471235684848248, + 1.041610642885693, + 0.9573001564339423, + 0.9696052598995775, + 1.007237442000292, + 0.7128891436386944, + 0.6222556937347655, + 0.568017177630325, + 0.8534056937268815, + 0.8583181137894533, + 0.7680260770400199, + 0.6696025604235553, + 0.6137087253643312, + 0.4869978469188338, + 0.45971006974425616, + 0.4342588806481867, + 0.47317993670947534, + 0.49584227841155437, + 0.6315916902570382, + 0.6446993912470474, + 0.5825669387471439 + ], + [ + 0.6512097574296891, + 0.40098832660997547, + 0.8217904224586922, + 1.183936344408245, + 1.485803190155229, + 2.2967483552546537, + 1.2091134623365896, + 0.8585350462054803, + 1.0042500648005865, + 1.0018474416582548, + 0.9933762252232546, + 0.9621227995153653, + 0.696909302382986, + 0.6173209992447204, + 0.584492383082575, + 0.9417926684185647, + 0.9804920771997399, + 0.8654061944230085, + 0.7982915952136304, + 0.693551712150731, + 0.49463228081020266, + 0.45137225107331364, + 0.43990946794546165, + 0.4617217454735904, + 0.535081916436093, + 0.6789559912123032, + 0.6682230919167835, + 0.5542534456702773 + ], + [ + 0.631399187420879, + 0.35615130217538943, + 0.805130531492367, + 1.1082009322507629, + 1.327137744734443, + 1.2091134623365896, + 2.3477764543003454, + 1.3226532341597808, + 1.391330620637103, + 1.1491906635237006, + 1.330624622598439, + 1.2899779542933039, + 0.9812795935011823, + 0.8137354257801147, + 0.7128203622741097, + 1.0943587368970968, + 0.9169852285979067, + 0.7489303132311632, + 0.6594020787989971, + 0.5682074043438511, + 0.5056922134447404, + 0.4160543269307774, + 0.4227857302717014, + 0.47646466167056034, + 0.46284063765685335, + 0.6661304821036966, + 0.6620494422312281, + 0.581969212820974 + ], + [ + 0.5855134762308328, + 0.43519508514758576, + 0.8220121195811046, + 0.9869828327866518, + 0.9471235684848248, + 0.8585350462054803, + 1.3226532341597808, + 2.4645174274691333, + 1.5029144393235752, + 0.9573721322151795, + 1.2301516083629374, + 1.2305852484401933, + 1.1399072532624648, + 0.9239914450556869, + 0.8093851963034749, + 0.9379028784095761, + 0.731517385991915, + 0.6448813877703499, + 0.5717717424334022, + 0.4714663961826335, + 0.45551041034889256, + 0.3919586756643936, + 0.3754624904030411, + 0.3884244698755106, + 0.380984488066055, + 0.5824022175313844, + 0.6066258466754166, + 0.6250936654391329 + ], + [ + 0.6074206194778445, + 0.3503926486536749, + 0.7808879677224255, + 0.9597145887539139, + 1.041610642885693, + 1.0042500648005865, + 1.391330620637103, + 1.5029144393235752, + 2.4052196230162677, + 1.2619624752451808, + 1.6629277581695627, + 1.4891374132962578, + 1.0460814411649866, + 0.8646820523019201, + 0.8616511378320537, + 1.0424249204378506, + 0.8597179961702175, + 0.6853907014738974, + 0.5940671202652917, + 0.5110226758298415, + 0.45984362316260796, + 0.3978230277118285, + 0.38853240489800867, + 0.41111756199119454, + 0.46565662533957985, + 0.6108760999093586, + 0.615934444355253, + 0.6398296558303973 + ], + [ + 0.6555240534054558, + 0.33321429661265745, + 0.7198356581526952, + 0.8597942447782176, + 0.9573001564339423, + 1.0018474416582548, + 1.1491906635237006, + 0.9573721322151795, + 1.2619624752451808, + 2.4560572801455933, + 1.483543481961692, + 1.3405276365717165, + 0.873279151443917, + 0.7367176797293109, + 0.7671022375573167, + 0.9327855360635636, + 1.0918270331754372, + 0.8987631835322829, + 0.803533839199152, + 0.7387411852170389, + 0.592435898640002, + 0.4946397590464865, + 0.4818822757302268, + 0.5451054029788187, + 0.6221854035519965, + 0.8041759652199647, + 0.77229822719718, + 0.6968078037259439 + ], + [ + 0.49958804122731876, + 0.33267757715099683, + 0.6651786755142716, + 0.8324508551527933, + 0.9696052598995775, + 0.9933762252232546, + 1.330624622598439, + 1.2301516083629374, + 1.6629277581695627, + 1.483543481961692, + 2.4914126330956137, + 1.6929237795968073, + 1.0771191337248727, + 0.8883623835176718, + 0.8878595069664904, + 1.1132836387670426, + 1.032671214420258, + 0.8192048616297526, + 0.662358373020083, + 0.6048540019320288, + 0.49502227461357323, + 0.40292790905984166, + 0.42632241050557057, + 0.46845061285433875, + 0.48986146415642073, + 0.6346994381867248, + 0.6401495703677096, + 0.5784163488599099 + ], + [ + 0.6371923983001465, + 0.37623434210878476, + 0.7394256448693735, + 0.905095248097947, + 1.007237442000292, + 0.9621227995153653, + 1.2899779542933039, + 1.2305852484401933, + 1.4891374132962578, + 1.3405276365717165, + 1.6929237795968073, + 2.510786418656704, + 1.105015632231669, + 0.9460946269422356, + 0.9918068018658639, + 1.1470943292218765, + 1.0083643873866202, + 0.8081600544791975, + 0.6716363352631979, + 0.581883479435235, + 0.503975827793527, + 0.46109022615033257, + 0.44639271265800956, + 0.479131893195918, + 0.5151531577594091, + 0.6842343576933878, + 0.7492961869665714, + 0.6770687854167308 + ], + [ + 0.4417405635438939, + 0.32133205919801977, + 0.5932303151559802, + 0.6673620409811332, + 0.7128891436386944, + 0.696909302382986, + 0.9812795935011823, + 1.1399072532624648, + 1.0460814411649866, + 0.873279151443917, + 1.0771191337248727, + 1.105015632231669, + 2.4424500948199106, + 1.2331711378465116, + 0.9869157393394576, + 0.9785032314839748, + 0.6539071204830524, + 0.5355085539514636, + 0.5056950225437449, + 0.45024533594856087, + 0.4264009212176895, + 0.32904911111956586, + 0.3539963832603928, + 0.36767176666680723, + 0.4606521695086941, + 0.5649219683729501, + 0.5968006961553914, + 0.5639173627496276 + ], + [ + 0.5458261478339751, + 0.3490059585089323, + 0.6590574115563346, + 0.5916311920292769, + 0.6222556937347655, + 0.6173209992447204, + 0.8137354257801147, + 0.9239914450556869, + 0.8646820523019201, + 0.7367176797293109, + 0.8883623835176718, + 0.9460946269422356, + 1.2331711378465116, + 2.4086109155702577, + 1.1621077679013359, + 0.8982730203378348, + 0.6927039380229185, + 0.6290895770560241, + 0.5843147569474538, + 0.5794452186493381, + 0.5525000392692625, + 0.4738953439605773, + 0.4732384296504443, + 0.4543980498410436, + 0.5012691862777366, + 0.6092561062767229, + 0.7063634297109176, + 0.6137245940104896 + ], + [ + 0.5147575575305561, + 0.3660249748943472, + 0.5715370352061608, + 0.5334841931361148, + 0.568017177630325, + 0.584492383082575, + 0.7128203622741097, + 0.8093851963034749, + 0.8616511378320537, + 0.7671022375573167, + 0.8878595069664904, + 0.9918068018658639, + 0.9869157393394576, + 1.1621077679013359, + 2.4712107267688586, + 0.8577210081001834, + 0.674081272784002, + 0.5751414578932731, + 0.5478054716933916, + 0.49815395164947046, + 0.5288598664301039, + 0.46018996158776276, + 0.4583655895097408, + 0.438774791031295, + 0.4697790475784892, + 0.5669287231932266, + 0.6967261075862243, + 0.6045783514176186 + ], + [ + 0.5456280200378638, + 0.3114854567755884, + 0.6433894891957147, + 0.7273803335574809, + 0.8534056937268815, + 0.9417926684185647, + 1.0943587368970968, + 0.9379028784095761, + 1.0424249204378506, + 0.9327855360635636, + 1.1132836387670426, + 1.1470943292218765, + 0.9785032314839748, + 0.8982730203378348, + 0.8577210081001834, + 2.35422460389475, + 1.1181007818213686, + 0.8714307710618016, + 0.7381816659115783, + 0.6476494026609263, + 0.49557930786416166, + 0.45058225966369114, + 0.43894389179458343, + 0.4768540183730887, + 0.5180276464332257, + 0.7077493350845457, + 0.6697031286586539, + 0.5335525158916894 + ], + [ + 0.5119727444468924, + 0.2663593264561916, + 0.6561537291529483, + 0.7331561725301285, + 0.8583181137894533, + 0.9804920771997399, + 0.9169852285979067, + 0.731517385991915, + 0.8597179961702175, + 1.0918270331754372, + 1.032671214420258, + 1.0083643873866202, + 0.6539071204830524, + 0.6927039380229185, + 0.674081272784002, + 1.1181007818213686, + 2.364160616417643, + 1.406379212095852, + 1.1413088181770794, + 0.9802747268836863, + 0.6601521103275246, + 0.5627223639863541, + 0.5643169982060225, + 0.6382812072503347, + 0.6475990795422849, + 0.8435547228706625, + 0.7548710993287076, + 0.4864587572313497 + ], + [ + 0.4906904475143589, + 0.2697431210006974, + 0.5636594465267478, + 0.634557790255331, + 0.7680260770400199, + 0.8654061944230085, + 0.7489303132311632, + 0.6448813877703499, + 0.6853907014738974, + 0.8987631835322829, + 0.8192048616297526, + 0.8081600544791975, + 0.5355085539514636, + 0.6290895770560241, + 0.5751414578932731, + 0.8714307710618016, + 1.406379212095852, + 2.375249320052241, + 1.5460048798765922, + 1.1211371830440595, + 0.826251932506181, + 0.7053121266212709, + 0.648007332201699, + 0.6859282462142468, + 0.7370603037565234, + 0.8135329680989616, + 0.6922123945090936, + 0.4578408835785252 + ], + [ + 0.5069969467582512, + 0.2708607670334084, + 0.5470659748216011, + 0.5878535143099074, + 0.6696025604235553, + 0.7982915952136304, + 0.6594020787989971, + 0.5717717424334022, + 0.5940671202652917, + 0.803533839199152, + 0.662358373020083, + 0.6716363352631979, + 0.5056950225437449, + 0.5843147569474538, + 0.5478054716933916, + 0.7381816659115783, + 1.1413088181770794, + 1.5460048798765922, + 2.3972158331560505, + 1.3129963258733297, + 1.0338351357632705, + 0.8176128556002724, + 0.7682947359500265, + 0.7982393095183105, + 0.8788859503522779, + 0.8736832272707794, + 0.7653734692450399, + 0.5345304460917677 + ], + [ + 0.509695920091663, + 0.2636171211243358, + 0.4820355727830177, + 0.5458337816977792, + 0.6137087253643312, + 0.693551712150731, + 0.5682074043438511, + 0.4714663961826335, + 0.5110226758298415, + 0.7387411852170389, + 0.6048540019320288, + 0.581883479435235, + 0.45024533594856087, + 0.5794452186493381, + 0.49815395164947046, + 0.6476494026609263, + 0.9802747268836863, + 1.1211371830440595, + 1.3129963258733297, + 2.423024856913207, + 1.2237360183481807, + 0.9275915012223467, + 0.9736963815916483, + 1.0590363622629884, + 1.1432648173065343, + 1.0371509431508756, + 0.841459157947284, + 0.5042021539028971 + ], + [ + 0.49398628694295066, + 0.2870144728303516, + 0.42359644388184126, + 0.4799224486802803, + 0.4869978469188338, + 0.49463228081020266, + 0.5056922134447404, + 0.45551041034889256, + 0.45984362316260796, + 0.592435898640002, + 0.49502227461357323, + 0.503975827793527, + 0.4264009212176895, + 0.5525000392692625, + 0.5288598664301039, + 0.49557930786416166, + 0.6601521103275246, + 0.826251932506181, + 1.0338351357632705, + 1.2237360183481807, + 2.563849009889373, + 1.6053637306718178, + 1.4287044617237288, + 1.3459008519221531, + 1.2747454884253004, + 0.9265554874236803, + 0.8033385579586865, + 0.5828186389444051 + ], + [ + 0.4777223980170616, + 0.3150619224401865, + 0.4290130649925284, + 0.44754294544947126, + 0.45971006974425616, + 0.45137225107331364, + 0.4160543269307774, + 0.3919586756643936, + 0.3978230277118285, + 0.4946397590464865, + 0.40292790905984166, + 0.46109022615033257, + 0.32904911111956586, + 0.4738953439605773, + 0.46018996158776276, + 0.45058225966369114, + 0.5627223639863541, + 0.7053121266212709, + 0.8176128556002724, + 0.9275915012223467, + 1.6053637306718178, + 2.5518011860560654, + 1.7846382378202132, + 1.5651474492987432, + 1.2176012383504526, + 0.8713671493977907, + 0.7758256083095822, + 0.5831075526615509 + ], + [ + 0.4483855704677067, + 0.32457032664387564, + 0.48633978571767406, + 0.42912129947190836, + 0.4342588806481867, + 0.43990946794546165, + 0.4227857302717014, + 0.3754624904030411, + 0.38853240489800867, + 0.4818822757302268, + 0.42632241050557057, + 0.44639271265800956, + 0.3539963832603928, + 0.4732384296504443, + 0.4583655895097408, + 0.43894389179458343, + 0.5643169982060225, + 0.648007332201699, + 0.7682947359500265, + 0.9736963815916483, + 1.4287044617237288, + 1.7846382378202132, + 2.509965443030394, + 1.7510576906084423, + 1.3591282714130228, + 0.9615071248049515, + 0.7826672651370301, + 0.5594151482232897 + ], + [ + 0.49889753614881016, + 0.37736365348917367, + 0.5306666992435854, + 0.47784591951956373, + 0.47317993670947534, + 0.4617217454735904, + 0.47646466167056034, + 0.3884244698755106, + 0.41111756199119454, + 0.5451054029788187, + 0.46845061285433875, + 0.479131893195918, + 0.36767176666680723, + 0.4543980498410436, + 0.438774791031295, + 0.4768540183730887, + 0.6382812072503347, + 0.6859282462142468, + 0.7982393095183105, + 1.0590363622629884, + 1.3459008519221531, + 1.5651474492987432, + 1.7510576906084423, + 2.401240529626188, + 1.5426661266325248, + 1.0628815319455236, + 0.8172041987696337, + 0.6160414997950703 + ], + [ + 0.5794776539454732, + 0.34805218453661785, + 0.5543464953014086, + 0.5093809784458568, + 0.49584227841155437, + 0.535081916436093, + 0.46284063765685335, + 0.380984488066055, + 0.46565662533957985, + 0.6221854035519965, + 0.48986146415642073, + 0.5151531577594091, + 0.4606521695086941, + 0.5012691862777366, + 0.4697790475784892, + 0.5180276464332257, + 0.6475990795422849, + 0.7370603037565234, + 0.8788859503522779, + 1.1432648173065343, + 1.2747454884253004, + 1.2176012383504526, + 1.3591282714130228, + 1.5426661266325248, + 2.347595174783102, + 1.245874905280682, + 0.9489876692994466, + 0.6418947637395174 + ], + [ + 0.6703168987807457, + 0.4174593559400913, + 0.6592011885387397, + 0.6366790259204592, + 0.6315916902570382, + 0.6789559912123032, + 0.6661304821036966, + 0.5824022175313844, + 0.6108760999093586, + 0.8041759652199647, + 0.6346994381867248, + 0.6842343576933878, + 0.5649219683729501, + 0.6092561062767229, + 0.5669287231932266, + 0.7077493350845457, + 0.8435547228706625, + 0.8135329680989616, + 0.8736832272707794, + 1.0371509431508756, + 0.9265554874236803, + 0.8713671493977907, + 0.9615071248049515, + 1.0628815319455236, + 1.245874905280682, + 2.3625104531178467, + 1.3602635569831139, + 0.767508645582742 + ], + [ + 0.7899735437392195, + 0.47956318979672663, + 0.7791423632616443, + 0.6621333392667872, + 0.6446993912470474, + 0.6682230919167835, + 0.6620494422312281, + 0.6066258466754166, + 0.615934444355253, + 0.77229822719718, + 0.6401495703677096, + 0.7492961869665714, + 0.5968006961553914, + 0.7063634297109176, + 0.6967261075862243, + 0.6697031286586539, + 0.7548710993287076, + 0.6922123945090936, + 0.7653734692450399, + 0.841459157947284, + 0.8033385579586865, + 0.7758256083095822, + 0.7826672651370301, + 0.8172041987696337, + 0.9489876692994466, + 1.3602635569831139, + 2.4398651928634596, + 1.0470794128105856 + ], + [ + 0.8221502726118711, + 0.42986351468781164, + 0.8075482555761011, + 0.6443837154801703, + 0.5825669387471439, + 0.5542534456702773, + 0.581969212820974, + 0.6250936654391329, + 0.6398296558303973, + 0.6968078037259439, + 0.5784163488599099, + 0.6770687854167308, + 0.5639173627496276, + 0.6137245940104896, + 0.6045783514176186, + 0.5335525158916894, + 0.4864587572313497, + 0.4578408835785252, + 0.5345304460917677, + 0.5042021539028971, + 0.5828186389444051, + 0.5831075526615509, + 0.5594151482232897, + 0.6160414997950703, + 0.6418947637395174, + 0.767508645582742, + 1.0470794128105856, + 2.690553158220629 + ] + ], + "entropies": [ + -0.6315610607587784, + -0.627416009583068, + -0.5861614941870391, + -0.6016038763611488, + -0.6130674217530055, + -0.6121981385094227, + -0.6033131501980972, + -0.5924187613341422, + -0.6069171484092294, + -0.6132380808987886, + -0.5909367743402253, + -0.590407987771964, + -0.5917503747664402, + -0.5967832540390615, + -0.6130424939063307, + -0.5930475051215599, + -0.6093573556090445, + -0.5989470593654461, + -0.5845659494901442, + -0.6006742712305501, + -0.5705183361386409, + -0.566425003102157, + -0.5875409475739463, + -0.6165914355649426, + -0.6507573345616348, + -0.6501803103780216, + -0.6403402608026175, + -0.5992278924805038 + ], + "pair_npib": 1.7846382378202132, + "source_lineage": [ + [ + 23, + 24 + ], + [ + 25 + ] + ], + "geometry_samples": 100, + "geometry_sequence_length": 512, + "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", + "selection_policy": "native_dynamic_adjacent_NPIB", + "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", + "removed_original_layers": [ + 25 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 20, + 21, + 23, + 26, + 27, + 29, + 30, + 31 + ] + }, + { + "cycle": 6, + "pair_index": 10, + "initializer": "mka", + "lambda_left": 0.6211211480841742, + "recipient_original_layer": 10, + "recipient_side": "left", + "removed_original_layer": 11, + "npib_matrix": [ + [ + 2.3598368318150484, + 0.3443452304720188, + 0.9511127221245259, + 0.6904843093120027, + 0.6690162505343388, + 0.6512097574296891, + 0.631399187420879, + 0.5855134762308328, + 0.6074206194778445, + 0.6555240534054558, + 0.49958804122731876, + 0.6371923983001465, + 0.4417405635438939, + 0.5458261478339751, + 0.5147575575305561, + 0.5456280200378638, + 0.5119727444468924, + 0.4906904475143589, + 0.5069969467582512, + 0.509695920091663, + 0.49398628694295066, + 0.45335080198516614, + 0.5374852803333448, + 0.5912983751202626, + 0.6628026440297746, + 0.8046898151644674, + 0.8004213305465817 + ], + [ + 0.3443452304720188, + 2.391816699157234, + 0.6105530658931005, + 0.4443044467140416, + 0.4158723960081373, + 0.40098832660997547, + 0.35615130217538943, + 0.43519508514758576, + 0.3503926486536749, + 0.33321429661265745, + 0.33267757715099683, + 0.37623434210878476, + 0.32133205919801977, + 0.3490059585089323, + 0.3660249748943472, + 0.3114854567755884, + 0.2663593264561916, + 0.2697431210006974, + 0.2708607670334084, + 0.2636171211243358, + 0.2870144728303516, + 0.28932097368218873, + 0.36935909320341626, + 0.3663841717189645, + 0.42961060100320225, + 0.4574026309807762, + 0.41391610881336044 + ], + [ + 0.9511127221245259, + 0.6105530658931005, + 2.4034261954132092, + 1.172988635221176, + 0.9543480188379591, + 0.8217904224586922, + 0.805130531492367, + 0.8220121195811046, + 0.7808879677224255, + 0.7198356581526952, + 0.6651786755142716, + 0.7394256448693735, + 0.5932303151559802, + 0.6590574115563346, + 0.5715370352061608, + 0.6433894891957147, + 0.6561537291529483, + 0.5636594465267478, + 0.5470659748216011, + 0.4820355727830177, + 0.42359644388184126, + 0.4791335095019951, + 0.5343428979883099, + 0.6128567995571936, + 0.6635883927748624, + 0.7676958336485146, + 0.7365717604639545 + ], + [ + 0.6904843093120027, + 0.4443044467140416, + 1.172988635221176, + 2.3196693821091636, + 1.4078769588470965, + 1.183936344408245, + 1.1082009322507629, + 0.9869828327866518, + 0.9597145887539139, + 0.8597942447782176, + 0.8324508551527933, + 0.905095248097947, + 0.6673620409811332, + 0.5916311920292769, + 0.5334841931361148, + 0.7273803335574809, + 0.7331561725301285, + 0.634557790255331, + 0.5878535143099074, + 0.5458337816977792, + 0.4799224486802803, + 0.41966968083390405, + 0.4811321512766612, + 0.5409721166476651, + 0.6454276123345728, + 0.6590416649528926, + 0.5854879013233093 + ], + [ + 0.6690162505343388, + 0.4158723960081373, + 0.9543480188379591, + 1.4078769588470965, + 2.2720808664678995, + 1.485803190155229, + 1.327137744734443, + 0.9471235684848248, + 1.041610642885693, + 0.9573001564339423, + 0.9696052598995775, + 1.007237442000292, + 0.7128891436386944, + 0.6222556937347655, + 0.568017177630325, + 0.8534056937268815, + 0.8583181137894533, + 0.7680260770400199, + 0.6696025604235553, + 0.6137087253643312, + 0.4869978469188338, + 0.42309744666214966, + 0.4840177480923737, + 0.546894729794062, + 0.658959151092131, + 0.677813976100921, + 0.5463673347846533 + ], + [ + 0.6512097574296891, + 0.40098832660997547, + 0.8217904224586922, + 1.183936344408245, + 1.485803190155229, + 2.2967483552546537, + 1.2091134623365896, + 0.8585350462054803, + 1.0042500648005865, + 1.0018474416582548, + 0.9933762252232546, + 0.9621227995153653, + 0.696909302382986, + 0.6173209992447204, + 0.584492383082575, + 0.9417926684185647, + 0.9804920771997399, + 0.8654061944230085, + 0.7982915952136304, + 0.693551712150731, + 0.49463228081020266, + 0.4486827991059572, + 0.5244718456702396, + 0.6082432042169559, + 0.7059912436002767, + 0.6750635636817831, + 0.4931043142446773 + ], + [ + 0.631399187420879, + 0.35615130217538943, + 0.805130531492367, + 1.1082009322507629, + 1.327137744734443, + 1.2091134623365896, + 2.3477764543003454, + 1.3226532341597808, + 1.391330620637103, + 1.1491906635237006, + 1.330624622598439, + 1.2899779542933039, + 0.9812795935011823, + 0.8137354257801147, + 0.7128203622741097, + 1.0943587368970968, + 0.9169852285979067, + 0.7489303132311632, + 0.6594020787989971, + 0.5682074043438511, + 0.5056922134447404, + 0.4591801604396694, + 0.46674236549241294, + 0.5066840790724988, + 0.6655189669653977, + 0.7041549202509346, + 0.49201372226319656 + ], + [ + 0.5855134762308328, + 0.43519508514758576, + 0.8220121195811046, + 0.9869828327866518, + 0.9471235684848248, + 0.8585350462054803, + 1.3226532341597808, + 2.4645174274691333, + 1.5029144393235752, + 0.9573721322151795, + 1.2301516083629374, + 1.2305852484401933, + 1.1399072532624648, + 0.9239914450556869, + 0.8093851963034749, + 0.9379028784095761, + 0.731517385991915, + 0.6448813877703499, + 0.5717717424334022, + 0.4714663961826335, + 0.45551041034889256, + 0.3851093115519923, + 0.4378482133858219, + 0.44613131360823594, + 0.581701601544973, + 0.6215321349331299, + 0.574942830834319 + ], + [ + 0.6074206194778445, + 0.3503926486536749, + 0.7808879677224255, + 0.9597145887539139, + 1.041610642885693, + 1.0042500648005865, + 1.391330620637103, + 1.5029144393235752, + 2.4052196230162677, + 1.2619624752451808, + 1.6629277581695627, + 1.4891374132962578, + 1.0460814411649866, + 0.8646820523019201, + 0.8616511378320537, + 1.0424249204378506, + 0.8597179961702175, + 0.6853907014738974, + 0.5940671202652917, + 0.5110226758298415, + 0.45984362316260796, + 0.42685467713137104, + 0.3987709149537458, + 0.5034143411954559, + 0.609679771090402, + 0.6510388783235462, + 0.5759651886195324 + ], + [ + 0.6555240534054558, + 0.33321429661265745, + 0.7198356581526952, + 0.8597942447782176, + 0.9573001564339423, + 1.0018474416582548, + 1.1491906635237006, + 0.9573721322151795, + 1.2619624752451808, + 2.4560572801455933, + 1.483543481961692, + 1.3405276365717165, + 0.873279151443917, + 0.7367176797293109, + 0.7671022375573167, + 0.9327855360635636, + 1.0918270331754372, + 0.8987631835322829, + 0.803533839199152, + 0.7387411852170389, + 0.592435898640002, + 0.5071858197489115, + 0.5593800335615383, + 0.6818176257505596, + 0.8199264660155218, + 0.8148431423308914, + 0.5940714029177753 + ], + [ + 0.49958804122731876, + 0.33267757715099683, + 0.6651786755142716, + 0.8324508551527933, + 0.9696052598995775, + 0.9933762252232546, + 1.330624622598439, + 1.2301516083629374, + 1.6629277581695627, + 1.483543481961692, + 2.4914126330956137, + 1.6929237795968073, + 1.0771191337248727, + 0.8883623835176718, + 0.8878595069664904, + 1.1132836387670426, + 1.032671214420258, + 0.8192048616297526, + 0.662358373020083, + 0.6048540019320288, + 0.49502227461357323, + 0.43072169932658816, + 0.4287633983344934, + 0.5407230157953236, + 0.6504626395451086, + 0.664993536957874, + 0.5257170308682046 + ], + [ + 0.6371923983001465, + 0.37623434210878476, + 0.7394256448693735, + 0.905095248097947, + 1.007237442000292, + 0.9621227995153653, + 1.2899779542933039, + 1.2305852484401933, + 1.4891374132962578, + 1.3405276365717165, + 1.6929237795968073, + 2.510786418656704, + 1.105015632231669, + 0.9460946269422356, + 0.9918068018658639, + 1.1470943292218765, + 1.0083643873866202, + 0.8081600544791975, + 0.6716363352631979, + 0.581883479435235, + 0.503975827793527, + 0.485055920295041, + 0.4806550571769317, + 0.5873893481172074, + 0.6893763806932546, + 0.786292851153349, + 0.608267240799632 + ], + [ + 0.4417405635438939, + 0.32133205919801977, + 0.5932303151559802, + 0.6673620409811332, + 0.7128891436386944, + 0.696909302382986, + 0.9812795935011823, + 1.1399072532624648, + 1.0460814411649866, + 0.873279151443917, + 1.0771191337248727, + 1.105015632231669, + 2.4424500948199106, + 1.2331711378465116, + 0.9869157393394576, + 0.9785032314839748, + 0.6539071204830524, + 0.5355085539514636, + 0.5056950225437449, + 0.45024533594856087, + 0.4264009212176895, + 0.34582647085959073, + 0.4083388671087673, + 0.49310761676989595, + 0.5433426653638141, + 0.6435378979011438, + 0.5012995486695285 + ], + [ + 0.5458261478339751, + 0.3490059585089323, + 0.6590574115563346, + 0.5916311920292769, + 0.6222556937347655, + 0.6173209992447204, + 0.8137354257801147, + 0.9239914450556869, + 0.8646820523019201, + 0.7367176797293109, + 0.8883623835176718, + 0.9460946269422356, + 1.2331711378465116, + 2.4086109155702577, + 1.1621077679013359, + 0.8982730203378348, + 0.6927039380229185, + 0.6290895770560241, + 0.5843147569474538, + 0.5794452186493381, + 0.5525000392692625, + 0.47785627640332257, + 0.47378280738765854, + 0.5249290070696155, + 0.630420371586362, + 0.6902369074870401, + 0.582000477312818 + ], + [ + 0.5147575575305561, + 0.3660249748943472, + 0.5715370352061608, + 0.5334841931361148, + 0.568017177630325, + 0.584492383082575, + 0.7128203622741097, + 0.8093851963034749, + 0.8616511378320537, + 0.7671022375573167, + 0.8878595069664904, + 0.9918068018658639, + 0.9869157393394576, + 1.1621077679013359, + 2.4712107267688586, + 0.8577210081001834, + 0.674081272784002, + 0.5751414578932731, + 0.5478054716933916, + 0.49815395164947046, + 0.5288598664301039, + 0.45706794093123443, + 0.49219456524179833, + 0.5292902176243887, + 0.598082340208793, + 0.6806485619911529, + 0.6007012223808397 + ], + [ + 0.5456280200378638, + 0.3114854567755884, + 0.6433894891957147, + 0.7273803335574809, + 0.8534056937268815, + 0.9417926684185647, + 1.0943587368970968, + 0.9379028784095761, + 1.0424249204378506, + 0.9327855360635636, + 1.1132836387670426, + 1.1470943292218765, + 0.9785032314839748, + 0.8982730203378348, + 0.8577210081001834, + 2.35422460389475, + 1.1181007818213686, + 0.8714307710618016, + 0.7381816659115783, + 0.6476494026609263, + 0.49557930786416166, + 0.42955547304924235, + 0.49160922525339257, + 0.5779728349962087, + 0.6606808103237822, + 0.6894120322521047, + 0.4602984068134883 + ], + [ + 0.5119727444468924, + 0.2663593264561916, + 0.6561537291529483, + 0.7331561725301285, + 0.8583181137894533, + 0.9804920771997399, + 0.9169852285979067, + 0.731517385991915, + 0.8597179961702175, + 1.0918270331754372, + 1.032671214420258, + 1.0083643873866202, + 0.6539071204830524, + 0.6927039380229185, + 0.674081272784002, + 1.1181007818213686, + 2.364160616417643, + 1.406379212095852, + 1.1413088181770794, + 0.9802747268836863, + 0.6601521103275246, + 0.5551784192069527, + 0.6666337972180617, + 0.7310804586054421, + 0.8272018085136099, + 0.7988167110746931, + 0.4160705564139947 + ], + [ + 0.4906904475143589, + 0.2697431210006974, + 0.5636594465267478, + 0.634557790255331, + 0.7680260770400199, + 0.8654061944230085, + 0.7489303132311632, + 0.6448813877703499, + 0.6853907014738974, + 0.8987631835322829, + 0.8192048616297526, + 0.8081600544791975, + 0.5355085539514636, + 0.6290895770560241, + 0.5751414578932731, + 0.8714307710618016, + 1.406379212095852, + 2.375249320052241, + 1.5460048798765922, + 1.1211371830440595, + 0.826251932506181, + 0.650318340998573, + 0.7350447723489837, + 0.7818303096658102, + 0.7795182008087975, + 0.7265897837932167, + 0.3869675083724319 + ], + [ + 0.5069969467582512, + 0.2708607670334084, + 0.5470659748216011, + 0.5878535143099074, + 0.6696025604235553, + 0.7982915952136304, + 0.6594020787989971, + 0.5717717424334022, + 0.5940671202652917, + 0.803533839199152, + 0.662358373020083, + 0.6716363352631979, + 0.5056950225437449, + 0.5843147569474538, + 0.5478054716933916, + 0.7381816659115783, + 1.1413088181770794, + 1.5460048798765922, + 2.3972158331560505, + 1.3129963258733297, + 1.0338351357632705, + 0.7883362507631262, + 0.8922133225354445, + 0.8935435632676368, + 0.844713505143054, + 0.7583090205701598, + 0.40405135644727525 + ], + [ + 0.509695920091663, + 0.2636171211243358, + 0.4820355727830177, + 0.5458337816977792, + 0.6137087253643312, + 0.693551712150731, + 0.5682074043438511, + 0.4714663961826335, + 0.5110226758298415, + 0.7387411852170389, + 0.6048540019320288, + 0.581883479435235, + 0.45024533594856087, + 0.5794452186493381, + 0.49815395164947046, + 0.6476494026609263, + 0.9802747268836863, + 1.1211371830440595, + 1.3129963258733297, + 2.423024856913207, + 1.2237360183481807, + 1.031074308782409, + 1.145089826206785, + 1.1436342260409007, + 0.9955223948078512, + 0.8204865772213197, + 0.4583539606159496 + ], + [ + 0.49398628694295066, + 0.2870144728303516, + 0.42359644388184126, + 0.4799224486802803, + 0.4869978469188338, + 0.49463228081020266, + 0.5056922134447404, + 0.45551041034889256, + 0.45984362316260796, + 0.592435898640002, + 0.49502227461357323, + 0.503975827793527, + 0.4264009212176895, + 0.5525000392692625, + 0.5288598664301039, + 0.49557930786416166, + 0.6601521103275246, + 0.826251932506181, + 1.0338351357632705, + 1.2237360183481807, + 2.563849009889373, + 1.477880237809162, + 1.3684614500812533, + 1.1207897512418006, + 0.8676624238184715, + 0.7357238033859386, + 0.5725877823490031 + ], + [ + 0.45335080198516614, + 0.28932097368218873, + 0.4791335095019951, + 0.41966968083390405, + 0.42309744666214966, + 0.4486827991059572, + 0.4591801604396694, + 0.3851093115519923, + 0.42685467713137104, + 0.5071858197489115, + 0.43072169932658816, + 0.485055920295041, + 0.34582647085959073, + 0.47785627640332257, + 0.45706794093123443, + 0.42955547304924235, + 0.5551784192069527, + 0.650318340998573, + 0.7883362507631262, + 1.031074308782409, + 1.477880237809162, + 2.508411073690039, + 1.6383673287816813, + 1.2370293013643483, + 0.9058571633339495, + 0.77111683624205, + 0.550325568462528 + ], + [ + 0.5374852803333448, + 0.36935909320341626, + 0.5343428979883099, + 0.4811321512766612, + 0.4840177480923737, + 0.5244718456702396, + 0.46674236549241294, + 0.4378482133858219, + 0.3987709149537458, + 0.5593800335615383, + 0.4287633983344934, + 0.4806550571769317, + 0.4083388671087673, + 0.47378280738765854, + 0.49219456524179833, + 0.49160922525339257, + 0.6666337972180617, + 0.7350447723489837, + 0.8922133225354445, + 1.145089826206785, + 1.3684614500812533, + 1.6383673287816813, + 2.474450282644287, + 1.534680079584603, + 1.0426708054773213, + 0.8645302621932621, + 0.5870668177798261 + ], + [ + 0.5912983751202626, + 0.3663841717189645, + 0.6128567995571936, + 0.5409721166476651, + 0.546894729794062, + 0.6082432042169559, + 0.5066840790724988, + 0.44613131360823594, + 0.5034143411954559, + 0.6818176257505596, + 0.5407230157953236, + 0.5873893481172074, + 0.49310761676989595, + 0.5249290070696155, + 0.5292902176243887, + 0.5779728349962087, + 0.7310804586054421, + 0.7818303096658102, + 0.8935435632676368, + 1.1436342260409007, + 1.1207897512418006, + 1.2370293013643483, + 1.534680079584603, + 2.373921388547628, + 1.3086193638067878, + 1.0225538119172788, + 0.6605252120913919 + ], + [ + 0.6628026440297746, + 0.42961060100320225, + 0.6635883927748624, + 0.6454276123345728, + 0.658959151092131, + 0.7059912436002767, + 0.6655189669653977, + 0.581701601544973, + 0.609679771090402, + 0.8199264660155218, + 0.6504626395451086, + 0.6893763806932546, + 0.5433426653638141, + 0.630420371586362, + 0.598082340208793, + 0.6606808103237822, + 0.8272018085136099, + 0.7795182008087975, + 0.844713505143054, + 0.9955223948078512, + 0.8676624238184715, + 0.9058571633339495, + 1.0426708054773213, + 1.3086193638067878, + 2.344644475708516, + 1.361074464898733, + 0.6830021185639601 + ], + [ + 0.8046898151644674, + 0.4574026309807762, + 0.7676958336485146, + 0.6590416649528926, + 0.677813976100921, + 0.6750635636817831, + 0.7041549202509346, + 0.6215321349331299, + 0.6510388783235462, + 0.8148431423308914, + 0.664993536957874, + 0.786292851153349, + 0.6435378979011438, + 0.6902369074870401, + 0.6806485619911529, + 0.6894120322521047, + 0.7988167110746931, + 0.7265897837932167, + 0.7583090205701598, + 0.8204865772213197, + 0.7357238033859386, + 0.77111683624205, + 0.8645302621932621, + 1.0225538119172788, + 1.361074464898733, + 2.5116875995643375, + 0.9551650658518527 + ], + [ + 0.8004213305465817, + 0.41391610881336044, + 0.7365717604639545, + 0.5854879013233093, + 0.5463673347846533, + 0.4931043142446773, + 0.49201372226319656, + 0.574942830834319, + 0.5759651886195324, + 0.5940714029177753, + 0.5257170308682046, + 0.608267240799632, + 0.5012995486695285, + 0.582000477312818, + 0.6007012223808397, + 0.4602984068134883, + 0.4160705564139947, + 0.3869675083724319, + 0.40405135644727525, + 0.4583539606159496, + 0.5725877823490031, + 0.550325568462528, + 0.5870668177798261, + 0.6605252120913919, + 0.6830021185639601, + 0.9551650658518527, + 2.539769603315872 + ] + ], + "entropies": [ + -0.6315610607587784, + -0.627416009583068, + -0.5861614941870391, + -0.6016038763611488, + -0.6130674217530055, + -0.6121981385094227, + -0.6033131501980972, + -0.5924187613341422, + -0.6069171484092294, + -0.6132380808987886, + -0.5909367743402253, + -0.590407987771964, + -0.5917503747664402, + -0.5967832540390615, + -0.6130424939063307, + -0.5930475051215599, + -0.6093573556090445, + -0.5989470593654461, + -0.5845659494901442, + -0.6006742712305501, + -0.5705183361386409, + -0.5843026773437968, + -0.6082050236179576, + -0.6400439647853179, + -0.6563589513748683, + -0.621065842292377, + -0.6347100964603006 + ], + "pair_npib": 1.6929237795968073, + "source_lineage": [ + [ + 10 + ], + [ + 11 + ] + ], + "geometry_samples": 100, + "geometry_sequence_length": 512, + "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", + "selection_policy": "native_dynamic_adjacent_NPIB", + "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", + "removed_original_layers": [ + 11 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 20, + 21, + 23, + 26, + 27, + 29, + 30, + 31 + ] + }, + { + "cycle": 7, + "pair_index": 16, + "initializer": "mka", + "lambda_left": 0.6229176202047336, + "recipient_original_layer": 17, + "recipient_side": "left", + "removed_original_layer": 18, + "npib_matrix": [ + [ + 2.3598368318150484, + 0.3443452304720188, + 0.9511127221245259, + 0.6904843093120027, + 0.6690162505343388, + 0.6512097574296891, + 0.631399187420879, + 0.5855134762308328, + 0.6074206194778445, + 0.6555240534054558, + 0.6468646245229188, + 0.48386512555638805, + 0.4010211722783301, + 0.5033915775726365, + 0.5220912093729436, + 0.5785801800316468, + 0.5403576156824978, + 0.551883923365223, + 0.5493686546625294, + 0.48268558491840385, + 0.4178902405001316, + 0.5134190314810202, + 0.6006848903274685, + 0.6688254188601732, + 0.8222855157502483, + 0.7286881779934441 + ], + [ + 0.3443452304720188, + 2.391816699157234, + 0.6105530658931005, + 0.4443044467140416, + 0.4158723960081373, + 0.40098832660997547, + 0.35615130217538943, + 0.43519508514758576, + 0.3503926486536749, + 0.33321429661265745, + 0.3978135185832393, + 0.3420862065975434, + 0.3599542742502537, + 0.3470112694914168, + 0.2751405713892427, + 0.2707433044229157, + 0.2561008995927251, + 0.2559001668033965, + 0.2721500478718662, + 0.2836198574923427, + 0.2977899072146095, + 0.3207801789622396, + 0.3834623288548558, + 0.419580539865363, + 0.4408961566095609, + 0.36241339475988876 + ], + [ + 0.9511127221245259, + 0.6105530658931005, + 2.4034261954132092, + 1.172988635221176, + 0.9543480188379591, + 0.8217904224586922, + 0.805130531492367, + 0.8220121195811046, + 0.7808879677224255, + 0.7198356581526952, + 0.7630851397226434, + 0.7113242876211381, + 0.6063371940317739, + 0.6725319341165956, + 0.6851840521708761, + 0.6759834056295376, + 0.6060124854462113, + 0.5462638551309971, + 0.5226523222336857, + 0.4203154495253417, + 0.4834741423558716, + 0.5344311351855867, + 0.6084240879643644, + 0.672357622493252, + 0.7892494050080828, + 0.705918075497121 + ], + [ + 0.6904843093120027, + 0.4443044467140416, + 1.172988635221176, + 2.3196693821091636, + 1.4078769588470965, + 1.183936344408245, + 1.1082009322507629, + 0.9869828327866518, + 0.9597145887539139, + 0.8597942447782176, + 0.9422178318724331, + 0.7935692463020498, + 0.710652236782754, + 0.7448813798028994, + 0.800758910237514, + 0.7656800657914152, + 0.6318455995475545, + 0.5683052366031275, + 0.4893217364790713, + 0.4829376705029892, + 0.4536680165653426, + 0.49412326106709614, + 0.5513340519950782, + 0.6500722242328474, + 0.6845465246677723, + 0.6394287268449844 + ], + [ + 0.6690162505343388, + 0.4158723960081373, + 0.9543480188379591, + 1.4078769588470965, + 2.2720808664678995, + 1.485803190155229, + 1.327137744734443, + 0.9471235684848248, + 1.041610642885693, + 0.9573001564339423, + 1.004890227172128, + 0.8369107452846558, + 0.7163701134323567, + 0.7609434960123262, + 0.8624160140167811, + 0.8674397726595604, + 0.7234553025736752, + 0.6311095584419916, + 0.557282324982113, + 0.49441397744016885, + 0.45708403671880304, + 0.5070768599378718, + 0.5569309945766417, + 0.67130330951018, + 0.7054391901605672, + 0.5675821771326574 + ], + [ + 0.6512097574296891, + 0.40098832660997547, + 0.8217904224586922, + 1.183936344408245, + 1.485803190155229, + 2.2967483552546537, + 1.2091134623365896, + 0.8585350462054803, + 1.0042500648005865, + 1.0018474416582548, + 0.9643373878370798, + 0.7928451544922585, + 0.7364243323486791, + 0.7988955099279339, + 0.9762560121929411, + 0.9664130712793463, + 0.8098446314328327, + 0.7077293917396646, + 0.6795931773917419, + 0.494722629936874, + 0.47892823059251277, + 0.5382118468373948, + 0.6053937002099455, + 0.7071696992158498, + 0.6980929877352766, + 0.5212772978530593 + ], + [ + 0.631399187420879, + 0.35615130217538943, + 0.805130531492367, + 1.1082009322507629, + 1.327137744734443, + 1.2091134623365896, + 2.3477764543003454, + 1.3226532341597808, + 1.391330620637103, + 1.1491906635237006, + 1.2893550102502047, + 1.1181698813701444, + 0.9673366523224821, + 1.008191184464644, + 1.1263658478892322, + 0.9117621378010781, + 0.7362499119186292, + 0.6340848017502989, + 0.5693860762335029, + 0.4782926219094823, + 0.4845669643055239, + 0.47931905364127514, + 0.5035437941006315, + 0.6672894905241743, + 0.6828827759946574, + 0.5209524907318311 + ], + [ + 0.5855134762308328, + 0.43519508514758576, + 0.8220121195811046, + 0.9869828327866518, + 0.9471235684848248, + 0.8585350462054803, + 1.3226532341597808, + 2.4645174274691333, + 1.5029144393235752, + 0.9573721322151795, + 1.1495888950698574, + 1.1923271187604316, + 1.1097961184670972, + 1.1255776191769986, + 0.9829260905226019, + 0.6964948583217169, + 0.5909789002639599, + 0.5253593659658348, + 0.4508843376259229, + 0.45255789873266705, + 0.43152914915895524, + 0.41728744721708955, + 0.4236662668932388, + 0.5508772757989226, + 0.6269548577350508, + 0.5610390884079554 + ], + [ + 0.6074206194778445, + 0.3503926486536749, + 0.7808879677224255, + 0.9597145887539139, + 1.041610642885693, + 1.0042500648005865, + 1.391330620637103, + 1.5029144393235752, + 2.4052196230162677, + 1.2619624752451808, + 1.4904255687370833, + 1.1505456864057921, + 0.9987906614639515, + 1.1190929279853943, + 1.0370464195501439, + 0.8212167185981412, + 0.66757661533987, + 0.5598082169046041, + 0.5032931170011931, + 0.4793831381252399, + 0.4717090062958921, + 0.4240815859301651, + 0.5095026531001848, + 0.5952342697251642, + 0.641358313032677, + 0.5405931692218373 + ], + [ + 0.6555240534054558, + 0.33321429661265745, + 0.7198356581526952, + 0.8597942447782176, + 0.9573001564339423, + 1.0018474416582548, + 1.1491906635237006, + 0.9573721322151795, + 1.2619624752451808, + 2.4560572801455933, + 1.532978540442259, + 0.9497134580898713, + 0.7932694884542277, + 1.0033565894397825, + 0.9039828912574503, + 1.0964581466100178, + 0.8676287427100094, + 0.7513955625692529, + 0.6912764135023558, + 0.5562575733346085, + 0.5145876288932697, + 0.5492051241365922, + 0.6681071610501748, + 0.770627626818291, + 0.795891118089989, + 0.5839508380954916 + ], + [ + 0.6468646245229188, + 0.3978135185832393, + 0.7630851397226434, + 0.9422178318724331, + 1.004890227172128, + 0.9643373878370798, + 1.2893550102502047, + 1.1495888950698574, + 1.4904255687370833, + 1.532978540442259, + 2.3842181406676346, + 1.1059470068324664, + 0.9528074090008355, + 1.1262690420717347, + 1.049328850873215, + 1.0223393758433283, + 0.8123800895308765, + 0.6816246225574429, + 0.5944463574720084, + 0.5222688131100603, + 0.49058015288008244, + 0.5035563232890979, + 0.594003481104933, + 0.7277272568617905, + 0.7547580688534902, + 0.5435079657445441 + ], + [ + 0.48386512555638805, + 0.3420862065975434, + 0.7113242876211381, + 0.7935692463020498, + 0.8369107452846558, + 0.7928451544922585, + 1.1181698813701444, + 1.1923271187604316, + 1.1505456864057921, + 0.9497134580898713, + 1.1059470068324664, + 2.3958333143153903, + 1.3748275467356477, + 1.1107893925064793, + 1.1010970888139984, + 0.6966066742454438, + 0.5227074601189505, + 0.4806852999960854, + 0.42759047289701907, + 0.4090417385590338, + 0.3968805143591941, + 0.3687680392920408, + 0.44038506376584513, + 0.5161478827860795, + 0.5617739421099501, + 0.5124161810545235 + ], + [ + 0.4010211722783301, + 0.3599542742502537, + 0.6063371940317739, + 0.710652236782754, + 0.7163701134323567, + 0.7364243323486791, + 0.9673366523224821, + 1.1097961184670972, + 0.9987906614639515, + 0.7932694884542277, + 0.9528074090008355, + 1.3748275467356477, + 2.3753773455518816, + 1.0836784667782404, + 1.064863627444301, + 0.6252111571092671, + 0.48457506241966886, + 0.424762211901511, + 0.41254121185334974, + 0.3851957559439322, + 0.3768856704341697, + 0.35341959373648607, + 0.3671209094120494, + 0.502034120130529, + 0.5785187307921954, + 0.47520434153202357 + ], + [ + 0.5033915775726365, + 0.3470112694914168, + 0.6725319341165956, + 0.7448813798028994, + 0.7609434960123262, + 0.7988955099279339, + 1.008191184464644, + 1.1255776191769986, + 1.1190929279853943, + 1.0033565894397825, + 1.1262690420717347, + 1.1107893925064793, + 1.0836784667782404, + 2.4361261299080312, + 1.2350278852110423, + 0.8337528696252383, + 0.5849397548771007, + 0.5408838052625088, + 0.5180426400881113, + 0.4846361749994343, + 0.4379960754806888, + 0.46207623566842543, + 0.5059380071760173, + 0.6240230692491472, + 0.7439188429860257, + 0.5073859182449295 + ], + [ + 0.5220912093729436, + 0.2751405713892427, + 0.6851840521708761, + 0.800758910237514, + 0.8624160140167811, + 0.9762560121929411, + 1.1263658478892322, + 0.9829260905226019, + 1.0370464195501439, + 0.9039828912574503, + 1.049328850873215, + 1.1010970888139984, + 1.064863627444301, + 1.2350278852110423, + 2.460555716215801, + 1.079432364500123, + 0.7728266006749084, + 0.6303725242489584, + 0.6067468808432535, + 0.49426114433282875, + 0.38966869524472664, + 0.45835347439887614, + 0.5002874486052681, + 0.6239673478458534, + 0.6479151332362771, + 0.4713393097867291 + ], + [ + 0.5785801800316468, + 0.2707433044229157, + 0.6759834056295376, + 0.7656800657914152, + 0.8674397726595604, + 0.9664130712793463, + 0.9117621378010781, + 0.6964948583217169, + 0.8212167185981412, + 1.0964581466100178, + 1.0223393758433283, + 0.6966066742454438, + 0.6252111571092671, + 0.8337528696252383, + 1.079432364500123, + 2.41637020390684, + 1.388554166549276, + 1.120954372712504, + 1.005270005147273, + 0.6988651146656154, + 0.5842282569512135, + 0.6799830136217646, + 0.7507405634588832, + 0.8625501243535848, + 0.7801232814340977, + 0.4648961489635178 + ], + [ + 0.5403576156824978, + 0.2561008995927251, + 0.6060124854462113, + 0.6318455995475545, + 0.7234553025736752, + 0.8098446314328327, + 0.7362499119186292, + 0.5909789002639599, + 0.66757661533987, + 0.8676287427100094, + 0.8123800895308765, + 0.5227074601189505, + 0.48457506241966886, + 0.5849397548771007, + 0.7728266006749084, + 1.388554166549276, + 2.382381471089437, + 1.5415356845175048, + 1.2263173755113101, + 0.922891846435451, + 0.7991039029011175, + 0.8222985837299797, + 0.8729705513273728, + 0.8564120485814887, + 0.7535525086597612, + 0.4483718078653066 + ], + [ + 0.551883923365223, + 0.2559001668033965, + 0.5462638551309971, + 0.5683052366031275, + 0.6311095584419916, + 0.7077293917396646, + 0.6340848017502989, + 0.5253593659658348, + 0.5598082169046041, + 0.7513955625692529, + 0.6816246225574429, + 0.4806852999960854, + 0.424762211901511, + 0.5408838052625088, + 0.6303725242489584, + 1.120954372712504, + 1.5415356845175048, + 2.415777418076167, + 1.4088702036617449, + 1.1354904872264522, + 0.9717830075234418, + 1.0525244571533197, + 1.055650137255634, + 0.9241732451635963, + 0.8297484041632065, + 0.5071466294454351 + ], + [ + 0.5493686546625294, + 0.2721500478718662, + 0.5226523222336857, + 0.4893217364790713, + 0.557282324982113, + 0.6795931773917419, + 0.5693860762335029, + 0.4508843376259229, + 0.5032931170011931, + 0.6912764135023558, + 0.5944463574720084, + 0.42759047289701907, + 0.41254121185334974, + 0.5180426400881113, + 0.6067468808432535, + 1.005270005147273, + 1.2263173755113101, + 1.4088702036617449, + 2.396697783379457, + 1.2953736461593668, + 1.0589944408139493, + 1.191899108912222, + 1.1883849202219805, + 0.9427693516320256, + 0.8073730226080222, + 0.49455356363347325 + ], + [ + 0.48268558491840385, + 0.2836198574923427, + 0.4203154495253417, + 0.4829376705029892, + 0.49441397744016885, + 0.494722629936874, + 0.4782926219094823, + 0.45255789873266705, + 0.4793831381252399, + 0.5562575733346085, + 0.5222688131100603, + 0.4090417385590338, + 0.3851957559439322, + 0.4846361749994343, + 0.49426114433282875, + 0.6988651146656154, + 0.922891846435451, + 1.1354904872264522, + 1.2953736461593668, + 2.6369181011860414, + 1.5270667645876577, + 1.2930069274674594, + 1.0705596325216846, + 0.7954691950540447, + 0.6567898607664578, + 0.5613238145951476 + ], + [ + 0.4178902405001316, + 0.2977899072146095, + 0.4834741423558716, + 0.4536680165653426, + 0.45708403671880304, + 0.47892823059251277, + 0.4845669643055239, + 0.43152914915895524, + 0.4717090062958921, + 0.5145876288932697, + 0.49058015288008244, + 0.3968805143591941, + 0.3768856704341697, + 0.4379960754806888, + 0.38966869524472664, + 0.5842282569512135, + 0.7991039029011175, + 0.9717830075234418, + 1.0589944408139493, + 1.5270667645876577, + 2.5065749566086835, + 1.5358753362151811, + 1.1613174413634975, + 0.8915822570597934, + 0.7187834085812282, + 0.5362838876699274 + ], + [ + 0.5134190314810202, + 0.3207801789622396, + 0.5344311351855867, + 0.49412326106709614, + 0.5070768599378718, + 0.5382118468373948, + 0.47931905364127514, + 0.41728744721708955, + 0.4240815859301651, + 0.5492051241365922, + 0.5035563232890979, + 0.3687680392920408, + 0.35341959373648607, + 0.46207623566842543, + 0.45835347439887614, + 0.6799830136217646, + 0.8222985837299797, + 1.0525244571533197, + 1.191899108912222, + 1.2930069274674594, + 1.5358753362151811, + 2.5012375721507363, + 1.5283555967263496, + 1.0255737291271385, + 0.8956400393932858, + 0.5525849241908769 + ], + [ + 0.6006848903274685, + 0.3834623288548558, + 0.6084240879643644, + 0.5513340519950782, + 0.5569309945766417, + 0.6053937002099455, + 0.5035437941006315, + 0.4236662668932388, + 0.5095026531001848, + 0.6681071610501748, + 0.594003481104933, + 0.44038506376584513, + 0.3671209094120494, + 0.5059380071760173, + 0.5002874486052681, + 0.7507405634588832, + 0.8729705513273728, + 1.055650137255634, + 1.1883849202219805, + 1.0705596325216846, + 1.1613174413634975, + 1.5283555967263496, + 2.3612303115930966, + 1.2621587714315874, + 1.0127729471628093, + 0.5599469137968626 + ], + [ + 0.6688254188601732, + 0.419580539865363, + 0.672357622493252, + 0.6500722242328474, + 0.67130330951018, + 0.7071696992158498, + 0.6672894905241743, + 0.5508772757989226, + 0.5952342697251642, + 0.770627626818291, + 0.7277272568617905, + 0.5161478827860795, + 0.502034120130529, + 0.6240230692491472, + 0.6239673478458534, + 0.8625501243535848, + 0.8564120485814887, + 0.9241732451635963, + 0.9427693516320256, + 0.7954691950540447, + 0.8915822570597934, + 1.0255737291271385, + 1.2621587714315874, + 2.2703663371451435, + 1.3574145206527946, + 0.6458944212630935 + ], + [ + 0.8222855157502483, + 0.4408961566095609, + 0.7892494050080828, + 0.6845465246677723, + 0.7054391901605672, + 0.6980929877352766, + 0.6828827759946574, + 0.6269548577350508, + 0.641358313032677, + 0.795891118089989, + 0.7547580688534902, + 0.5617739421099501, + 0.5785187307921954, + 0.7439188429860257, + 0.6479151332362771, + 0.7801232814340977, + 0.7535525086597612, + 0.8297484041632065, + 0.8073730226080222, + 0.6567898607664578, + 0.7187834085812282, + 0.8956400393932858, + 1.0127729471628093, + 1.3574145206527946, + 2.5560589083367704, + 0.9099970312359303 + ], + [ + 0.7286881779934441, + 0.36241339475988876, + 0.705918075497121, + 0.6394287268449844, + 0.5675821771326574, + 0.5212772978530593, + 0.5209524907318311, + 0.5610390884079554, + 0.5405931692218373, + 0.5839508380954916, + 0.5435079657445441, + 0.5124161810545235, + 0.47520434153202357, + 0.5073859182449295, + 0.4713393097867291, + 0.4648961489635178, + 0.4483718078653066, + 0.5071466294454351, + 0.49455356363347325, + 0.5613238145951476, + 0.5362838876699274, + 0.5525849241908769, + 0.5599469137968626, + 0.6458944212630935, + 0.9099970312359303, + 2.585960123292869 + ] + ], + "entropies": [ + -0.6315610607587784, + -0.627416009583068, + -0.5861614941870391, + -0.6016038763611488, + -0.6130674217530055, + -0.6121981385094227, + -0.6033131501980972, + -0.5924187613341422, + -0.6069171484092294, + -0.6132380808987886, + -0.607843819939205, + -0.6085076526449892, + -0.5918690386938749, + -0.5995608511332241, + -0.5767638850935354, + -0.5998789692930665, + -0.5994408320409431, + -0.5950893317180167, + -0.5982691857051824, + -0.5578064876569259, + -0.577818168115036, + -0.6012980952371977, + -0.6334446234704915, + -0.6592623178960838, + -0.6091736365869417, + -0.616569194453633 + ], + "pair_npib": 1.5415356845175048, + "source_lineage": [ + [ + 17 + ], + [ + 18, + 19 + ] + ], + "geometry_samples": 100, + "geometry_sequence_length": 512, + "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", + "selection_policy": "native_dynamic_adjacent_NPIB", + "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", + "removed_original_layers": [ + 18 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 12, + 13, + 14, + 15, + 16, + 17, + 20, + 21, + 23, + 26, + 27, + 29, + 30, + 31 + ] + }, + { + "cycle": 8, + "pair_index": 16, + "initializer": "mka", + "lambda_left": 0.6223904334015297, + "recipient_original_layer": 17, + "recipient_side": "left", + "removed_original_layer": 20, + "npib_matrix": [ + [ + 2.3598368318150484, + 0.3443452304720188, + 0.9511127221245259, + 0.6904843093120027, + 0.6690162505343388, + 0.6512097574296891, + 0.631399187420879, + 0.5855134762308328, + 0.6074206194778445, + 0.6555240534054558, + 0.6468646245229188, + 0.48386512555638805, + 0.4010211722783301, + 0.5033915775726365, + 0.5220912093729436, + 0.5785801800316468, + 0.6442455233325804, + 0.6228956526917968, + 0.5203496643623892, + 0.5371261678840263, + 0.5825351017560767, + 0.6503846227179654, + 0.6900385431718811, + 0.829548144288587, + 0.5189759258959196 + ], + [ + 0.3443452304720188, + 2.391816699157234, + 0.6105530658931005, + 0.4443044467140416, + 0.4158723960081373, + 0.40098832660997547, + 0.35615130217538943, + 0.43519508514758576, + 0.3503926486536749, + 0.33321429661265745, + 0.3978135185832393, + 0.3420862065975434, + 0.3599542742502537, + 0.3470112694914168, + 0.2751405713892427, + 0.2707433044229157, + 0.2992515509507363, + 0.3181859515554761, + 0.2684602964727382, + 0.3273533306066217, + 0.37040159366374903, + 0.3482640919635858, + 0.36463216687678607, + 0.4109825242943798, + 0.3445118406932491 + ], + [ + 0.9511127221245259, + 0.6105530658931005, + 2.4034261954132092, + 1.172988635221176, + 0.9543480188379591, + 0.8217904224586922, + 0.805130531492367, + 0.8220121195811046, + 0.7808879677224255, + 0.7198356581526952, + 0.7630851397226434, + 0.7113242876211381, + 0.6063371940317739, + 0.6725319341165956, + 0.6851840521708761, + 0.6759834056295376, + 0.6412837749387339, + 0.6170135528478194, + 0.4659896434992889, + 0.5154770995741725, + 0.623589790712757, + 0.622994720095284, + 0.6902225834909954, + 0.8283326967834336, + 0.5705570318269632 + ], + [ + 0.6904843093120027, + 0.4443044467140416, + 1.172988635221176, + 2.3196693821091636, + 1.4078769588470965, + 1.183936344408245, + 1.1082009322507629, + 0.9869828327866518, + 0.9597145887539139, + 0.8597942447782176, + 0.9422178318724331, + 0.7935692463020498, + 0.710652236782754, + 0.7448813798028994, + 0.800758910237514, + 0.7656800657914152, + 0.6321218110852141, + 0.624411309877914, + 0.5205187175655668, + 0.5174667841839965, + 0.5637470371681916, + 0.5877686771950626, + 0.6512787003126866, + 0.6773719290754073, + 0.5644084109626554 + ], + [ + 0.6690162505343388, + 0.4158723960081373, + 0.9543480188379591, + 1.4078769588470965, + 2.2720808664678995, + 1.485803190155229, + 1.327137744734443, + 0.9471235684848248, + 1.041610642885693, + 0.9573001564339423, + 1.004890227172128, + 0.8369107452846558, + 0.7163701134323567, + 0.7609434960123262, + 0.8624160140167811, + 0.8674397726595604, + 0.7049473680951935, + 0.7085088111638074, + 0.5428656560134781, + 0.5583678902905691, + 0.5314273995515417, + 0.6135557226824734, + 0.6853964432086879, + 0.6803708900398123, + 0.5598869959214031 + ], + [ + 0.6512097574296891, + 0.40098832660997547, + 0.8217904224586922, + 1.183936344408245, + 1.485803190155229, + 2.2967483552546537, + 1.2091134623365896, + 0.8585350462054803, + 1.0042500648005865, + 1.0018474416582548, + 0.9643373878370798, + 0.7928451544922585, + 0.7364243323486791, + 0.7988955099279339, + 0.9762560121929411, + 0.9664130712793463, + 0.8284376126934864, + 0.824938481145348, + 0.5662137821381902, + 0.5317460848158277, + 0.545977200572727, + 0.6348808310741693, + 0.7288851823113339, + 0.7011945147356602, + 0.5376287350881994 + ], + [ + 0.631399187420879, + 0.35615130217538943, + 0.805130531492367, + 1.1082009322507629, + 1.327137744734443, + 1.2091134623365896, + 2.3477764543003454, + 1.3226532341597808, + 1.391330620637103, + 1.1491906635237006, + 1.2893550102502047, + 1.1181698813701444, + 0.9673366523224821, + 1.008191184464644, + 1.1263658478892322, + 0.9117621378010781, + 0.6718970345276649, + 0.6737162330196917, + 0.5525530998897352, + 0.5301520444261728, + 0.5161351872845089, + 0.5517299255921414, + 0.7214146188966725, + 0.7244491139729449, + 0.49954805524291146 + ], + [ + 0.5855134762308328, + 0.43519508514758576, + 0.8220121195811046, + 0.9869828327866518, + 0.9471235684848248, + 0.8585350462054803, + 1.3226532341597808, + 2.4645174274691333, + 1.5029144393235752, + 0.9573721322151795, + 1.1495888950698574, + 1.1923271187604316, + 1.1097961184670972, + 1.1255776191769986, + 0.9829260905226019, + 0.6964948583217169, + 0.5506044880379102, + 0.520064888795904, + 0.4692765354424516, + 0.4405922854732826, + 0.4365038323976361, + 0.42575447548424816, + 0.6459967116646106, + 0.6565507704531675, + 0.5056571667882572 + ], + [ + 0.6074206194778445, + 0.3503926486536749, + 0.7808879677224255, + 0.9597145887539139, + 1.041610642885693, + 1.0042500648005865, + 1.391330620637103, + 1.5029144393235752, + 2.4052196230162677, + 1.2619624752451808, + 1.4904255687370833, + 1.1505456864057921, + 0.9987906614639515, + 1.1190929279853943, + 1.0370464195501439, + 0.8212167185981412, + 0.6444833306766371, + 0.5978018442791028, + 0.5024456004466917, + 0.477704823190764, + 0.48371026920775306, + 0.5536837028534546, + 0.6590376945056714, + 0.6625524271974509, + 0.5040892625273508 + ], + [ + 0.6555240534054558, + 0.33321429661265745, + 0.7198356581526952, + 0.8597942447782176, + 0.9573001564339423, + 1.0018474416582548, + 1.1491906635237006, + 0.9573721322151795, + 1.2619624752451808, + 2.4560572801455933, + 1.532978540442259, + 0.9497134580898713, + 0.7932694884542277, + 1.0033565894397825, + 0.9039828912574503, + 1.0964581466100178, + 0.8621107039315997, + 0.8434192501276628, + 0.6669639197378779, + 0.6259300872290396, + 0.6450903857983621, + 0.7188527626635436, + 0.8266800694499348, + 0.8047764149520525, + 0.5747952231886803 + ], + [ + 0.6468646245229188, + 0.3978135185832393, + 0.7630851397226434, + 0.9422178318724331, + 1.004890227172128, + 0.9643373878370798, + 1.2893550102502047, + 1.1495888950698574, + 1.4904255687370833, + 1.532978540442259, + 2.3842181406676346, + 1.1059470068324664, + 0.9528074090008355, + 1.1262690420717347, + 1.049328850873215, + 1.0223393758433283, + 0.7604847830760503, + 0.7269755873937245, + 0.602681655110297, + 0.5767761825521954, + 0.547967415967466, + 0.6218418526908494, + 0.7851249662947132, + 0.8059729003896411, + 0.5294778228287806 + ], + [ + 0.48386512555638805, + 0.3420862065975434, + 0.7113242876211381, + 0.7935692463020498, + 0.8369107452846558, + 0.7928451544922585, + 1.1181698813701444, + 1.1923271187604316, + 1.1505456864057921, + 0.9497134580898713, + 1.1059470068324664, + 2.3958333143153903, + 1.3748275467356477, + 1.1107893925064793, + 1.1010970888139984, + 0.6966066742454438, + 0.5353720054101343, + 0.5383844980406993, + 0.4049761202549989, + 0.41512071833402153, + 0.3643432184438462, + 0.43866097635211976, + 0.5591585047709325, + 0.5793258809010147, + 0.5045414251023796 + ], + [ + 0.4010211722783301, + 0.3599542742502537, + 0.6063371940317739, + 0.710652236782754, + 0.7163701134323567, + 0.7364243323486791, + 0.9673366523224821, + 1.1097961184670972, + 0.9987906614639515, + 0.7932694884542277, + 0.9528074090008355, + 1.3748275467356477, + 2.3753773455518816, + 1.0836784667782404, + 1.064863627444301, + 0.6252111571092671, + 0.45343458527358527, + 0.4731977451445141, + 0.42752150801150135, + 0.36797948997187413, + 0.3347795095826747, + 0.37807187386482705, + 0.5151768166636508, + 0.5761943359295074, + 0.46788122124163767 + ], + [ + 0.5033915775726365, + 0.3470112694914168, + 0.6725319341165956, + 0.7448813798028994, + 0.7609434960123262, + 0.7988955099279339, + 1.008191184464644, + 1.1255776191769986, + 1.1190929279853943, + 1.0033565894397825, + 1.1262690420717347, + 1.1107893925064793, + 1.0836784667782404, + 2.4361261299080312, + 1.2350278852110423, + 0.8337528696252383, + 0.6224859391604839, + 0.6173959123620536, + 0.5603911891747919, + 0.46176987297702615, + 0.48178615216468335, + 0.5485012698043523, + 0.6884394302577381, + 0.7780224245895322, + 0.5026570644874869 + ], + [ + 0.5220912093729436, + 0.2751405713892427, + 0.6851840521708761, + 0.800758910237514, + 0.8624160140167811, + 0.9762560121929411, + 1.1263658478892322, + 0.9829260905226019, + 1.0370464195501439, + 0.9039828912574503, + 1.049328850873215, + 1.1010970888139984, + 1.064863627444301, + 1.2350278852110423, + 2.460555716215801, + 1.079432364500123, + 0.7171138801309918, + 0.7199854863633666, + 0.5323931857659948, + 0.44882314827530173, + 0.46942869739136567, + 0.5736103414523603, + 0.6818465967917177, + 0.6541606220212755, + 0.44315699991861396 + ], + [ + 0.5785801800316468, + 0.2707433044229157, + 0.6759834056295376, + 0.7656800657914152, + 0.8674397726595604, + 0.9664130712793463, + 0.9117621378010781, + 0.6964948583217169, + 0.8212167185981412, + 1.0964581466100178, + 1.0223393758433283, + 0.6966066742454438, + 0.6252111571092671, + 0.8337528696252383, + 1.079432364500123, + 2.41637020390684, + 1.3019558092668593, + 1.2850730037794416, + 0.8707862367222533, + 0.6705159472070225, + 0.7036765255094707, + 0.8342894302420797, + 0.9132611810061501, + 0.7564618834031983, + 0.44478630575440686 + ], + [ + 0.6442455233325804, + 0.2992515509507363, + 0.6412837749387339, + 0.6321218110852141, + 0.7049473680951935, + 0.8284376126934864, + 0.6718970345276649, + 0.5506044880379102, + 0.6444833306766371, + 0.8621107039315997, + 0.7604847830760503, + 0.5353720054101343, + 0.45343458527358527, + 0.6224859391604839, + 0.7171138801309918, + 1.3019558092668593, + 2.4007279174945406, + 1.7124458804253397, + 1.194572523636401, + 0.9313501607241519, + 1.0149950209860852, + 1.0582516290804644, + 0.9514328404786745, + 0.8586175825539353, + 0.435150621832919 + ], + [ + 0.6228956526917968, + 0.3181859515554761, + 0.6170135528478194, + 0.624411309877914, + 0.7085088111638074, + 0.824938481145348, + 0.6737162330196917, + 0.520064888795904, + 0.5978018442791028, + 0.8434192501276628, + 0.7269755873937245, + 0.5383844980406993, + 0.4731977451445141, + 0.6173959123620536, + 0.7199854863633666, + 1.2850730037794416, + 1.7124458804253397, + 2.467086679582349, + 1.2030016092012947, + 0.9467143327181656, + 1.0293672387376402, + 1.1093489607387628, + 0.9877207768166859, + 0.8350015330927684, + 0.45026156288813607 + ], + [ + 0.5203496643623892, + 0.2684602964727382, + 0.4659896434992889, + 0.5205187175655668, + 0.5428656560134781, + 0.5662137821381902, + 0.5525530998897352, + 0.4692765354424516, + 0.5024456004466917, + 0.6669639197378779, + 0.602681655110297, + 0.4049761202549989, + 0.42752150801150135, + 0.5603911891747919, + 0.5323931857659948, + 0.8707862367222533, + 1.194572523636401, + 1.2030016092012947, + 2.5884559636536073, + 1.445526070573155, + 1.230225336381816, + 1.0928325155414353, + 0.8359746665541254, + 0.7270111771864228, + 0.4707625666563379 + ], + [ + 0.5371261678840263, + 0.3273533306066217, + 0.5154770995741725, + 0.5174667841839965, + 0.5583678902905691, + 0.5317460848158277, + 0.5301520444261728, + 0.4405922854732826, + 0.477704823190764, + 0.6259300872290396, + 0.5767761825521954, + 0.41512071833402153, + 0.36797948997187413, + 0.46176987297702615, + 0.44882314827530173, + 0.6705159472070225, + 0.9313501607241519, + 0.9467143327181656, + 1.445526070573155, + 2.5161662814947405, + 1.6171110576939063, + 1.2413252140677744, + 0.8761315645860267, + 0.7721572936568967, + 0.4372316727636177 + ], + [ + 0.5825351017560767, + 0.37040159366374903, + 0.623589790712757, + 0.5637470371681916, + 0.5314273995515417, + 0.545977200572727, + 0.5161351872845089, + 0.4365038323976361, + 0.48371026920775306, + 0.6450903857983621, + 0.547967415967466, + 0.3643432184438462, + 0.3347795095826747, + 0.48178615216468335, + 0.46942869739136567, + 0.7036765255094707, + 1.0149950209860852, + 1.0293672387376402, + 1.230225336381816, + 1.6171110576939063, + 2.4033379169351146, + 1.5298995674223748, + 1.0482261219970401, + 0.903539970688283, + 0.4379072780956452 + ], + [ + 0.6503846227179654, + 0.3482640919635858, + 0.622994720095284, + 0.5877686771950626, + 0.6135557226824734, + 0.6348808310741693, + 0.5517299255921414, + 0.42575447548424816, + 0.5536837028534546, + 0.7188527626635436, + 0.6218418526908494, + 0.43866097635211976, + 0.37807187386482705, + 0.5485012698043523, + 0.5736103414523603, + 0.8342894302420797, + 1.0582516290804644, + 1.1093489607387628, + 1.0928325155414353, + 1.2413252140677744, + 1.5298995674223748, + 2.351916369133564, + 1.2592330865089845, + 1.0620707172321349, + 0.43126250301533786 + ], + [ + 0.6900385431718811, + 0.36463216687678607, + 0.6902225834909954, + 0.6512787003126866, + 0.6853964432086879, + 0.7288851823113339, + 0.7214146188966725, + 0.6459967116646106, + 0.6590376945056714, + 0.8266800694499348, + 0.7851249662947132, + 0.5591585047709325, + 0.5151768166636508, + 0.6884394302577381, + 0.6818465967917177, + 0.9132611810061501, + 0.9514328404786745, + 0.9877207768166859, + 0.8359746665541254, + 0.8761315645860267, + 1.0482261219970401, + 1.2592330865089845, + 2.3101590134454266, + 1.387604392709601, + 0.5382870216112317 + ], + [ + 0.829548144288587, + 0.4109825242943798, + 0.8283326967834336, + 0.6773719290754073, + 0.6803708900398123, + 0.7011945147356602, + 0.7244491139729449, + 0.6565507704531675, + 0.6625524271974509, + 0.8047764149520525, + 0.8059729003896411, + 0.5793258809010147, + 0.5761943359295074, + 0.7780224245895322, + 0.6541606220212755, + 0.7564618834031983, + 0.8586175825539353, + 0.8350015330927684, + 0.7270111771864228, + 0.7721572936568967, + 0.903539970688283, + 1.0620707172321349, + 1.387604392709601, + 2.5257138042918843, + 0.6982534605427622 + ], + [ + 0.5189759258959196, + 0.3445118406932491, + 0.5705570318269632, + 0.5644084109626554, + 0.5598869959214031, + 0.5376287350881994, + 0.49954805524291146, + 0.5056571667882572, + 0.5040892625273508, + 0.5747952231886803, + 0.5294778228287806, + 0.5045414251023796, + 0.46788122124163767, + 0.5026570644874869, + 0.44315699991861396, + 0.44478630575440686, + 0.435150621832919, + 0.45026156288813607, + 0.4707625666563379, + 0.4372316727636177, + 0.4379072780956452, + 0.43126250301533786, + 0.5382870216112317, + 0.6982534605427622, + 2.3380258673288785 + ] + ], + "entropies": [ + -0.6315610607587784, + -0.627416009583068, + -0.5861614941870391, + -0.6016038763611488, + -0.6130674217530055, + -0.6121981385094227, + -0.6033131501980972, + -0.5924187613341422, + -0.6069171484092294, + -0.6132380808987886, + -0.607843819939205, + -0.6085076526449892, + -0.5918690386938749, + -0.5995608511332241, + -0.5767638850935354, + -0.5998789692930665, + -0.6060303112437687, + -0.5976469364022053, + -0.5767187710745335, + -0.5862940540626368, + -0.6120057979779193, + -0.6468870503045397, + -0.6486871845158716, + -0.601268769843721, + -0.6931420893705896 + ], + "pair_npib": 1.7124458804253397, + "source_lineage": [ + [ + 17, + 18, + 19 + ], + [ + 20 + ] + ], + "geometry_samples": 100, + "geometry_sequence_length": 512, + "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", + "selection_policy": "native_dynamic_adjacent_NPIB", + "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", + "removed_original_layers": [ + 20 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 12, + 13, + 14, + 15, + 16, + 17, + 21, + 23, + 26, + 27, + 29, + 30, + 31 + ] + } +] diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/selection_inputs.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/selection_inputs.json new file mode 100644 index 0000000000000000000000000000000000000000..6e87a5a584648978c56be9ea8d5a04fca39cdf27 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/audit/selection_inputs.json @@ -0,0 +1,10 @@ +{ + "input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", + "attention_mask_sha256": "ffe472b00e055e867ecb0129008048236f4d8f7a3730ec6fecda87fc1666dd88", + "sequences": 100, + "sequence_length": 512, + "valid_tokens": 51200, + "source": "/workspace/mka-fit-batch-20261126/calibration/selection.pt", + "independent_of_fit_loader": true, + "selection_protocol": "native_MKA_saved_geometry_dynamic_NPIB" +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/batch_profile.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/batch_profile.json new file mode 100644 index 0000000000000000000000000000000000000000..7802e55057988b0b494ad00ed1baf0555b8c783f --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/batch_profile.json @@ -0,0 +1,82 @@ +{ + "profiles": [ + { + "batch_size": 1, + "return_code": 0, + "completed": true, + "seconds": 32.977131435181946, + "dataset_tokens": 65536, + "tokens_per_second": 1987.3165781206287, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 38916334592, + "peak_reserved_bytes": 40705720320, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 64, + "student:1x1024": 64 + }, + "memory_margin_bytes": 44389105664 + }, + { + "batch_size": 2, + "return_code": 0, + "completed": true, + "seconds": 25.37713863281533, + "dataset_tokens": 65536, + "tokens_per_second": 2582.481852987752, + "batches_per_epoch": 32, + "grad_accumulation": 1, + "peak_allocated_bytes": 42557828096, + "peak_reserved_bytes": 45833256960, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:2x1024": 32, + "student:2x1024": 32 + }, + "memory_margin_bytes": 39261569024 + }, + { + "batch_size": 4, + "return_code": 0, + "completed": true, + "seconds": 22.732720613945276, + "dataset_tokens": 65536, + "tokens_per_second": 2882.8929503403683, + "batches_per_epoch": 16, + "grad_accumulation": 1, + "peak_allocated_bytes": 49839612928, + "peak_reserved_bytes": 56088330240, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:4x1024": 16, + "student:4x1024": 16 + }, + "memory_margin_bytes": 29006495744 + }, + { + "batch_size": 8, + "return_code": 0, + "completed": true, + "seconds": 21.956195652019233, + "dataset_tokens": 65536, + "tokens_per_second": 2984.852250301973, + "batches_per_epoch": 8, + "grad_accumulation": 1, + "peak_allocated_bytes": 64399123456, + "peak_reserved_bytes": 76701237248, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 8, + "student:8x1024": 8 + }, + "memory_margin_bytes": 8393588736 + } + ], + "selected_larger_batch": 8, + "selection_rule": "Required user comparison batch, profiled with >=4GiB margin", + "training_updates_per_stage": { + "batch1": 512, + "batch_large": 64 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/abprune_compact.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/abprune_compact.py new file mode 100644 index 0000000000000000000000000000000000000000..ffabddabd8ced8b87666f63fb9f99fae8b36cb38 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/abprune_compact.py @@ -0,0 +1,284 @@ +"""Package and reconstruct compact ABPrune stage checkpoints. + +ABPrune already writes ``fused_layer.pt`` for every cycle. This utility makes +those files portable by pairing them with an explicit, immutable stage record; +the dense base model plus that record is sufficient to reconstruct a student. +""" +from __future__ import annotations + +import argparse, hashlib, json, shutil +from pathlib import Path +from typing import Any + +import torch + + +def copy_stage_state(src: Path, dst: Path, *, hard_link: bool = False) -> None: + """Optionally share immutable stage bytes within one experiment filesystem.""" + if not hard_link: + shutil.copy2(src, dst) + elif dst.exists(): + if not src.samefile(dst): + raise FileExistsError(f"Refusing to replace existing non-linked stage: {dst}") + else: + # Fail instead of silently consuming space if cross-device linking is + # unavailable. The caller explicitly selected the storage strategy. + dst.hardlink_to(src) + + +def sha256(path: Path) -> str: + h = hashlib.sha256() + with path.open("rb") as f: + for chunk in iter(lambda: f.read(8 * 1024 * 1024), b""): + h.update(chunk) + return h.hexdigest() + + +def post_merge_scale(source_cycle: Path) -> dict | None: + """Return the deployable post-merge scale stored for a cycle, if present.""" + metadata_path = source_cycle / "cycle_metadata.json" + if not metadata_path.is_file(): + return None + metadata = json.loads(metadata_path.read_text(encoding="utf-8")) + distill = metadata.get("distill", {}) + scale = distill.get("post_merge_nll_scale") or {} + source = "post_merge_nll" + if not scale.get("enabled"): + scale = (distill.get("reparam_stats") or {}).get("residual_scale") or {} + source = "scale_aware_fit" + if not scale.get("enabled"): + return None + gamma = scale["gamma"] + cumulative_gamma = scale["cumulative_gamma"] + if not isinstance(gamma, list): + gamma = float(gamma) + else: + gamma = [float(value) for value in gamma] + if not isinstance(cumulative_gamma, list): + cumulative_gamma = float(cumulative_gamma) + else: + cumulative_gamma = [float(value) for value in cumulative_gamma] + result = { + "enabled": True, + "mode": scale.get("mode", "residual"), + "scale_parameterization": scale.get("scale_parameterization", "scalar"), + "gamma": gamma, + "cumulative_gamma": cumulative_gamma, + "source": source, + } + for field in ( + "optimization_mode", + "gamma_gradient_sources", + "theta_gradient_sources", + "nll_used", + ): + if field in scale: + result[field] = scale[field] + if "cumulative_gamma_statistics" in scale: + result["cumulative_gamma_statistics"] = scale["cumulative_gamma_statistics"] + if "raw" in scale and "ppl" in scale["raw"]: + result["calibration_raw_ppl"] = float(scale["raw"]["ppl"]) + if "fitted" in scale and "ppl" in scale["fitted"]: + result["calibration_fitted_ppl"] = float(scale["fitted"]["ppl"]) + return result + + +def read_compact_metadata(compact_stage: Path) -> dict[str, Any]: + return json.loads((compact_stage / "metadata.json").read_text(encoding="utf-8")) + + +def compact_scale_targets(metadata: dict[str, Any]) -> list[dict[str, Any]]: + """Return residual scales and current student indices for a compact stage.""" + if metadata.get("format") == "abprune_compact_stage_v2": + active = [int(value) for value in metadata["active_original_layers"]] + current_index = {original: index for index, original in enumerate(active)} + targets = [] + for state in metadata.get("retained_layer_states", []): + scale = state.get("post_merge_scale") or {} + if scale.get("enabled") and scale.get("mode") == "residual": + original = int(state["original_layer"]) + targets.append( + { + "original_layer": original, + "student_index": current_index[original], + "scale": scale, + } + ) + return targets + + scale = metadata.get("post_merge_scale") or {} + if scale.get("enabled") and scale.get("mode") == "residual": + return [ + { + "original_layer": int(metadata["anchor_index"]), + "student_index": int(metadata["anchor_index"]), + "scale": scale, + } + ] + return [] + + +def _package_topology_aware(args, source: Path, out: Path, order: list[int]) -> None: + """Package cycles whose recipients may switch between pair boundaries.""" + if int(getattr(args, "start_cycle", 1)) != 1: + raise ValueError("topology-aware compact packaging must start at cycle 1") + + removed: set[int] = set() + latest_states: dict[int, dict[str, Any]] = {} + stages: list[dict[str, Any]] = [] + original_layer_count: int | None = None + + for cycle in range(1, args.cycles + 1): + source_cycle = source / f"cycle_{cycle}" + src = source_cycle / "fused_layer.pt" + if not src.is_file(): + raise FileNotFoundError(src) + cycle_metadata_path = source_cycle / "cycle_metadata.json" + if not cycle_metadata_path.is_file(): + raise FileNotFoundError(cycle_metadata_path) + cycle_metadata = json.loads(cycle_metadata_path.read_text(encoding="utf-8")) + recipient = int(cycle_metadata["recipient_original_layer"]) + removed_original = int(cycle_metadata["removed_original_layer"]) + recipient_side = str(cycle_metadata["recipient_side"]) + if recipient_side not in {"left", "right"}: + raise ValueError(f"invalid recipient_side at cycle {cycle}: {recipient_side}") + if original_layer_count is None: + original_layer_count = int(cycle_metadata["num_layers_before"]) + if removed_original in removed: + raise ValueError(f"original layer {removed_original} removed more than once") + if recipient in removed: + raise ValueError(f"cycle {cycle} selects removed recipient {recipient}") + + removed.add(removed_original) + latest_states.pop(removed_original, None) + latest_states[recipient] = { + "original_layer": recipient, + "source_cycle": cycle, + "recipient_side": recipient_side, + "source_state": src, + "post_merge_scale": post_merge_scale(source_cycle), + } + + stage_dir = out / f"stage_{cycle:02d}" + stage_dir.mkdir(exist_ok=True) + retained_states = [] + for original, record in sorted(latest_states.items()): + state_name = f"layer_original_{original:04d}.pt" + state_path = stage_dir / state_name + copy_stage_state(record["source_state"], state_path, hard_link=bool(getattr(args, "hard_link", False))) + packaged = { + "original_layer": original, + "state_file": state_name, + "sha256": sha256(state_path), + "source_cycle": int(record["source_cycle"]), + "recipient_side": record["recipient_side"], + } + if record["post_merge_scale"] is not None: + packaged["post_merge_scale"] = record["post_merge_scale"] + retained_states.append(packaged) + + assert original_layer_count is not None + active = [ + original + for original in range(original_layer_count) + if original not in removed + ] + meta = { + "format": "abprune_compact_stage_v2", + "model": args.model, + "base_model_revision": args.base_revision, + "run_id": args.run_id, + "target_prune_count": args.cycles, + "stage": cycle, + "removed_count": len(removed), + "original_layer_count": original_layer_count, + "layer_order": order, + "latest_pair_index": order[cycle - 1], + "latest_recipient_side": recipient_side, + "latest_recipient_original_layer": recipient, + "latest_removed_original_layer": removed_original, + "removed_original_layers": sorted(removed), + "active_original_layers": active, + "retained_layer_states": retained_states, + "source_cycle": f"cycle_{cycle}", + } + (stage_dir / "metadata.json").write_text( + json.dumps(meta, indent=2) + "\n", encoding="utf-8" + ) + stages.append(meta) + + manifest = { + "format": "abprune_compact_manifest_v2", + "model": args.model, + "base_model_revision": args.base_revision, + "run_id": args.run_id, + "target_prune_count": args.cycles, + "original_layer_count": original_layer_count, + "layer_order": order, + "stages": stages, + } + (out / "manifest.json").write_text( + json.dumps(manifest, indent=2) + "\n", encoding="utf-8" + ) + + +def package(args): + source = Path(args.run_root); out = Path(args.output_root); out.mkdir(parents=True, exist_ok=True) + order = [int(x) for x in args.layer_order.replace(',', ' ').split()] + start_cycle = int(getattr(args, "start_cycle", 1)) + expected_order = args.cycles - start_cycle + 1 + if not 1 <= start_cycle <= args.cycles: + raise ValueError("start_cycle must be between 1 and cycles") + if len(order) != expected_order: + raise ValueError("layer_order length must equal cycles - start_cycle + 1") + first_metadata_path = source / f"cycle_{start_cycle}" / "cycle_metadata.json" + if first_metadata_path.is_file(): + first_metadata = json.loads(first_metadata_path.read_text(encoding="utf-8")) + topology_fields = { + "recipient_side", + "recipient_original_layer", + "removed_original_layer", + } + if topology_fields.issubset(first_metadata): + _package_topology_aware(args, source, out, order) + return + stages = [] + for cycle in range(start_cycle, args.cycles + 1): + order_index = cycle - start_cycle + source_cycle = source / f"cycle_{cycle}" + src = source_cycle / "fused_layer.pt" + if not src.exists(): raise FileNotFoundError(src) + dst_dir = out / f"stage_{cycle:02d}"; dst_dir.mkdir(exist_ok=True) + dst = dst_dir / "anchor_layer.pt"; copy_stage_state(src, dst, hard_link=bool(getattr(args, "hard_link", False))) + meta = { + "format": "abprune_compact_stage_v1", "model": args.model, + "base_model_revision": args.base_revision, "run_id": args.run_id, + "target_prune_count": args.cycles, "stage": cycle, + "removed_count": cycle, "anchor_index": order[order_index], + "layer_order": order, + "packaged_stage_range": [start_cycle, args.cycles], + "removed_original_layers": list(range(order[order_index] + 1, order[order_index] + cycle + 1)), + "source_cycle": f"cycle_{cycle}", "anchor_state_file": "anchor_layer.pt", + "sha256": sha256(dst), + } + scale = post_merge_scale(source_cycle) + if scale is not None: + meta["post_merge_scale"] = scale + (dst_dir / "metadata.json").write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8") + stages.append(meta) + manifest = {"format": "abprune_compact_manifest_v1", "model": args.model, + "base_model_revision": args.base_revision, "run_id": args.run_id, + "target_prune_count": args.cycles, "layer_order": order, "stages": stages} + (out / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") + + +def main(): + p = argparse.ArgumentParser(); p.add_argument("--run-root", required=True); p.add_argument("--output-root", required=True) + p.add_argument("--model", required=True); p.add_argument("--base-revision", required=True); p.add_argument("--run-id", required=True) + p.add_argument("--cycles", type=int, required=True); p.add_argument("--layer-order", required=True) + p.add_argument("--start-cycle", type=int, default=1) + p.add_argument("--hard-link", action="store_true", help="Hard-link immutable stage weights on the same filesystem") + package(p.parse_args()) + + +if __name__ == "__main__": main() diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/bootstrap_llama31_come_fit2.sh b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/bootstrap_llama31_come_fit2.sh new file mode 100644 index 0000000000000000000000000000000000000000..bb1e27f5279db1f94780bf302ecbf53967a1c944 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/bootstrap_llama31_come_fit2.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +set -euo pipefail +project="$1"; external="$2"; root="$3"; base_model="$4"; inst_model="$5" +export HF_HOME=/workspace/.hf_home HF_TOKEN_PATH=/root/.cache/huggingface/token +export HF_DATASETS_CACHE=/workspace/.hf_datasets36 HF_DATASETS_TRUST_REMOTE_CODE=1 +export PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false OMP_NUM_THREADS=4 HF_XET_HIGH_PERFORMANCE=1 +mkdir -p "$root" "$(dirname "$external")" +trap 'rc=$?; if ((rc)); then touch "$root/BOOTSTRAP_FAILED"; fi' EXIT +python -m pip install 'transformers==5.15.1' 'datasets==3.6.0' 'huggingface_hub==1.33.0' \ + 'lm_eval==0.4.12' accelerate scipy scikit-learn sentencepiece protobuf pytest +if [[ ! -d "$external/.git" ]]; then git clone "$project/vendor/abprune_experiment_base_39e.bundle" "$external"; fi +python - "$external" <<'PY' +from huggingface_hub import hf_hub_download +from pathlib import Path +import hashlib,shutil,sys +r=Path(sys.argv[1]);prefix='runs/vast-paper_revision-llama31-base-fit4-54645332-20261007/20261007-llama-base-fit4/wa/code/' +for n in ['fuse_layers.py','fuse_layers_distill.py','source_feature_transport.py']: + p=Path(hf_hub_download('LJYAI/paper_revision',prefix+n,revision='61734e7b1a77fd279fe1e2584f7a0fdc26c175c2')) + shutil.copy2(p,r/'src'/n); print('PINNED_SOURCE',n,hashlib.sha256(p.read_bytes()).hexdigest(),flush=True) +PY +if ! grep -q '^def model_is_sharded' "$external/src/progressive_loader.py"; then + git -C "$external" apply "$project/patches/0005-Add-progressive-loader-device-helpers.patch" +fi +git -C "$external" apply --check "$project/patches/abprune_transport_instruction_masks.patch" +git -C "$external" apply "$project/patches/abprune_transport_instruction_masks.patch" +python -m compileall -q "$external/src" +touch "$root/DEPS_READY" +python - "$root" "$base_model" "$inst_model" <<'PY' +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from huggingface_hub import snapshot_download +from datasets import load_dataset +import sys +root=Path(sys.argv[1]) +def prepare(family,model_id,model_rev,local,dataset,data_rev): + def model(): + return snapshot_download(model_id,revision=model_rev,local_dir=local, + allow_patterns=['*.json','*.safetensors','tokenizer*','*.model','*.jinja'],max_workers=12) + def data(): + snapshot_download(dataset,repo_type='dataset',revision=data_rev,max_workers=12) + return len(load_dataset(dataset,name=None,split='train',revision=data_rev,trust_remote_code=True)) + with ThreadPoolExecutor(max_workers=2) as p: + for f in [p.submit(model),p.submit(data)]: print(family,'SNAPSHOT_READY',f.result(),flush=True) + (root/(family.upper()+'_READY')).touch() +with ThreadPoolExecutor(max_workers=2) as p: + jobs=[p.submit(prepare,'base','meta-llama/Llama-3.1-8B','d04e592bb4f6aa9cfee91e2e20afa771667e1d4b',sys.argv[2], + 'DKYoon/SlimPajama-6B','b5f90f419b7489cdba26fdbc8c022fcb5562f968'), + p.submit(prepare,'instruct','meta-llama/Llama-3.1-8B-Instruct','0e9e39f249a16976918f6564b8830bc894c89659',sys.argv[3], + 'Open-Orca/SlimOrca','ce9ed009ef3292bac33d3520afaf5ec804066120')] + for f in jobs:f.result() +PY +touch "$root/BOOTSTRAP_COMPLETE" diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/collect_mka_batch_comparison.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/collect_mka_batch_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..495a0463a112b56beee748828e787598619cf97d --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/collect_mka_batch_comparison.py @@ -0,0 +1,66 @@ +"""Collect the native-MKA MLP FiT pair, reporting Bench12, MMLU and CMMLU.""" +import argparse +import json +import math +from pathlib import Path + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("root", type=Path) + p.add_argument("--output", type=Path) + a = p.parse_args() + rows = [] + for arm in ("batch1", "batch_large"): + run = a.root / "full" / arm + scores = json.loads((run / "eval/final_14bench.json").read_text())["task_scores"] + tasks = [name for name in scores if name not in ("mmlu", "cmmlu")] + assert len(tasks) == 12 and len(scores) == 14 + assert all(math.isfinite(v) and 0 <= v <= 1 for v in scores.values()) + fits = [json.loads((run / "audit" / f"cycle_{cycle:02d}_fit.json").read_text()) + for cycle in range(1, 9)] + for fit in fits: + assert fit["trained"] and fit["num_trainable_mlp_gates"] == 3 + assert fit["num_trainable_attn_gates"] == fit["num_trainable_other_gates"] == 0 + assert fit["ablation"]["frozen_attention_norm_unchanged"] + fingerprints = json.loads((run / "audit/data_fingerprints.json").read_text()) + ppl = json.loads((run / "eval/final_ppl.json").read_text()) + metrics = ppl.get("metrics", ppl) + value = next((metrics[k] for k in ("ppl", "perplexity") if k in metrics), None) + assert value is not None and math.isfinite(value) and value > 0 + batch = fits[0]["runtime"]["batch_size"] + native = json.loads((run / "audit/selection_inputs.json").read_text()) + rows.append({"arm": arm, "batch_size": batch, "fit_scope": "mlp", + "bench12": sum(scores[k] for k in tasks) / 12, + "mmlu": scores["mmlu"], "cmmlu": scores["cmmlu"], "ppl": value, + "task_scores": scores, + "training_wall_seconds": json.loads((run / "training_elapsed.json").read_text())["wall_seconds"], + "fit_seconds": sum(f["runtime"]["seconds"] for f in fits), + "peak_allocated_bytes": max(f["runtime"]["peak_allocated_bytes"] for f in fits), + "peak_reserved_bytes": max(f["runtime"]["peak_reserved_bytes"] for f in fits), + "optimizer_updates_per_stage": 512 // batch, + "fit_input_sha256": fingerprints["distill_loader"]["sha256"], + "fit_mask_sha256": fingerprints["distill_loader"]["attention_mask_sha256"], + "selection_input_sha256": native["input_ids_sha256"], + "selection_inputs": native, "cycles": fits, + "selection_trace": json.loads((run / "audit/selection.json").read_text()), + "backup": json.loads((a.root / f"{arm}_backup.json").read_text())}) + for field in ("fit_input_sha256", "fit_mask_sha256", "selection_input_sha256"): + assert rows[0][field] == rows[1][field] + assert rows[0]["fit_input_sha256"] == "2b2d044c8c040f67891817ecc110f0fa0de2f469db4c6731114ff7816bbf1cd0" + assert rows[0]["fit_mask_sha256"] == "c8e7f8e30cd532b82e6af4b98d596bc7106f29f9fb2b398b44355e624898a30d" + result = {"model": "meta-llama/Llama-3.1-8B", "removed_blocks": 8, + "method": "native MKA plus stagewise MLP-only FiT", "fit_scope": "mlp", + "accuracy_scale": "fraction", "rows": rows, + "profile": json.loads((a.root / "batch_profile.json").read_text()), + "selection_provenance": json.loads((a.root / "selection_provenance.json").read_text()), + "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"} + destination = a.output or a.root / "summary.json" + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(json.dumps(result, indent=2) + "\n") + for row in rows: + print({key: row[key] for key in ("arm", "batch_size", "bench12", "mmlu", "cmmlu", "ppl", "training_wall_seconds")}) + + +if __name__ == "__main__": + main() diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/come.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/come.py new file mode 100644 index 0000000000000000000000000000000000000000..22d1937fdbf534bb2c3e37af3357627040ef4372 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/come.py @@ -0,0 +1,612 @@ +"""Native Hugging Face implementation of CoMe structured layer pruning. + +This module implements the pruning-only portion of CoMe for decoder-only +models whose blocks use Llama-style attention and gated MLP projections. It +intentionally does not implement post-pruning distillation. +""" + +from __future__ import annotations + +import json +import math +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Iterable, Sequence + +import torch +from torch import Tensor, nn +from tqdm.auto import tqdm + + +@dataclass +class CalibrationScores: + """Scores collected from one pass over the calibration sequences.""" + + block_importance: list[float] + pair_similarity: list[float] + attention_groups: list[Tensor] + mlp_neurons: list[Tensor] + + +@dataclass +class MergeRecord: + step: int + left_index: int + source_layers: list[list[int]] + retention_ratios: list[float] + retained_attention_groups: list[int] + retained_mlp_neurons: list[int] + pair_score: float + + +def allocate_retained_channels(total: int, ratios: Sequence[float]) -> list[int]: + """Allocate exactly ``total`` channels, putting rounding slack in the max arm.""" + + if total < 1: + raise ValueError("total must be positive") + if not ratios or any(value < 0 for value in ratios): + raise ValueError("ratios must be a non-empty sequence of non-negative values") + ratio_sum = float(sum(ratios)) + if ratio_sum <= 0: + normalized = [1.0 / len(ratios)] * len(ratios) + else: + normalized = [float(value) / ratio_sum for value in ratios] + + largest = max(range(len(normalized)), key=normalized.__getitem__) + counts = [0] * len(normalized) + for index, ratio in enumerate(normalized): + if index != largest: + counts[index] = math.floor(total * ratio) + counts[largest] = total - sum(counts) + return counts + + +def gqa_projection_indices( + groups: Tensor, + *, + num_attention_heads: int, + num_key_value_heads: int, + head_dim: int, +) -> tuple[Tensor, Tensor]: + """Return Q and KV row indices for complete GQA groups. + + Hugging Face stores query heads contiguously by KV group. Expanding a KV + mask with ``repeat`` mixes these groups for GQA models; this explicit + mapping keeps all query heads belonging to each selected KV head together. + """ + + if num_attention_heads % num_key_value_heads: + raise ValueError("num_attention_heads must be divisible by num_key_value_heads") + queries_per_kv = num_attention_heads // num_key_value_heads + q_parts: list[Tensor] = [] + kv_parts: list[Tensor] = [] + for group in groups.to(dtype=torch.long, device="cpu").tolist(): + if group < 0 or group >= num_key_value_heads: + raise IndexError(f"KV group {group} is outside [0, {num_key_value_heads})") + q_start = group * queries_per_kv * head_dim + kv_start = group * head_dim + q_parts.append(torch.arange(q_start, q_start + queries_per_kv * head_dim)) + kv_parts.append(torch.arange(kv_start, kv_start + head_dim)) + empty = torch.empty(0, dtype=torch.long) + return ( + torch.cat(q_parts) if q_parts else empty, + torch.cat(kv_parts) if kv_parts else empty, + ) + + +def _copy_tensor(target: Tensor, value: Tensor) -> None: + with torch.no_grad(): + target.copy_(value.to(device=target.device, dtype=target.dtype)) + + +def _selected_indices(scores: Tensor, count: int) -> Tensor: + if count == 0: + return torch.empty(0, dtype=torch.long) + if count > scores.numel(): + raise ValueError(f"cannot select {count} values from {scores.numel()} scores") + # Sorting the selected indices preserves the original within-layer order. + return torch.sort(torch.topk(scores.float(), count, largest=True).indices).values.cpu() + + +def _cat_selected( + modules: Sequence[nn.Linear], + indices: Sequence[Tensor], + *, + dimension: int, +) -> Tensor: + chunks = [] + for module, selected in zip(modules, indices, strict=True): + chunks.append(torch.index_select(module.weight.detach(), dimension, selected.to(module.weight.device))) + return torch.cat(chunks, dim=dimension) + + +def _weighted_optional_bias(modules: Sequence[nn.Linear], ratios: Sequence[float]) -> Tensor | None: + biases = [module.bias for module in modules] + if all(bias is None for bias in biases): + return None + if any(bias is None for bias in biases): + raise ValueError("projection bias presence differs across the layers being merged") + assert all(bias is not None for bias in biases) + result = torch.zeros_like(biases[0]) + for bias, ratio in zip(biases, ratios, strict=True): + result.add_(bias.detach().to(result.device), alpha=float(ratio)) + return result + + +def merge_attention( + layers: Sequence[nn.Module], + ratios: Sequence[float], + group_scores: Sequence[Tensor], +) -> list[int]: + """Merge attention projections in-place into the first decoder layer.""" + + attentions = [layer.self_attn for layer in layers] + first = attentions[0] + q_heads = int(first.config.num_attention_heads) + kv_heads = int(first.config.num_key_value_heads) + head_dim = int(getattr(first, "head_dim", first.q_proj.out_features // q_heads)) + counts = allocate_retained_channels(kv_heads, ratios) + groups = [_selected_indices(score, count) for score, count in zip(group_scores, counts, strict=True)] + q_indices: list[Tensor] = [] + kv_indices: list[Tensor] = [] + for selected in groups: + q_index, kv_index = gqa_projection_indices( + selected, + num_attention_heads=q_heads, + num_key_value_heads=kv_heads, + head_dim=head_dim, + ) + q_indices.append(q_index) + kv_indices.append(kv_index) + + q_modules = [attention.q_proj for attention in attentions] + k_modules = [attention.k_proj for attention in attentions] + v_modules = [attention.v_proj for attention in attentions] + o_modules = [attention.o_proj for attention in attentions] + q_weight = _cat_selected(q_modules, q_indices, dimension=0) + k_weight = _cat_selected(k_modules, kv_indices, dimension=0) + v_weight = _cat_selected(v_modules, kv_indices, dimension=0) + o_weight = _cat_selected(o_modules, q_indices, dimension=1) + + _copy_tensor(first.q_proj.weight, q_weight) + _copy_tensor(first.k_proj.weight, k_weight) + _copy_tensor(first.v_proj.weight, v_weight) + _copy_tensor(first.o_proj.weight, o_weight) + for destination, source_modules, selected in ( + (first.q_proj, q_modules, q_indices), + (first.k_proj, k_modules, kv_indices), + (first.v_proj, v_modules, kv_indices), + ): + biases = [module.bias for module in source_modules] + if not all(bias is None for bias in biases): + if any(bias is None for bias in biases): + raise ValueError("projection bias presence differs across merged layers") + bias_chunks = [ + torch.index_select(module.bias.detach(), 0, index.to(module.bias.device)) + for module, index in zip(source_modules, selected, strict=True) + ] + assert destination.bias is not None + _copy_tensor(destination.bias, torch.cat(bias_chunks)) + merged_o_bias = _weighted_optional_bias(o_modules, ratios) + if merged_o_bias is not None: + assert first.o_proj.bias is not None + _copy_tensor(first.o_proj.bias, merged_o_bias) + + # Qwen3 applies a shared per-head RMSNorm after Q/K projection. It cannot + # be sliced by group, so use the same convex merge as other shared values. + for norm_name in ("q_norm", "k_norm"): + norms = [getattr(attention, norm_name, None) for attention in attentions] + if all(norm is None for norm in norms): + continue + if any(norm is None for norm in norms): + raise ValueError(f"{norm_name} presence differs across merged layers") + destination = norms[0] + merged = torch.zeros_like(destination.weight) + for norm, ratio in zip(norms, ratios, strict=True): + merged.add_(norm.weight.detach().to(merged.device), alpha=float(ratio)) + _copy_tensor(destination.weight, merged) + + return counts + + +def merge_mlp( + layers: Sequence[nn.Module], + ratios: Sequence[float], + neuron_scores: Sequence[Tensor], +) -> list[int]: + """Merge gated MLP projections in-place into the first decoder layer.""" + + mlps = [layer.mlp for layer in layers] + intermediate_size = int(mlps[0].gate_proj.out_features) + counts = allocate_retained_channels(intermediate_size, ratios) + selected = [_selected_indices(score, count) for score, count in zip(neuron_scores, counts, strict=True)] + + for name in ("gate_proj", "up_proj"): + modules = [getattr(mlp, name) for mlp in mlps] + merged = _cat_selected(modules, selected, dimension=0) + destination = getattr(mlps[0], name) + _copy_tensor(destination.weight, merged) + biases = [module.bias for module in modules] + if not all(bias is None for bias in biases): + if any(bias is None for bias in biases): + raise ValueError(f"{name} bias presence differs across merged layers") + bias_chunks = [ + torch.index_select(module.bias.detach(), 0, index.to(module.bias.device)) + for module, index in zip(modules, selected, strict=True) + ] + assert destination.bias is not None + _copy_tensor(destination.bias, torch.cat(bias_chunks)) + + down_modules = [mlp.down_proj for mlp in mlps] + _copy_tensor(mlps[0].down_proj.weight, _cat_selected(down_modules, selected, dimension=1)) + merged_bias = _weighted_optional_bias(down_modules, ratios) + if merged_bias is not None: + assert mlps[0].down_proj.bias is not None + _copy_tensor(mlps[0].down_proj.bias, merged_bias) + return counts + + +def merge_norms(layers: Sequence[nn.Module]) -> None: + """Average the two residual-stream norms into the destination block.""" + + for name in ("input_layernorm", "post_attention_layernorm"): + norms = [getattr(layer, name) for layer in layers] + destination = norms[0] + _copy_tensor(destination.weight, torch.stack([norm.weight.detach().to(destination.weight.device) for norm in norms]).mean(0)) + destination_bias = getattr(destination, "bias", None) + if destination_bias is not None: + source_biases = [getattr(norm, "bias", None) for norm in norms] + if any(bias is None for bias in source_biases): + raise ValueError(f"{name} bias presence differs across merged layers") + _copy_tensor( + destination_bias, + torch.stack([bias.detach().to(destination_bias.device) for bias in source_biases]).mean(0), + ) + + +def compute_retention_ratios( + importance: Sequence[float], + *, + power: float, + minimum: float, +) -> list[float]: + if power < 0: + raise ValueError("power must be non-negative") + if not 0 <= minimum <= 1: + raise ValueError("minimum must be in [0, 1]") + values = [max(float(value), 0.0) ** power for value in importance] + total = sum(values) + ratios = [value / total for value in values] if total > 0 else [1 / len(values)] * len(values) + largest = max(range(len(ratios)), key=ratios.__getitem__) + if ratios[largest] < minimum: + if len(ratios) == 1: + return [1.0] + remainder = sum(ratios) - ratios[largest] + scale = (1.0 - minimum) / remainder if remainder > 0 else 0.0 + ratios = [ratio * scale for ratio in ratios] + ratios[largest] = minimum + return ratios + + +class _ProjectionScoreCollector: + def __init__(self, modules: Sequence[nn.Linear]): + self.scores = [torch.zeros(module.in_features, dtype=torch.float64) for module in modules] + self._handles = [] + for index, module in enumerate(modules): + self._handles.append(module.register_forward_pre_hook(self._hook(index))) + + def _hook(self, index: int): + def collect(module: nn.Linear, inputs: tuple[Tensor, ...]) -> None: + activation = inputs[0].detach().float().abs() + reduce_dims = tuple(range(activation.ndim - 1)) + activation_sum = activation.sum(dim=reduce_dims) + weight_l1 = module.weight.detach().float().abs().sum(dim=0) + self.scores[index].add_((activation_sum * weight_l1).double().cpu()) + + return collect + + def close(self) -> None: + for handle in self._handles: + handle.remove() + + +def _angular_distance(left: Tensor, right: Tensor, *, last_token_only: bool) -> Tensor: + if last_token_only: + left = left[:, -1:, :] + right = right[:, -1:, :] + cosine = torch.nn.functional.cosine_similarity(left.float(), right.float(), dim=-1) + if last_token_only: + return torch.acos(cosine.clamp(0, 1)) / math.pi + return 1 - cosine + + +@torch.inference_mode() +def collect_calibration_scores( + model: nn.Module, + batches: Iterable[dict[str, Tensor]], + *, + sbi_metric: str = "angular_last", +) -> CalibrationScores: + """Collect CoMe block, adjacent-pair, attention, and MLP scores.""" + + if sbi_metric not in {"angular_last", "cosine_all"}: + raise ValueError("sbi_metric must be 'angular_last' or 'cosine_all'") + backbone = model.model + layers = list(backbone.layers) + attention = _ProjectionScoreCollector([layer.self_attn.o_proj for layer in layers]) + mlp = _ProjectionScoreCollector([layer.mlp.down_proj for layer in layers]) + block_sums = torch.zeros(len(layers), dtype=torch.float64) + pair_sums = torch.zeros(len(layers) - 1, dtype=torch.float64) + block_count = 0 + pair_count = 0 + input_device = model.get_input_embeddings().weight.device + try: + for batch in tqdm(batches, desc=f"CoMe calibration ({len(layers)} layers)"): + prepared = {key: value.to(input_device) for key, value in batch.items()} + outputs = backbone( + **prepared, + use_cache=False, + output_hidden_states=True, + return_dict=True, + ) + hidden = outputs.hidden_states + for index in range(len(layers)): + distance = _angular_distance(hidden[index], hidden[index + 1], last_token_only=False) + block_sums[index] += distance.double().sum().cpu() + batch_token_count = hidden[0].shape[0] * hidden[0].shape[1] + block_count += batch_token_count + for index in range(len(layers) - 1): + distance = _angular_distance( + hidden[index], + hidden[index + 2], + last_token_only=sbi_metric == "angular_last", + ) + pair_sums[index] += distance.double().sum().cpu() + pair_count += hidden[0].shape[0] if sbi_metric == "angular_last" else batch_token_count + finally: + attention.close() + mlp.close() + + if block_count == 0: + raise ValueError("calibration batches are empty") + attention_groups: list[Tensor] = [] + for layer, score in zip(layers, attention.scores, strict=True): + attn = layer.self_attn + q_heads = int(attn.config.num_attention_heads) + kv_heads = int(attn.config.num_key_value_heads) + head_dim = int(getattr(attn, "head_dim", attn.q_proj.out_features // q_heads)) + queries_per_kv = q_heads // kv_heads + expected = kv_heads * queries_per_kv * head_dim + if score.numel() != expected: + raise ValueError(f"unexpected attention input width {score.numel()} (expected {expected})") + attention_groups.append(score.reshape(kv_heads, queries_per_kv, head_dim).mean((1, 2))) + return CalibrationScores( + block_importance=(block_sums / block_count).tolist(), + pair_similarity=(pair_sums / max(pair_count, 1)).tolist(), + attention_groups=attention_groups, + mlp_neurons=mlp.scores, + ) + + +def _choose_pair(pair_scores: Sequence[float], lineage: Sequence[Sequence[int]], allow_repeat: bool) -> int: + candidates = [] + for index, score in enumerate(pair_scores): + repeated = len(lineage[index]) > 1 or len(lineage[index + 1]) > 1 + if allow_repeat or not repeated: + candidates.append((float(score), index)) + if not candidates: + raise RuntimeError( + "no legal adjacent pair remains; use --allow-repeat or choose a target at least ceil(original_layers / 2)" + ) + return min(candidates)[1] + + +def _update_config_after_delete(model: nn.Module, deleted_index: int) -> None: + model.config.num_hidden_layers = len(model.model.layers) + if hasattr(model.config, "layer_types") and model.config.layer_types is not None: + layer_types = list(model.config.layer_types) + if deleted_index < len(layer_types): + del layer_types[deleted_index] + model.config.layer_types = layer_types + for index, layer in enumerate(model.model.layers): + if hasattr(layer.self_attn, "layer_idx"): + layer.self_attn.layer_idx = index + + +@torch.inference_mode() +def progressive_prune( + model: nn.Module, + calibration_batches: Sequence[dict[str, Tensor]], + *, + target_layers: int, + power: float = 1.0, + minimum_retention: float = 0.0, + allow_repeat: bool = False, + sbi_metric: str = "angular_last", +) -> list[MergeRecord]: + """Progressively merge adjacent layer pairs until ``target_layers`` remain.""" + + original_layers = len(model.model.layers) + if not 1 <= target_layers <= original_layers: + raise ValueError(f"target_layers must be in [1, {original_layers}]") + if not allow_repeat and target_layers < math.ceil(original_layers / 2): + raise ValueError("without repeated merges, target_layers cannot be below ceil(original_layers / 2)") + lineage: list[list[int]] = [[index] for index in range(original_layers)] + records: list[MergeRecord] = [] + model.eval() + model.config.use_cache = False + + while len(model.model.layers) > target_layers: + scores = collect_calibration_scores(model, calibration_batches, sbi_metric=sbi_metric) + left = _choose_pair(scores.pair_similarity, lineage, allow_repeat) + indices = [left, left + 1] + leaf_count = sum(len(lineage[index]) for index in indices) + adjusted_minimum = minimum_retention + if allow_repeat and minimum_retention > 0 and leaf_count > 2: + adjusted_minimum = minimum_retention ** (1 / (leaf_count - 1)) + ratios = compute_retention_ratios( + [scores.block_importance[index] for index in indices], + power=power, + minimum=adjusted_minimum, + ) + print( + f"CoMe step {len(records) + 1}: merge current layers {left}/{left + 1} " + f"(sources {lineage[left]} + {lineage[left + 1]}, ratios={ratios})", + flush=True, + ) + merge_layers = [model.model.layers[index] for index in indices] + attention_counts = merge_attention( + merge_layers, + ratios, + [scores.attention_groups[index] for index in indices], + ) + mlp_counts = merge_mlp( + merge_layers, + ratios, + [scores.mlp_neurons[index] for index in indices], + ) + merge_norms(merge_layers) + records.append( + MergeRecord( + step=len(records) + 1, + left_index=left, + source_layers=[list(lineage[index]) for index in indices], + retention_ratios=ratios, + retained_attention_groups=attention_counts, + retained_mlp_neurons=mlp_counts, + pair_score=float(scores.pair_similarity[left]), + ) + ) + del model.model.layers[left + 1] + lineage[left] = lineage[left] + lineage[left + 1] + del lineage[left + 1] + _update_config_after_delete(model, left + 1) + if torch.cuda.is_available(): + torch.cuda.empty_cache() + return records + + +def build_wikitext2_calibration( + tokenizer, + *, + samples: int, + sequence_length: int, + seed: int, +) -> list[dict[str, Tensor]]: + """Reproduce CoMe's shuffled WikiText-2 prefix calibration stream. + + The upstream ``nsamples`` argument counts shuffled dataset rows, not 2,048 + token windows. Full windows are carved from their concatenated token stream + and the short tail is discarded. + """ + + from datasets import load_dataset + + dataset = load_dataset("wikitext", "wikitext-2-raw-v1", split="train").shuffle(seed=seed) + selected = dataset.select(range(min(samples, len(dataset)))) + text = "\n\n".join(selected["text"]) + token_ids = tokenizer(text, return_tensors="pt").input_ids[0] + windows = token_ids.numel() // sequence_length + if windows == 0: + raise ValueError("selected WikiText-2 rows contain fewer tokens than sequence_length") + batches = [] + for index in range(windows): + start = index * sequence_length + input_ids = token_ids[start : start + sequence_length].unsqueeze(0) + batches.append({"input_ids": input_ids, "attention_mask": torch.ones_like(input_ids)}) + return batches + + +def build_slimpajama_calibration( + tokenizer, + *, + rows: int, + sequence_length: int, + seed: int, + shuffle_buffer: int = 10_000, +) -> list[dict[str, Tensor]]: + """Pack full windows after concatenating shuffled SlimPajama rows. + + This mirrors upstream CoMe's WikiText loader: ``nsamples`` counts dataset + rows, not model-forward windows. + """ + + from datasets import load_dataset + + if rows < 1: + raise ValueError("rows must be positive") + dataset = load_dataset( + "DKYoon/SlimPajama-6B", + split="train", + streaming=True, + ).shuffle(seed=seed, buffer_size=shuffle_buffer) + token_buffer: list[int] = [] + selected_rows = 0 + for row in dataset: + text = row.get("text") + selected_rows += 1 + if isinstance(text, str): + token_buffer.extend(tokenizer.encode(text, add_special_tokens=False)) + if selected_rows == rows: + break + if selected_rows != rows: + raise RuntimeError(f"could only read {selected_rows}/{rows} SlimPajama rows") + windows = len(token_buffer) // sequence_length + if windows == 0: + raise ValueError("selected SlimPajama rows contain fewer tokens than sequence_length") + batches: list[dict[str, Tensor]] = [] + for index in range(windows): + start = index * sequence_length + input_ids = torch.tensor(token_buffer[start : start + sequence_length], dtype=torch.long).unsqueeze(0) + batches.append({"input_ids": input_ids, "attention_mask": torch.ones_like(input_ids)}) + return batches + + +def batch_calibration( + samples: Sequence[dict[str, Tensor]], batch_size: int +) -> list[dict[str, Tensor]]: + if batch_size < 1: + raise ValueError("batch_size must be positive") + batches = [] + for start in range(0, len(samples), batch_size): + chunk = samples[start : start + batch_size] + batches.append({key: torch.cat([item[key] for item in chunk], dim=0) for key in chunk[0]}) + return batches + + +def save_merge_metadata( + output_dir: str | Path, + *, + source_model: str, + records: Sequence[MergeRecord], + arguments: dict, +) -> None: + path = Path(output_dir) / "come_pruning.json" + payload = { + "method": "CoMe structured pruning (no distillation)", + "source_model": source_model, + "arguments": arguments, + "merges": [asdict(record) for record in records], + } + path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + + +def enable_torch24_dtensor_save_compat() -> None: + """Expose PyTorch 2.4's private DTensor where Transformers 4.52 expects it.""" + + try: + import torch.distributed.tensor as public_tensor + except ImportError: + return + if hasattr(public_tensor, "DTensor"): + return + try: + from torch.distributed._tensor import DTensor + except ImportError: + return + public_tensor.DTensor = DTensor + # Transformers 4.52 imports this name only when it detects torch >= 2.5, + # but save_pretrained references it unconditionally on torch 2.4. + import transformers.modeling_utils as modeling_utils + + modeling_utils.DTensor = DTensor diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/eval_llama31_8b_12bench.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/eval_llama31_8b_12bench.py new file mode 100644 index 0000000000000000000000000000000000000000..8bbc8713a4d0f04209bec7ee454a24744f9d3bb8 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/eval_llama31_8b_12bench.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Evaluate the lm-eval portion of the requested Llama benchmark suite. + +RACE-H/M, C3, CMNLI, and CHID are evaluated with their canonical OpenCompass +PPL task definitions by the companion launcher. This script handles the +remaining eight tasks plus full zero-shot MMLU and CMMLU. +""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +from typing import Any + +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + + +TASKS = ( + "piqa", + "winogrande", + "hellaswag", + "arc_challenge", + "arc_easy", + "openbookqa", + "sciq", + "mmlu", + "cmmlu", +) + +# Use normalized accuracy where the standard harness exposes it. The +# extraction code falls back to plain accuracy for tasks/versions without it. +PREFERRED_METRICS = { + "piqa": "acc_norm,none", + "hellaswag": "acc_norm,none", + "arc_challenge": "acc_norm,none", + "arc_easy": "acc_norm,none", + "openbookqa": "acc_norm,none", + "sciq": "acc_norm,none", +} + + +def _score(task: str, result: dict[str, Any]) -> tuple[str, float]: + preferred = PREFERRED_METRICS.get(task, "acc,none") + candidates = (preferred, "acc_norm,none", "acc,none") + for metric in candidates: + value = result.get(metric) + if value is not None: + return metric, float(value) + available = sorted(key for key in result if "," in key and not key.endswith("_stderr,none")) + raise KeyError(f"No supported accuracy metric for {task}; available={available}") + + +def _load_model(args: argparse.Namespace): + if args.compact_stage is None: + model = AutoModelForCausalLM.from_pretrained( + args.model, + revision=args.revision, + torch_dtype=torch.bfloat16, + attn_implementation="eager", + local_files_only=args.local_files_only, + ).cuda().eval() + tokenizer = AutoTokenizer.from_pretrained( + args.model, + revision=args.revision, + local_files_only=args.local_files_only, + ) + return model, tokenizer + + if args.cycle is None or args.anchor is None: + raise ValueError("--compact-stage requires --cycle and --anchor") + from fusegpt.abprune_stagewise_geometry import load_compact_model + + model = load_compact_model( + args.model, + args.compact_stage, + cycle=args.cycle, + anchor=args.anchor, + dtype=torch.bfloat16, + device=torch.device("cuda"), + attn="eager", + revision=args.revision, + ) + tokenizer = AutoTokenizer.from_pretrained( + args.model, revision=args.revision, local_files_only=args.local_files_only) + return model, tokenizer + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--model", required=True) + parser.add_argument("--revision", default=None) + parser.add_argument("--local-files-only", action="store_true") + parser.add_argument("--compact-stage", type=Path, default=None) + parser.add_argument("--cycle", type=int, default=None) + parser.add_argument("--anchor", type=int, default=None) + parser.add_argument("--batch-size", default="auto:4") + parser.add_argument("--limit", type=float, default=None) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--dataset-cache", type=Path, default=None) + parser.add_argument("--tasks", nargs="+", choices=TASKS, default=list(TASKS), + help="Evaluate a subset without repeating already scored tasks") + args = parser.parse_args() + if len(set(args.tasks)) != len(args.tasks): + parser.error("--tasks must not contain duplicates") + + # CMMLU is still distributed through a Hugging Face dataset loading + # script. Opt in explicitly so non-interactive experiment jobs do not + # stop at the datasets trust prompt. + os.environ.setdefault("HF_DATASETS_TRUST_REMOTE_CODE", "1") + + from lm_eval import evaluator + from lm_eval.models.huggingface import HFLM + + if args.dataset_cache is not None: + from prepare_lmeval9_local_cache import install_local_loader + install_local_loader(args.dataset_cache) + + model, tokenizer = _load_model(args) + model.config.use_cache = False + if getattr(model, "generation_config", None) is not None: + model.generation_config.use_cache = False + for layer_idx, layer in enumerate(model.model.layers): + if hasattr(layer, "self_attn") and hasattr(layer.self_attn, "layer_idx"): + layer.self_attn.layer_idx = layer_idx + + lm = HFLM( + pretrained=model, + tokenizer=tokenizer, + backend="causal", + batch_size=args.batch_size, + ) + raw = evaluator.simple_evaluate( + model=lm, + tasks=args.tasks, + num_fewshot=0, + batch_size=args.batch_size, + random_seed=0, + numpy_random_seed=1234, + torch_random_seed=1234, + fewshot_random_seed=1234, + bootstrap_iters=0, + limit=args.limit, + ) + + scores: dict[str, float] = {} + metrics: dict[str, str] = {} + for task in args.tasks: + source = raw.get("groups", {}) if task in {"mmlu", "cmmlu"} else raw["results"] + if task not in source: + raise KeyError( + f"Requested task {task!r} missing from lm-eval results: " + f"results={sorted(raw['results'])}, groups={sorted(raw.get('groups', {}))}" + ) + metric, value = _score(task, source[task]) + metrics[task] = metric + scores[task] = value + + report = { + "model": args.model, + "revision": args.revision, + "compact_stage": str(args.compact_stage) if args.compact_stage else None, + "cycle": args.cycle, + "anchor": args.anchor, + "tasks": args.tasks, + "num_fewshot": 0, + "batch_size": args.batch_size, + "limit": args.limit, + "dataset_cache": str(args.dataset_cache) if args.dataset_cache else None, + "preferred_metrics": metrics, + "task_scores": scores, + "macro_mean_all_rows": sum(scores.values()) / len(scores), + "lm_eval_results": raw["results"], + "lm_eval_groups": raw.get("groups"), + "lm_eval_versions": raw.get("versions"), + "lm_eval_config": raw.get("config"), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text( + json.dumps(report, indent=2, ensure_ascii=False, default=str) + "\n", + encoding="utf-8", + ) + print( + json.dumps( + {"task_scores": scores, "macro_mean_all_rows": report["macro_mean_all_rows"]}, + indent=2, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/eval_llama31_fit_ablation_one.sh b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/eval_llama31_fit_ablation_one.sh new file mode 100644 index 0000000000000000000000000000000000000000..b64dcaa488d68367fedff793ba3a68caa6919491 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/eval_llama31_fit_ablation_one.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +set -euo pipefail +project="$1"; root="$2"; model="$3"; data="$4"; python="$5" +anchor="$6"; cycles="$7"; gpu="$8" +stage="$root/compact/stage_$(printf '%02d' "$cycles")" +export HF_HOME=/workspace/.hf_home HF_TOKEN_PATH=/root/.cache/huggingface/token +export HF_DATASETS_CACHE=/workspace/.hf_datasets36 HF_DATASETS_TRUST_REMOTE_CODE=1 +export TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1 PYTHONPATH="$project/src" +revision="${MODEL_REVISION:-49e3418fbbbca6ecbdf9608b4d22e5a407081db4}" +if [[ -n "${LMEVAL_LOCAL_CACHE:-}" ]]; then + export HF_HUB_OFFLINE=1 HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 + [[ -d "$model" ]] || { echo 'Offline bench requires a local model directory'; exit 1; } + "$python" "$project/scripts/prepare_lmeval9_local_cache.py" "$LMEVAL_LOCAL_CACHE" --validate-local + 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 + [[ -s "$data/$file" ]] || { echo "Offline OpenCompass input missing: $file"; exit 1; } + done + echo 'STRICT_OFFLINE_BENCH_PREFLIGHT_OK' +fi +opencompass_gpu="$gpu"; lmeval_gpu="${9:-$gpu}" +if [[ -f "$root/eval/gpu_assignment.json" ]]; then + read -r opencompass_gpu lmeval_gpu < <("$python" - "$root/eval/gpu_assignment.json" <<'PY' +import json, sys +assignment = json.load(open(sys.argv[1])) +values = [assignment[key] for key in ("opencompass_gpu", "lmeval_gpu")] +assert all(type(value) is int and value >= 0 for value in values) +print(*values) +PY + ) +fi +run_opencompass() { + [[ -f "$root/eval/final_opencompass5.json" ]] && return 0 + CUDA_VISIBLE_DEVICES="$opencompass_gpu" "$python" "$project/scripts/eval_opencompass_ppl_fast.py" \ + --model "$model" --revision "$revision" --tokenizer "$model" \ + --compact-stage "$stage" --cycle "$cycles" --anchor "$anchor" \ + --data-root "$data" --max-batch 32 --token-budget 8192 \ + --output "$root/eval/final_opencompass5.json" +} +run_lmeval() { + [[ -f "$root/eval/final_lmeval9.json" ]] && return 0 + local cache_args=() + if [[ -n "${LMEVAL_LOCAL_CACHE:-}" ]]; then + [[ -f "$LMEVAL_LOCAL_CACHE/manifest.json" ]] || return 1 + cache_args=(--dataset-cache "$LMEVAL_LOCAL_CACHE" --local-files-only) + export HF_HUB_OFFLINE=1 HF_DATASETS_OFFLINE=1 + fi + CUDA_VISIBLE_DEVICES="$lmeval_gpu" "$python" "$project/scripts/eval_llama31_8b_12bench.py" \ + --model "$model" --revision "$revision" --compact-stage "$stage" \ + --cycle "$cycles" --anchor "$anchor" --batch-size auto:4 \ + --output "$root/eval/final_lmeval9.json" "${cache_args[@]}" +} +if [[ "$opencompass_gpu" != "$lmeval_gpu" ]]; then + echo "Parallel evaluation: OpenCompass GPU=$opencompass_gpu; lm-eval GPU=$lmeval_gpu" + run_opencompass >> "$root/logs/eval_opencompass.log" 2>&1 & oc_pid=$! + run_lmeval >> "$root/logs/eval_lmeval.log" 2>&1 & lm_pid=$! + status=0 + wait "$oc_pid" || status=1 + wait "$lm_pid" || status=1 + if ((status)); then exit 1; fi +else + run_opencompass >> "$root/logs/eval14.log" 2>&1 + run_lmeval >> "$root/logs/eval14.log" 2>&1 +fi +"$python" "$project/scripts/aggregate_transport_rho_fit_14bench.py" "$root" diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/evaluate_abprune_compact_ppl.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/evaluate_abprune_compact_ppl.py new file mode 100644 index 0000000000000000000000000000000000000000..40ba37eaa42227fb5065410015f6407e126237e1 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/evaluate_abprune_compact_ppl.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +"""Evaluate an unscaled or residual-scaled compact ABPrune checkpoint.""" + +from __future__ import annotations + +import argparse +import json +from contextlib import ExitStack +from pathlib import Path +import sys + +from offline_eval_policy import apply_run_offline_policy + +OFFLINE_POLICY = apply_run_offline_policy(sys.argv) + +import torch + +from evaluate_hchc_wikitext2_ppl import evaluate_perplexity, packed_wikitext_tokens +from fusegpt.abprune_residual_scale import residual_scale_hook +from fusegpt.abprune_compact import compact_scale_targets, read_compact_metadata +from fusegpt.abprune_stagewise_geometry import load_compact_model +from fusegpt.hadamard_channel_fusion import linear_patch_hook + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--model", required=True) + parser.add_argument("--revision", required=True) + parser.add_argument("--compact-stage", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--anchor", type=int, default=None) + parser.add_argument("--cycles", type=int, required=True) + parser.add_argument("--original-layers", type=int, required=True) + parser.add_argument("--seq-len", type=int, default=2048) + parser.add_argument("--batch-size", type=int, default=4) + parser.add_argument("--device", default="cuda") + parser.add_argument("--apply-post-merge-scale", action="store_true") + parser.add_argument("--linear-patch", type=Path, default=None) + args = parser.parse_args() + + # Long training supervisors may be asked to stop after model construction. + # A run-local marker makes that request durable without killing training. + run_root = args.output.parent.parent + if (run_root / "DEFER_EVAL").exists(): + print(f"[eval] deferred by {run_root / 'DEFER_EVAL'}", flush=True) + raise SystemExit(75) + + device = torch.device(args.device) + model = load_compact_model( + args.model, + args.compact_stage, + cycle=args.cycles, + anchor=args.anchor, + dtype=torch.bfloat16, + device=device, + attn="eager", + revision=args.revision, + ) + model.eval() + expected_depth = args.original_layers - args.cycles + if len(model.model.layers) != expected_depth: + raise RuntimeError( + f"Unexpected decoder depth: {len(model.model.layers)} != {expected_depth}" + ) + + from transformers import AutoTokenizer + + if OFFLINE_POLICY and not Path(args.model).is_dir(): + raise ValueError('Strict offline PPL requires a local model directory') + tokenizer = AutoTokenizer.from_pretrained( + args.model, revision=args.revision, local_files_only=bool(OFFLINE_POLICY)) + applied_scales = [] + scale_stack = ExitStack() + linear_patch = None + if args.apply_post_merge_scale: + metadata = read_compact_metadata(args.compact_stage) + targets = compact_scale_targets(metadata) + if not targets: + raise RuntimeError( + "--apply-post-merge-scale requires enabled residual scale metadata" + ) + for target in targets: + stored_scale = target["scale"]["cumulative_gamma"] + applied = ( + torch.tensor(stored_scale, device=device, dtype=torch.float32) + if isinstance(stored_scale, list) + else float(stored_scale) + ) + scale_stack.enter_context( + residual_scale_hook(model, int(target["student_index"]), applied) + ) + applied_scales.append( + { + "original_layer": int(target["original_layer"]), + "student_index": int(target["student_index"]), + "value": applied, + } + ) + if args.linear_patch is not None: + linear_patch = json.loads(args.linear_patch.read_text(encoding="utf-8")) + patch_scale = torch.tensor( + linear_patch["scale"], device=device, dtype=torch.float32 + ) + patch_anchor = int(linear_patch["anchor_student_index"]) + scale_stack.enter_context( + linear_patch_hook( + model.model.layers[patch_anchor], + patch_scale, + hadamard=linear_patch["mode"] == "hadamard", + ) + ) + + with scale_stack: + tokens = packed_wikitext_tokens( + tokenizer, "test", dataset_cache=( + Path(OFFLINE_POLICY['wikitext_cache']) if OFFLINE_POLICY else None)) + metrics = evaluate_perplexity( + model=model, + tokens=tokens, + sequence_length=args.seq_len, + batch_size=args.batch_size, + ) + + report = { + "model": args.model, + "revision": args.revision, + "compact_stage": str(args.compact_stage), + "dataset": "Salesforce/wikitext:wikitext-2-raw-v1:test", + "offline_policy": OFFLINE_POLICY, + "protocol": ( + "HCHC experiment.py: filter empty rows, join with double newline, " + "then tokenize the complete stream once" + ), + "sequence_length": args.seq_len, + "batch_size": args.batch_size, + "dtype": "bfloat16", + "metrics": metrics, + "anchor": args.anchor, + "cycles": args.cycles, + "original_layers": args.original_layers, + "decoder_layers": len(model.model.layers), + "post_merge_residual_scale": ( + applied_scales[0]["value"].tolist() + if len(applied_scales) == 1 + and torch.is_tensor(applied_scales[0]["value"]) + else ( + applied_scales[0]["value"] + if len(applied_scales) == 1 + else None + ) + ), + "post_merge_residual_scales": [ + { + "original_layer": item["original_layer"], + "student_index": item["student_index"], + "parameterization": ( + "vector" if torch.is_tensor(item["value"]) else "scalar" + ), + "value": ( + item["value"].tolist() + if torch.is_tensor(item["value"]) + else item["value"] + ), + } + for item in applied_scales + ], + "parameterization": ( + "X_interface <- X_interface H D H.T" + if linear_patch and linear_patch["mode"] == "hadamard" + else ( + "X_interface <- X_interface D" + if linear_patch + else ( + "h_out = h_in + gamma * (block(h_in) - h_in)" + if applied_scales else "unscaled compact ABPrune" + ) + ) + ), + "linear_patch": linear_patch, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/evaluate_hchc_wikitext2_ppl.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/evaluate_hchc_wikitext2_ppl.py new file mode 100644 index 0000000000000000000000000000000000000000..28ea302a1e40246a770b97e6ee6fd9198cf57c28 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/evaluate_hchc_wikitext2_ppl.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Evaluate a saved causal LM with the HCHC WikiText-2 PPL protocol.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path +from typing import Any + +import torch +from datasets import load_dataset, load_from_disk + + +def primary(output: Any) -> torch.Tensor: + if torch.is_tensor(output): + return output + if isinstance(output, (tuple, list)) and output and torch.is_tensor(output[0]): + return output[0] + raise TypeError(f"Unsupported decoder-layer output type: {type(output)!r}") + + +def replace_primary(output: Any, hidden: torch.Tensor) -> Any: + if torch.is_tensor(output): + return hidden + if isinstance(output, tuple): + return (hidden, *output[1:]) + if isinstance(output, list): + return [hidden, *output[1:]] + raise TypeError(f"Unsupported decoder-layer output type: {type(output)!r}") + + +def register_residual_scale_hook(layer, gamma: float): + """Install h_out = h_in + gamma * (block(h_in) - h_in).""" + scale = torch.tensor(gamma, device=next(layer.parameters()).device) + + def hook(_module, inputs, output): + if not inputs or not torch.is_tensor(inputs[0]): + raise RuntimeError("Could not capture decoder-layer residual input") + layer_input = inputs[0] + corrected = layer_input + scale * (primary(output) - layer_input) + return replace_primary(output, corrected) + + return layer.register_forward_hook(hook) + + +def packed_wikitext_tokens(tokenizer, split: str, *, dataset_cache: Path | None = None) -> torch.Tensor: + """Reproduce the canonical HCHC WikiText-2 packing protocol.""" + if dataset_cache is not None: + dataset = load_from_disk(str(dataset_cache))[split] + else: + dataset = load_dataset( + "Salesforce/wikitext", "wikitext-2-raw-v1", split=split + ) + text = "\n\n".join(row for row in dataset["text"] if row.strip()) + return tokenizer( + text, add_special_tokens=False, return_tensors="pt" + ).input_ids[0] + + +@torch.no_grad() +def evaluate_perplexity( + model, + tokens: torch.Tensor, + sequence_length: int, + batch_size: int, +) -> dict[str, float | int]: + num_sequences = tokens.numel() // sequence_length + ids = tokens[: num_sequences * sequence_length].view(num_sequences, sequence_length) + total_nll = 0.0 + total_predicted_tokens = 0 + model.eval() + for start in range(0, num_sequences, batch_size): + batch = ids[start : start + batch_size].to("cuda") + output = model(input_ids=batch, labels=batch, use_cache=False) + predicted = batch.shape[0] * (batch.shape[1] - 1) + total_nll += output.loss.float().item() * predicted + total_predicted_tokens += predicted + mean_nll = total_nll / total_predicted_tokens + return { + "nll": mean_nll, + "perplexity": math.exp(mean_nll), + "tokens": total_predicted_tokens, + "sequences": num_sequences, + "source_tokens": int(tokens.numel()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--model", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--sequence-length", type=int, default=2048) + parser.add_argument("--batch-size", type=int, default=8) + parser.add_argument("--residual-anchor", type=int) + parser.add_argument("--residual-gamma", type=float) + args = parser.parse_args() + + if (args.residual_anchor is None) != (args.residual_gamma is None): + parser.error("--residual-anchor and --residual-gamma must be supplied together") + + from transformers import AutoModelForCausalLM, AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained(args.model, local_files_only=True) + model = AutoModelForCausalLM.from_pretrained( + args.model, + torch_dtype=torch.bfloat16, + local_files_only=True, + low_cpu_mem_usage=True, + attn_implementation="sdpa", + ).to("cuda") + model.config.use_cache = False + + handle = None + if args.residual_gamma is not None: + if args.residual_anchor >= len(model.model.layers): + raise ValueError( + f"Residual anchor {args.residual_anchor} is outside decoder depth " + f"{len(model.model.layers)}" + ) + handle = register_residual_scale_hook( + model.model.layers[args.residual_anchor], args.residual_gamma + ) + + tokens = packed_wikitext_tokens(tokenizer, "test") + try: + metrics = evaluate_perplexity( + model, tokens, args.sequence_length, args.batch_size + ) + finally: + if handle is not None: + handle.remove() + + report = { + "model": str(args.model), + "dataset": "Salesforce/wikitext:wikitext-2-raw-v1:test", + "protocol": "HCHC experiment.py: non-empty rows joined with double newline before one-shot tokenization", + "sequence_length": args.sequence_length, + "batch_size": args.batch_size, + "dtype": "bfloat16", + "residual_anchor": args.residual_anchor, + "residual_gamma": args.residual_gamma, + "metrics": metrics, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/finalize_mka_batch_report.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/finalize_mka_batch_report.py new file mode 100644 index 0000000000000000000000000000000000000000..b734dc55dcfe011ee227d089adb9cc7fc639c1ed --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/finalize_mka_batch_report.py @@ -0,0 +1,218 @@ +"""Register the completed MKA MLP-only FiT pair and its matched-data controls.""" +import argparse +import csv +import io +import json +import math +from pathlib import Path +import re +import subprocess + + +RESULT_NAME = "llama31_mka_mlp_batch_20261126" +STATE_NAME = "mka-fit-batch-20261126" +NOTE_NAME = "2026-11-26_llama31-mka-mlp-batch-comparison.md" +SESSION = "vast-paper_revision-come-attn-fit-20261126-62646539" +EXPERIMENT = "20261126-llama31-mka-mlp-batch" +INSTANCE = 62646539 +MODEL_REVISION = "d04e592bb4f6aa9cfee91e2e20afa771667e1d4b" +MKA_INPUT = "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075" +COME_INPUT = "0d5ee3894a716120c8f738c25d05838ca6871137f7b471d4616da55cab4a7361" +FIT_INPUT = "2b2d044c8c040f67891817ecc110f0fa0de2f469db4c6731114ff7816bbf1cd0" +FIT_MASK = "c8e7f8e30cd532b82e6af4b98d596bc7106f29f9fb2b398b44355e624898a30d" + + +def load(path): + return json.loads(path.read_text(encoding="utf-8-sig")) + + +def read_catalog(path): + with path.open(encoding="utf-8-sig", newline="") as stream: + reader = csv.DictReader(stream) + return reader.fieldnames, list(reader) + + +def historical_catalog_row(path, record_id): + return next(row for row in read_catalog(path)[1] if row["record_id"] == record_id) + + +def validate_scores(row): + for key in ("bench12", "mmlu", "cmmlu"): + assert math.isfinite(row[key]) and 0 <= row[key] <= 1, key + assert math.isfinite(row["ppl"]) and row["ppl"] > 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--reference", type=Path, + help="Optional verified historical MKA no-FiT reference JSON, one row or {'rows': [...]} with fraction scores and source") + args = parser.parse_args() + repo = Path(__file__).resolve().parents[1] + root = repo / "results" / RESULT_NAME + summary = load(root / "summary.json") + assert summary["model"] == "meta-llama/Llama-3.1-8B" and summary["removed_blocks"] == 8 + assert summary["fit_scope"] == "mlp" and len(summary["rows"]) == 2 + assert {row["batch_size"] for row in summary["rows"]} == {1, 8} + assert {row["arm"] for row in summary["rows"]} == {"batch1", "batch_large"} + audit = load(repo / "outputs" / STATE_NAME / "model_backup_audit.json") + assert audit["verified"] and len(audit["records"]) == 2 + assert all(record["verified"] and record["all_payload_hashes_verified"] for record in audit["records"]) + audited = {(record["path_in_repo"], record["revision"]) for record in audit["records"]} + commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo).decode().strip() + catalog = repo / "results/instruct_pruning_experiment_catalog.csv" + fields, old_rows = read_catalog(catalog) + old_ids = {row["record_id"]: row for row in old_rows} + assert len(old_rows) == len(old_ids), "Existing catalog contains duplicate record IDs" + + come = historical_catalog_row(repo / "results/laco_come_experiment_catalog.csv", + "llama31_base_come_allowrepeat_8block") + ab = old_ids["llama31_base_transport_8block"] + ab_nofit = next(row for row in load( + repo / "results/llama31_base_nofit_transport_bench14_20261009/summary.json")["rows"] + if row["transport"] == "on") + comparison = [ + {"method": "CoMe without FiT", "fit_scope": "none", "fit_batch": None, + "bench12": float(come["zs12_mean"]), "mmlu": float(come["mmlu"]), + "cmmlu": float(come["cmmlu"]), "ppl": float(come["ppl"]), + "source": "llama31_base_come_allowrepeat_8block", "new_run": False, + "selection_input_sha256": COME_INPUT}, + {"method": "ABPrune without FiT", "fit_scope": "none", "fit_batch": None, + "bench12": ab_nofit["zs12"], "mmlu": ab_nofit["mmlu"], + "cmmlu": ab_nofit["cmmlu"], "ppl": ab_nofit["ppl"], + "source": "llama31_base_nofit_transport_bench14_20261009/on", "new_run": False}, + {"method": "ABPrune + MLP FiT", "fit_scope": "mlp", "fit_batch": 1, + "bench12": float(ab["zs12_mean"]), "mmlu": float(ab["mmlu"]), + "cmmlu": float(ab["cmmlu"]), "ppl": float(ab["ppl"]), + "source": "llama31_base_transport_8block", "new_run": False}, + ] + if args.reference: + reference = load(args.reference) + references = reference["rows"] if "rows" in reference else [reference] + for row in references: + validate_scores(row) + assert row.get("source") and row.get("method"), "Reference must name its method and source" + assert row.get("fit_scope", "none") == "none", "Only a no-FiT MKA reference is accepted" + assert row.get("selection_input_sha256") == MKA_INPUT, "Historical native MKA inputs must match" + comparison.append({**row, "fit_scope": "none", "fit_batch": None, "new_run": False}) + prior = load(repo / "results/llama31_come_batch_20261126/summary.json") + for row in prior["rows"]: + assert row["selection_input_sha256"] == COME_INPUT + assert row["fit_input_sha256"] == FIT_INPUT and row["fit_mask_sha256"] == FIT_MASK + comparison.append({"method": "CoMe + MLP FiT", "fit_scope": "mlp", "fit_batch": row["batch_size"], + **{key: row[key] for key in ("bench12", "mmlu", "cmmlu", "ppl", "training_wall_seconds", + "selection_input_sha256", "fit_input_sha256", "fit_mask_sha256")}, + "source": "llama31_come_batch_20261126/" + row["arm"], "new_run": False, + "hf_path": row["backup"]["path_in_repo"], "hf_revision": row["backup"]["revision"]}) + + additions = [] + for row in summary["rows"]: + validate_scores(row) + assert row["selection_input_sha256"] == MKA_INPUT + assert row["fit_input_sha256"] == FIT_INPUT and row["fit_mask_sha256"] == FIT_MASK + arm, batch, receipt = row["arm"], row["batch_size"], row["backup"] + assert receipt["verified"] and (receipt["path_in_repo"], receipt["revision"]) in audited + assert receipt["path_in_repo"] == f"runs/{SESSION}/{EXPERIMENT}/{arm}" + assert re.fullmatch(r"[0-9a-f]{40}", receipt["revision"]) + assert row["optimizer_updates_per_stage"] == 512 // batch + scores = row["task_scores"] + assert len(scores) == 14 + assert abs(sum(v for k, v in scores.items() if k not in ("mmlu", "cmmlu")) / 12 - row["bench12"]) < 1e-12 + assert scores["mmlu"] == row["mmlu"] and scores["cmmlu"] == row["cmmlu"] + assert len(row["cycles"]) == 8 + for fit in row["cycles"]: + assert fit["trained"] and fit["num_trainable_mlp_gates"] == 3 + assert fit["num_trainable_attn_gates"] == fit["num_trainable_other_gates"] == 0 + assert fit["ablation"]["frozen_attention_norm_unchanged"] + assert fit["ablation"]["attention_initialization"] == "MKA_merge" + assert not fit["ablation"]["norms_trainable"] + execution_commit = (root / arm / "execution_commit.txt").read_text().strip() + assert re.fullmatch(r"[0-9a-f]{40}", execution_commit) + comparison.append({"method": "MKA + MLP FiT", "fit_scope": "mlp", "fit_batch": batch, + **{key: row[key] for key in ("bench12", "mmlu", "cmmlu", "ppl", "training_wall_seconds", + "selection_input_sha256", "fit_input_sha256", "fit_mask_sha256")}, + "source": RESULT_NAME + "/" + arm, "new_run": True, + "hf_path": receipt["path_in_repo"], "hf_revision": receipt["revision"]}) + settings = {"method": "native stagewise MKA + MLP-only FiT", + "selection": {"dataset": "DKYoon/SlimPajama-6B", "samples": 100, + "sequence_length": 512, "seed": 0, "batch_size": 1, + "geometry": "native MKA dynamic adjacent NPIB", "input_ids_sha256": MKA_INPUT, + "attention_mask_sha256": row["selection_inputs"].get("attention_mask_sha256"), + "sample_source": "Frozen historical native MKA Base calibration cache"}, + "training": {"samples": 512, "sequence_length": 1024, "tokens_per_stage": 524288, + "epochs_per_stage": 1, "batch_size": batch, "grad_accumulation": 1, + "optimizer_updates_per_stage": 512 // batch, "lr": 1e-4, + "weight_decay": 0, "clip": 1, "hidden_mse": 1, "mlp_mse": 1, + "attention_mse": 0, "kl_weight": .02, "temperature": 4, "seed": 42, + "teacher": "previous_cycle", "scope": "mlp", "trainable_projection_tensors": 3, + "attention_trainable": False, "norms_trainable": False, + "input_ids_sha256": FIT_INPUT, "mask_sha256": FIT_MASK}, + "initialization": {"attention": "native MKA weighted merge", "mlp": "native MKA weighted merge", + "norms": "recipient anchor Wa", "source_feature_transport": False}, + "selection_provenance": summary.get("selection_provenance", {})} + record_id = f"llama31_base_mka_mlp_fit_batch{batch}_8block_20261126" + record = {key: "" for key in fields} + record.update({"record_id": record_id, "model_name": "meta-llama/Llama-3.1-8B", + "model_revision": MODEL_REVISION, "model_variant": "Base", "method": "MKA+MLP-FiT", + "blocks_removed": 8, "selector": "Frozen historical MKA100x512/seed0; dynamic NPIB reselection after FiT", + "removed_interval": "non-contiguous; see selection trace", "ppl": row["ppl"], + "zs12_count": 12, "zs12_mean": row["bench12"], "mmlu": row["mmlu"], "cmmlu": row["cmmlu"], + "macro14_mean": sum(scores.values()) / 14, "metric_scale": "accuracy_fraction_0_to_1", + "experiment_settings": f"Native MKA100x512/seed0; FiT512x1024/1epoch/LR1e-4/MLP3/frozen-attention-norms/batch{batch}/seed42", + "experiment_settings_json": json.dumps(settings, separators=(",", ":")), + "experiment_date": "2026-11-26", "status": "complete", "storage_host": SESSION, + "vast_instance": INSTANCE, "weight_path": f"/workspace/{STATE_NAME}/full/{arm}/compact/stage_08", + "hf_backup_path": f"hf://LJYAI/paper_revision/{receipt['path_in_repo']}@{receipt['revision']}", + "backup_status": "verified_huggingface_backup", "journal_commit": commit, + "code_commit": execution_commit, + "protocol_path": f"hf://LJYAI/paper_revision/{receipt['path_in_repo']}/protocol.md@{receipt['revision']}", + "ppl_result_path": f"results/{RESULT_NAME}/{arm}/final_ppl.json", + "bench14_result_path": f"results/{RESULT_NAME}/{arm}/final_14bench.json", + "evaluation_protocol": "Packed WikiText2 seq2048 BF16; canonical OpenCompass5 full-prompt PPL; lm-eval0.4.12 zero-shot auto:4, full offline131 cache", + "experiment_log": "exp_md/" + NOTE_NAME, + "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."}) + record.update(scores) + record = {key: str(value) if value is not None else "" for key, value in record.items() if key in fields} + if record_id in old_ids: + existing = old_ids[record_id] + for key in ("zs12_mean", "mmlu", "cmmlu", "ppl", "hf_backup_path", "experiment_settings_json"): + assert existing[key] == record[key], f"Existing record conflicts: {record_id}/{key}" + else: + additions.append(record) + + for row in comparison: + validate_scores(row) + comparison_result = {"rows": comparison, "accuracy_scale": "fraction", "model": "Llama-3.1-8B Base", + "removed_blocks": 8, "reference_rows": "Historical results, not fresh benchmark reruns", + "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."} + # Preserve the exact bytes of every existing canonical record and append only new IDs. + payload = catalog.read_bytes() + if additions: + assert not payload or payload.endswith(b"\n"), "Canonical catalog must end with a newline" + buffer = io.StringIO(newline="") + writer = csv.DictWriter(buffer, fields, quoting=csv.QUOTE_ALL, lineterminator="\n") + writer.writerows(additions) + updated = payload + buffer.getvalue().encode("utf-8") + parsed = list(csv.DictReader(io.StringIO(updated.decode("utf-8-sig")))) + assert len(parsed) == len(old_rows) + len(additions) + assert parsed[:len(old_rows)] == old_rows + assert len({row["record_id"] for row in parsed}) == len(parsed) + temporary = catalog.with_suffix(".csv.partial") + temporary.write_bytes(updated) + temporary.replace(catalog) + (root / "comparison.json").write_text(json.dumps(comparison_result, indent=2) + "\n", encoding="utf-8") + with (root / "comparison.csv").open("w", encoding="utf-8-sig", newline="") as stream: + columns = ["method", "fit_scope", "fit_batch", "bench12_pct", "mmlu_pct", "cmmlu_pct", "ppl", + "training_wall_seconds", "new_run", "source", "selection_input_sha256", + "fit_input_sha256", "fit_mask_sha256", "hf_revision"] + writer = csv.DictWriter(stream, columns) + writer.writeheader() + for row in comparison: + data = {key: row.get(key, "") for key in columns} + data.update({key + "_pct": row[key] * 100 for key in ("bench12", "mmlu", "cmmlu")}) + writer.writerow(data) + (root / "backup_audit.json").write_text(json.dumps(audit, indent=2) + "\n", encoding="utf-8") + print(f"MKA_FINAL_COMPARISON_WRITTEN rows={len(comparison)} canonical_additions={len(additions)}") + + +if __name__ == "__main__": + main() diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/fit_ablation_come.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/fit_ablation_come.py new file mode 100644 index 0000000000000000000000000000000000000000..a38f56086dce61410a30283b79e3f07233cbcd1f --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/fit_ablation_come.py @@ -0,0 +1,54 @@ +"""CoMe initialization for stagewise full-block additive-U fitting. + +Use native CoMe selection/channel allocation; never mutate the teacher model. +Instruction calibration trims right padding before native CoMe scoring, so +angular-last measures the last valid token and channel scores omit padding. +""" +from __future__ import annotations + +import copy + +import torch + +from fusegpt import come + + +def valid_calibration_batches(loader): + batches = [] + for item in loader: + ids, masks = (item["input_ids"], item["attention_mask"]) if isinstance(item, dict) else item[:2] + for row, mask in zip(ids, masks, strict=True): + n = int(mask.sum()) + if n < 1 or not bool(mask[:n].all()) or bool(mask[n:].any()): + raise ValueError("CoMe calibration requires nonempty right-padded records") + batches.append({"input_ids": row[:n][None, :], "attention_mask": mask[:n][None, :]}) + return batches + + +def select_and_initialize(model, loader, lineage, *, minimum=.97, power=1.): + scores = come.collect_calibration_scores( + model, valid_calibration_batches(loader), sbi_metric="angular_last") + left = come._choose_pair(scores.pair_similarity, lineage, allow_repeat=True) + indices = [left, left + 1] + leaves = sum(len(lineage[i]) for i in indices) + adjusted = minimum ** (1 / (leaves - 1)) if leaves > 2 and minimum > 0 else minimum + ratios = come.compute_retention_ratios( + [scores.block_importance[i] for i in indices], power=power, minimum=adjusted) + # Small block copies only. Native helpers modify these, never the live + # previous-cycle teacher or the layer objects used to collect scores. + pair = [copy.deepcopy(model.model.layers[i]).cpu() for i in indices] + attention = come.merge_attention(pair, ratios, [scores.attention_groups[i] for i in indices]) + mlp = come.merge_mlp(pair, ratios, [scores.mlp_neurons[i] for i in indices]) + come.merge_norms(pair) + initial = {n: p.detach().float().clone() for n, p in pair[0].named_parameters()} + audit = { + "source_lineage": [list(lineage[i]) for i in indices], + "retention_ratios": ratios, "retained_attention_groups": attention, + "retained_mlp_neurons": mlp, "pair_score": scores.pair_similarity[left], + "minimum_retention": minimum, "adjusted_minimum": adjusted, + "power": power, "allow_repeat": True, "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": False, + } + del pair, scores + return left, initial, audit diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/fit_ablation_mka.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/fit_ablation_mka.py new file mode 100644 index 0000000000000000000000000000000000000000..5d0ff3b1ab1c31a493f7d54d607aef04cafd8046 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/fit_ablation_mka.py @@ -0,0 +1,482 @@ +"""Corrected MKA variant: adjacent NPIB selection, upstream lambda, real fusion. + +Not an exact reproduction of the paper: use sequence-level pooled activations, +recompute geometry after every merge, and resolve NPIB ties back-to-front. +The seven projection weights are fused; residual and Q/K norms stay at anchor. +""" + +from __future__ import annotations + +import hashlib +import math +import random +from collections.abc import Callable, Iterable, Sequence +from dataclasses import asdict, dataclass + +import numpy as np +import torch +from scipy.linalg import eigh +from scipy.spatial.distance import pdist, squareform +from sklearn.feature_selection import mutual_info_regression +from sklearn.neighbors import NearestNeighbors +from torch import Tensor, nn + +PROJECTION_WEIGHTS = ( + "mlp.down_proj.weight", + "mlp.up_proj.weight", + "mlp.gate_proj.weight", + "self_attn.k_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_proj.weight", + "self_attn.v_proj.weight", +) +UPSTREAM = "https://github.com/SempraETY/Pruning-via-Merging" +UPSTREAM_COMMIT = "3b60b002a0963266e2f4ca78f133b4e091bc607a" + + +@dataclass(frozen=True) +class GeometryConfig: + sigma: float = 8.0 + alpha: float = 0.5 + dimensions: int = 2 + mi_neighbors: int = 5 + entropy_neighbors: int = 50 + beta: float = 1.0 + seed: int = 0 + pooling: str = "mean" + + def validate(self) -> None: + if not math.isfinite(self.sigma) or self.sigma <= 0: + raise ValueError("sigma must be positive and finite") + if not math.isfinite(self.alpha) or not 0 <= self.alpha <= 1: + raise ValueError("alpha must be finite and in [0, 1]") + if self.dimensions < 1 or min(self.mi_neighbors, self.entropy_neighbors) < 1: + raise ValueError("dimensions and neighbor counts must be positive") + if not math.isfinite(self.beta) or self.beta < 0: + raise ValueError("beta must be non-negative and finite") + if self.pooling not in {"mean", "last"}: + raise ValueError("pooling must be 'mean' or 'last'") + + +def sample_slimpajama( + tokenizer, + *, + samples: int = 100, + sequence_length: int = 512, + seed: int = 0, + revision: str = "b5f90f419b7489cdba26fdbc8c022fcb5562f968", + shuffle_buffer: int = 10000, + max_documents: int = 100000, + documents: Iterable[dict] | None = None, +) -> tuple[list[dict[str, Tensor]], dict]: + """Exactly one random fixed-length, no-BOS window from each distinct document. + + Unlike CoMe's row-packing loader, ``samples`` is the number of sequences. + Persist returned IDs and provenance; do not sample again between stages. + """ + if min(samples, sequence_length, shuffle_buffer, max_documents) < 1: + raise ValueError("sampling counts, length and buffer must be positive") + if documents is None: + from datasets import load_dataset + + documents = load_dataset( + "DKYoon/SlimPajama-6B", revision=revision, split="train", streaming=True + ).shuffle(seed=seed, buffer_size=shuffle_buffer) + rng = random.Random(seed) + batches, records, seen = [], [], set() + iterator = iter(documents) + try: + for row_index, row in enumerate(iterator): + if row_index >= max_documents: + break + text = row.get("text") + if not isinstance(text, str) or not text.strip(): + continue + digest = hashlib.sha256(text.encode("utf-8")).hexdigest() + if digest in seen: + continue + seen.add(digest) + ids = tokenizer.encode(text, add_special_tokens=False) + if len(ids) < sequence_length: + continue + start = rng.randrange(len(ids) - sequence_length + 1) + tensor = torch.tensor( + ids[start : start + sequence_length], dtype=torch.long + )[None, :] + batches.append( + {"input_ids": tensor, "attention_mask": torch.ones_like(tensor)} + ) + records.append( + { + "stream_row": row_index, + "document_sha256": digest, + "document_tokens": len(ids), + "window_start": start, + } + ) + if len(batches) == samples: + break + finally: + close = getattr(iterator, "close", None) + if close is not None: + close() + if len(batches) != samples: + raise RuntimeError( + f"Only found {len(batches)}/{samples} distinct sufficiently long documents" + ) + checksum = hashlib.sha256() + for batch in batches: + checksum.update(batch["input_ids"].numpy().astype(" list[np.ndarray]: + """One backbone forward per batch; block hooks avoid hidden-state off-by-one. + + Collect outputs *before* the final backbone norm, including the final block. + Pool only valid tokens; activations are CPU float32 after pooling. + """ + if pooling not in {"mean", "last"} or not batches: + raise ValueError("valid pooling and nonempty calibration batches are required") + layers = model.model.layers + features: list[list[Tensor]] = [[] for _ in layers] + current_mask: Tensor | None = None + + def hook(index): + def capture(module, inputs, output): + hidden = output[0] if isinstance(output, (tuple, list)) else output + mask = current_mask.to(hidden.device, dtype=torch.bool) + if hidden.shape[:2] != mask.shape or (mask.sum(-1) == 0).any(): + raise ValueError("block output and valid-token mask do not match") + if pooling == "mean": + value = (hidden.float() * mask[:, :, None]).sum(1) / mask.sum(1)[ + :, None + ] + else: + positions = torch.arange(mask.shape[1], device=mask.device)[None, :] + last = positions.expand_as(mask).masked_fill(~mask, -1).max(1).values + value = hidden[ + torch.arange(hidden.shape[0], device=hidden.device), last + ].float() + if not torch.isfinite(value).all(): + raise FloatingPointError(f"nonfinite activation in block {index}") + features[index].append(value.cpu()) + + return capture + + handles = [layer.register_forward_hook(hook(i)) for i, layer in enumerate(layers)] + was_training = model.training + model.eval() + try: + device = model.get_input_embeddings().weight.device + for batch in batches: + prepared = {key: value.to(device) for key, value in batch.items()} + current_mask = prepared.get( + "attention_mask", torch.ones_like(prepared["input_ids"]) + ) + model.model(**prepared, use_cache=False, return_dict=True) + finally: + for handle in handles: + handle.remove() + model.train(was_training) + expected = sum(batch["input_ids"].shape[0] for batch in batches) + arrays = [torch.cat(parts, dim=0).numpy() for parts in features] + if any(array.shape[0] != expected for array in arrays): + raise RuntimeError("not all calibration examples reached each decoder block") + return arrays + + +def diffusion_embedding( + features: np.ndarray, config: GeometryConfig +) -> tuple[np.ndarray, dict]: + """Correctly shaped sample-by-sample diffusion kernel, following upstream SVD geometry.""" + config.validate() + x = np.asarray(features, dtype=np.float64) + if x.ndim != 2 or not np.isfinite(x).all() or len(x) <= config.dimensions + 1: + raise ValueError( + "features must be finite [samples, features], samples > dimensions + 1" + ) + distance = squareform(pdist(x, metric="euclidean")) + if distance.max() <= np.finfo(float).eps: + raise ValueError( + "constant calibration features: cannot estimate manifold geometry" + ) + kernel = np.exp(-np.sqrt(distance / config.sigma)) + p = kernel.sum(0) + normalized = kernel / np.outer(p, p) ** config.alpha + v = np.sqrt(normalized.sum(0)) + operator = normalized / np.outer(v, v) + condition = float(np.linalg.cond(operator)) + regularization = 1e-6 if not math.isfinite(condition) or condition > 1e12 else 0.0 + if regularization: + operator += regularization * np.eye(len(x)) + values, vectors = eigh( + operator, subset_by_index=(len(x) - config.dimensions - 1, len(x) - 1) + ) + values, vectors = values[::-1], vectors[:, ::-1] + # Fix arbitrary eigenvector signs; the leading vector of this positive kernel is positive. + for dim in range(vectors.shape[1]): + if vectors[np.argmax(np.abs(vectors[:, dim])), dim] < 0: + vectors[:, dim] *= -1 + if np.any(np.abs(vectors[:, 0]) < 1e-12): + raise FloatingPointError( + "diffusion normalization has a near-zero leading eigenvector" + ) + embedding = vectors[:, 1:] / vectors[:, :1] + if not np.isfinite(embedding).all(): + raise FloatingPointError("nonfinite diffusion embedding") + # Upstream uses per-axis rank normalization before its KNN estimators. + embedding = np.argsort( + np.argsort(embedding, axis=0, kind="stable"), axis=0, kind="stable" + ) / len(x) + return embedding, { + "samples": len(x), + "condition_number": condition if math.isfinite(condition) else None, + "regularization": regularization, + "eigenvalues": values.tolist(), + } + + +def entropy_knn(x: np.ndarray, neighbors: int) -> float: + """Upstream differential-entropy estimator, evaluated in log space.""" + n, dimensions = x.shape + k = min(neighbors, n - 1) + distances = NearestNeighbors(n_neighbors=k + 1).fit(x).kneighbors(x)[0][:, -1] + if np.any(distances <= 0) or not np.isfinite(distances).all(): + raise FloatingPointError( + "duplicate/degenerate manifold points in entropy estimator" + ) + return float(math.log(n / k) + dimensions * np.log(distances).mean()) + + +def npib_matrix( + embeddings: Sequence[np.ndarray], config: GeometryConfig +) -> tuple[np.ndarray, list[float]]: + """Match upstream axis-wise MI average and symmetric sqrt(H_i*H_j) normalization. + + Differential entropies can be negative. Preserve upstream's formula when + their product is positive; fail clearly for zero/negative products or NaNs. + This estimator is a heuristic, not a guaranteed [0, 1] similarity. + """ + config.validate() + if not embeddings or len({x.shape for x in embeddings}) != 1: + raise ValueError("embeddings must have identical sample/coordinate shapes") + n = len(embeddings[0]) + if n < 3 or any(not np.isfinite(x).all() for x in embeddings): + raise ValueError("need at least three finite manifold points") + entropies = [entropy_knn(x, config.entropy_neighbors) for x in embeddings] + scores = np.empty((len(embeddings), len(embeddings)), dtype=np.float64) + for i, left in enumerate(embeddings): + for j in range(i, len(embeddings)): + right = embeddings[j] + product = entropies[i] * entropies[j] + if not math.isfinite(product) or product <= 1e-12: + raise FloatingPointError( + f"invalid entropy product at ({i}, {j}): {entropies[i]}, {entropies[j]}" + ) + mi = np.mean( + [ + np.mean( + mutual_info_regression( + left, + right[:, dim], + n_neighbors=min(config.mi_neighbors, n - 1), + random_state=config.seed, + ) + ) + for dim in range(right.shape[1]) + ] + ) + scores[i, j] = scores[j, i] = mi / math.sqrt(product) + if not np.isfinite(scores).all(): + raise FloatingPointError("NPIB contains nonfinite scores") + return scores, entropies + + +def upstream_lambda( + scores: np.ndarray, left: int, right: int, beta: float = 1.0 +) -> float: + """Exactly upstream's sigmoid(beta * row_mean_i / (row_mean_i + row_mean_j)).""" + means = np.mean(scores[[left, right]], axis=1) + total = float(means.sum()) + if not np.isfinite(means).all() or (means < 0).any() or total <= 1e-12: + raise FloatingPointError( + "cannot compute upstream lambda from nonpositive/nonfinite row means" + ) + if not math.isfinite(beta) or beta < 0: + raise ValueError("beta must be non-negative and finite") + value = beta * float(means[0]) / total + return 1.0 / (1.0 + math.exp(-value)) + + +def select_pair( + scores: np.ndarray, + *, + selection: str = "npib", + protected_first: int = 0, + protected_last: int = 0, +) -> int: + """Adjacent pairs only; NPIB descending, and deeper pair wins exact ties.""" + n = len(scores) + if scores.shape != (n, n) or not np.isfinite(scores).all(): + raise ValueError("scores must be a finite square matrix") + if min(protected_first, protected_last) < 0: + raise ValueError("protected layer counts must be non-negative") + candidates = range(protected_first, n - protected_last - 1) + if not candidates: + raise ValueError("no eligible adjacent pair remains") + if selection == "back-to-front": + return candidates[-1] + if selection != "npib": + raise ValueError("selection must be 'npib' or 'back-to-front'") + return max(candidates, key=lambda i: (float(scores[i, i + 1]), i)) + + +@torch.inference_mode() +def merge_pair(model: nn.Module, left: int, ratio: float) -> int: + """FP32 weighted sum copied into real parameters, then delete the right block.""" + layers = model.model.layers + if ( + not 0 <= left < len(layers) - 1 + or not math.isfinite(ratio) + or not 0 <= ratio <= 1 + ): + raise ValueError("invalid adjacent pair or merge ratio") + destination, source = layers[left], layers[left + 1] + pairs = [] + for name in PROJECTION_WEIGHTS: + pairs.append((destination.get_parameter(name), source.get_parameter(name))) + # Qwen2.5 has Q/K/V biases. Fuse them with the same coefficient; + # Llama and Qwen3 (bias-free projections) retain their existing behavior. + module_name = name.rsplit('.', 1)[0] + a_bias = getattr(destination.get_submodule(module_name), 'bias', None) + b_bias = getattr(source.get_submodule(module_name), 'bias', None) + if (a_bias is None) != (b_bias is None): + raise ValueError('projection bias presence differs between merge layers') + if a_bias is not None: + pairs.append((a_bias, b_bias)) + # Validate all shapes/values/config before any model mutation. + if any(a.shape != b.shape for a, b in pairs): + raise ValueError("projection shapes differ between merge layers") + if any(not torch.isfinite(p).all() for pair in pairs for p in pair): + raise FloatingPointError("nonfinite source weight") + configs = [model.config, model.model.config] + for config in configs: + types = getattr(config, "layer_types", None) + if types is not None and len(types) != len(layers): + raise ValueError("config.layer_types length does not match decoder depth") + changed = 0 + for target, other in pairs: + merged = torch.lerp( + other.detach().to(target.device, dtype=torch.float32), target.float(), ratio + ) + merged = merged.to(target.dtype) + if not torch.isfinite(merged).all(): + raise FloatingPointError("merge overflow after conversion to model dtype") + changed += int(not torch.equal(target, merged)) + target.copy_(merged) + del layers[left + 1] + handled = set() + for config in configs: + if id(config) in handled: + continue + handled.add(id(config)) + config.num_hidden_layers = len(layers) + if getattr(config, "layer_types", None) is not None: + config.layer_types = list(config.layer_types[: left + 1]) + list( + config.layer_types[left + 2 :] + ) + for index, layer in enumerate(layers): + if hasattr(layer.self_attn, "layer_idx"): + layer.self_attn.layer_idx = index + return changed + + +def progressive_prune( + model: nn.Module, + batches: Sequence[dict[str, Tensor]], + *, + target_layers: int, + geometry: GeometryConfig | None = None, + selection: str = "npib", + protected_first: int = 0, + protected_last: int = 0, + on_stage: Callable[[nn.Module, dict], None] | None = None, +) -> list[dict]: + """Recompute activations/manifolds/NPIB on fixed data after every accepted merge. + + No threshold or forced fallbacks; stop at the requested exact depth. Repeated + merging of a previously merged block is allowed and recorded in its lineage. + """ + geometry = geometry or GeometryConfig() + geometry.validate() + depth = len(model.model.layers) + if min(protected_first, protected_last) < 0 or not 1 <= target_layers <= depth: + raise ValueError("invalid target depth or protected counts") + if target_layers < protected_first + protected_last + 1: + raise ValueError("target depth would remove protected layers") + if selection not in {"npib", "back-to-front"}: + raise ValueError("invalid selection mode") + lineage = [[i] for i in range(depth)] + records = [] + model.eval() + while len(model.model.layers) > target_layers: + step = len(records) + 1 + print( + f"MKA stage {step}: collecting features for {len(lineage)} layers", + flush=True, + ) + features = collect_features(model, batches, pooling=geometry.pooling) + results = [diffusion_embedding(x, geometry) for x in features] + del features + scores, entropies = npib_matrix([x[0] for x in results], geometry) + left = select_pair( + scores, + selection=selection, + protected_first=protected_first, + protected_last=protected_last, + ) + ratio = upstream_lambda(scores, left, left + 1, geometry.beta) + record = { + "step": step, + "selection": selection, + "left_index": left, + "source_layers": [lineage[left][:], lineage[left + 1][:]], + "pair_npib": float(scores[left, left + 1]), + "lambda_left": ratio, + "lambda_right": 1 - ratio, + "row_means": scores.mean(1).tolist(), + "npib_matrix": scores.tolist(), + "entropies": entropies, + "geometry": asdict(geometry), + "manifolds": [x[1] for x in results], + } + record["changed_parameter_tensors"] = merge_pair(model, left, ratio) + lineage[left] += lineage.pop(left + 1) + record["lineage_after"] = [x[:] for x in lineage] + record["remaining_layers"] = len(lineage) + records.append(record) + print( + f"MKA stage {step}: merge {left}/{left + 1}, NPIB={record['pair_npib']:.6g}, " + f"lambda={ratio:.6g}, remaining={len(lineage)}", + flush=True, + ) + if on_stage is not None: + on_stage(model, record) + return records diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/fuse_layers.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/fuse_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..5cca981f0f2f951ce21d88119fd12d26c6d8a089 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/fuse_layers.py @@ -0,0 +1,3600 @@ +#!/usr/bin/env python3 +"""Fuse adjacent layers via attention head alignment + Fisher-barycentric merge.""" + +import argparse +import copy +import gc +import json +import os +import random +import time +from dataclasses import dataclass +from typing import Dict, List, Optional, Set, Tuple + +import torch + +try: + import numpy as np +except Exception: # pragma: no cover - optional dependency + np = None + +try: + from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig +except Exception as exc: # pragma: no cover - fail early with clear error + raise SystemExit("transformers is required: pip install transformers") from exc + +try: + import ppl_eval +except Exception as exc: # pragma: no cover - optional dependency + raise SystemExit("ppl_eval.py is required (missing or invalid)") from exc + +try: + import eval_ppl as legacy_eval_ppl +except Exception: # pragma: no cover - optional dependency + legacy_eval_ppl = None + +from fuse_layers_data import ( + FixedSeqDataset, + build_token_chunks, + expand_dataset_configs, + load_instruction_records, + load_texts, + load_texts_from_datasets, +) +from common_lm_data import SharedLMDataSpec, build_chunks, build_dataloader +from fuse_layers_distill import ( + commutator_precondition, + compute_fisher_gate_priors, + distill_reparam_merge, + lora_ce_finetune, + summarize_fisher_gate_prior_inputs, +) +from fuse_layers_model import ( + apply_norm_policy, + build_head_permutation, + clone_state_dict, + compute_fisher, + compute_head_means, + decrement_config, + drop_layer, + find_attention_module, + find_colon_modules, + find_layer_container, + get_dtype, + get_norm_pair, + merge_layers, + permute_attention_heads, +) +from fuse_layers_select import select_best_region_by_cosine, select_layer_auto +from progressive_loader import ( + load_causal_lm, + load_progressive_model, + model_is_sharded, + model_parameter_devices, + model_primary_device, + resolve_model_device_map_spec, +) +from source_feature_transport import ( + compute_same_anchor_contextual_fisher, + fit_and_apply_source_feature_transport, +) +try: + from post_merge_nll_scale import ( + build_scale_chunks, + fit_and_fold_post_merge_scales, + ) +except ImportError: + # The zero-safe / sequential-rho experiments do not enable the optional + # post-merge NLL-scaling ablation. Keep the core ABPrune runner usable + # when that standalone ablation module is not present, but fail clearly if + # a caller explicitly requests it. + def _missing_post_merge_nll_scale(*_args, **_kwargs): + raise RuntimeError( + "post_merge_nll_scale.py is required when " + "--post_merge_nll_scale is enabled" + ) + + build_scale_chunks = _missing_post_merge_nll_scale + fit_and_fold_post_merge_scales = _missing_post_merge_nll_scale + + +def _sync_for_timing() -> None: + if torch.cuda.is_available(): + torch.cuda.synchronize() + + +def _timing_start() -> float: + _sync_for_timing() + return time.perf_counter() + + +def _timing_elapsed(start: float) -> float: + _sync_for_timing() + return time.perf_counter() - start + + +def _timing_summary(seconds: Dict[str, float]) -> Dict[str, object]: + cycle_total = float(seconds.get("cycle_total", 0.0)) + component_seconds = { + key: float(value) + for key, value in seconds.items() + if key != "cycle_total" and isinstance(value, (int, float)) + } + tracked_total = float(sum(component_seconds.values())) + if cycle_total <= 0.0: + cycle_total = tracked_total + return { + "seconds": {key: float(value) for key, value in seconds.items()}, + "tracked_component_total_seconds": tracked_total, + "cycle_total_seconds": cycle_total, + "ratios_of_tracked_components": { + key: (value / tracked_total if tracked_total > 0.0 else None) + for key, value in component_seconds.items() + }, + "ratios_of_cycle_total": { + key: (value / cycle_total if cycle_total > 0.0 else None) + for key, value in component_seconds.items() + }, + } + + +def _print_cycle_timing(cycle_idx: int, timing: Dict[str, object]) -> None: + seconds = timing.get("seconds", {}) + ratios = timing.get("ratios_of_cycle_total", {}) + if not isinstance(seconds, dict) or not isinstance(ratios, dict): + return + print(f"[timing] Cycle {cycle_idx} component wall-clock:") + preferred = [ + "selection", + "rebase", + "head_permutation", + "fisher", + "fit", + "materialize_save_layer", + "metadata_write", + "teacher_snapshot", + "cycle_cleanup", + ] + for name in preferred: + if name not in seconds: + continue + ratio = ratios.get(name) + ratio_text = "n/a" if ratio is None else f"{100.0 * float(ratio):.2f}%" + print(f"[timing] {name}: {float(seconds[name]):.3f}s ({ratio_text} of cycle)") + cycle_total = timing.get("cycle_total_seconds") + tracked_total = timing.get("tracked_component_total_seconds") + if isinstance(cycle_total, (int, float)): + print(f"[timing] cycle_total: {float(cycle_total):.3f}s") + if isinstance(tracked_total, (int, float)): + print(f"[timing] tracked_components_total: {float(tracked_total):.3f}s") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Fuse layer i and i+1 using head alignment + Fisher barycenter." + ) + parser.add_argument("--model", required=True, help="HF model id or local path") + parser.add_argument( + "--model_cache_dir", + default=None, + help="Optional cache dir for model/tokenizer downloads", + ) + parser.add_argument( + "--layer", + type=str, + default="auto", + help="Layer index i (int) or 'auto' to select via auto metric", + ) + parser.add_argument( + "--selection_method", + choices=["dwce", "sequential"], + default="dwce", + help=( + "Pair selection policy for progressive pruning. " + "'dwce' uses downstream-weighted composition error; " + "'sequential' always takes the next available pair." + ), + ) + parser.add_argument( + "--exclude_pairs", + "--exclude_layers", + nargs="*", + default=None, + dest="exclude_pairs", + help=( + "Exclude pair indices from consideration for any fusion. Indices refer to " + "pair start positions in [0..N-2]. Negative indices count from the end " + "(-1 = last pair, -2 = second last). Accepts space- or comma-separated ints. " + "Alias: --exclude_layers (deprecated)." + ), + ) + parser.add_argument( + "--output_dir", required=True, help="Directory to write fused model" + ) + parser.add_argument( + "--dataset", + action="append", + default=[], + help=( + "HF dataset name (repeatable). Optional if using --text or --text_file." + ), + ) + parser.add_argument( + "--dataset_config", + action="append", + default=[], + help="Optional dataset config (repeatable or single shared config).", + ) + parser.add_argument( + "--dataset_split", + default="train", + help="Dataset split to use (default: train)", + ) + parser.add_argument( + "--dataset_text_field", + default=None, + help="Text field in dataset (default: auto-detect, applies to all datasets)", + ) + parser.add_argument( + "--text", + action="append", + default=[], + help="Inline text samples (can pass multiple)", + ) + parser.add_argument( + "--text_file", + default=None, + help="Path to a text file for calibration data", + ) + parser.add_argument( + "--num_samples", + type=int, + default=128, + help="Number of token sequences to use", + ) + parser.add_argument( + "--target_tokens", + type=int, + default=0, + help="Target token budget for common_lm_data-backed calibration/distillation (0 = disabled)", + ) + parser.add_argument("--seq_len", type=int, default=256, help="Sequence length") + parser.add_argument("--batch_size", type=int, default=2, help="Batch size") + parser.add_argument( + "--device", + default="cuda" if torch.cuda.is_available() else "cpu", + help="Device for model + compute", + ) + parser.add_argument( + "--dtype", + default="auto", + choices=["auto", "float32", "float16", "bfloat16"], + help="Model dtype", + ) + parser.add_argument( + "--model_device_map", + default=None, + help=( + "Optional transformers device_map for the student model. " + "Use auto/balanced/balanced_low_0/sequential, split_half, " + "split_half:cuda:0,cuda:1, or split_layers:cuda:0,cuda:1,..." + ), + ) + parser.add_argument( + "--layer_path", + default=None, + help="Override layer attribute path (e.g., model.layers)", + ) + parser.add_argument( + "--fisher_mode", + default="tensor", + choices=["tensor", "param"], + help="Fisher approximation granularity", + ) + parser.add_argument( + "--no_head_permute", + action="store_true", + help=( + "Deprecated alias for --no_head_permute_merge. " + "Disables merge-stage head permutation only." + ), + ) + parser.add_argument( + "--no_head_permute_merge", + action="store_true", + help="Disable attention head permutation alignment before merge", + ) + parser.add_argument( + "--no_head_permute_select", + action="store_true", + help="Disable attention head permutation alignment during auto selection", + ) + parser.add_argument("--eps", type=float, default=1e-8, help="Stability epsilon") + parser.add_argument("--seed", type=int, default=0, help="Random seed") + parser.add_argument( + "--trust_remote_code", + action="store_true", + help="Allow custom model code from hub", + ) + parser.add_argument( + "--save_metadata", + action="store_true", + help="Backward-compatible no-op; metadata is always written.", + ) + parser.add_argument( + "--skip_eval", + action="store_true", + help="Skip pre/post perplexity evaluation", + ) + parser.add_argument( + "--eval_dataset", + action="append", + default=[], + help="Evaluation dataset name (repeatable). Defaults to wikitext.", + ) + parser.add_argument( + "--eval_dataset_config", + action="append", + default=[], + help="Evaluation dataset config (repeatable or single shared config).", + ) + parser.add_argument( + "--eval_split", + default="test", + help="Evaluation dataset split (default: test)", + ) + parser.add_argument( + "--eval_text_field", + default=None, + help="Evaluation text field override (default: auto-detect)", + ) + parser.add_argument( + "--eval_model_family", + type=str, + choices=["auto", "llama", "qwen"], + default="auto", + help="Model family for BOS handling during eval", + ) + parser.add_argument( + "--eval_add_bos", + type=str, + choices=["single", "auto", "always", "never"], + default="single", + help="Whether to prepend BOS to each eval sample", + ) + parser.add_argument( + "--eval_num_samples", + type=int, + default=0, + help="Number of token sequences per eval dataset (0 = all)", + ) + parser.add_argument( + "--eval_seq_len", + type=int, + default=1024, + help="Sequence length for eval", + ) + parser.add_argument( + "--eval_batch_size", + type=int, + default=4, + help="Batch size for eval (default: 4 to match run_eval_ppl.sh)", + ) + parser.add_argument( + "--eval_dtype", + default="float16", + choices=["auto", "float32", "float16", "bfloat16"], + help="Model dtype for eval (default: float16 to match run_eval_ppl.sh)", + ) + parser.add_argument( + "--eval_max_batches", + type=int, + default=None, + help="Optional max number of eval batches per dataset", + ) + parser.add_argument( + "--eval_cache_dir", + default=None, + help="Optional datasets cache dir for eval", + ) + parser.add_argument( + "--eval_num_workers", + type=int, + default=0, + help="Eval DataLoader workers", + ) + parser.add_argument( + "--eval_device", + default=None, + help="Device for eval (defaults to --device)", + ) + parser.add_argument( + "--eval_merge_only_ppl", + action="store_true", + help=( + "Evaluate PPL after a temporary Fisher merge and before reparam/distill." + ), + ) + parser.add_argument( + "--skip_distill", + action="store_true", + help="Skip reparameterized distillation after head alignment/Fisher setup", + ) + parser.add_argument( + "--distill_calib_samples", + type=int, + default=256, + help="Number of distillation sequences from calibration datasets", + ) + parser.add_argument( + "--distill_inst_samples", + type=int, + default=0, + help="Number of distillation sequences from instruction dataset (0 = all)", + ) + parser.add_argument( + "--distill_seq_len", + type=int, + default=512, + help="Sequence length for distillation", + ) + parser.add_argument( + "--distill_batch_size", + type=int, + default=2, + help="Batch size for distillation", + ) + parser.add_argument( + "--distill_epochs", + type=float, + default=1.0, + help="Number of distillation epochs (float allowed, e.g. 0.5)", + ) + parser.add_argument( + "--distill_lr", + type=float, + default=1e-4, + help="Learning rate for distillation", + ) + parser.add_argument( + "--distill_method", + choices=["reparam"], + default="reparam", + help="Distillation strategy (reparam only).", + ) + parser.add_argument( + "--distill_kl_weight", + type=float, + default=1e-2, + help="Weight for KL loss on logits", + ) + parser.add_argument( + "--distill_kl_temp", + type=float, + default=4.0, + help="Temperature for KL distillation on logits", + ) + parser.add_argument( + "--kl_chunk_size", + type=int, + default=16384, + help=( + "Vocabulary chunk size for streaming KL calculations. The default " + "preserves the previous implementation; lower values reduce peak memory." + ), + ) + parser.add_argument( + "--distill_hidden_mse_weight", + type=float, + default=1.0, + help="Weight for hidden-state MSE in reparam distillation (0 disables it)", + ) + parser.add_argument( + "--distill_attn_mse_weight", + type=float, + default=0.0, + help="Weight for auxiliary attention-output MSE in reparam distillation", + ) + parser.add_argument( + "--distill_mlp_mse_weight", + type=float, + default=0.0, + help="Weight for auxiliary MLP-output MSE in reparam distillation", + ) + parser.add_argument( + "--reparam_eta", + type=float, + default=1e-2, + help="Eta: ||lambda - lambda_gate||^2 regularizer weight for --distill_method reparam", + ) + parser.add_argument( + "--reparam_gamma", + type=float, + default=1e-4, + help="Gamma: ||U - U0||^2 regularizer weight for --distill_method reparam", + ) + parser.add_argument( + "--reparam_attn_reg_scale", + type=float, + default=1.0, + help="Relative scale applied to attention-parameter reparam regularizers", + ) + parser.add_argument( + "--reparam_mlp_reg_scale", + type=float, + default=1.0, + help="Relative scale applied to MLP-parameter reparam regularizers", + ) + parser.add_argument( + "--reparam_param_subset", + type=str, + choices=["all", "mlp", "attn", "down_proj"], + default="all", + help=( + "Restrict reparam merge/recovery capacity to only this parameter family " + "or module subset" + ), + ) + parser.add_argument( + "--reparam_fisher_init_subset", + type=str, + choices=["same", "all", "mlp", "attn", "down_proj", "mlp_o", "mlp_v", "mlp_vo"], + default="same", + help=( + "Restrict Fisher initialization to this subset while still materializing " + "and fitting --reparam_param_subset. Parameters outside this subset " + "start exactly at the anchor value." + ), + ) + parser.add_argument( + "--reparam_train_subset", + type=str, + choices=["same", "all", "mlp", "attn", "down_proj"], + default="same", + help=( + "Restrict which materialized reparam parameters are optimized. " + "Default 'same' preserves --reparam_param_subset behavior." + ), + ) + parser.add_argument( + "--reparam_skip_train", + action="store_true", + help=( + "Materialize the Fisher-prior reparam merge without optimizing U/gates. " + "Useful for separating Fisher initialization from reparam training." + ), + ) + parser.add_argument( + "--reparam_rho_objective", + choices=["none", "full", "hidden_kl", "kl_only"], + default="none", + help=( + "Replace trainable element-wise Fisher gates with gate/up/down rho " + "coefficients. U still uses the full FiT loss; rho receives only the " + "selected objective." + ), + ) + parser.add_argument( + "--reparam_rho_lr", + type=float, + default=2e-3, + help="Learning rate for projection-level Fisher-undo rho coefficients", + ) + parser.add_argument( + "--reparam_rho_schedule", + choices=["joint", "sequential"], + default="joint", + help=( + "joint optimizes rho and U together; sequential first optimizes rho " + "on the fixed Fisher-to-anchor axis, then freezes rho and trains an " + "additive U correction with the full FiT objective." + ), + ) + parser.add_argument( + "--reparam_additive_u", + action="store_true", + help=( + "Freeze the Fisher interpolation point and train a zero-initialized " + "additive U correction: W = W_F + U_add. This removes the " + "coordinatewise (2*lambda_F-1) gradient mask used by the standard " + "W0/U parameterization." + ), + ) + parser.add_argument( + "--reparam_rho_epochs", + type=float, + default=1.0, + help="Rho-only epochs before U training in sequential mode", + ) + parser.add_argument("--reparam_rho_min", type=float, default=-1.0) + parser.add_argument("--reparam_rho_max", type=float, default=2.0) + parser.add_argument( + "--source_feature_transport", + action="store_true", + help=( + "Before each progressive merge, fit X_anchor @ T ~= X_source and " + "rewrite the source MLP gate/up input projections as W_source @ T.T. " + "Then measure anchor and transported-source Fisher in the same " + "post-pruning anchor slot before merging." + ), + ) + parser.add_argument( + "--source_feature_transport_ridge_relative", + type=float, + default=1e-3, + help="Relative ridge used by the stage-local feature transport OLS solve", + ) + parser.add_argument( + "--source_feature_transport_max_batches", + type=int, + default=0, + help="Maximum calibration batches per transport solve (0 uses all)", + ) + parser.add_argument( + "--post_merge_nll_scale", + choices=["none", "mlp", "joint"], + default="none", + help="After every progressive merge, fit MLP-only or joint attention/MLP output scales with next-token NLL and fold them into output projections.", + ) + parser.add_argument("--post_merge_nll_scale_dataset", default="DKYoon/SlimPajama-6B") + parser.add_argument("--post_merge_nll_scale_config", default="none") + parser.add_argument("--post_merge_nll_scale_split", default="train") + parser.add_argument("--post_merge_nll_scale_text_field", default="text") + parser.add_argument("--post_merge_nll_scale_sequences", type=int, default=16) + parser.add_argument("--post_merge_nll_scale_seq_len", type=int, default=512) + parser.add_argument("--post_merge_nll_scale_seed", type=int, default=42) + parser.add_argument("--post_merge_nll_scale_steps", type=int, default=128) + parser.add_argument("--post_merge_nll_scale_lr", type=float, default=0.02) + parser.add_argument("--post_merge_nll_scale_regularization", type=float, default=1e-4) + parser.add_argument("--post_merge_nll_scale_min", type=float, default=0.25) + parser.add_argument("--post_merge_nll_scale_max", type=float, default=4.0) + parser.add_argument( + "--norm_policy", + type=str, + choices=["hybrid", "merge_all", "copy_n1", "copy_n1_n2"], + default="hybrid", + help="Norm merge policy (default: hybrid)", + ) + parser.add_argument( + "--distill_weight_decay", + type=float, + default=0.0, + help="Weight decay for distillation", + ) + parser.add_argument( + "--distill_max_grad_norm", + type=float, + default=1.0, + help="Max grad norm for distillation", + ) + parser.add_argument( + "--distill_grad_accum_steps", + type=int, + default=1, + help="Gradient accumulation steps for distillation", + ) + parser.add_argument( + "--distill_log_steps", + type=int, + default=100, + help="Log distillation loss every N steps", + ) + parser.add_argument( + "--distill_eval_every", + type=int, + default=0, + help="Evaluate PPL every N distill steps (0 = disable)", + ) + parser.add_argument( + "--distill_eval_max_batches", + type=int, + default=None, + help="Max eval batches per dataset during distill (default: all)", + ) + parser.add_argument( + "--distill_teacher_device", + default=None, + help="Device for teacher model during distillation (defaults to --device)", + ) + parser.add_argument( + "--distill_teacher_device_map", + default=None, + help=( + "Optional transformers device_map for the teacher model. " + "Use auto/balanced/balanced_low_0/sequential, split_half, " + "split_half:cuda:2,cuda:3, or split_layers:cuda:0,cuda:1,..." + ), + ) + parser.add_argument( + "--disable_previous_cycle_teacher_cache", + action="store_true", + help=( + "Disable the in-memory previous-cycle teacher snapshot and always reload " + "teachers from disk/base checkpoints. Useful when the student model is sharded " + "or when the teacher runs on CPU." + ), + ) + parser.add_argument( + "--distill_teacher_load_in_4bit", + action="store_true", + help=( + "Prototype-only rescue path: load the distillation/previous-cycle teacher in " + "4-bit NF4 on a CUDA device to reduce memory pressure." + ), + ) + parser.add_argument( + "--comm_enabled", + action="store_true", + help=( + "Enable commutator-style preconditioning before each progressive " + "cycle's fusion." + ), + ) + parser.add_argument( + "--comm_include_cycle1", + action="store_true", + help="Run commutator preconditioning for cycle 1 as well (default: skip cycle 1).", + ) + parser.add_argument( + "--comm_data_source", + choices=["auto", "calib", "distill"], + default="auto", + help=( + "Data source for commutator preconditioning. 'auto' preserves the " + "existing behavior: use distillation data when available, otherwise " + "fall back to calibration data." + ), + ) + parser.add_argument( + "--comm_topk", + type=int, + default=1, + help="Top-K lowest-score pairs used as the commutator candidate set", + ) + parser.add_argument( + "--comm_sample_eta", + type=float, + default=0.5, + help="Mixture weight between uniform and score-biased candidate sampling", + ) + parser.add_argument( + "--comm_sample_dwce_scale", + type=float, + default=1.0, + help="Scale c in softmax(-c * score(i)) for commutator pair sampling", + ) + parser.add_argument( + "--comm_temp", + type=float, + default=2.0, + help="Temperature for teacher-anchor KL in commutator preconditioning", + ) + parser.add_argument( + "--comm_steps_ratio", + type=float, + default=0.1, + help="Run this fraction of distillation optimizer steps for commutator phase", + ) + parser.add_argument( + "--comm_lr_scale", + type=float, + default=0.1, + help="Commutator LR = --distill_lr * this scale", + ) + parser.add_argument( + "--comm_train_mode", + choices=["lora", "full"], + default="lora", + help=( + "Commutator trainable parameter mode: " + "'lora' updates LoRA adapters on sampled receiver layers; " + "'full' updates full receiver-layer weights." + ), + ) + parser.add_argument( + "--comm_interaction_mode", + choices=["mse", "relative"], + default="relative", + help="Interaction loss form: plain MSE or relative MSE", + ) + parser.add_argument( + "--comm_interaction_eps", + type=float, + default=1e-8, + help="Epsilon for relative commutator interaction normalization", + ) + parser.add_argument( + "--comm_mu", + type=float, + default=None, + help=( + "Weight for interaction loss. Defaults to 0.1 for --comm_interaction_mode=mse " + "and 0.5 for --comm_interaction_mode=relative." + ), + ) + parser.add_argument( + "--comm_mu_auto", + action="store_true", + help="Enable automatic mu scaling via gradient-norm balancing", + ) + parser.add_argument( + "--comm_mu_auto_rho", + type=float, + default=0.1, + help="Target anchor-to-interaction gradient ratio constant for auto-mu", + ) + parser.add_argument( + "--comm_mu_auto_eps", + type=float, + default=1e-8, + help="Numerical epsilon in auto-mu denominator", + ) + parser.add_argument( + "--comm_log_steps", + type=int, + default=50, + help="Log commutator preconditioning loss every N optimizer steps", + ) + parser.add_argument( + "--comm_skip_post_reselect", + action="store_true", + help=( + "Keep the pre-comm selected fusion pair and skip recomputing " + "selection after commutator preconditioning." + ), + ) + parser.add_argument( + "--comm_measure_gap", + action="store_true", + help=( + "Measure commutator residual gap before and after preconditioning. " + "Uses prepared eval data when available, otherwise the commutator dataloader." + ), + ) + parser.add_argument( + "--comm_gap_max_batches", + type=int, + default=8, + help="Max batches for --comm_measure_gap (0 = all available batches).", + ) + parser.add_argument( + "--redistrib_teacher_source", + type=str, + choices=["base_model", "previous_cycle"], + default="base_model", + help=( + "Teacher source for commutator preconditioning teacher loading. " + "'base_model' uses --model for all cycles; " + "'previous_cycle' uses cycle-1 checkpoint (cycle 1 falls back to base_model)." + ), + ) + parser.add_argument( + "--lora_epochs", + type=float, + default=1.0, + help="LoRA CE finetuning epochs after distill (0 = disable)", + ) + parser.add_argument( + "--lora_rank", + type=int, + default=8, + help="LoRA rank (r)", + ) + parser.add_argument( + "--lora_alpha", + type=float, + default=16.0, + help="LoRA alpha", + ) + parser.add_argument( + "--lora_dropout", + type=float, + default=0.0, + help="LoRA dropout", + ) + parser.add_argument( + "--lora_kl_enabled", + action="store_true", + help="Add KL regularization between pre/post LoRA logits", + ) + parser.add_argument( + "--lora_kl_weight", + type=float, + default=1e-1, + help="KL weight for LoRA regularization", + ) + parser.add_argument( + "--lora_kl_temp", + type=float, + default=4.0, + help="Temperature for LoRA KL regularization", + ) + parser.add_argument( + "--lora_target_modules", + nargs="*", + default=[ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "down_proj", + "up_proj", + ], + help="Module name suffixes to LoRA-wrap", + ) + parser.add_argument( + "--lora_respect_exclude_pairs", + action="store_true", + help=( + "When attaching LoRA adapters, skip linear modules under layers touched by " + "--exclude_pairs (i and i+1 for each excluded pair)." + ), + ) + parser.add_argument( + "--lora_lr", + type=float, + default=1e-4, + help="Learning rate for LoRA finetuning", + ) + parser.add_argument( + "--lora_weight_decay", + type=float, + default=0.0, + help="Weight decay for LoRA finetuning", + ) + parser.add_argument( + "--lora_max_grad_norm", + type=float, + default=1.0, + help="Max grad norm for LoRA finetuning", + ) + parser.add_argument( + "--lora_grad_accum_steps", + type=int, + default=1, + help="Gradient accumulation steps for LoRA finetuning", + ) + parser.add_argument( + "--lora_log_steps", + type=int, + default=100, + help="Log LoRA loss every N steps", + ) + parser.add_argument( + "--lora_eval_every", + type=int, + default=0, + help="Evaluate PPL every N LoRA steps (0 = disable)", + ) + parser.add_argument( + "--lora_eval_max_batches", + type=int, + default=None, + help="Max eval batches per dataset during LoRA (default: all)", + ) + parser.add_argument( + "--instruction_dataset", + default=None, + help="HF dataset name for alpaca-style instruction data", + ) + parser.add_argument( + "--instruction_config", + default=None, + help="Optional instruction dataset config", + ) + parser.add_argument( + "--instruction_split", + default="train", + help="Instruction dataset split", + ) + parser.add_argument( + "--instruction_field_instruction", + default="instruction", + help="Instruction field name", + ) + parser.add_argument( + "--instruction_field_input", + default="input", + help="Optional input field name", + ) + parser.add_argument( + "--instruction_field_output", + default="output", + help="Response/output field name", + ) + parser.add_argument( + "--auto_max_batches", + type=int, + default=0, + help="Max calibration batches for auto selection scoring (0 = all)", + ) + parser.add_argument( + "--auto_metric", + type=str, + choices=[ + "dwce", + "final_hidden_relative_error", + "cosine", + "region_cosine_dwce", + "hybrid", + "hybrid_cosine", + "hybrid_global_rel", + ], + default="dwce", + help=( + "Auto pair scoring metric. 'dwce' uses downstream-weighted composition error; " + "'final_hidden_relative_error' measures surrogate-fusion error at the final hidden state; " + "'cosine' uses average token-level cosine distance between adjacent layer outputs; " + "'region_cosine_dwce' first finds the most cosine-redundant contiguous region " + "and then applies DWCE only within that region; " + "'hybrid'/'hybrid_cosine' use DWCE to shortlist then adjacent cosine for final scoring; " + "'hybrid_global_rel' uses DWCE to shortlist then reranks by the change in " + "pair-to-final-layer cosine relation after surrogate fusion." + ), + ) + parser.add_argument( + "--auto_cosine_topk", + type=int, + default=3, + help="Top-K DWCE candidates to rescore with cosine in --auto_metric=hybrid", + ) + parser.add_argument( + "--auto_region_width", + type=int, + default=4, + help=( + "Contiguous region width in adjacent pairs for " + "--auto_metric=region_cosine_dwce" + ), + ) + parser.add_argument( + "--fixed_region_pairs", + type=str, + default=None, + help=( + "Optional fixed original pair-start indices to restrict auto selection to. " + "Accepts comma-separated integers or ranges like 22-27. When set, " + "cosine region search is skipped and only these original pair starts are " + "considered by DWCE." + ), + ) + parser.add_argument( + "--auto_norm", + type=str, + choices=["relative", "none"], + default="relative", + help="Normalization mode for DWCE scoring (ignored for cosine)", + ) + parser.add_argument( + "--auto_dwce_mode", + type=str, + choices=["separate", "shared"], + default="separate", + help=( + "DWCE implementation for auto scoring. " + "'separate' runs distinct Fisher and DWCE backward passes; " + "'shared' reuses one backward pass and replays DWCE with cached gradients." + ), + ) + parser.add_argument( + "--auto_dwce_grad_power", + type=int, + choices=[1, 2], + default=2, + help="Exponent for DWCE gradient weighting. 2 matches the original DWCE; 1 uses |grad|.", + ) + parser.add_argument( + "--num_progressive", + type=int, + default=0, + help="Number of progressive fusions (>0 required)", + ) + parser.add_argument( + "--resume_from_cycle", + type=int, + default=0, + help=( + "Resume from this completed cycle index. When > 0, --model should point " + "to the saved full model directory for that cycle." + ), + ) + parser.add_argument( + "--save_full_model_cycles", + nargs="*", + default=[], + help=( + "Cycle indices whose full models should be saved. Requesting cycle c " + "also saves cycle c-1 automatically (c=1 saves only cycle 1)." + ), + ) + parser.add_argument( + "--profile_no_save", + action="store_true", + help=( + "Profiling-only mode: write metadata/timing logs but skip all weight " + "artifacts, including per-cycle fused layers and final save_pretrained outputs." + ), + ) + parser.add_argument( + "--skip_final_model_save", + action="store_true", + help=( + "Compact-checkpoint mode: keep each cycle's fused_layer.pt and metadata " + "but skip the duplicate final pre-LoRA and final model save_pretrained outputs." + ), + ) + return parser.parse_args() + + +def parse_exclude_pairs(exclude_raw: Optional[List[str]], num_pairs: int) -> List[int]: + """Parse --exclude_pairs into normalized pair indices for the current model. + + Indices refer to the start of an adjacent pair (i, i+1) and must be in [0..N-2]. + Negative indices count from the end (-1 = last pair). + """ + if not exclude_raw: + return [] + exclude: List[int] = [] + for item in exclude_raw: + if item is None: + continue + for part in str(item).split(","): + part = part.strip() + if not part: + continue + try: + idx = int(part) + except ValueError as exc: + raise SystemExit("--exclude_pairs must contain integers.") from exc + if idx < 0: + idx = num_pairs + idx + if 0 <= idx < num_pairs: + exclude.append(idx) + return sorted(set(exclude)) + + +def parse_cycle_list(raw_values: Optional[List[str]]) -> List[int]: + if not raw_values: + return [] + cycles: List[int] = [] + for item in raw_values: + if item is None: + continue + for part in str(item).split(","): + part = part.strip() + if not part: + continue + try: + cycles.append(int(part)) + except ValueError as exc: + raise SystemExit( + "--save_full_model_cycles must contain integers." + ) from exc + return cycles + + +def resolve_full_model_save_cycles( + requested_cycles: List[int], num_progressive: int +) -> Set[int]: + resolved: Set[int] = set() + for cycle in requested_cycles: + if cycle <= 0 or cycle > num_progressive: + raise SystemExit( + "--save_full_model_cycles entries must be within [1, --num_progressive]." + ) + resolved.add(cycle) + if cycle > 1: + resolved.add(cycle - 1) + return resolved + + +def load_resume_metadata(model_path: str) -> Optional[Dict[str, object]]: + resume_meta_path = os.path.join(model_path, "resume_info.json") + if not os.path.exists(resume_meta_path): + return None + with open(resume_meta_path, "r", encoding="utf-8") as handle: + loaded = json.load(handle) + return loaded if isinstance(loaded, dict) else None + + +def build_generator(seed: int) -> torch.Generator: + generator = torch.Generator(device="cpu") + generator.manual_seed(int(seed)) + return generator + + +def capture_rng_state() -> Dict[str, object]: + state: Dict[str, object] = { + "python_random_state": random.getstate(), + "torch_cpu_rng_state": torch.get_rng_state(), + } + if np is not None: + state["numpy_random_state"] = np.random.get_state() + if torch.cuda.is_available(): + state["torch_cuda_rng_state_all"] = torch.cuda.get_rng_state_all() + return state + + +def restore_rng_state(state: Dict[str, object]) -> None: + python_state = state.get("python_random_state") + if python_state is not None: + random.setstate(python_state) + + numpy_state = state.get("numpy_random_state") + if numpy_state is not None and np is not None: + np.random.set_state(numpy_state) + + torch_cpu_state = state.get("torch_cpu_rng_state") + if torch_cpu_state is not None: + torch.set_rng_state(torch_cpu_state) + + torch_cuda_state = state.get("torch_cuda_rng_state_all") + if torch_cuda_state is not None and torch.cuda.is_available(): + torch.cuda.set_rng_state_all(torch_cuda_state) + + +def save_rng_state(path: str) -> None: + torch.save(capture_rng_state(), path) + + +def load_rng_state(path: str) -> Optional[Dict[str, object]]: + if not os.path.exists(path): + return None + loaded = torch.load(path, map_location="cpu", weights_only=False) + return loaded if isinstance(loaded, dict) else None + + +def configure_reproducibility(seed: int) -> None: + random.seed(seed) + if np is not None: + np.random.seed(seed) + torch.manual_seed(seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed_all(seed) + if hasattr(torch.backends, "cudnn"): + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + if hasattr(torch, "use_deterministic_algorithms"): + torch.use_deterministic_algorithms(True, warn_only=True) + + +def save_loader_generator_state( + base_dir: str, + *, + distill_generator: Optional[torch.Generator] = None, + lora_generator: Optional[torch.Generator] = None, +) -> None: + state: Dict[str, object] = {} + if distill_generator is not None: + state["distill_generator_state"] = distill_generator.get_state() + if lora_generator is not None: + state["lora_generator_state"] = lora_generator.get_state() + if state: + torch.save(state, os.path.join(base_dir, "loader_generators.pt")) + + +def load_loader_generator_state(base_dir: str) -> Optional[Dict[str, object]]: + path = os.path.join(base_dir, "loader_generators.pt") + if not os.path.exists(path): + return None + loaded = torch.load(path, map_location="cpu") + return loaded if isinstance(loaded, dict) else None + + +def parse_fixed_region_pairs(spec: Optional[str]) -> Optional[List[int]]: + if spec is None: + return None + text = str(spec).strip() + if not text: + return None + values: List[int] = [] + for part in text.split(","): + token = part.strip() + if not token: + continue + if "-" in token: + pieces = token.split("-") + if len(pieces) != 2: + raise SystemExit( + "--fixed_region_pairs accepts comma-separated integers or simple ranges like 22-27" + ) + start = int(pieces[0].strip()) + end = int(pieces[1].strip()) + if end < start: + start, end = end, start + values.extend(range(start, end + 1)) + else: + values.append(int(token)) + if not values: + return None + return sorted(set(values)) + + +def resolve_layer_idx( + args: argparse.Namespace, + model, + layers: List[torch.nn.Module], + dataloader, + cosine_dataloader, + previous_scores, + start_index: int, + exclude_pairs: Set[int], +): + layer_arg = str(getattr(args, "layer", "auto")).strip().lower() + selection_method = str(getattr(args, "selection_method", "dwce")).strip().lower() + + if layer_arg != "auto": + try: + layer_idx = int(layer_arg) + except ValueError as exc: + raise SystemExit("--layer must be 'auto' or an integer index") from exc + num_pairs = max(len(layers) - 1, 0) + if layer_idx < 0: + layer_idx += num_pairs + if layer_idx in exclude_pairs: + raise SystemExit(f"--layer resolved to excluded pair index {layer_idx}") + return layer_idx, previous_scores, {"method": "manual", "exclude_pairs": sorted(exclude_pairs)} + + if selection_method == "sequential": + num_pairs = len(layers) - 1 + for layer_idx in range(max(start_index, 0), num_pairs): + if layer_idx not in exclude_pairs: + return layer_idx, previous_scores, { + "method": "sequential", + "start_index": max(start_index, 0), + "exclude_pairs": sorted(exclude_pairs), + } + raise SystemExit("No eligible layer pairs remain after exclusions") + + layer_idx, dwce_scores, dwce_meta = select_layer_auto( + model, + layers, + dataloader, + cosine_dataloader, + args, + previous_scores=previous_scores, + start_index=start_index, + exclude_pairs=exclude_pairs, + ) + return layer_idx, dwce_scores, dwce_meta + + +@dataclass +class PreparedData: + calib_loader: torch.utils.data.DataLoader + calib_num_sequences: int + distill_loader: Optional[torch.utils.data.DataLoader] + distill_generator: Optional[torch.Generator] + distill_meta: Dict[str, object] + lora_loader: Optional[torch.utils.data.DataLoader] + lora_generator: Optional[torch.Generator] + lora_meta: Dict[str, object] + eval_datasets: List[str] + eval_configs: List[Optional[str]] + eval_dataloaders: Optional[Dict[str, torch.utils.data.DataLoader]] + + +def resolve_eval_datasets(args: argparse.Namespace) -> Tuple[List[str], List[Optional[str]]]: + eval_datasets = args.eval_dataset or ["wikitext2"] + eval_configs = args.eval_dataset_config or [] + eval_configs = ppl_eval._expand_dataset_configs(eval_datasets, eval_configs) + return eval_datasets, eval_configs + + +def _legacy_eval_compatible( + args: argparse.Namespace, + eval_datasets: List[str], + eval_configs: List[Optional[str]], +) -> bool: + # The legacy eval_ppl parser hardcodes the benchmark text field and split, + # so only use it for the default fuse_layers evaluation settings. + if legacy_eval_ppl is None: + return False + if args.eval_text_field is not None: + return False + if str(args.eval_split).strip().lower() != "test": + return False + return all( + legacy_eval_ppl.is_supported_dataset(dataset_name, config) + for dataset_name, config in zip(eval_datasets, eval_configs) + ) + + +def _legacy_eval_bos_mode(args: argparse.Namespace) -> str: + if args.eval_add_bos == "single": + return "single" + if args.eval_add_bos == "always": + return "every" + if args.eval_add_bos == "never": + return "none" + # Match script/run_eval_ppl.sh default behavior: one BOS at corpus start. + return "single" + + +def _ppl_eval_add_bos_mode(args: argparse.Namespace) -> str: + if args.eval_add_bos == "single": + # ppl_eval has no exact "single BOS at corpus start" mode. + # Fall back to its closest default behavior when legacy eval is unavailable. + return "auto" + return args.eval_add_bos + + +def _legacy_eval_labels( + eval_datasets: List[str], + eval_configs: List[Optional[str]], +) -> List[str]: + return [ + dataset_name if config is None else f"{dataset_name}:{config}" + for dataset_name, config in zip(eval_datasets, eval_configs) + ] + + +def _build_legacy_eval_dataloaders( + tokenizer, + eval_datasets: List[str], + eval_configs: List[Optional[str]], + args: argparse.Namespace, +) -> Dict[str, torch.utils.data.DataLoader]: + return legacy_eval_ppl.build_ppl_dataloaders( + eval_datasets, + tokenizer, + seq_len=args.eval_seq_len, + batch_size=args.eval_batch_size or args.batch_size, + configs=eval_configs, + labels=_legacy_eval_labels(eval_datasets, eval_configs), + bos_mode=_legacy_eval_bos_mode(args), + num_samples=args.eval_num_samples, + ) + + +def _resolve_eval_runtime_device( + model: torch.nn.Module, + requested_device: str, + *, + context: str, +) -> str: + if not model_is_sharded(model): + return requested_device + + primary_device = str(model_primary_device(model)) + devices = ", ".join(model_parameter_devices(model)) + if primary_device != requested_device: + print( + f"[device] {context}: keeping sharded model on {devices}; " + f"using primary device {primary_device} instead of requested {requested_device}." + ) + else: + print(f"[device] {context}: using existing sharded model placement {devices}.") + return primary_device + + +def _teacher_compute_dtype(args: argparse.Namespace) -> torch.dtype: + dtype = get_dtype(args.dtype) + if dtype is not None: + return dtype + return torch.bfloat16 + + +def _resolve_teacher_device_map( + args: argparse.Namespace, + model_id_or_path: str, +): + spec_raw = getattr(args, "distill_teacher_device_map", None) + if spec_raw is None: + return None + spec = str(spec_raw).strip() + if not spec or spec.lower() in {"none", "null"}: + return None + if bool(getattr(args, "distill_teacher_load_in_4bit", False)): + raise SystemExit( + "--distill_teacher_device_map cannot be combined with " + "--distill_teacher_load_in_4bit; use bf16 sharding or 4-bit single-device " + "teacher loading, not both." + ) + return resolve_model_device_map_spec( + spec, + model_path_or_id=model_id_or_path, + trust_remote_code=args.trust_remote_code, + cache_dir=args.model_cache_dir, + ) + + +def _teacher_load_kwargs( + args: argparse.Namespace, + teacher_device: str, + model_id_or_path: str, +) -> Tuple[Dict[str, object], bool]: + kwargs: Dict[str, object] = { + "cache_dir": args.model_cache_dir, + } + needs_manual_to = True + teacher_device_map = _resolve_teacher_device_map(args, model_id_or_path) + if teacher_device_map is not None: + kwargs["device_map"] = teacher_device_map + needs_manual_to = False + return kwargs, needs_manual_to + if bool(getattr(args, "distill_teacher_load_in_4bit", False)): + normalized = str(teacher_device).strip().lower() + if not normalized.startswith("cuda"): + raise SystemExit( + "--distill_teacher_load_in_4bit requires --distill_teacher_device to be a CUDA device." + ) + kwargs["quantization_config"] = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_compute_dtype=_teacher_compute_dtype(args), + bnb_4bit_quant_type="nf4", + bnb_4bit_use_double_quant=True, + ) + target_device = teacher_device if normalized != "cuda" else "cuda:0" + kwargs["device_map"] = {"": target_device} + needs_manual_to = False + return kwargs, needs_manual_to + + +def _load_teacher_causal_lm( + model_id_or_path: str, + args: argparse.Namespace, + teacher_device: str, +) -> torch.nn.Module: + teacher_kwargs, needs_manual_to = _teacher_load_kwargs( + args, + teacher_device, + model_id_or_path, + ) + model = load_causal_lm( + model_id_or_path, + torch_dtype=get_dtype(args.dtype), + trust_remote_code=args.trust_remote_code, + **teacher_kwargs, + ) + if needs_manual_to: + model.to(teacher_device) + model.eval() + return model + + +def run_ppl_eval( + model_id_or_path: str, + eval_datasets: List[str], + eval_configs: List[Optional[str]], + args: argparse.Namespace, + prepared_eval_dataloaders: Optional[Dict[str, torch.utils.data.DataLoader]] = None, +) -> Dict[str, float]: + eval_device = args.eval_device or args.device + dtype = get_dtype(args.eval_dtype) + resolved_device_map = resolve_model_device_map_spec( + getattr(args, "model_device_map", None), + model_path_or_id=model_id_or_path, + trust_remote_code=args.trust_remote_code, + ) + + eval_model = load_causal_lm( + model_id_or_path, + torch_dtype=dtype, + trust_remote_code=args.trust_remote_code, + device_map=resolved_device_map, + ) + + if model_is_sharded(eval_model): + eval_device = _resolve_eval_runtime_device( + eval_model, + eval_device, + context="run_ppl_eval", + ) + else: + eval_model.to(eval_device) + if prepared_eval_dataloaders is not None: + results = ppl_eval.evaluate_ppl_dataloaders( + eval_model, + prepared_eval_dataloaders, + eval_device, + max_batches=args.eval_max_batches, + ) + elif _legacy_eval_compatible(args, eval_datasets, eval_configs): + eval_tokenizer = AutoTokenizer.from_pretrained( + model_id_or_path, trust_remote_code=args.trust_remote_code + ) + if eval_tokenizer.pad_token is None and eval_tokenizer.eos_token is not None: + eval_tokenizer.pad_token = eval_tokenizer.eos_token + results = ppl_eval.evaluate_ppl_dataloaders( + eval_model, + _build_legacy_eval_dataloaders( + eval_tokenizer, + eval_datasets, + eval_configs, + args, + ), + eval_device, + max_batches=args.eval_max_batches, + ) + else: + eval_batch_size = args.eval_batch_size or args.batch_size + eval_tokenizer = AutoTokenizer.from_pretrained( + model_id_or_path, trust_remote_code=args.trust_remote_code + ) + if eval_tokenizer.pad_token is None and eval_tokenizer.eos_token is not None: + eval_tokenizer.pad_token = eval_tokenizer.eos_token + + results = ppl_eval.evaluate_ppl_datasets( + eval_model, + eval_tokenizer, + datasets=eval_datasets, + configs=eval_configs, + split=args.eval_split, + text_field=args.eval_text_field, + num_samples=args.eval_num_samples, + seq_len=args.eval_seq_len, + batch_size=eval_batch_size, + device=eval_device, + seed=args.seed, + shuffle=False, + model_family=args.eval_model_family, + add_bos=_ppl_eval_add_bos_mode(args), + max_batches=args.eval_max_batches, + cache_dir=args.eval_cache_dir, + num_workers=args.eval_num_workers, + ) + + del eval_model + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + return results + + +def build_calibration_dataloader( + args: argparse.Namespace, tokenizer +) -> Tuple[List[str], List[torch.Tensor], torch.utils.data.DataLoader]: + if args.dataset: + datasets = list(args.dataset) + configs = expand_dataset_configs(datasets, list(args.dataset_config)) + chunks: List[torch.Tensor] = [] + for idx, (dataset_name, config) in enumerate(zip(datasets, configs)): + spec = SharedLMDataSpec( + dataset=dataset_name, + config=config, + split=args.dataset_split, + text_field=args.dataset_text_field, + seq_len=args.seq_len, + num_sequences=args.num_samples, + seed=args.seed + idx, + ) + chunks.extend(build_chunks(spec, tokenizer)) + if not chunks: + raise SystemExit("Not enough text to build token sequences.") + input_ids = torch.stack(chunks) + attention_mask = torch.ones_like(input_ids) + dataset = torch.utils.data.TensorDataset(input_ids, attention_mask) + dataloader = torch.utils.data.DataLoader( + dataset, batch_size=args.batch_size, shuffle=False + ) + return [], chunks, dataloader + + texts = load_texts(args) + if not texts: + raise SystemExit( + "No calibration text found. Provide --dataset, --text, or --text_file." + ) + + chunks = build_token_chunks(texts, tokenizer, args.seq_len, args.num_samples) + if not chunks: + raise SystemExit("Not enough text to build token sequences.") + + input_ids = torch.stack(chunks) + attention_mask = torch.ones_like(input_ids) + dataset = torch.utils.data.TensorDataset(input_ids, attention_mask) + dataloader = torch.utils.data.DataLoader( + dataset, batch_size=args.batch_size, shuffle=False + ) + return texts, chunks, dataloader + + +def prepare_distillation_data( + args: argparse.Namespace, tokenizer, include_instruction: bool = True +) -> Tuple[Optional[torch.utils.data.DataLoader], Optional[torch.Generator], Dict[str, object]]: + if ( + include_instruction + and args.distill_inst_samples != 0 + and not args.instruction_dataset + ): + print( + "Warning: --distill_inst_samples > 0 but no --instruction_dataset " + "provided; instruction distillation will be skipped." + ) + + calib_texts: List[str] = [] + calib_dataset = None + if args.target_tokens > 0 and args.dataset: + datasets = list(args.dataset) + configs = expand_dataset_configs(datasets, list(args.dataset_config)) + per_dataset = args.target_tokens // len(datasets) + remainder = args.target_tokens % len(datasets) + calib_chunks: List[torch.Tensor] = [] + for idx, (dataset_name, config) in enumerate(zip(datasets, configs)): + dataset_tokens = per_dataset + (remainder if idx == 0 else 0) + spec = SharedLMDataSpec( + dataset=dataset_name, + config=config, + split=args.dataset_split, + text_field=args.dataset_text_field, + seq_len=args.distill_seq_len, + target_tokens=dataset_tokens, + seed=args.seed + 17 + idx, + ) + calib_chunks.extend(build_chunks(spec, tokenizer)) + if calib_chunks: + input_ids = torch.stack(calib_chunks) + attention_mask = torch.ones_like(input_ids) + calib_dataset = torch.utils.data.TensorDataset(input_ids, attention_mask) + else: + calib_texts = load_texts_from_datasets( + datasets=list(args.dataset), + configs=expand_dataset_configs(list(args.dataset), list(args.dataset_config)), + split=args.dataset_split, + text_field=args.dataset_text_field, + num_samples=args.distill_calib_samples, + seed=args.seed + 17, + manifest_env_var="ABPRUNE_DISTILL_DATA_INDICES_FILE", + ) + inst_records = [] + if include_instruction: + inst_records = load_instruction_records( + args, + args.distill_inst_samples, + "ABPRUNE_DISTILL_DATA_INDICES_FILE", + ) + + distill_datasets = [] + if calib_dataset is not None: + distill_datasets.append(calib_dataset) + elif calib_texts: + calib_records = [{"text": text} for text in calib_texts] + distill_datasets.append( + FixedSeqDataset(calib_records, tokenizer, args.distill_seq_len) + ) + if inst_records: + distill_datasets.append( + FixedSeqDataset(inst_records, tokenizer, args.distill_seq_len) + ) + + distill_meta: Dict[str, object] = { + "calib_texts": len(calib_texts), + "calib_sequences": len(calib_dataset) if calib_dataset is not None else len(calib_texts), + "inst_sequences": len(inst_records), + "total_sequences": 0, + } + + if not distill_datasets: + return None, None, distill_meta + if len(distill_datasets) == 1: + distill_dataset = distill_datasets[0] + else: + distill_dataset = torch.utils.data.ConcatDataset(distill_datasets) + + distill_meta["total_sequences"] = len(distill_dataset) + distill_generator = build_generator( + args.seed + 1000 + (1000000 if include_instruction else 0) + ) + distill_loader = torch.utils.data.DataLoader( + distill_dataset, + batch_size=args.distill_batch_size, + shuffle=True, + generator=distill_generator, + ) + return distill_loader, distill_generator, distill_meta + + +def prepare_eval_dataloaders( + args: argparse.Namespace, + tokenizer, + model: torch.nn.Module, + eval_datasets: List[str], + eval_configs: List[Optional[str]], +) -> Optional[Dict[str, torch.utils.data.DataLoader]]: + if args.skip_eval: + return None + + if _legacy_eval_compatible(args, eval_datasets, eval_configs): + return _build_legacy_eval_dataloaders( + tokenizer, + eval_datasets, + eval_configs, + args, + ) + + eval_batch_size = args.eval_batch_size or args.batch_size + resolved_family = args.eval_model_family + if resolved_family == "auto": + resolved_family = ppl_eval._infer_model_family(model) + + return ppl_eval.prepare_ppl_dataloaders( + tokenizer=tokenizer, + datasets=eval_datasets, + configs=eval_configs, + split=args.eval_split, + text_field=args.eval_text_field, + num_samples=args.eval_num_samples, + seq_len=args.eval_seq_len, + batch_size=eval_batch_size, + seed=args.seed, + shuffle=False, + model_family=resolved_family, + add_bos=_ppl_eval_add_bos_mode(args), + cache_dir=args.eval_cache_dir, + num_workers=args.eval_num_workers, + model=model, + ) + + +def prepare_all_data( + args: argparse.Namespace, + tokenizer, + model: torch.nn.Module, + eval_datasets: List[str], + eval_configs: List[Optional[str]], + loader_generator_state: Optional[Dict[str, object]] = None, +) -> PreparedData: + texts, chunks, calib_loader = build_calibration_dataloader(args, tokenizer) + calib_num_sequences = len(chunks) + del texts + del chunks + + distill_loader = None + distill_generator = None + distill_meta: Dict[str, object] = { + "calib_texts": 0, + "calib_sequences": 0, + "inst_sequences": 0, + "total_sequences": 0, + } + lora_loader = None + lora_generator = None + lora_meta: Dict[str, object] = { + "calib_texts": 0, + "calib_sequences": 0, + "inst_sequences": 0, + "total_sequences": 0, + } + if (not args.skip_distill) or bool(getattr(args, "comm_enabled", False)): + distill_loader, distill_generator, distill_meta = prepare_distillation_data( + args, tokenizer, include_instruction=False + ) + if ( + distill_generator is not None + and loader_generator_state is not None + and loader_generator_state.get("distill_generator_state") is not None + ): + distill_generator.set_state(loader_generator_state["distill_generator_state"]) + if args.lora_epochs > 0: + lora_loader, lora_generator, lora_meta = prepare_distillation_data( + args, tokenizer, include_instruction=True + ) + if ( + lora_generator is not None + and loader_generator_state is not None + and loader_generator_state.get("lora_generator_state") is not None + ): + lora_generator.set_state(loader_generator_state["lora_generator_state"]) + + eval_dataloaders = prepare_eval_dataloaders( + args, tokenizer, model, eval_datasets, eval_configs + ) + + return PreparedData( + calib_loader=calib_loader, + calib_num_sequences=calib_num_sequences, + distill_loader=distill_loader, + distill_generator=distill_generator, + distill_meta=distill_meta, + lora_loader=lora_loader, + lora_generator=lora_generator, + lora_meta=lora_meta, + eval_datasets=eval_datasets, + eval_configs=eval_configs, + eval_dataloaders=eval_dataloaders, + ) + + +def evaluate_ppl_model( + model: torch.nn.Module, + tokenizer, + eval_datasets: List[str], + eval_configs: List[Optional[str]], + args: argparse.Namespace, + max_batches: Optional[int] = None, + prepared_eval_dataloaders: Optional[Dict[str, torch.utils.data.DataLoader]] = None, +) -> Dict[str, float]: + eval_device = args.eval_device or args.device + prev_mode = model.training + eval_dtype = get_dtype(args.eval_dtype) + sharded = model_is_sharded(model) + try: + first_param = next(model.parameters()) + prev_device = first_param.device + prev_dtype = first_param.dtype + except StopIteration: + prev_device = torch.device(eval_device) + prev_dtype = None + + model.eval() + if sharded: + eval_device = _resolve_eval_runtime_device( + model, + eval_device, + context="evaluate_ppl_model", + ) + if eval_dtype is not None and prev_dtype is not None and prev_dtype != eval_dtype: + print( + f"[eval] Sharded model kept at dtype={prev_dtype}; " + f"ignoring requested eval dtype {eval_dtype}." + ) + elif str(prev_device) != eval_device or ( + eval_dtype is not None and prev_dtype is not None and prev_dtype != eval_dtype + ): + move_kwargs = {"device": eval_device} + if eval_dtype is not None: + move_kwargs["dtype"] = eval_dtype + model.to(**move_kwargs) + + if prepared_eval_dataloaders is not None: + results = ppl_eval.evaluate_ppl_dataloaders( + model, + prepared_eval_dataloaders, + eval_device, + max_batches=max_batches if max_batches is not None else args.eval_max_batches, + ) + elif _legacy_eval_compatible(args, eval_datasets, eval_configs): + results = ppl_eval.evaluate_ppl_dataloaders( + model, + _build_legacy_eval_dataloaders( + tokenizer, + eval_datasets, + eval_configs, + args, + ), + eval_device, + max_batches=max_batches if max_batches is not None else args.eval_max_batches, + ) + else: + eval_batch_size = args.eval_batch_size or args.batch_size + results = ppl_eval.evaluate_ppl_datasets( + model, + tokenizer, + datasets=eval_datasets, + configs=eval_configs, + split=args.eval_split, + text_field=args.eval_text_field, + num_samples=args.eval_num_samples, + seq_len=args.eval_seq_len, + batch_size=eval_batch_size, + device=eval_device, + seed=args.seed, + shuffle=False, + model_family=args.eval_model_family, + add_bos=_ppl_eval_add_bos_mode(args), + max_batches=max_batches if max_batches is not None else args.eval_max_batches, + cache_dir=args.eval_cache_dir, + num_workers=args.eval_num_workers, + ) + + if prev_mode: + model.train() + if (not sharded) and ( + str(prev_device) != eval_device or ( + eval_dtype is not None and prev_dtype is not None and prev_dtype != eval_dtype + ) + ): + restore_kwargs = {"device": prev_device} + if prev_dtype is not None: + restore_kwargs["dtype"] = prev_dtype + model.to(**restore_kwargs) + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + return results + + +def evaluate_temporary_fisher_merge_ppl( + model: torch.nn.Module, + tokenizer, + parent: object, + layer_attr: str, + container: object, + layer_idx: int, + layer_a: torch.nn.Module, + layer_b: torch.nn.Module, + fisher_sums, + num_batches: int, + param_numels, + norm_policy: str, + norm1_state: Optional[Dict[str, torch.Tensor]], + norm2_state: Optional[Dict[str, torch.Tensor]], + norm_names: Tuple[Optional[str], Optional[str]], + eval_datasets: List[str], + eval_configs: List[Optional[str]], + args: argparse.Namespace, + prepared_eval_dataloaders: Optional[Dict[str, torch.utils.data.DataLoader]] = None, +) -> Dict[str, float]: + layer_a_state = clone_state_dict(layer_a) + original_container = container + original_training = model.training + try: + with torch.no_grad(): + merge_layers( + layer_a, + layer_b, + fisher_sums[0], + fisher_sums[1], + num_batches, + param_numels[0], + param_numels[1], + fisher_mode=args.fisher_mode, + eps=args.eps, + ) + apply_norm_policy( + layer_a, + norm_policy, + norm1_state, + norm2_state, + norm_names, + ) + merged_container = drop_layer(original_container, layer_idx + 1) + setattr(parent, layer_attr, merged_container) + + return evaluate_ppl_model( + model, + tokenizer, + eval_datasets, + eval_configs, + args, + prepared_eval_dataloaders=prepared_eval_dataloaders, + ) + finally: + setattr(parent, layer_attr, original_container) + layer_a.load_state_dict(layer_a_state) + if original_training: + model.train() + else: + model.eval() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + +def has_post_fusion_data( + distill_loader: Optional[torch.utils.data.DataLoader], + distill_meta: Optional[Dict[str, object]], +) -> bool: + if distill_loader is None or distill_meta is None: + return False + return distill_meta.get("total_sequences", 0) > 0 + + +def summarize_gate_lambdas(gates: Dict[str, torch.Tensor]) -> Dict[str, object]: + if not gates: + return {"num_tensors": 0, "num_elements": 0} + + total_sum = 0.0 + total_elems = 0 + per_tensor_mean: Dict[str, Optional[float]] = {} + for name, gate in gates.items(): + g = gate.detach().float() + if g.numel() == 0: + per_tensor_mean[name] = None + continue + per_tensor_mean[name] = float(g.mean().item()) + total_sum += float(g.sum().item()) + total_elems += int(g.numel()) + + global_mean = None if total_elems == 0 else total_sum / float(total_elems) + return { + "num_tensors": len(gates), + "num_elements": total_elems, + "global_mean": global_mean, + "per_tensor_mean": per_tensor_mean, + } + + +def compute_path_bytes(path: str) -> int: + if os.path.isfile(path): + return os.path.getsize(path) + + total = 0 + for root, _, files in os.walk(path): + for name in files: + file_path = os.path.join(root, name) + if os.path.islink(file_path): + continue + try: + total += os.path.getsize(file_path) + except OSError: + continue + return total + + +def save_stage_checkpoint( + model: torch.nn.Module, + tokenizer, + stage_dir: str, + stage_name: str, + ppl_results: Optional[Dict[str, float]], +) -> Dict[str, object]: + os.makedirs(stage_dir, exist_ok=True) + colon_modules = find_colon_modules(model) + if colon_modules: + raise RuntimeError( + "Unexpected module names with ':' detected before save: " + f"{', '.join(colon_modules)}." + ) + + model.save_pretrained(stage_dir) + tokenizer.save_pretrained(stage_dir) + + stage_meta = { + "stage": stage_name, + "path": stage_dir, + "weight_bytes": compute_path_bytes(stage_dir), + "post_ppl": ppl_results, + } + with open( + os.path.join(stage_dir, "stage_metrics.json"), + "w", + encoding="utf-8", + ) as handle: + json.dump(stage_meta, handle, indent=2) + return stage_meta + + +def save_cycle_full_model( + model: torch.nn.Module, + tokenizer, + cycle_dir: str, + cycle_idx: int, + args: argparse.Namespace, + ppl_results: Optional[Dict[str, float]], +) -> Dict[str, object]: + full_model_dir = os.path.join(cycle_dir, "full_model") + stage_meta = save_stage_checkpoint( + model=model, + tokenizer=tokenizer, + stage_dir=full_model_dir, + stage_name=f"cycle_{cycle_idx}_full_model", + ppl_results=ppl_results, + ) + resume_meta = { + "base_model": getattr(args, "base_model_id", args.model), + "cycle": cycle_idx, + "output_dir": args.output_dir, + "layer_path": args.layer_path, + "rng_state": "rng_state.pt", + "loader_generators": "loader_generators.pt", + } + with open( + os.path.join(full_model_dir, "resume_info.json"), + "w", + encoding="utf-8", + ) as handle: + json.dump(resume_meta, handle, indent=2) + stage_meta["resume_info"] = "resume_info.json" + return stage_meta + + +def run_lora_phase( + model: torch.nn.Module, + tokenizer, + eval_datasets: List[str], + eval_configs: List[Optional[str]], + args: argparse.Namespace, + lora_loader: Optional[torch.utils.data.DataLoader] = None, + lora_meta: Optional[Dict[str, object]] = None, + eval_dataloaders: Optional[Dict[str, torch.utils.data.DataLoader]] = None, + cycle_idx: Optional[int] = None, + num_cycles: Optional[int] = None, +) -> List[Dict[str, object]]: + lora_eval_history: List[Dict[str, object]] = [] + if args.lora_epochs <= 0: + return lora_eval_history + if not has_post_fusion_data(lora_loader, lora_meta): + print("No post-fusion sequences built; skipping LoRA finetuning.") + return lora_eval_history + + lora_ce_finetune( + model=model, + dataloader=lora_loader, + eval_tokenizer=tokenizer, + eval_datasets=eval_datasets, + eval_configs=eval_configs, + eval_history=lora_eval_history, + args=args, + eval_dataloaders=eval_dataloaders, + progressive_cycle=cycle_idx, + progressive_total=num_cycles, + ) + return lora_eval_history + + +def run_progressive( + args: argparse.Namespace, + model: torch.nn.Module, + tokenizer, + prepared: PreparedData, +) -> None: + eval_datasets = prepared.eval_datasets + eval_configs = prepared.eval_configs + student_sharded = model_is_sharded(model) + if student_sharded: + print( + "[device] student model loaded across " + f"{', '.join(model_parameter_devices(model))}." + ) + + dataloader = prepared.calib_loader + num_sequences = prepared.calib_num_sequences + selection_args = args + fixed_region_start: Optional[int] = None + fixed_region_pairs: Optional[List[int]] = None + fixed_region_nodes: Optional[Set[int]] = None + fixed_region_score: Optional[float] = None + fixed_region_meta: Optional[Dict[str, object]] = None + active_layer_orig_ids: List[int] = list(range(len(list(find_layer_container(model, args.layer_path)[2])))) + manual_fixed_region_pairs = parse_fixed_region_pairs(getattr(args, "fixed_region_pairs", None)) + + if manual_fixed_region_pairs is not None: + fixed_region_pairs = list(manual_fixed_region_pairs) + fixed_region_nodes = set(fixed_region_pairs) + if fixed_region_pairs: + fixed_region_nodes.add(fixed_region_pairs[-1] + 1) + fixed_region_start = fixed_region_pairs[0] + fixed_region_score = None + fixed_region_meta = { + "source": "manual", + "region_pairs": list(fixed_region_pairs), + } + print( + "[auto] using manual fixed region pairs: " + f"{','.join(str(x) for x in fixed_region_pairs)}" + ) + selection_args = copy.copy(args) + selection_args.auto_metric = "dwce" + elif str(getattr(args, "auto_metric", "dwce")).strip().lower() == "region_cosine_dwce": + cosine_loader = ( + prepared.distill_loader + if prepared.distill_loader is not None + else prepared.calib_loader + ) + if cosine_loader is None: + raise SystemExit( + "--auto_metric=region_cosine_dwce requires calibration or distillation data." + ) + if not student_sharded: + model.to(args.device) + initial_exclude_pairs = set( + parse_exclude_pairs(args.exclude_pairs, max(len(active_layer_orig_ids) - 1, 0)) + ) + ( + fixed_region_start, + fixed_region_pairs, + fixed_region_score, + fixed_region_meta, + ) = select_best_region_by_cosine( + model, + list(find_layer_container(model, args.layer_path)[2]), + cosine_loader, + args, + start_index=0, + exclude_pairs=initial_exclude_pairs, + ) + print( + "[auto] fixed cosine region " + f"{fixed_region_start}-{fixed_region_pairs[-1] + 1} " + f"(pair-width={len(fixed_region_pairs)}, mean_cosine_distance={fixed_region_score:.6e})" + ) + dwce_candidate_pairs = fixed_region_meta.get("dwce_candidate_pairs") + if isinstance(dwce_candidate_pairs, list) and dwce_candidate_pairs: + fixed_region_pairs = [int(x) for x in dwce_candidate_pairs] + fixed_region_nodes = set(fixed_region_pairs) + fixed_region_nodes.add(fixed_region_pairs[-1] + 1) + print( + "[auto] remapped DWCE candidate pairs " + f"{fixed_region_pairs[0]}-{fixed_region_pairs[-1]} " + "(left-anchor interpretation)" + ) + selection_args = copy.copy(args) + selection_args.auto_metric = "dwce" + if not student_sharded: + model.cpu() + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + if not student_sharded: + model.to(args.device) + + os.makedirs(args.output_dir, exist_ok=True) + progressive_meta_path = os.path.join(args.output_dir, "progressive_metadata.json") + existing_meta: Dict[str, object] = {} + if args.resume_from_cycle > 0 and os.path.exists(progressive_meta_path): + with open(progressive_meta_path, "r", encoding="utf-8") as handle: + loaded_meta = json.load(handle) + if isinstance(loaded_meta, dict): + existing_meta = loaded_meta + + bootstrap_meta = { + "base_model": getattr(args, "base_model_id", args.model), + "num_progressive": args.num_progressive, + "layer_path": args.layer_path, + "resume_from_cycle": args.resume_from_cycle, + "save_full_model_cycles": sorted(args.full_model_save_cycles), + "student_device": args.device, + "student_model_device_map": getattr(args, "model_device_map", None), + "distill_teacher_device": args.distill_teacher_device or args.device, + "distill_teacher_device_map": getattr(args, "distill_teacher_device_map", None), + "distill_teacher_load_in_4bit": bool( + getattr(args, "distill_teacher_load_in_4bit", False) + ), + "kl_chunk_size": args.kl_chunk_size, + "cycles": ( + existing_meta.get("cycles", []) + if isinstance(existing_meta.get("cycles"), list) + else [] + ), + } + with open( + progressive_meta_path, + "w", + encoding="utf-8", + ) as handle: + json.dump(bootstrap_meta, handle, indent=2) + + pre_eval = None + if not args.skip_eval: + pre_eval = evaluate_ppl_model( + model, + tokenizer, + eval_datasets, + eval_configs, + args, + prepared_eval_dataloaders=prepared.eval_dataloaders, + ) + print("Pre-pruning perplexity:") + for dataset_name, ppl in pre_eval.items(): + print(f"{dataset_name}: {ppl:.4f}") + + post_merge_scale_chunks = None + if str(getattr(args, "post_merge_nll_scale", "none")) != "none": + post_merge_scale_chunks = build_scale_chunks(args, tokenizer) + print( + "[post-merge-nll-scale] prepared " + f"{len(post_merge_scale_chunks)} deterministic calibration chunks", + flush=True, + ) + + parent, name, container = find_layer_container(model, args.layer_path) + layers = list(container) + if args.num_progressive > (len(layers) - 1 + args.resume_from_cycle): + raise SystemExit( + f"--num_progressive ({args.num_progressive}) exceeds available pairs " + f"after resume offset ({len(layers) - 1 + args.resume_from_cycle})" + ) + + dwce_scores = None + dwce_meta = None + last_fused_idx = 0 + cycle_summaries: List[Dict[str, object]] = [] + existing_cycles = existing_meta.get("cycles", []) + if isinstance(existing_cycles, list): + for entry in existing_cycles: + if not isinstance(entry, dict): + continue + cycle_value = entry.get("cycle") + if isinstance(cycle_value, int) and cycle_value <= args.resume_from_cycle: + cycle_summaries.append(entry) + + comm_enabled = bool(getattr(args, "comm_enabled", False)) + comm_teacher_model = None + comm_teacher_cycle: Optional[int] = None + teacher_device = args.distill_teacher_device or args.device + teacher_cache_disabled_reason = None + if bool(getattr(args, "disable_previous_cycle_teacher_cache", False)): + teacher_cache_disabled_reason = "explicit flag" + elif student_sharded: + teacher_cache_disabled_reason = "sharded student model" + elif getattr(args, "distill_teacher_device_map", None): + teacher_cache_disabled_reason = "teacher device_map" + elif str(teacher_device).strip().lower() == "cpu": + teacher_cache_disabled_reason = "teacher_device=cpu" + if teacher_cache_disabled_reason is not None: + print( + "[teacher] previous-cycle in-memory cache disabled " + f"({teacher_cache_disabled_reason}); reloading from disk/base as needed." + ) + previous_cycle_teacher_model = None + previous_cycle_teacher_cycle: Optional[int] = None + + def _release_comm_teacher() -> None: + nonlocal comm_teacher_model, comm_teacher_cycle + if comm_teacher_model is not None: + del comm_teacher_model + comm_teacher_model = None + comm_teacher_cycle = None + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + def _release_previous_cycle_teacher() -> None: + nonlocal previous_cycle_teacher_model, previous_cycle_teacher_cycle + if previous_cycle_teacher_model is not None: + del previous_cycle_teacher_model + previous_cycle_teacher_model = None + previous_cycle_teacher_cycle = None + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + def _snapshot_previous_cycle_teacher(cycle_idx: int) -> None: + nonlocal previous_cycle_teacher_model, previous_cycle_teacher_cycle + if teacher_cache_disabled_reason is not None: + return + _release_previous_cycle_teacher() + previous_cycle_teacher_model = copy.deepcopy(model) + previous_cycle_teacher_model.to(teacher_device) + previous_cycle_teacher_model.eval() + previous_cycle_teacher_cycle = cycle_idx + + def _get_previous_cycle_teacher( + cycle_idx: int, + ) -> Tuple[Optional[torch.nn.Module], str, Optional[int]]: + prev_cycle = cycle_idx - 1 + if prev_cycle <= 0: + return None, "base_model", 0 + if ( + previous_cycle_teacher_model is not None + and previous_cycle_teacher_cycle == prev_cycle + ): + return previous_cycle_teacher_model, "previous_cycle_memory", prev_cycle + teacher_model_path_for_map = os.path.join( + args.output_dir, + f"cycle_{prev_cycle}", + "full_model", + ) + if not os.path.isdir(teacher_model_path_for_map): + teacher_model_path_for_map = getattr(args, "base_model_id", args.model) + teacher_kwargs, teacher_needs_manual_to = _teacher_load_kwargs( + args, + teacher_device, + teacher_model_path_for_map, + ) + teacher_model = load_progressive_model( + getattr(args, "base_model_id", args.model), + args.output_dir, + cycle=prev_cycle, + device=teacher_device if teacher_needs_manual_to else None, + dtype=args.dtype, + trust_remote_code=args.trust_remote_code, + layer_path=args.layer_path, + **teacher_kwargs, + ) + teacher_model.eval() + return teacher_model, "previous_cycle_disk", prev_cycle + + def _get_comm_teacher(cycle_idx: int) -> Tuple[Optional[torch.nn.Module], str, Optional[int]]: + nonlocal comm_teacher_model, comm_teacher_cycle + if not comm_enabled: + return None, "disabled", None + + source = str(getattr(args, "redistrib_teacher_source", "base_model")) + if source == "base_model": + if comm_teacher_model is None: + print( + "[comm] Loading fixed base teacher for anchor loss " + f"(device={teacher_device})." + ) + comm_teacher_model = _load_teacher_causal_lm( + getattr(args, "base_model_id", args.model), + args, + teacher_device, + ) + comm_teacher_cycle = 0 + return comm_teacher_model, "base_model", 0 + + prev_cycle = cycle_idx - 1 + if prev_cycle <= 0: + if comm_teacher_model is None or comm_teacher_cycle != 0: + _release_comm_teacher() + print( + "[comm] --redistrib_teacher_source=previous_cycle but cycle 1 " + "has no prior checkpoint; using base teacher." + ) + comm_teacher_model = _load_teacher_causal_lm( + getattr(args, "base_model_id", args.model), + args, + teacher_device, + ) + comm_teacher_cycle = 0 + return comm_teacher_model, "base_model", 0 + + if ( + previous_cycle_teacher_model is not None + and previous_cycle_teacher_cycle == prev_cycle + ): + if comm_teacher_model is not previous_cycle_teacher_model: + _release_comm_teacher() + comm_teacher_model = previous_cycle_teacher_model + comm_teacher_cycle = prev_cycle + return comm_teacher_model, "previous_cycle_memory", prev_cycle + + if comm_teacher_model is None or comm_teacher_cycle != prev_cycle: + _release_comm_teacher() + print( + "[comm] Loading teacher from previous cycle " + f"{prev_cycle} (device={teacher_device})." + ) + teacher_model_path_for_map = os.path.join( + args.output_dir, + f"cycle_{prev_cycle}", + "full_model", + ) + if not os.path.isdir(teacher_model_path_for_map): + teacher_model_path_for_map = getattr(args, "base_model_id", args.model) + teacher_kwargs, teacher_needs_manual_to = _teacher_load_kwargs( + args, + teacher_device, + teacher_model_path_for_map, + ) + comm_teacher_model = load_progressive_model( + getattr(args, "base_model_id", args.model), + args.output_dir, + cycle=prev_cycle, + device=teacher_device if teacher_needs_manual_to else None, + dtype=args.dtype, + trust_remote_code=args.trust_remote_code, + layer_path=args.layer_path, + **teacher_kwargs, + ) + comm_teacher_model.eval() + comm_teacher_cycle = prev_cycle + return comm_teacher_model, "previous_cycle_disk", prev_cycle + + def _comm_gap_dataloader(): + if prepared.eval_dataloaders: + first_key = next(iter(prepared.eval_dataloaders)) + return prepared.eval_dataloaders[first_key] + return prepared.calib_loader + + def _comm_train_dataloader(): + source = str(getattr(args, "comm_data_source", "auto")).strip().lower() + if source == "calib": + return prepared.calib_loader, "calib" + if source == "distill": + return prepared.distill_loader, "distill" + if prepared.distill_loader is not None: + return prepared.distill_loader, "distill" + return prepared.calib_loader, "calib" + + if args.resume_from_cycle > 0: + _snapshot_previous_cycle_teacher(args.resume_from_cycle) + + start_cycle = args.resume_from_cycle + 1 + for cycle_idx in range(start_cycle, args.num_progressive + 1): + cycle_timing_start = _timing_start() + component_seconds: Dict[str, float] = {} + + def _record_component(name: str, start: float) -> float: + elapsed = _timing_elapsed(start) + component_seconds[name] = component_seconds.get(name, 0.0) + elapsed + return elapsed + + print(f"[progressive] Cycle {cycle_idx}/{args.num_progressive}") + run_comm = comm_enabled and ( + cycle_idx > 1 or bool(getattr(args, "comm_include_cycle1", False)) + ) + comm_stats: Dict[str, object] = {"enabled": False} + comm_post_eval = None + comm_teacher_model_loaded = None + if run_comm: + # Preconditioning updates model weights, so DWCE reuse is unreliable. + start_index = 0 + reuse_scores = None + else: + start_index = last_fused_idx if cycle_idx > 1 else 0 + reuse_scores = dwce_scores + exclude_pairs = set(parse_exclude_pairs(args.exclude_pairs, max(len(layers) - 1, 0))) + if fixed_region_nodes is not None: + for idx in range(max(len(layers) - 1, 0)): + left_orig = active_layer_orig_ids[idx] + right_orig = active_layer_orig_ids[idx + 1] + if left_orig not in fixed_region_nodes or right_orig not in fixed_region_nodes: + exclude_pairs.add(idx) + selection_timing_start = _timing_start() + layer_idx, dwce_scores, dwce_meta = resolve_layer_idx( + selection_args, + model, + layers, + dataloader, + prepared.distill_loader, + reuse_scores, + start_index, + exclude_pairs, + ) + _record_component("selection", selection_timing_start) + if fixed_region_meta is not None: + dwce_meta = dict(dwce_meta or {}) + dwce_meta["fixed_cosine_region"] = { + "region_start": fixed_region_start, + "region_pairs": list( + fixed_region_meta.get("cosine_region_pairs", fixed_region_pairs or []) + ), + "dwce_candidate_pairs": list(fixed_region_pairs or []), + "region_score": fixed_region_score, + "region_meta": fixed_region_meta, + } + + rebase_timing_start = _timing_start() if run_comm else None + component_seconds["rebase"] = 0.0 + if run_comm: + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + dwce_scores_pre_comm = dwce_scores + comm_dataloader, comm_data_source = _comm_train_dataloader() + if comm_dataloader is None: + requested_source = str( + getattr(args, "comm_data_source", "auto") + ).strip().lower() + if requested_source in {"calib", "distill"}: + raise RuntimeError( + "comm_enabled but the requested " + f"--comm_data_source={requested_source} loader was not built." + ) + print( + "[comm] Enabled but no distillation/calibration sequences were built; skipping." + ) + else: + ( + comm_teacher_model_loaded, + comm_teacher_source, + comm_teacher_cycle_idx, + ) = _get_comm_teacher(cycle_idx) + if comm_teacher_model_loaded is None: + raise RuntimeError("comm_enabled but teacher model was not loaded.") + comm_stats = commutator_precondition( + student_model=model, + student_layers=layers, + teacher_model=comm_teacher_model_loaded, + dataloader=comm_dataloader, + dwce_scores=dwce_scores_pre_comm, + exclude_pairs=exclude_pairs, + args=args, + progressive_cycle=cycle_idx, + progressive_total=args.num_progressive, + measure_dataloader=( + _comm_gap_dataloader() + if bool(getattr(args, "comm_measure_gap", False)) + else None + ), + ) + if comm_stats.get("enabled"): + comm_stats["teacher_source"] = comm_teacher_source + comm_stats["teacher_cycle"] = comm_teacher_cycle_idx + comm_stats["data_source"] = comm_data_source + comm_stats["dwce_scores_pre"] = dwce_scores_pre_comm + print( + "[comm] Done:" + f" opt_steps={comm_stats.get('opt_steps')}" + f" lr={comm_stats.get('lr')}" + ) + if not args.skip_eval: + comm_post_eval = evaluate_ppl_model( + model, + tokenizer, + eval_datasets, + eval_configs, + args, + prepared_eval_dataloaders=prepared.eval_dataloaders, + ) + comm_stats["post_ppl"] = comm_post_eval + print(f"[progressive] Cycle {cycle_idx} post-comm perplexity:") + for dataset_name, ppl in comm_post_eval.items(): + print(f"{dataset_name}: {ppl:.4f}") + + if bool(getattr(args, "comm_skip_post_reselect", False)): + comm_stats["post_selection_recomputed"] = False + comm_stats["selected_layer_post"] = int(layer_idx) + print( + "[comm] Keeping pre-comm DWCE pair selection for fusion." + ) + else: + print( + "[comm] Recomputing DWCE after preconditioning for fusion selection." + ) + layer_idx, dwce_scores, dwce_meta = resolve_layer_idx( + selection_args, + model, + layers, + dataloader, + prepared.distill_loader, + None, + 0, + exclude_pairs, + ) + comm_stats["post_selection_recomputed"] = True + comm_stats["selected_layer_post"] = int(layer_idx) + if ( + run_comm + and comm_teacher_model_loaded is not None + and teacher_cache_disabled_reason is not None + ): + reparam_teacher_cycle_for_release = cycle_idx - 1 + if reparam_teacher_cycle_for_release <= 0: + comm_teacher_matches_reparam = ( + comm_teacher_source == "base_model" + and comm_teacher_cycle_idx == 0 + ) + else: + comm_teacher_matches_reparam = ( + comm_teacher_source in {"previous_cycle_memory", "previous_cycle_disk"} + and comm_teacher_cycle_idx == reparam_teacher_cycle_for_release + ) + keep_comm_teacher_for_reparam = ( + (not args.skip_distill) + and has_post_fusion_data(prepared.distill_loader, prepared.distill_meta) + and (not bool(getattr(args, "reparam_skip_train", False))) + and float(args.distill_epochs) > 0.0 + and comm_teacher_matches_reparam + ) + if keep_comm_teacher_for_reparam: + print( + "[comm] Keeping comm teacher for FiT/reparam phase " + f"(source={comm_teacher_source}, cycle={comm_teacher_cycle_idx})." + ) + else: + print( + "[comm] Releasing comm teacher after comm phase " + f"({teacher_cache_disabled_reason})." + ) + comm_teacher_model_loaded = None + _release_comm_teacher() + if rebase_timing_start is not None: + _record_component("rebase", rebase_timing_start) + + if layer_idx < 0 or layer_idx >= len(layers) - 1: + raise SystemExit("--layer must be in [0, num_layers-2]") + + num_layers_before = len(layers) + layer_a = layers[layer_idx] + layer_b = layers[layer_idx + 1] + + norm1_state = None + norm2_state = None + norm1, norm2, norm_names = get_norm_pair(layer_a) + if norm1 is not None: + norm1_state = clone_state_dict(norm1) + if norm2 is not None: + norm2_state = clone_state_dict(norm2) + + attn_a = find_attention_module(layer_a) + attn_b = find_attention_module(layer_b) + hidden_size = getattr(model.config, "hidden_size", None) + if hidden_size is None: + hidden_size = getattr(model.config, "n_embd", None) + if hidden_size is None: + raise SystemExit("Model config missing hidden_size/n_embd") + + no_head_permute_merge = bool( + getattr(args, "no_head_permute_merge", False) + or getattr(args, "no_head_permute", False) + ) + if no_head_permute_merge: + print("[fuse] Head permutation disabled; merging with original head order.") + else: + head_timing_start = _timing_start() + mean_a, mean_b, num_heads, num_kv_heads, head_dim = compute_head_means( + model, + attn_a, + attn_b, + dataloader, + args.device, + hidden_size, + ) + + perm = build_head_permutation( + mean_a, + mean_b, + num_heads=num_heads, + num_kv_heads=num_kv_heads, + eps=args.eps, + ) + permute_attention_heads( + attn_b, perm, num_heads, num_kv_heads, head_dim=head_dim + ) + _record_component("head_permutation", head_timing_start) + + source_feature_transport_stats = None + contextual_fisher_stats = None + component_seconds["source_feature_transport"] = 0.0 + if bool(getattr(args, "source_feature_transport", False)): + transport_timing_start = _timing_start() + source_feature_transport_stats = fit_and_apply_source_feature_transport( + model=model, + layer_a=layer_a, + layer_b=layer_b, + dataloader=dataloader, + device=args.device, + ridge_relative=float(args.source_feature_transport_ridge_relative), + max_batches=int(args.source_feature_transport_max_batches), + ) + _record_component("source_feature_transport", transport_timing_start) + print( + "[source-feature-transport] " + f"cycle={cycle_idx} batches={source_feature_transport_stats['batches']} " + f"tokens={source_feature_transport_stats['tokens']} " + f"nmse={source_feature_transport_stats['calibration_nmse']:.6f} " + f"cosine={source_feature_transport_stats['calibration_cosine']:.6f} " + f"norm_ratio={source_feature_transport_stats['calibration_norm_ratio']:.6f}", + flush=True, + ) + + fisher_timing_start = _timing_start() + if bool(getattr(args, "source_feature_transport", False)): + ( + fisher_sums, + num_batches, + param_numels, + contextual_fisher_stats, + ) = compute_same_anchor_contextual_fisher( + model=model, + parent=parent, + layer_attr=name, + container=container, + layer_idx=layer_idx, + layer_a=layer_a, + layer_b=layer_b, + dataloader=dataloader, + device=args.device, + fisher_mode=args.fisher_mode, + ) + source_feature_transport_stats["fisher_order"] = ( + "source transport first; same-anchor post-pruning contextual Fisher second" + ) + print( + "[source-feature-transport] contextual-fisher " + f"cycle={cycle_idx} " + f"anchor_nll={contextual_fisher_stats['anchor_candidate_mean_nll']:.6f} " + f"source_nll={contextual_fisher_stats['transported_source_candidate_mean_nll']:.6f}", + flush=True, + ) + else: + fisher_sums, num_batches, param_numels = compute_fisher( + model, + layer_a, + layer_b, + dataloader, + fisher_mode=args.fisher_mode, + device=args.device, + ) + _record_component("fisher", fisher_timing_start) + + fit_timing_start = _timing_start() + distill_ready = has_post_fusion_data( + prepared.distill_loader, prepared.distill_meta + ) + teacher_cycle = cycle_idx - 1 + teacher_source = "previous_cycle" if teacher_cycle > 0 else "base_model" + + merge_method = "fisher" + distill_method = str(getattr(args, "distill_method", "reparam")) + reparam_stats: Optional[Dict[str, object]] = None + reparam_gate_summary: Optional[Dict[str, object]] = None + merge_only_eval = None + if bool(getattr(args, "eval_merge_only_ppl", False)) and not args.skip_eval: + print( + f"[progressive] Cycle {cycle_idx} temporary merge-only perplexity " + f"for pair {layer_idx}-{layer_idx + 1}:" + ) + merge_only_eval = evaluate_temporary_fisher_merge_ppl( + model=model, + tokenizer=tokenizer, + parent=parent, + layer_attr=name, + container=container, + layer_idx=layer_idx, + layer_a=layer_a, + layer_b=layer_b, + fisher_sums=fisher_sums, + num_batches=num_batches, + param_numels=param_numels, + norm_policy=args.norm_policy, + norm1_state=norm1_state, + norm2_state=norm2_state, + norm_names=norm_names, + eval_datasets=eval_datasets, + eval_configs=eval_configs, + args=args, + prepared_eval_dataloaders=prepared.eval_dataloaders, + ) + for dataset_name, ppl in merge_only_eval.items(): + print(f"{dataset_name}: {ppl:.4f}") + + reparam_teacher_cycle = cycle_idx - 1 + reparam_teacher_source = ( + "previous_cycle" if reparam_teacher_cycle > 0 else "base_model" + ) + needs_teacher_for_reparam = ( + (not args.skip_distill) + and distill_ready + and (not bool(getattr(args, "reparam_skip_train", False))) + and float(args.distill_epochs) > 0.0 + ) + def _comm_teacher_matches_reparam_teacher() -> bool: + if comm_teacher_model_loaded is None: + return False + if reparam_teacher_cycle <= 0: + return comm_teacher_source == "base_model" and comm_teacher_cycle_idx == 0 + return ( + comm_teacher_source in {"previous_cycle_memory", "previous_cycle_disk"} + and comm_teacher_cycle_idx == reparam_teacher_cycle + ) + + can_reuse_comm_teacher_for_reparam = ( + needs_teacher_for_reparam and _comm_teacher_matches_reparam_teacher() + ) + teacher_model = None + teacher_parent = None + teacher_layer_attr = None + teacher_layers: Optional[List[torch.nn.Module]] = None + teacher_from_cache = False + reused_comm_teacher_for_reparam = False + if needs_teacher_for_reparam: + if can_reuse_comm_teacher_for_reparam: + teacher_model = comm_teacher_model_loaded + teacher_source = comm_teacher_source + teacher_cycle = comm_teacher_cycle_idx + teacher_from_cache = True + reused_comm_teacher_for_reparam = True + print( + "[reparam] Reusing comm teacher for FiT/reparam phase " + f"(source={teacher_source}, cycle={teacher_cycle})." + ) + else: + teacher_model, teacher_source, teacher_cycle = _get_previous_cycle_teacher( + cycle_idx + ) + teacher_from_cache = ( + teacher_source == "previous_cycle_memory" + and teacher_model is previous_cycle_teacher_model + ) + if teacher_model is None: + teacher_model = _load_teacher_causal_lm( + getattr(args, "base_model_id", args.model), + args, + teacher_device, + ) + teacher_source = "base_model" + teacher_cycle = 0 + teacher_parent, teacher_layer_attr, teacher_container = find_layer_container( + teacher_model, args.layer_path + ) + teacher_layers = list(teacher_container) + + do_reparam = ( + (not args.skip_distill) + and distill_ready + and prepared.distill_loader is not None + ) + if (not args.skip_distill) and not do_reparam: + print("[reparam] No distillation sequences built; skipping reparam distill.") + distill_post_eval = None + if do_reparam: + lambda_source = "fisher_prior" + fisher_prior_input_summary = summarize_fisher_gate_prior_inputs( + layer_a=layer_a, + layer_b=layer_b, + fisher_a=fisher_sums[0], + fisher_b=fisher_sums[1], + num_batches=num_batches, + numels_a=param_numels[0], + numels_b=param_numels[1], + fisher_mode=args.fisher_mode, + eps=float(args.eps), + param_subset=args.reparam_param_subset, + ) + print( + "[reparam] fisher_prior_inputs " + f"fa_mean={fisher_prior_input_summary.get('fa_mean')} " + f"fb_mean={fisher_prior_input_summary.get('fb_mean')} " + f"active_ratio={fisher_prior_input_summary.get('active_ratio')} " + f"rel_contrast={fisher_prior_input_summary.get('mean_relative_contrast')} " + f"prior_mean={fisher_prior_input_summary.get('prior_mean')} " + f"prior_active_mean={fisher_prior_input_summary.get('prior_active_mean')}" + ) + reparam_gate_targets: Dict[str, object] = compute_fisher_gate_priors( + layer_a=layer_a, + layer_b=layer_b, + fisher_a=fisher_sums[0], + fisher_b=fisher_sums[1], + num_batches=num_batches, + numels_a=param_numels[0], + numels_b=param_numels[1], + fisher_mode=args.fisher_mode, + eps=float(args.eps), + ) + if not reparam_gate_targets: + raise SystemExit("[reparam] No mergeable parameters found; cannot continue.") + reparam_train_enabled = ( + (not bool(getattr(args, "reparam_skip_train", False))) + and float(args.distill_epochs) > 0.0 + ) + if reparam_train_enabled and (teacher_model is None or teacher_layers is None): + raise SystemExit("--distill_method reparam requires a teacher model.") + reparam_action = ( + "training U + gates" + if reparam_train_enabled + else "materializing Fisher-prior U + gates without training" + ) + print( + f"[reparam] Cycle {cycle_idx}: {reparam_action} for pair " + f"{layer_idx}-{layer_idx + 1} (epochs={args.distill_epochs}, " + f"skip_train={bool(getattr(args, 'reparam_skip_train', False))}, " + f"hidden_mse_w={args.distill_hidden_mse_weight}, " + f"attn_mse_w={args.distill_attn_mse_weight}, " + f"mlp_mse_w={args.distill_mlp_mse_weight}, " + f"eta={args.reparam_eta}, gamma={args.reparam_gamma}, " + f"attn_reg_scale={args.reparam_attn_reg_scale}, " + f"mlp_reg_scale={args.reparam_mlp_reg_scale}, " + f"param_subset={args.reparam_param_subset}, " + f"fisher_init_subset={args.reparam_fisher_init_subset}, " + f"train_subset={args.reparam_train_subset}, " + f"lambda_init={lambda_source})." + ) + merged, final_gates, reparam_stats = distill_reparam_merge( + student_model=model, + student_parent=parent, + student_layer_attr=name, + student_layers=layers, + teacher_model=teacher_model, + teacher_parent=teacher_parent, + teacher_layer_attr=teacher_layer_attr, + teacher_layers=teacher_layers, + layer_idx=layer_idx, + gate_lambdas=reparam_gate_targets, + dataloader=prepared.distill_loader, + args=args, + progressive_cycle=cycle_idx, + progressive_total=args.num_progressive, + ) + reparam_gate_summary = summarize_gate_lambdas(final_gates) + merge_method = "reparam" + if reparam_stats is not None: + reparam_stats["lambda_init"] = lambda_source + reparam_stats["fisher_prior_input_summary"] = fisher_prior_input_summary + else: + merged = merge_layers( + layer_a, + layer_b, + fisher_sums[0], + fisher_sums[1], + num_batches, + param_numels[0], + param_numels[1], + fisher_mode=args.fisher_mode, + eps=args.eps, + ) + + apply_norm_policy( + layer_a, + args.norm_policy, + norm1_state, + norm2_state, + norm_names, + ) + if teacher_model is not None and not teacher_from_cache: + del teacher_model + teacher_model = None + teacher_parent = None + teacher_layer_attr = None + teacher_layers = None + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + if reused_comm_teacher_for_reparam: + teacher_model = None + teacher_parent = None + teacher_layer_attr = None + teacher_layers = None + comm_teacher_model_loaded = None + _release_comm_teacher() + _record_component("fit", fit_timing_start) + + materialize_timing_start = _timing_start() + new_container = drop_layer(container, layer_idx + 1) + setattr(parent, name, new_container) + decrement_config(model.config) + layers = list(new_container) + del active_layer_orig_ids[layer_idx + 1] + + post_merge_nll_scale_stats = None + if post_merge_scale_chunks is not None: + post_merge_nll_scale_stats = fit_and_fold_post_merge_scales( + model, + layers[layer_idx], + post_merge_scale_chunks, + args, + cycle=cycle_idx, + ) + + lora_post_eval = None + if (not args.skip_eval) and (not args.skip_distill) and do_reparam: + distill_post_eval = evaluate_ppl_model( + model, + tokenizer, + eval_datasets, + eval_configs, + args, + prepared_eval_dataloaders=prepared.eval_dataloaders, + ) + print(f"[progressive] Cycle {cycle_idx} post-distill perplexity:") + for dataset_name, ppl in distill_post_eval.items(): + print(f"{dataset_name}: {ppl:.4f}") + + post_eval = None + if not args.skip_eval: + if distill_post_eval is not None: + post_eval = distill_post_eval + else: + post_eval = evaluate_ppl_model( + model, + tokenizer, + eval_datasets, + eval_configs, + args, + prepared_eval_dataloaders=prepared.eval_dataloaders, + ) + print(f"[progressive] Cycle {cycle_idx} perplexity:") + for dataset_name, ppl in post_eval.items(): + print(f"{dataset_name}: {ppl:.4f}") + + cycle_dir = os.path.join(args.output_dir, f"cycle_{cycle_idx}") + os.makedirs(cycle_dir, exist_ok=True) + fused_layer_file = None + if args.profile_no_save: + print( + f"[profile] Skipping fused layer weight save for cycle {cycle_idx}." + ) + else: + fused_layer_file = "fused_layer.pt" + fused_layer_path = os.path.join(cycle_dir, fused_layer_file) + torch.save(layers[layer_idx].state_dict(), fused_layer_path) + _record_component("materialize_save_layer", materialize_timing_start) + + cycle_meta: Dict[str, object] = { + "cycle": cycle_idx, + "layer_merged": layer_idx, + "num_layers_before": num_layers_before, + "num_layers_after": num_layers_before - 1, + "fused_layer_state": fused_layer_file, + "profile_no_save": bool(args.profile_no_save), + "dwce_score": dwce_scores[layer_idx] if dwce_scores else None, + "dwce_scores": dwce_scores, + "dwce_meta": dwce_meta, + "fisher_num_batches": num_batches, + "merge_method": merge_method, + "merged_params": merged, + "num_sequences": num_sequences, + "teacher_source": teacher_source, + "teacher_cycle": teacher_cycle, + "eval": { + "datasets": eval_datasets, + "configs": eval_configs, + "split": args.eval_split, + "num_samples": args.eval_num_samples, + "seq_len": args.eval_seq_len, + "post_ppl": post_eval, + "merge_only_ppl": merge_only_eval, + }, + "comm": comm_stats, + "distill": { + "enabled": not args.skip_distill, + "method": distill_method, + "calib_samples": args.distill_calib_samples, + "inst_samples": args.distill_inst_samples, + "seq_len": args.distill_seq_len, + "batch_size": args.distill_batch_size, + "epochs": args.distill_epochs, + "lr": args.distill_lr, + "kl_weight": args.distill_kl_weight, + "kl_temp": args.distill_kl_temp, + "kl_chunk_size": args.kl_chunk_size, + "hidden_mse_weight": args.distill_hidden_mse_weight, + "attn_mse_weight": args.distill_attn_mse_weight, + "mlp_mse_weight": args.distill_mlp_mse_weight, + "reparam_eta": args.reparam_eta, + "reparam_gamma": args.reparam_gamma, + "reparam_attn_reg_scale": args.reparam_attn_reg_scale, + "reparam_mlp_reg_scale": args.reparam_mlp_reg_scale, + "reparam_param_subset": args.reparam_param_subset, + "reparam_train_subset": args.reparam_train_subset, + "reparam_skip_train": bool(getattr(args, "reparam_skip_train", False)), + "reparam_stats": reparam_stats, + "reparam_gate_summary": reparam_gate_summary, + "post_merge_nll_scale": post_merge_nll_scale_stats, + "merge_only_ppl": merge_only_eval, + "post_ppl": distill_post_eval, + "weight_decay": args.distill_weight_decay, + "max_grad_norm": args.distill_max_grad_norm, + "grad_accum_steps": args.distill_grad_accum_steps, + "instruction_dataset": args.instruction_dataset, + "instruction_config": args.instruction_config, + "instruction_split": args.instruction_split, + }, + "lora": { + "enabled": args.lora_epochs > 0, + "seq_len": args.distill_seq_len, + "batch_size": args.distill_batch_size, + "epochs": args.lora_epochs, + "rank": args.lora_rank, + "alpha": args.lora_alpha, + "dropout": args.lora_dropout, + "target_modules": args.lora_target_modules, + "respect_exclude_pairs": args.lora_respect_exclude_pairs, + "kl_enabled": args.lora_kl_enabled, + "kl_weight": args.lora_kl_weight, + "kl_temp": args.lora_kl_temp, + "post_ppl": lora_post_eval, + "lr": args.lora_lr, + "weight_decay": args.lora_weight_decay, + "max_grad_norm": args.lora_max_grad_norm, + "grad_accum_steps": args.lora_grad_accum_steps, + "log_steps": args.lora_log_steps, + "eval_every": args.lora_eval_every, + "eval_max_batches": args.lora_eval_max_batches, + }, + "norm_policy": args.norm_policy, + "source_feature_transport": source_feature_transport_stats, + "same_anchor_contextual_fisher": contextual_fisher_stats, + } + + saved_full_model_dir = None + if cycle_idx in args.full_model_save_cycles: + cycle_meta["full_model_saved"] = True + cycle_meta["full_model"] = save_cycle_full_model( + model=model, + tokenizer=tokenizer, + cycle_dir=cycle_dir, + cycle_idx=cycle_idx, + args=args, + ppl_results=post_eval, + ) + saved_full_model_dir = os.path.join(cycle_dir, "full_model") + else: + cycle_meta["full_model_saved"] = False + + metadata_timing_start = _timing_start() + cycle_meta_path = os.path.join(cycle_dir, "cycle_metadata.json") + with open( + cycle_meta_path, + "w", + encoding="utf-8", + ) as handle: + json.dump(cycle_meta, handle, indent=2) + _record_component("metadata_write", metadata_timing_start) + + cycle_summary: Dict[str, object] = { + "cycle": cycle_idx, + "layer_merged": layer_idx, + "dwce_score": dwce_scores[layer_idx] if dwce_scores else None, + "comm_post_ppl": comm_post_eval, + "merge_only_ppl": merge_only_eval, + "distill_post_ppl": distill_post_eval, + "lora_post_ppl": lora_post_eval, + "post_ppl": post_eval, + "cycle_dir": f"cycle_{cycle_idx}", + } + cycle_summaries.append(cycle_summary) + + last_fused_idx = layer_idx + snapshot_timing_start = _timing_start() + _snapshot_previous_cycle_teacher(cycle_idx) + _record_component("teacher_snapshot", snapshot_timing_start) + + cleanup_timing_start = _timing_start() + parent, name, container = find_layer_container(model, args.layer_path) + layers = list(container) + if dwce_scores: + dwce_scores = dwce_scores[: max(len(layers) - 1, 0)] + + # Encourage allocator to release cached blocks between cycles. + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.ipc_collect() + gc.collect() + _record_component("cycle_cleanup", cleanup_timing_start) + + if saved_full_model_dir is not None: + save_rng_state(os.path.join(saved_full_model_dir, "rng_state.pt")) + save_loader_generator_state( + saved_full_model_dir, + distill_generator=prepared.distill_generator, + lora_generator=prepared.lora_generator, + ) + + component_seconds["cycle_total"] = _timing_elapsed(cycle_timing_start) + timing_meta = _timing_summary(component_seconds) + cycle_meta["timing"] = timing_meta + cycle_summary["timing"] = timing_meta + with open(cycle_meta_path, "w", encoding="utf-8") as handle: + json.dump(cycle_meta, handle, indent=2) + _print_cycle_timing(cycle_idx, timing_meta) + + _release_comm_teacher() + _release_previous_cycle_teacher() + + final_pre_lora_eval = cycle_summaries[-1]["post_ppl"] if cycle_summaries else None + final_pre_lora_dir = f"{os.path.abspath(args.output_dir.rstrip(os.sep))}_final_pre_lora_hf" + if args.profile_no_save or args.skip_final_model_save: + skip_reason = "profile_no_save" if args.profile_no_save else "compact_only" + final_pre_lora_meta = { + "stage": "final_pre_lora", + "path": final_pre_lora_dir, + "skipped": True, + "reason": skip_reason, + "post_ppl": final_pre_lora_eval, + } + print(f"[save] Skipping final pre-LoRA weight save ({skip_reason}).") + else: + final_pre_lora_meta = save_stage_checkpoint( + model=model, + tokenizer=tokenizer, + stage_dir=final_pre_lora_dir, + stage_name="final_pre_lora", + ppl_results=final_pre_lora_eval, + ) + + # Optional final LoRA finetune after all pruning cycles. + lora_eval_history: List[Dict[str, object]] = [] + lora_post_eval = None + lora_ready = has_post_fusion_data(prepared.lora_loader, prepared.lora_meta) + if args.lora_epochs > 0: + if not lora_ready: + print("No post-fusion sequences built; skipping LoRA finetuning.") + else: + print( + f"[progressive] Running final LoRA finetuning (epochs={args.lora_epochs})." + ) + lora_eval_history = run_lora_phase( + model=model, + tokenizer=tokenizer, + eval_datasets=eval_datasets, + eval_configs=eval_configs, + args=args, + lora_loader=prepared.lora_loader, + lora_meta=prepared.lora_meta, + eval_dataloaders=prepared.eval_dataloaders, + cycle_idx=args.num_progressive, + num_cycles=args.num_progressive, + ) + + if not args.skip_eval: + lora_post_eval = evaluate_ppl_model( + model, + tokenizer, + eval_datasets, + eval_configs, + args, + prepared_eval_dataloaders=prepared.eval_dataloaders, + ) + print("[progressive] Post-LoRA perplexity:") + for dataset_name, ppl in lora_post_eval.items(): + print(f"{dataset_name}: {ppl:.4f}") + + # Update final cycle metadata and summary with the post-LoRA PPL. + if cycle_summaries: + cycle_summaries[-1]["lora_post_ppl"] = lora_post_eval + if lora_post_eval is not None: + cycle_summaries[-1]["post_ppl"] = lora_post_eval + + final_cycle_dir = os.path.join( + args.output_dir, f"cycle_{args.num_progressive}" + ) + final_cycle_meta_path = os.path.join(final_cycle_dir, "cycle_metadata.json") + if os.path.exists(final_cycle_meta_path): + with open(final_cycle_meta_path, "r", encoding="utf-8") as handle: + final_cycle_meta = json.load(handle) + + lora_meta_entry = final_cycle_meta.get("lora") + if not isinstance(lora_meta_entry, dict): + lora_meta_entry = {} + final_cycle_meta["lora"] = lora_meta_entry + lora_meta_entry["ran"] = True + lora_meta_entry["post_ppl"] = lora_post_eval + if lora_post_eval is not None and isinstance( + final_cycle_meta.get("eval"), dict + ): + final_cycle_meta["eval"]["post_ppl"] = lora_post_eval + + if lora_eval_history: + lora_path = os.path.join(final_cycle_dir, "ppl_over_lora.json") + with open(lora_path, "w", encoding="utf-8") as handle: + json.dump(lora_eval_history, handle, indent=2) + lora_meta_entry["ppl_over_lora"] = "ppl_over_lora.json" + + with open(final_cycle_meta_path, "w", encoding="utf-8") as handle: + json.dump(final_cycle_meta, handle, indent=2) + + os.makedirs(args.output_dir, exist_ok=True) + if args.profile_no_save or args.skip_final_model_save: + skip_reason = "profile_no_save" if args.profile_no_save else "compact_only" + final_post_lora_meta = { + "stage": "final_post_lora" if lora_post_eval is not None else "final_model", + "path": args.output_dir, + "skipped": True, + "reason": skip_reason, + "post_ppl": lora_post_eval, + } + print(f"[save] Skipping final model weight save ({skip_reason}).") + else: + final_post_lora_meta = save_stage_checkpoint( + model=model, + tokenizer=tokenizer, + stage_dir=args.output_dir, + stage_name="final_post_lora" if lora_post_eval is not None else "final_model", + ppl_results=lora_post_eval, + ) + + progressive_meta = { + "base_model": getattr(args, "base_model_id", args.model), + "num_progressive": args.num_progressive, + "layer_path": args.layer_path, + "resume_from_cycle": args.resume_from_cycle, + "profile_no_save": bool(args.profile_no_save), + "skip_final_model_save": bool(args.skip_final_model_save), + "save_full_model_cycles": sorted(args.full_model_save_cycles), + "num_sequences": num_sequences, + "seq_len": args.seq_len, + "lora": { + "enabled": args.lora_epochs > 0, + "ran": args.lora_epochs > 0 and lora_ready, + "seq_len": args.distill_seq_len, + "batch_size": args.distill_batch_size, + "epochs": args.lora_epochs, + "rank": args.lora_rank, + "alpha": args.lora_alpha, + "dropout": args.lora_dropout, + "target_modules": args.lora_target_modules, + "respect_exclude_pairs": args.lora_respect_exclude_pairs, + "kl_enabled": args.lora_kl_enabled, + "kl_weight": args.lora_kl_weight, + "kl_temp": args.lora_kl_temp, + "post_ppl": lora_post_eval, + "ppl_over_lora": ( + f"cycle_{args.num_progressive}/ppl_over_lora.json" + if lora_eval_history + else None + ), + "lr": args.lora_lr, + "weight_decay": args.lora_weight_decay, + "max_grad_norm": args.lora_max_grad_norm, + "grad_accum_steps": args.lora_grad_accum_steps, + "log_steps": args.lora_log_steps, + "eval_every": args.lora_eval_every, + "eval_max_batches": args.lora_eval_max_batches, + }, + "artifacts": { + "final_pre_lora": final_pre_lora_meta, + "final_post_lora": final_post_lora_meta, + }, + "eval": { + "datasets": eval_datasets, + "configs": eval_configs, + "split": args.eval_split, + "num_samples": args.eval_num_samples, + "seq_len": args.eval_seq_len, + "pre_ppl": pre_eval, + "post_ppl": cycle_summaries[-1]["post_ppl"] if cycle_summaries else None, + }, + "cycles": cycle_summaries, + "final_num_layers": len(layers), + } + + with open( + os.path.join(args.output_dir, "progressive_metadata.json"), + "w", + encoding="utf-8", + ) as handle: + json.dump(progressive_meta, handle, indent=2) + + print( + f"[progressive] Completed {args.num_progressive} cycles. " + + ( + f"Profiling metadata written to {args.output_dir}; final model save skipped." + if args.profile_no_save + else ( + f"Compact weights written to {args.output_dir}; final dense model save skipped." + if args.skip_final_model_save else f"Final model saved to {args.output_dir}." + ) + ) + ) + + +def main() -> None: + args = parse_args() + if args.num_progressive <= 0: + raise SystemExit( + "Single-cycle mode has been removed. Pass --num_progressive > 0." + ) + if args.resume_from_cycle < 0: + raise SystemExit("--resume_from_cycle must be >= 0.") + if args.resume_from_cycle >= args.num_progressive: + raise SystemExit("--resume_from_cycle must be smaller than --num_progressive.") + args.full_model_save_cycles = resolve_full_model_save_cycles( + parse_cycle_list(args.save_full_model_cycles), + args.num_progressive, + ) + if args.profile_no_save: + args.full_model_save_cycles = set() + args.base_model_id = args.model + if args.resume_from_cycle > 0: + resume_meta = load_resume_metadata(args.model) + if resume_meta is None: + raise SystemExit( + "--resume_from_cycle requires --model to point to a saved cycle full model " + "directory containing resume_info.json." + ) + resume_cycle = resume_meta.get("cycle") + if resume_cycle is not None and int(resume_cycle) != args.resume_from_cycle: + raise SystemExit( + "resume_info.json cycle does not match --resume_from_cycle." + ) + base_model = resume_meta.get("base_model") + if isinstance(base_model, str) and base_model: + args.base_model_id = base_model + configure_reproducibility(args.seed) + + eval_datasets, eval_configs = resolve_eval_datasets(args) + dtype = get_dtype(args.dtype) + student_device_map = resolve_model_device_map_spec( + args.model_device_map, + model_path_or_id=args.model, + trust_remote_code=args.trust_remote_code, + cache_dir=args.model_cache_dir, + ) + if student_device_map is not None: + print(f"[device] student model_device_map={args.model_device_map}") + model = load_causal_lm( + args.model, + torch_dtype=dtype, + trust_remote_code=args.trust_remote_code, + cache_dir=args.model_cache_dir, + device_map=student_device_map, + ) + loader_generator_state = None + if args.resume_from_cycle > 0: + rng_state_path = os.path.join(args.model, "rng_state.pt") + rng_state = load_rng_state(rng_state_path) + if rng_state is not None: + restore_rng_state(rng_state) + loader_generator_state = load_loader_generator_state(args.model) + tokenizer = AutoTokenizer.from_pretrained( + args.model, + trust_remote_code=args.trust_remote_code, + cache_dir=args.model_cache_dir, + ) + print(model) + if tokenizer.pad_token is None and tokenizer.eos_token is not None: + tokenizer.pad_token = tokenizer.eos_token + + # for llama? + model.config.use_cache = False + + prepared = prepare_all_data( + args, + tokenizer, + model, + eval_datasets, + eval_configs, + loader_generator_state=loader_generator_state, + ) + run_progressive(args, model, tokenizer, prepared) + + +if __name__ == "__main__": + main() diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/fuse_layers_distill.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/fuse_layers_distill.py new file mode 100644 index 0000000000000000000000000000000000000000..3112fcf513cbf4963f90b2b9707c1972dba458e4 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/fuse_layers_distill.py @@ -0,0 +1,3824 @@ +#!/usr/bin/env python3 +"""Distillation helpers for fuse_layers.""" + +import argparse +import gc +import itertools +import math +import os +from contextlib import contextmanager, nullcontext +from typing import Dict, List, Optional, Set, Tuple + +import torch +import torch.nn.functional as F + +try: + import ppl_eval +except Exception as exc: # pragma: no cover - optional dependency + raise SystemExit("ppl_eval.py is required (missing or invalid)") from exc +try: + from tqdm import tqdm +except Exception: # pragma: no cover - optional dependency + tqdm = None + +try: + from torch.func import functional_call as _functional_call +except Exception: # pragma: no cover - depends on torch version + try: + from torch.nn.utils.stateless import functional_call as _functional_call + except Exception: # pragma: no cover - depends on torch version + _functional_call = None + +from fuse_layers_model import find_attention_module, find_mlp_module + + +def _tqdm_enabled() -> bool: + value = os.environ.get("DISABLE_TQDM", os.environ.get("TQDM_DISABLE", "0")) + return value.strip().lower() not in {"1", "true", "yes", "on"} + + +@contextmanager +def temporary_layers(parent: object, name: str, new_layers: torch.nn.Module): + original = getattr(parent, name) + setattr(parent, name, new_layers) + try: + yield + finally: + setattr(parent, name, original) + + +@contextmanager +def temporary_norm(parent: object): + if hasattr(parent, "norm"): + original = getattr(parent, "norm") + setattr(parent, "norm", torch.nn.Identity()) + try: + yield + finally: + setattr(parent, "norm", original) + else: + yield + + +def forward_truncated( + parent: torch.nn.Module, + layer_attr: str, + layers: List[torch.nn.Module], + upto: int, + input_ids: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, +) -> torch.Tensor: + truncated = torch.nn.ModuleList(layers[:upto]) + with temporary_layers(parent, layer_attr, truncated), temporary_norm(parent): + outputs = parent( + input_ids=input_ids, + attention_mask=attention_mask, + use_cache=False, + ) + if hasattr(outputs, "last_hidden_state"): + return outputs.last_hidden_state + return outputs[0] + + +def _masked_hidden_mse(diff: torch.Tensor, attention_mask: torch.Tensor) -> Optional[torch.Tensor]: + diff_f = diff.float() + mask = attention_mask.to(device=diff.device, dtype=torch.float32) + denom = mask.sum() * diff_f.size(-1) + if denom.item() == 0: + return None + return (diff_f.pow(2) * mask.unsqueeze(-1)).sum() / denom + + +def _extract_hidden_like(output) -> Optional[torch.Tensor]: + if torch.is_tensor(output): + return output + if isinstance(output, (tuple, list)) and output: + first = output[0] + if torch.is_tensor(first): + return first + if hasattr(output, "last_hidden_state"): + hidden = getattr(output, "last_hidden_state") + if torch.is_tensor(hidden): + return hidden + return None + + +def _add_weighted_loss( + total_loss: Optional[torch.Tensor], + term: Optional[torch.Tensor], + weight: float, +) -> Optional[torch.Tensor]: + if term is None: + return total_loss + weighted = float(weight) * term + if total_loss is None: + return weighted + if weighted.device != total_loss.device: + weighted = weighted.to(total_loss.device) + return total_loss + weighted + + +def _move_tensor_tree_to_device(value: object, device: torch.device) -> object: + if isinstance(value, torch.Tensor): + return value.to(device=device) + if isinstance(value, tuple): + return tuple(_move_tensor_tree_to_device(item, device) for item in value) + if isinstance(value, list): + return [_move_tensor_tree_to_device(item, device) for item in value] + if isinstance(value, dict): + return { + key: _move_tensor_tree_to_device(item, device) + for key, item in value.items() + } + return value + + +def _sum_grad_to_shape(grad: torch.Tensor, shape: torch.Size) -> torch.Tensor: + while grad.dim() > len(shape): + grad = grad.sum(dim=0) + for dim, size in enumerate(shape): + if size == 1 and grad.shape[dim] != 1: + grad = grad.sum(dim=dim, keepdim=True) + return grad + + +def _to_reparam_work_tensor(tensor: torch.Tensor, device: torch.device) -> torch.Tensor: + return tensor.detach().to(device=device, dtype=torch.float32) + + +def _initial_reparam_u( + param_a: torch.Tensor, + param_b: torch.Tensor, + device: torch.device, +) -> torch.Tensor: + return 0.5 * ( + _to_reparam_work_tensor(param_a, device) + - _to_reparam_work_tensor(param_b, device) + ) + + +class _ReparamMergedParamFn(torch.autograd.Function): + @staticmethod + def forward( + ctx, + param_a: torch.Tensor, + param_b: torch.Tensor, + gate: torch.Tensor, + u: torch.Tensor, + out_dtype: torch.dtype, + ) -> torch.Tensor: + ctx.save_for_backward(gate, u) + ctx.gate_shape = gate.shape + + work = torch.empty_like(u, dtype=torch.float32) + work.copy_(param_a.detach()) + work.add_(param_b.detach().to(device=work.device, dtype=work.dtype)).mul_(0.5) + scale = torch.sigmoid(gate.to(dtype=torch.float32)).mul_(2.0).sub_(1.0) + work.addcmul_(scale, u.to(dtype=torch.float32)) + return work.to(dtype=out_dtype) + + @staticmethod + def backward(ctx, grad_output: torch.Tensor): + gate, u = ctx.saved_tensors + grad_f = grad_output.to(device=u.device, dtype=torch.float32) + scale = torch.sigmoid(gate.to(dtype=torch.float32)).mul_(2.0).sub_(1.0) + + grad_gate = grad_f * u.to(dtype=torch.float32) + grad_u = grad_f.mul_(scale) + scale.square_().neg_().add_(1.0).mul_(0.5) + grad_gate.mul_(scale) + grad_gate = _sum_grad_to_shape(grad_gate, ctx.gate_shape) + return None, None, grad_gate, grad_u, None + + +def _merge_reparam_param( + param_a: torch.Tensor, + param_b: torch.Tensor, + gate: torch.Tensor, + u: torch.Tensor, +) -> torch.Tensor: + return _ReparamMergedParamFn.apply(param_a, param_b, gate, u, param_a.dtype) + + +def _merge_reparam_param_no_grad( + param_a: torch.Tensor, + param_b: torch.Tensor, + gate: torch.Tensor, + u: torch.Tensor, +) -> torch.Tensor: + work = torch.empty_like(u, dtype=torch.float32) + work.copy_(param_a.detach()) + work.add_(param_b.detach().to(device=work.device, dtype=work.dtype)).mul_(0.5) + scale = torch.sigmoid(gate.to(dtype=torch.float32)).mul_(2.0).sub_(1.0) + work.addcmul_(scale, u.to(dtype=torch.float32)) + return work.to(dtype=param_a.dtype) + + +class _AdditiveUMergedParamFn(torch.autograd.Function): + """Frozen Fisher initialization plus a free additive FiT correction.""" + + @staticmethod + def forward( + ctx, + param_a: torch.Tensor, + param_b: torch.Tensor, + fisher_gate: torch.Tensor, + u_add: torch.Tensor, + out_dtype: torch.dtype, + ) -> torch.Tensor: + fisher_lambda = torch.sigmoid(fisher_gate.detach().float()) + a = param_a.detach().to(device=u_add.device, dtype=torch.float32) + b = param_b.detach().to(device=u_add.device, dtype=torch.float32) + fisher = b + fisher_lambda * (a - b) + ctx.u_device = u_add.device + return (fisher + u_add.float()).to(dtype=out_dtype) + + @staticmethod + def backward(ctx, grad_output: torch.Tensor): + grad_u = grad_output.to(device=ctx.u_device, dtype=torch.float32) + return None, None, None, grad_u, None + + +def _merge_reparam_param_additive_u( + param_a: torch.Tensor, + param_b: torch.Tensor, + fisher_gate: torch.Tensor, + u_add: torch.Tensor, +) -> torch.Tensor: + return _AdditiveUMergedParamFn.apply( + param_a, param_b, fisher_gate, u_add, param_a.dtype + ) + + +def _merge_reparam_param_additive_u_no_grad( + param_a: torch.Tensor, + param_b: torch.Tensor, + fisher_gate: torch.Tensor, + u_add: torch.Tensor, +) -> torch.Tensor: + fisher_lambda = torch.sigmoid(fisher_gate.detach().float()) + a = param_a.detach().to(device=u_add.device, dtype=torch.float32) + b = param_b.detach().to(device=u_add.device, dtype=torch.float32) + fisher = b + fisher_lambda * (a - b) + return (fisher + u_add.detach().float()).to(dtype=param_a.dtype) + + +def _rho_projection(name: str) -> Optional[str]: + for projection in ("gate_proj", "up_proj", "down_proj"): + if f".{projection}." in f".{name}.": + return projection + return None + + +class _RhoMergedParamFn(torch.autograd.Function): + """Reparam merge with a frozen Fisher gate and one projection-level rho.""" + + @staticmethod + def forward( + ctx, + param_a: torch.Tensor, + param_b: torch.Tensor, + fisher_gate: torch.Tensor, + u: torch.Tensor, + rho: torch.Tensor, + out_dtype: torch.dtype, + ) -> torch.Tensor: + fisher_lambda = torch.sigmoid(fisher_gate.detach().float()) + effective_lambda = fisher_lambda + rho.float() * (1.0 - fisher_lambda) + scale = effective_lambda.mul(2.0).sub(1.0) + ctx.save_for_backward(fisher_lambda, scale, u) + work = torch.empty_like(u, dtype=torch.float32) + work.copy_(param_a.detach()) + work.add_(param_b.detach().to(device=work.device, dtype=work.dtype)).mul_(0.5) + work.addcmul_(scale, u.float()) + return work.to(dtype=out_dtype) + + @staticmethod + def backward(ctx, grad_output: torch.Tensor): + fisher_lambda, scale, u = ctx.saved_tensors + grad_f = grad_output.to(device=u.device, dtype=torch.float32) + grad_u = grad_f * scale + grad_rho = (grad_f * u.float() * (2.0 * (1.0 - fisher_lambda))).sum() + return None, None, None, grad_u, grad_rho, None + + +def _merge_reparam_param_rho( + param_a: torch.Tensor, + param_b: torch.Tensor, + fisher_gate: torch.Tensor, + u: torch.Tensor, + rho: torch.Tensor, +) -> torch.Tensor: + return _RhoMergedParamFn.apply( + param_a, param_b, fisher_gate, u, rho, param_a.dtype + ) + + +def _merge_reparam_param_rho_no_grad( + param_a: torch.Tensor, + param_b: torch.Tensor, + fisher_gate: torch.Tensor, + u: torch.Tensor, + rho: torch.Tensor, +) -> torch.Tensor: + fisher_lambda = torch.sigmoid(fisher_gate.detach().float()) + effective_lambda = fisher_lambda + rho.detach().float() * (1.0 - fisher_lambda) + work = torch.empty_like(u, dtype=torch.float32) + work.copy_(param_a.detach()) + work.add_(param_b.detach().to(device=work.device, dtype=work.dtype)).mul_(0.5) + work.addcmul_(effective_lambda.mul(2.0).sub(1.0), u.float()) + return work.to(dtype=param_a.dtype) + + +class _SequentialRhoMergedParamFn(torch.autograd.Function): + """Fixed Fisher-to-anchor rho direction plus an additive FiT correction.""" + + @staticmethod + def forward( + ctx, + param_a: torch.Tensor, + param_b: torch.Tensor, + fisher_gate: torch.Tensor, + u_add: torch.Tensor, + rho: torch.Tensor, + out_dtype: torch.dtype, + ) -> torch.Tensor: + fisher_lambda = torch.sigmoid(fisher_gate.detach().float()) + a = param_a.detach().to(device=u_add.device, dtype=torch.float32) + b = param_b.detach().to(device=u_add.device, dtype=torch.float32) + fisher = b + fisher_lambda * (a - b) + anchor_delta = a - fisher + ctx.save_for_backward(anchor_delta) + work = fisher + rho.float() * anchor_delta + u_add.float() + return work.to(dtype=out_dtype) + + @staticmethod + def backward(ctx, grad_output: torch.Tensor): + (anchor_delta,) = ctx.saved_tensors + grad_f = grad_output.to(device=anchor_delta.device, dtype=torch.float32) + grad_u = grad_f + grad_rho = (grad_f * anchor_delta).sum() + return None, None, None, grad_u, grad_rho, None + + +def _merge_reparam_param_sequential_rho( + param_a: torch.Tensor, + param_b: torch.Tensor, + fisher_gate: torch.Tensor, + u_add: torch.Tensor, + rho: torch.Tensor, +) -> torch.Tensor: + return _SequentialRhoMergedParamFn.apply( + param_a, param_b, fisher_gate, u_add, rho, param_a.dtype + ) + + +def _merge_reparam_param_sequential_rho_no_grad( + param_a: torch.Tensor, + param_b: torch.Tensor, + fisher_gate: torch.Tensor, + u_add: torch.Tensor, + rho: torch.Tensor, +) -> torch.Tensor: + fisher_lambda = torch.sigmoid(fisher_gate.detach().float()) + a = param_a.detach().to(device=u_add.device, dtype=torch.float32) + b = param_b.detach().to(device=u_add.device, dtype=torch.float32) + fisher = b + fisher_lambda * (a - b) + return ( + fisher + rho.detach().float() * (a - fisher) + u_add.detach().float() + ).to(dtype=param_a.dtype) + + +@contextmanager +def capture_module_output(module: torch.nn.Module): + cache: Dict[str, Optional[torch.Tensor]] = {"output": None} + + def hook(_module, _inputs, output): + cache["output"] = _extract_hidden_like(output) + + handle = module.register_forward_hook(hook) + try: + yield cache + finally: + handle.remove() + + +_ATTN_NAME_FRAGMENTS = ( + "self_attn.", + "attn.", + "attention.", + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "q_norm", + "k_norm", +) +_MLP_NAME_FRAGMENTS = ( + "mlp.", + "ffn.", + "feed_forward", + "feedforward", + "gate_proj", + "up_proj", + "down_proj", + "fc1", + "fc2", + "dense_h_to_4h", + "dense_4h_to_h", + "w1", + "w2", + "w3", +) + + +def _classify_param_family(name: str) -> str: + lowered = name.lower() + if any(fragment in lowered for fragment in _MLP_NAME_FRAGMENTS): + return "mlp" + if any(fragment in lowered for fragment in _ATTN_NAME_FRAGMENTS): + return "attn" + return "other" + + +def _family_reg_scale(family: str, attn_scale: float, mlp_scale: float) -> float: + if family == "attn": + return attn_scale + if family == "mlp": + return mlp_scale + return 1.0 + + +def _subset_allows_param(name: str, subset: str) -> bool: + if subset == "all": + return True + if subset == "down_proj": + parts = name.lower().split(".") + return len(parts) >= 2 and parts[-2] == "down_proj" + return _classify_param_family(name) == subset + + +def _resolve_reparam_train_subset(param_subset: str, train_subset: object) -> str: + value = str(train_subset).strip().lower() + if value in {"", "same", "param_subset"}: + return param_subset + if value not in {"all", "mlp", "attn", "down_proj"}: + raise SystemExit( + "--reparam_train_subset must be one of: same, all, mlp, attn, down_proj" + ) + return value + + +def _resolve_reparam_fisher_init_subset(param_subset: str, init_subset: object) -> str: + value = str(init_subset).strip().lower() + if value in {"", "same", "param_subset"}: + return param_subset + valid = {"all", "mlp", "attn", "down_proj", "mlp_o", "mlp_v", "mlp_vo"} + if value not in valid: + raise SystemExit( + "--reparam_fisher_init_subset must be one of: same, all, mlp, attn, " + "down_proj, mlp_o, mlp_v, mlp_vo" + ) + return value + + +def _gate_logit_from_prior(prior: torch.Tensor) -> torch.Tensor: + # Stable logit: log(p) - log(1 - p). + return torch.log(prior) - torch.log1p(-prior) + + +def _tensor_debug_summary(tensors: Dict[str, torch.Tensor]) -> Dict[str, object]: + total_sum = 0.0 + total_sq_sum = 0.0 + total_abs_from_half = 0.0 + total_elems = 0 + global_min: Optional[float] = None + global_max: Optional[float] = None + per_tensor: Dict[str, Dict[str, float]] = {} + + with torch.no_grad(): + for name, tensor in tensors.items(): + t = tensor.detach().float() + if t.numel() == 0: + continue + numel = int(t.numel()) + t_sum = float(t.sum().item()) + t_sq_sum = float(t.pow(2).sum().item()) + t_min = float(t.min().item()) + t_max = float(t.max().item()) + t_abs_half = float((t - 0.5).abs().sum().item()) + per_tensor[name] = { + "mean": t_sum / float(numel), + "std": math.sqrt(max(t_sq_sum / float(numel) - (t_sum / float(numel)) ** 2, 0.0)), + "min": t_min, + "max": t_max, + "mean_abs_from_0_5": t_abs_half / float(numel), + } + total_sum += t_sum + total_sq_sum += t_sq_sum + total_abs_from_half += t_abs_half + total_elems += numel + global_min = t_min if global_min is None else min(global_min, t_min) + global_max = t_max if global_max is None else max(global_max, t_max) + + if total_elems == 0: + return {"num_tensors": len(tensors), "num_elements": 0} + mean = total_sum / float(total_elems) + return { + "num_tensors": len(tensors), + "num_elements": total_elems, + "mean": mean, + "std": math.sqrt(max(total_sq_sum / float(total_elems) - mean ** 2, 0.0)), + "min": global_min, + "max": global_max, + "mean_abs_from_0_5": total_abs_from_half / float(total_elems), + "per_tensor": per_tensor, + } + + +def _lambda_delta_summary( + final_lambdas: Dict[str, torch.Tensor], + init_lambdas: Dict[str, object], +) -> Dict[str, object]: + total_abs = 0.0 + total_sq = 0.0 + total_elems = 0 + max_abs = 0.0 + per_tensor: Dict[str, Dict[str, float]] = {} + + with torch.no_grad(): + for name, final in final_lambdas.items(): + init = init_lambdas.get(name) + if init is None: + init_t = torch.full_like(final.detach().float(), 0.5) + elif isinstance(init, torch.Tensor): + init_t = init.detach().to(device=final.device, dtype=torch.float32) + else: + init_t = torch.full_like(final.detach().float(), float(init)) + diff = final.detach().float() - init_t + if diff.numel() == 0: + continue + abs_diff = diff.abs() + numel = int(diff.numel()) + abs_sum = float(abs_diff.sum().item()) + sq_sum = float(diff.pow(2).sum().item()) + tensor_max_abs = float(abs_diff.max().item()) + per_tensor[name] = { + "mean_abs": abs_sum / float(numel), + "rms": math.sqrt(sq_sum / float(numel)), + "max_abs": tensor_max_abs, + } + total_abs += abs_sum + total_sq += sq_sum + total_elems += numel + max_abs = max(max_abs, tensor_max_abs) + + if total_elems == 0: + return {"num_tensors": len(final_lambdas), "num_elements": 0} + return { + "num_tensors": len(final_lambdas), + "num_elements": total_elems, + "mean_abs": total_abs / float(total_elems), + "rms": math.sqrt(total_sq / float(total_elems)), + "max_abs": max_abs, + "per_tensor": per_tensor, + } + + +def _lambda_summary_from_gates( + name_map: Dict[str, str], + gates: torch.nn.ParameterDict, +) -> Dict[str, object]: + total_sum = 0.0 + total_sq_sum = 0.0 + total_abs_from_half = 0.0 + total_elems = 0 + global_min: Optional[float] = None + global_max: Optional[float] = None + per_tensor: Dict[str, Dict[str, float]] = {} + + with torch.no_grad(): + for orig, safe in name_map.items(): + t = torch.sigmoid(gates[safe]).detach().float() + if t.numel() == 0: + continue + numel = int(t.numel()) + t_sum = float(t.sum().item()) + t_sq_sum = float(t.pow(2).sum().item()) + t_min = float(t.min().item()) + t_max = float(t.max().item()) + t_abs_half = float((t - 0.5).abs().sum().item()) + per_tensor[orig] = { + "mean": t_sum / float(numel), + "std": math.sqrt(max(t_sq_sum / float(numel) - (t_sum / float(numel)) ** 2, 0.0)), + "min": t_min, + "max": t_max, + "mean_abs_from_0_5": t_abs_half / float(numel), + } + total_sum += t_sum + total_sq_sum += t_sq_sum + total_abs_from_half += t_abs_half + total_elems += numel + global_min = t_min if global_min is None else min(global_min, t_min) + global_max = t_max if global_max is None else max(global_max, t_max) + + if total_elems == 0: + return {"num_tensors": len(name_map), "num_elements": 0} + mean = total_sum / float(total_elems) + return { + "num_tensors": len(name_map), + "num_elements": total_elems, + "mean": mean, + "std": math.sqrt(max(total_sq_sum / float(total_elems) - mean ** 2, 0.0)), + "min": global_min, + "max": global_max, + "mean_abs_from_0_5": total_abs_from_half / float(total_elems), + "per_tensor": per_tensor, + } + + +def _grad_debug_summary(params: List[torch.nn.Parameter]) -> Dict[str, object]: + total_sq = 0.0 + total_abs = 0.0 + total_elems = 0 + max_abs = 0.0 + none_count = 0 + with torch.no_grad(): + for param in params: + grad = param.grad + if grad is None: + none_count += 1 + continue + g = grad.detach().float() + if g.numel() == 0: + continue + abs_g = g.abs() + total_sq += float(g.pow(2).sum().item()) + total_abs += float(abs_g.sum().item()) + total_elems += int(g.numel()) + max_abs = max(max_abs, float(abs_g.max().item())) + return { + "num_tensors": len(params), + "num_tensors_without_grad": none_count, + "num_elements": total_elems, + "l2": math.sqrt(total_sq), + "mean_abs": None if total_elems == 0 else total_abs / float(total_elems), + "max_abs": max_abs, + } + + +def _u_delta_debug_summary( + name_map: Dict[str, str], + u_params: torch.nn.ParameterDict, + params_a: Dict[str, torch.nn.Parameter], + params_b: Dict[str, torch.nn.Parameter], + initial_scale: float = 1.0, +) -> Dict[str, object]: + total_sum = 0.0 + total_sq_sum = 0.0 + total_abs = 0.0 + total_elems = 0 + global_min: Optional[float] = None + global_max: Optional[float] = None + per_tensor: Dict[str, Dict[str, float]] = {} + + with torch.no_grad(): + for orig, safe in name_map.items(): + param_a = params_a.get(orig) + param_b = params_b.get(orig) + if param_a is None or param_b is None or param_b.shape != param_a.shape: + continue + u0 = float(initial_scale) * _initial_reparam_u( + param_a, param_b, u_params[safe].device + ) + delta = u_params[safe].detach().float() - u0 + if delta.numel() == 0: + continue + numel = int(delta.numel()) + delta_sum = float(delta.sum().item()) + delta_sq_sum = float(delta.pow(2).sum().item()) + delta_abs_sum = float(delta.abs().sum().item()) + delta_min = float(delta.min().item()) + delta_max = float(delta.max().item()) + per_tensor[orig] = { + "mean": delta_sum / float(numel), + "std": math.sqrt(max(delta_sq_sum / float(numel) - (delta_sum / float(numel)) ** 2, 0.0)), + "rms": math.sqrt(delta_sq_sum / float(numel)), + "mean_abs": delta_abs_sum / float(numel), + "min": delta_min, + "max": delta_max, + } + total_sum += delta_sum + total_sq_sum += delta_sq_sum + total_abs += delta_abs_sum + total_elems += numel + global_min = delta_min if global_min is None else min(global_min, delta_min) + global_max = delta_max if global_max is None else max(global_max, delta_max) + + if total_elems == 0: + return {"num_tensors": len(name_map), "num_elements": 0} + mean = total_sum / float(total_elems) + return { + "num_tensors": len(name_map), + "num_elements": total_elems, + "mean": mean, + "std": math.sqrt(max(total_sq_sum / float(total_elems) - mean ** 2, 0.0)), + "rms": math.sqrt(total_sq_sum / float(total_elems)), + "mean_abs": total_abs / float(total_elems), + "min": global_min, + "max": global_max, + "per_tensor": per_tensor, + } + + +def _build_gate_priors( + layer_a: torch.nn.Module, + layer_b: torch.nn.Module, + fisher_a: Dict[str, object], + fisher_b: Dict[str, object], + num_batches: int, + numels_a: Dict[str, int], + numels_b: Dict[str, int], + fisher_mode: str, + eps: float, + clamp_eps: float, +) -> Dict[str, torch.Tensor]: + """Return lambda priors for parameters that can be merged.""" + priors: Dict[str, torch.Tensor] = {} + params_b = {name: param for name, param in layer_b.named_parameters()} + for name, param_a in layer_a.named_parameters(): + param_b = params_b.get(name) + if param_b is None or param_b.shape != param_a.shape: + continue + if fisher_mode == "param": + fa = fisher_a[name] / max(num_batches, 1) + fb = fisher_b[name] / max(num_batches, 1) + denom = fa + fb + if not isinstance(denom, torch.Tensor): + denom = torch.tensor(float(denom)) + # If Fisher is uninformative, default to symmetric init. + prior = torch.where( + denom > eps, + fa / (denom + eps), + torch.full_like(denom, 0.5), + ) + prior = prior.clamp(clamp_eps, 1.0 - clamp_eps) + priors[name] = prior + else: + fa = fisher_a[name] / (max(num_batches, 1) * numels_a[name]) + fb = fisher_b[name] / (max(num_batches, 1) * numels_b[name]) + denom = fa + fb + if denom <= eps: + prior_val = 0.5 + else: + prior_val = float(fa / (denom + eps)) + prior_val = min(max(prior_val, clamp_eps), 1.0 - clamp_eps) + priors[name] = torch.tensor(prior_val, dtype=torch.float32) + return priors + + +def compute_fisher_gate_priors( + layer_a: torch.nn.Module, + layer_b: torch.nn.Module, + fisher_a: Dict[str, object], + fisher_b: Dict[str, object], + num_batches: int, + numels_a: Dict[str, int], + numels_b: Dict[str, int], + fisher_mode: str, + eps: float, + clamp_eps: float = 1e-4, +) -> Dict[str, torch.Tensor]: + """Compute Fisher prior gate lambdas (lambda_prior) for mergeable parameters.""" + return _build_gate_priors( + layer_a=layer_a, + layer_b=layer_b, + fisher_a=fisher_a, + fisher_b=fisher_b, + num_batches=num_batches, + numels_a=numels_a, + numels_b=numels_b, + fisher_mode=fisher_mode, + eps=eps, + clamp_eps=clamp_eps, + ) + + +_FISHER_DISTRIBUTION_QUANTILES = ( + ("p0", 0.0), + ("p1", 0.01), + ("p10", 0.10), + ("p25", 0.25), + ("p50", 0.50), + ("p75", 0.75), + ("p90", 0.90), + ("p95", 0.95), + ("p99", 0.99), + ("p99_9", 0.999), + ("p100", 1.0), +) + + +def _deterministic_fisher_sample( + values: torch.Tensor, + max_samples: int = 131_072, +) -> torch.Tensor: + """Return an evenly strided, deterministic CPU sample for quantiles.""" + flat = values.detach().float().reshape(-1) + if flat.numel() <= max_samples: + return flat + stride = max(1, math.ceil(flat.numel() / max_samples)) + return flat[::stride][:max_samples] + + +def _sampled_fisher_quantiles(sample: torch.Tensor) -> Dict[str, float]: + if sample.numel() == 0: + return {} + probabilities = torch.tensor( + [probability for _, probability in _FISHER_DISTRIBUTION_QUANTILES], + dtype=torch.float32, + device=sample.device, + ) + values = torch.quantile(sample.float(), probabilities) + return { + name: float(value.item()) + for (name, _), value in zip(_FISHER_DISTRIBUTION_QUANTILES, values) + } + + +def _summarize_fisher_distribution( + values: torch.Tensor, + eps: float, +) -> Dict[str, object]: + """Summarize one non-negative Fisher tensor without retaining it.""" + flat = values.detach().float().reshape(-1) + numel = int(flat.numel()) + if numel == 0: + return {"num_elements": 0} + finite = torch.isfinite(flat) + finite_count = int(finite.sum().item()) + if finite_count != numel: + finite_values = flat[finite] + else: + finite_values = flat + if finite_values.numel() == 0: + return { + "num_elements": numel, + "finite_count": 0, + "finite_ratio": 0.0, + } + + finite_numel = int(finite_values.numel()) + value_sum = float(finite_values.sum().item()) + value_sq_sum = float(finite_values.square().sum().item()) + mean = value_sum / float(finite_numel) + variance = max(value_sq_sum / float(finite_numel) - mean * mean, 0.0) + zero_count = int((finite_values == 0).sum().item()) + le_eps_count = int((finite_values <= eps).sum().item()) + sample = _deterministic_fisher_sample(finite_values) + return { + "num_elements": numel, + "finite_count": finite_count, + "finite_ratio": finite_count / float(numel), + "zero_count": zero_count, + "zero_ratio": zero_count / float(finite_numel), + "le_eps_count": le_eps_count, + "le_eps_ratio": le_eps_count / float(finite_numel), + "mean": mean, + "std": math.sqrt(variance), + "min": float(finite_values.min().item()), + "max": float(finite_values.max().item()), + "quantile_method": "deterministic_even_stride_sample", + "quantile_sample_count": int(sample.numel()), + "quantiles": _sampled_fisher_quantiles(sample), + } + + +def summarize_fisher_gate_prior_inputs( + layer_a: torch.nn.Module, + layer_b: torch.nn.Module, + fisher_a: Dict[str, object], + fisher_b: Dict[str, object], + num_batches: int, + numels_a: Dict[str, int], + numels_b: Dict[str, int], + fisher_mode: str, + eps: float, + param_subset: str = "all", +) -> Dict[str, object]: + """Summarize Fisher inputs that determine lambda priors without storing tensors.""" + params_b = {name: param for name, param in layer_b.named_parameters()} + per_tensor: Dict[str, Dict[str, object]] = {} + global_samples: Dict[str, List[torch.Tensor]] = { + "fa": [], + "fb": [], + "denom": [], + } + total_elems = 0 + total_fa = 0.0 + total_fb = 0.0 + total_denom = 0.0 + total_abs_diff = 0.0 + total_contrast = 0.0 + total_active = 0.0 + total_prior = 0.0 + total_prior_active = 0.0 + active_elems = 0 + + with torch.no_grad(): + for name, param_a in layer_a.named_parameters(): + param_b = params_b.get(name) + if param_b is None or param_b.shape != param_a.shape: + continue + if not _subset_allows_param(name, param_subset): + continue + + if fisher_mode == "param": + fa = (fisher_a[name] / max(num_batches, 1)).detach().float() + fb = (fisher_b[name] / max(num_batches, 1)).detach().float() + else: + fa_val = float( + fisher_a[name] + / (max(num_batches, 1) * max(numels_a.get(name, 1), 1)) + ) + fb_val = float( + fisher_b[name] + / (max(num_batches, 1) * max(numels_b.get(name, 1), 1)) + ) + fa = torch.tensor(fa_val, dtype=torch.float32) + fb = torch.tensor(fb_val, dtype=torch.float32) + + denom = fa + fb + active = denom > eps + prior = torch.where( + active, + fa / (denom + eps), + torch.full_like(denom, 0.5), + ) + contrast = (fa - fb).abs() / (denom + eps) + numel = int(denom.numel()) + active_count = int(active.sum().item()) + fa_sum = float(fa.sum().item()) + fb_sum = float(fb.sum().item()) + denom_sum = float(denom.sum().item()) + abs_diff_sum = float((fa - fb).abs().sum().item()) + contrast_sum = float(contrast.sum().item()) + prior_sum = float(prior.sum().item()) + if active_count > 0: + prior_active_mean = float(prior[active].mean().item()) + else: + prior_active_mean = 0.5 + + fa_distribution = _summarize_fisher_distribution(fa, eps) + fb_distribution = _summarize_fisher_distribution(fb, eps) + denom_distribution = _summarize_fisher_distribution(denom, eps) + global_samples["fa"].append(_deterministic_fisher_sample(fa)) + global_samples["fb"].append(_deterministic_fisher_sample(fb)) + global_samples["denom"].append(_deterministic_fisher_sample(denom)) + + per_tensor[name] = { + "num_elements": numel, + "fa_mean": fa_sum / float(numel), + "fb_mean": fb_sum / float(numel), + "denom_mean": denom_sum / float(numel), + "active_ratio": active_count / float(numel), + "mean_abs_fa_minus_fb": abs_diff_sum / float(numel), + "mean_relative_contrast": contrast_sum / float(numel), + "prior_mean": prior_sum / float(numel), + "prior_active_mean": prior_active_mean, + "fa_distribution": fa_distribution, + "fb_distribution": fb_distribution, + "denom_distribution": denom_distribution, + } + + total_elems += numel + total_fa += fa_sum + total_fb += fb_sum + total_denom += denom_sum + total_abs_diff += abs_diff_sum + total_contrast += contrast_sum + total_active += float(active_count) + total_prior += prior_sum + total_prior_active += prior_active_mean * float(active_count) + active_elems += active_count + + if total_elems == 0: + return {"num_tensors": 0, "num_elements": 0, "per_tensor": per_tensor} + + distributions = {} + for distribution_name, samples in global_samples.items(): + sample = torch.cat(samples) if samples else torch.empty(0, dtype=torch.float32) + distributions[distribution_name] = { + "quantile_method": "concatenated_per_tensor_even_stride_samples", + "quantile_sample_count": int(sample.numel()), + "quantiles": _sampled_fisher_quantiles(sample), + } + + return { + "num_tensors": len(per_tensor), + "num_elements": total_elems, + "fisher_mode": fisher_mode, + "eps": float(eps), + "param_subset": param_subset, + "fa_mean": total_fa / float(total_elems), + "fb_mean": total_fb / float(total_elems), + "denom_mean": total_denom / float(total_elems), + "active_ratio": total_active / float(total_elems), + "mean_abs_fa_minus_fb": total_abs_diff / float(total_elems), + "mean_relative_contrast": total_contrast / float(total_elems), + "prior_mean": total_prior / float(total_elems), + "prior_active_mean": ( + 0.5 if active_elems == 0 else total_prior_active / float(active_elems) + ), + "distributions": distributions, + "per_tensor": per_tensor, + } + + +class ReparamMergedLayer(torch.nn.Module): + """Virtual layer that merges parameters via W0/U reparameterization. + + Parameters of layer_a/layer_b are treated as frozen (detached). We train: + - gate logits s (lambda = sigmoid(s)) + - U (initialized as U0 = (W_a - W_b) / 2) + + Forward uses: + W_merge = W0 + (2 * lambda - 1) * U + where W0 = (W_a + W_b) / 2 + """ + + def __init__( + self, + layer_a: torch.nn.Module, + layer_b: torch.nn.Module, + gate_targets: Dict[str, object], + param_subset: str = "all", + clamp_eps: float = 1e-4, + tensor_rho: bool = False, + sequential_rho: bool = False, + additive_u: bool = False, + ) -> None: + super().__init__() + if sequential_rho and additive_u: + raise ValueError("sequential_rho and additive_u are mutually exclusive") + self.layer_a = layer_a + self.layer_b = layer_b + self.param_subset = param_subset + self.sequential_rho = bool(sequential_rho) + self.additive_u = bool(additive_u) + self._name_map: Dict[str, str] = {} + + self.gates = torch.nn.ParameterDict() + self.u = torch.nn.ParameterDict() + self.rho = torch.nn.ParameterDict() + + params_b = {name: param for name, param in layer_b.named_parameters()} + try: + device = next(layer_a.parameters()).device + except StopIteration: + device = torch.device("cpu") + + for name, param_a in layer_a.named_parameters(): + param_b = params_b.get(name) + if param_b is None or param_b.shape != param_a.shape: + continue + if not _subset_allows_param(name, self.param_subset): + continue + + target = gate_targets.get(name) + if target is None: + target_t = torch.tensor(0.5, device=device, dtype=torch.float32) + elif isinstance(target, torch.Tensor): + target_t = target.detach().to(device=device, dtype=torch.float32) + else: + target_t = torch.tensor(float(target), device=device, dtype=torch.float32) + + target_t = target_t.clamp(clamp_eps, 1.0 - clamp_eps) + s0 = _gate_logit_from_prior(target_t) + u0 = _initial_reparam_u(param_a, param_b, device) + if self.sequential_rho or self.additive_u: + # Both modes use an explicit additive FiT correction. Additive-U + # fixes rho at zero: W = W_F + U_add. + u0 = torch.zeros_like(u0) + + safe = name.replace(".", "__") + if safe in self.gates: + safe = f"{safe}_{len(self.gates)}" + self._name_map[name] = safe + self.gates[safe] = torch.nn.Parameter(s0) + self.u[safe] = torch.nn.Parameter(u0) + projection = _rho_projection(name) + if tensor_rho and projection is not None and projection not in self.rho: + self.rho[projection] = torch.nn.Parameter( + torch.zeros((), device=device, dtype=torch.float32) + ) + + def __getattr__(self, name: str): + # Delegate model-specific attributes (e.g. Qwen's `attention_type`) to + # the underlying layer so the parent forward doesn't break. + try: + return super().__getattr__(name) + except AttributeError as exc: + try: + layer_a = super().__getattr__("layer_a") + if hasattr(layer_a, name): + return getattr(layer_a, name) + except AttributeError: + pass + try: + layer_b = super().__getattr__("layer_b") + if hasattr(layer_b, name): + return getattr(layer_b, name) + except AttributeError: + pass + raise exc + + def _safe_for(self, orig: str) -> Optional[str]: + return self._name_map.get(orig) + + def gate_lambdas(self) -> Dict[str, torch.Tensor]: + out: Dict[str, torch.Tensor] = {} + for orig, safe in self._name_map.items(): + fisher_lambda = torch.sigmoid(self.gates[safe]).detach() + projection = _rho_projection(orig) + if projection is not None and projection in self.rho: + fisher_lambda = fisher_lambda + self.rho[projection].detach() * ( + 1.0 - fisher_lambda + ) + out[orig] = fisher_lambda + return out + + def rho_values(self) -> Dict[str, float]: + return { + name: float(value.detach().float().cpu()) + for name, value in self.rho.items() + } + + def _merged_params(self) -> Dict[str, torch.Tensor]: + params_a = {name: p for name, p in self.layer_a.named_parameters()} + params_b = {name: p for name, p in self.layer_b.named_parameters()} + merged_params: Dict[str, torch.Tensor] = {} + + for name, param_a in params_a.items(): + param_b = params_b.get(name) + safe = self._safe_for(name) + if safe is None or param_b is None or param_b.shape != param_a.shape: + merged_params[name] = param_a.detach() + continue + + projection = _rho_projection(name) + if self.additive_u: + merged_params[name] = _merge_reparam_param_additive_u( + param_a.detach(), + param_b.detach(), + self.gates[safe], + self.u[safe], + ) + elif projection is not None and projection in self.rho: + if self.sequential_rho: + merged_params[name] = _merge_reparam_param_sequential_rho( + param_a.detach(), + param_b.detach(), + self.gates[safe], + self.u[safe], + self.rho[projection], + ) + else: + merged_params[name] = _merge_reparam_param_rho( + param_a.detach(), + param_b.detach(), + self.gates[safe], + self.u[safe], + self.rho[projection], + ) + else: + merged_params[name] = _merge_reparam_param( + param_a.detach(), + param_b.detach(), + self.gates[safe], + self.u[safe], + ) + return merged_params + + def forward(self, *args, **kwargs): + if _functional_call is None: + raise RuntimeError( + "Reparam distillation requires torch.func.functional_call" + ) + + merged_params = self._merged_params() + return _functional_call(self.layer_a, merged_params, args, kwargs) + + def materialize_into_layer_a(self) -> int: + merged = 0 + params_a = {name: p for name, p in self.layer_a.named_parameters()} + params_b = {name: p for name, p in self.layer_b.named_parameters()} + with torch.no_grad(): + for orig, safe in self._name_map.items(): + param_a = params_a.get(orig) + param_b = params_b.get(orig) + if param_a is None or param_b is None or param_b.shape != param_a.shape: + continue + projection = _rho_projection(orig) + if self.additive_u: + merged_param = _merge_reparam_param_additive_u_no_grad( + param_a.detach(), + param_b.detach(), + self.gates[safe], + self.u[safe], + ) + elif projection is not None and projection in self.rho: + if self.sequential_rho: + merged_param = _merge_reparam_param_sequential_rho_no_grad( + param_a.detach(), + param_b.detach(), + self.gates[safe], + self.u[safe], + self.rho[projection], + ) + else: + merged_param = _merge_reparam_param_rho_no_grad( + param_a.detach(), + param_b.detach(), + self.gates[safe], + self.u[safe], + self.rho[projection], + ) + else: + merged_param = _merge_reparam_param_no_grad( + param_a.detach(), + param_b.detach(), + self.gates[safe], + self.u[safe], + ) + param_a.copy_(merged_param.to(dtype=param_a.dtype)) + merged += 1 + return merged + + +def _sequential_u_fisher_orthogonality( + reparam_layer: ReparamMergedLayer, +) -> Dict[str, object]: + """Summarize additive FiT U versus the original Fisher displacement. + + The fixed reference direction is Delta_F = W_F - W_anchor, before rho or + U training. Statistics are accumulated without concatenating the large + projection tensors. + """ + if not (reparam_layer.sequential_rho or reparam_layer.additive_u): + return {} + params_a = dict(reparam_layer.layer_a.named_parameters()) + params_b = dict(reparam_layer.layer_b.named_parameters()) + accum: Dict[str, Dict[str, float]] = {} + + def add(group: str, u: torch.Tensor, delta_f: torch.Tensor) -> None: + bucket = accum.setdefault( + group, + {"dot": 0.0, "u_sq": 0.0, "fisher_sq": 0.0, "num_elements": 0.0}, + ) + bucket["dot"] += float((u * delta_f).sum().item()) + bucket["u_sq"] += float(u.square().sum().item()) + bucket["fisher_sq"] += float(delta_f.square().sum().item()) + bucket["num_elements"] += float(u.numel()) + + with torch.no_grad(): + for orig, safe in reparam_layer._name_map.items(): + projection = _rho_projection(orig) + if projection is None: + continue + if reparam_layer.sequential_rho and projection not in reparam_layer.rho: + continue + param_a = params_a.get(orig) + param_b = params_b.get(orig) + if param_a is None or param_b is None or param_a.shape != param_b.shape: + continue + lam = torch.sigmoid(reparam_layer.gates[safe].detach().float()) + a = param_a.detach().to(device=lam.device, dtype=torch.float32) + b = param_b.detach().to(device=lam.device, dtype=torch.float32) + delta_f = (b + lam * (a - b)) - a + u = reparam_layer.u[safe].detach().float() + add(projection, u, delta_f) + add("global", u, delta_f) + + result: Dict[str, object] = {} + for group, values in accum.items(): + u_norm = math.sqrt(max(values["u_sq"], 0.0)) + fisher_norm = math.sqrt(max(values["fisher_sq"], 0.0)) + denom = u_norm * fisher_norm + cosine = None if denom == 0.0 else values["dot"] / denom + if cosine is not None: + cosine = max(-1.0, min(1.0, cosine)) + result[group] = { + "num_elements": int(values["num_elements"]), + "cosine_u_vs_fisher_delta": cosine, + "orthogonal_fraction_of_u": ( + None if cosine is None else math.sqrt(max(0.0, 1.0 - cosine * cosine)) + ), + "u_norm": u_norm, + "fisher_delta_norm": fisher_norm, + "u_over_fisher_delta_norm": ( + None if fisher_norm == 0.0 else u_norm / fisher_norm + ), + "projection_coefficient_on_fisher": ( + None + if values["fisher_sq"] == 0.0 + else values["dot"] / values["fisher_sq"] + ), + } + return result + + +def distill_reparam_merge( + student_model: torch.nn.Module, + student_parent: object, + student_layer_attr: str, + student_layers: List[torch.nn.Module], + teacher_model: torch.nn.Module, + teacher_parent: object, + teacher_layer_attr: str, + teacher_layers: List[torch.nn.Module], + layer_idx: int, + gate_lambdas: Dict[str, object], + dataloader, + args: argparse.Namespace, + progressive_cycle: Optional[int] = None, + progressive_total: Optional[int] = None, +) -> Tuple[int, Dict[str, torch.Tensor], Dict[str, object]]: + """Reparameterized distillation that materializes a fused layer into layer_a. + + Trains U and gate logits s (lambda = sigmoid(s)) using: + - composition MSE + distill-KL + - eta * ||lambda - lambda_gate||^2 + gamma * ||U - U0||^2 + """ + requested_epochs = float(args.distill_epochs) + skip_train = bool(getattr(args, "reparam_skip_train", False)) + total_epochs = 0.0 if skip_train else requested_epochs + + hidden_mse_weight = float(getattr(args, "distill_hidden_mse_weight", 1.0)) + if hidden_mse_weight < 0.0: + raise SystemExit("--distill_hidden_mse_weight must be >= 0") + attn_mse_weight = float(getattr(args, "distill_attn_mse_weight", 0.0)) + if attn_mse_weight < 0.0: + raise SystemExit("--distill_attn_mse_weight must be >= 0") + mlp_mse_weight = float(getattr(args, "distill_mlp_mse_weight", 0.0)) + if mlp_mse_weight < 0.0: + raise SystemExit("--distill_mlp_mse_weight must be >= 0") + param_subset = str(getattr(args, "reparam_param_subset", "all")) + if param_subset not in {"all", "mlp", "attn", "down_proj"}: + raise SystemExit( + "--reparam_param_subset must be one of: all, mlp, attn, down_proj" + ) + train_subset = _resolve_reparam_train_subset( + param_subset, + getattr(args, "reparam_train_subset", "same"), + ) + fisher_init_subset = _resolve_reparam_fisher_init_subset( + param_subset, + getattr(args, "reparam_fisher_init_subset", "same"), + ) + + kl_weight = float(args.distill_kl_weight) + kl_temp = float(args.distill_kl_temp) + if kl_weight < 0.0: + raise SystemExit("--distill_kl_weight must be >= 0") + if kl_temp <= 0.0: + raise SystemExit("--distill_kl_temp must be > 0") + + rho_objective = str(getattr(args, "reparam_rho_objective", "none")) + valid_rho_objectives = {"none", "full", "hidden_kl", "kl_only"} + if rho_objective not in valid_rho_objectives: + raise SystemExit( + "--reparam_rho_objective must be one of: " + + ", ".join(sorted(valid_rho_objectives)) + ) + rho_enabled = rho_objective != "none" + rho_schedule = str(getattr(args, "reparam_rho_schedule", "joint")) + if rho_schedule not in {"joint", "sequential"}: + raise SystemExit("--reparam_rho_schedule must be joint or sequential") + if not rho_enabled and rho_schedule == "sequential": + raise SystemExit("sequential rho schedule requires an enabled rho objective") + rho_epochs = float(getattr(args, "reparam_rho_epochs", 1.0)) + if rho_epochs <= 0.0: + raise SystemExit("--reparam_rho_epochs must be > 0") + sequential_rho = rho_enabled and rho_schedule == "sequential" + if sequential_rho and abs(rho_epochs - round(rho_epochs)) > 1e-8: + raise SystemExit("sequential rho currently requires integer --reparam_rho_epochs") + if sequential_rho and not skip_train: + total_epochs = rho_epochs + requested_epochs + additive_u = bool(getattr(args, "reparam_additive_u", False)) + if additive_u and rho_enabled: + raise SystemExit("--reparam_additive_u cannot be combined with rho") + rho_lr = float(getattr(args, "reparam_rho_lr", 2e-3)) + rho_min = float(getattr(args, "reparam_rho_min", -1.0)) + rho_max = float(getattr(args, "reparam_rho_max", 2.0)) + if rho_lr <= 0.0: + raise SystemExit("--reparam_rho_lr must be > 0") + if rho_min >= rho_max: + raise SystemExit("--reparam_rho_min must be below --reparam_rho_max") + if rho_enabled and kl_weight <= 0.0 and rho_objective in {"hidden_kl", "kl_only"}: + raise SystemExit("rho objective requires nonzero distillation KL weight") + + eta = float(getattr(args, "reparam_eta", 0.0)) + gamma = float(getattr(args, "reparam_gamma", 0.0)) + if eta < 0.0: + raise SystemExit("--reparam_eta must be >= 0") + if gamma < 0.0: + raise SystemExit("--reparam_gamma must be >= 0") + attn_reg_scale = float(getattr(args, "reparam_attn_reg_scale", 1.0)) + mlp_reg_scale = float(getattr(args, "reparam_mlp_reg_scale", 1.0)) + if attn_reg_scale < 0.0: + raise SystemExit("--reparam_attn_reg_scale must be >= 0") + if mlp_reg_scale < 0.0: + raise SystemExit("--reparam_mlp_reg_scale must be >= 0") + if ( + total_epochs > 0.0 + and hidden_mse_weight == 0.0 + and attn_mse_weight == 0.0 + and mlp_mse_weight == 0.0 + and kl_weight == 0.0 + and eta == 0.0 + and gamma == 0.0 + ): + raise SystemExit( + "Reparam distillation has no active loss terms. " + "Enable hidden/attention/MLP MSE, KL, or at least one reparam regularizer." + ) + + if not gate_lambdas: + raise SystemExit("Reparam distillation requires non-empty gate lambdas.") + + layer_a = student_layers[layer_idx] + layer_b = student_layers[layer_idx + 1] + + reparam_layer = ReparamMergedLayer( + layer_a, + layer_b, + gate_lambdas, + param_subset=param_subset, + clamp_eps=1e-4, + tensor_rho=rho_enabled, + sequential_rho=sequential_rho, + additive_u=additive_u, + ) + if not reparam_layer._name_map: + raise RuntimeError( + "No mergeable parameters found for reparam distillation under " + f"--reparam_param_subset={param_subset!r}." + ) + + teacher_attn = None + student_attn = None + if total_epochs > 0.0 and attn_mse_weight > 0.0: + try: + teacher_attn = find_attention_module(teacher_layers[layer_idx + 1]) + student_attn = find_attention_module(reparam_layer.layer_a) + except ValueError as exc: + raise SystemExit( + "Attention-output preservation was requested but an attention module " + f"could not be resolved: {exc}" + ) from exc + + teacher_mlp = None + student_mlp = None + if total_epochs > 0.0 and mlp_mse_weight > 0.0: + try: + teacher_mlp = find_mlp_module(teacher_layers[layer_idx + 1]) + student_mlp = find_mlp_module(reparam_layer.layer_a) + except ValueError as exc: + raise SystemExit( + "MLP-output preservation was requested but an MLP module could not be " + f"resolved: {exc}" + ) from exc + + # Virtual layer list: replace layer_a with reparam layer and remove layer_b. + virtual_layers = list(student_layers) + virtual_layers[layer_idx] = reparam_layer + del virtual_layers[layer_idx + 1] + + # Only selected reparam (U, s) tensors are trainable. Parameters outside + # train_subset are still materialized from their Fisher-prior initialization. + for param in student_model.parameters(): + param.requires_grad_(False) + trainable_safe_names = set() + train_family_counts: Dict[str, int] = {"attn": 0, "mlp": 0, "other": 0} + for orig, safe in reparam_layer._name_map.items(): + is_trainable = _subset_allows_param(orig, train_subset) + reparam_layer.gates[safe].requires_grad_( + is_trainable and not rho_enabled and not additive_u + ) + reparam_layer.u[safe].requires_grad_(is_trainable) + if is_trainable: + trainable_safe_names.add(safe) + train_family_counts[_classify_param_family(orig)] += 1 + for rho in reparam_layer.rho.values(): + rho.requires_grad_(rho_enabled) + trainable_base_params = [ + param + for param in itertools.chain( + reparam_layer.gates.parameters(), + reparam_layer.u.parameters(), + ) + if param.requires_grad + ] + trainable_rho_params = [ + param for param in reparam_layer.rho.parameters() if param.requires_grad + ] + trainable_reparam_params = [*trainable_base_params, *trainable_rho_params] + if total_epochs > 0.0 and not trainable_reparam_params: + raise SystemExit( + "Reparam training requested but --reparam_train_subset selects no " + "materialized parameters." + ) + + do_train = total_epochs > 0.0 + if do_train: + teacher_model.eval() + student_model.train() + elif skip_train: + print("[reparam] skip_train enabled; using Fisher-prior initialization only.") + + # Rough memory heads-up (esp. when --fisher_mode param makes per-element gates). + total_gate_elems = sum(int(p.numel()) for p in reparam_layer.gates.parameters()) + total_u_elems = sum(int(p.numel()) for p in reparam_layer.u.parameters()) + gate_mib = total_gate_elems * 4.0 / (1024.0 * 1024.0) + u_mib = total_u_elems * 4.0 / (1024.0 * 1024.0) + family_counts: Dict[str, int] = {"attn": 0, "mlp": 0, "other": 0} + for orig in reparam_layer._name_map: + family_counts[_classify_param_family(orig)] += 1 + lambda_init_summary = _lambda_summary_from_gates( + reparam_layer._name_map, + reparam_layer.gates, + ) + print( + f"[reparam] subset={param_subset} gates={len(reparam_layer.gates)} " + f"(attn={family_counts['attn']}, mlp={family_counts['mlp']}, other={family_counts['other']}) " + f"train_subset={train_subset} " + f"(attn={train_family_counts['attn']}, mlp={train_family_counts['mlp']}, " + f"other={train_family_counts['other']}) " + f"elems={total_gate_elems} (~{gate_mib:.1f} MiB), " + f"U_elems={total_u_elems} (~{u_mib:.1f} MiB; +optimizer state)" + ) + print( + "[reparam] lambda_init " + f"mean={lambda_init_summary.get('mean')} " + f"std={lambda_init_summary.get('std')} " + f"min={lambda_init_summary.get('min')} " + f"max={lambda_init_summary.get('max')} " + f"mean_abs_from_0.5={lambda_init_summary.get('mean_abs_from_0_5')}" + ) + if rho_enabled: + print( + f"[reparam-rho] objective={rho_objective} schedule={rho_schedule} " + f"rho_epochs={rho_epochs if sequential_rho else 0.0} lr={rho_lr} " + f"bounds=[{rho_min}, {rho_max}] projections={sorted(reparam_layer.rho)}" + ) + if additive_u: + print("[reparam] additive_u enabled: W = W_F + U_add, U_add initialized at zero") + + optimizer = None + if do_train: + groups = [] + if trainable_base_params: + groups.append( + { + "params": trainable_base_params, + "lr": float(args.distill_lr), + "weight_decay": float(args.distill_weight_decay), + } + ) + if trainable_rho_params: + groups.append( + { + "params": trainable_rho_params, + "lr": rho_lr, + "weight_decay": 0.0, + } + ) + optimizer = torch.optim.AdamW(groups) + + device_type = torch.device(args.device).type + amp_dtype = None + if args.dtype == "float16": + amp_dtype = torch.float16 + elif args.dtype == "bfloat16": + amp_dtype = torch.bfloat16 + use_amp = do_train and amp_dtype is not None and device_type == "cuda" + use_scaler = use_amp and amp_dtype == torch.float16 + if rho_enabled and use_scaler: + raise SystemExit("tensor-rho gradient routing requires bf16 or fp32 training") + scaler = torch.cuda.amp.GradScaler() if use_scaler else None + teacher_runtime_device = torch.device(args.distill_teacher_device or args.device) + if teacher_model is not None: + try: + teacher_runtime_device = next(teacher_model.parameters()).device + except StopIteration: + pass + + full_epochs = int(total_epochs) if do_train else 0 + fractional = (total_epochs - full_epochs) if do_train else 0.0 + if fractional < 1e-8: + fractional = 0.0 + + epoch_plan = [(epoch_idx, None) for epoch_idx in range(full_epochs)] + if fractional > 0: + try: + batches_per_epoch = len(dataloader) + except TypeError as exc: + raise SystemExit( + "Fractional distill epochs require a dataloader with finite length." + ) from exc + if batches_per_epoch > 0: + frac_batches = int(round(fractional * batches_per_epoch)) + if frac_batches <= 0: + frac_batches = 1 + epoch_plan.append((full_epochs, frac_batches)) + + grad_accum = int(getattr(args, "distill_grad_accum_steps", 1)) + if grad_accum <= 0: + raise SystemExit("--distill_grad_accum_steps must be >= 1") + if rho_enabled and grad_accum != 1: + raise SystemExit("tensor-rho gradient routing currently requires grad accumulation 1") + + log_steps = int(getattr(args, "distill_log_steps", 100)) + max_grad_norm = getattr(args, "distill_max_grad_norm", 1.0) + + params_a = {name: p for name, p in layer_a.named_parameters()} + params_b = {name: p for name, p in layer_b.named_parameters()} + + first_grad_summary: Dict[str, object] = {} + rho_after_phase: Optional[Dict[str, float]] = None + step = 0 + for epoch_idx, max_batches in epoch_plan: + if sequential_rho: + phase = "rho" if epoch_idx < int(round(rho_epochs)) else "u" + for param in trainable_base_params: + param.requires_grad_(phase == "u") + for param in trainable_rho_params: + param.requires_grad_(phase == "rho") + if phase == "u" and rho_after_phase is None: + rho_after_phase = reparam_layer.rho_values() + print(f"[reparam-rho] rho phase complete values={rho_after_phase}") + else: + phase = "joint" + if max_batches is None: + epoch_iter = dataloader + else: + epoch_iter = itertools.islice(dataloader, max_batches) + iterator = epoch_iter + if tqdm is not None and _tqdm_enabled(): + if progressive_cycle is not None: + if progressive_total is not None: + desc = ( + f"Reparam (cycle {progressive_cycle}/{progressive_total}, " + f"epoch {epoch_idx+1})" + ) + else: + desc = f"Reparam (cycle {progressive_cycle}, epoch {epoch_idx+1})" + else: + desc = f"Reparam (epoch {epoch_idx+1})" + iterator = tqdm(epoch_iter, desc=desc, unit="batch", total=max_batches) + + for batch in iterator: + input_ids = batch[0].to(args.device) + attention_mask = batch[1].to(args.device) + teacher_ids = input_ids.to(teacher_runtime_device) + teacher_mask = attention_mask.to(teacher_runtime_device) + + teacher_depth = layer_idx + 2 + student_depth = layer_idx + 1 + + autocast_ctx = ( + torch.autocast(device_type=device_type, dtype=amp_dtype) + if use_amp + else nullcontext() + ) + with autocast_ctx: + teacher_attn_ctx = ( + capture_module_output(teacher_attn) + if teacher_attn is not None + else nullcontext({"output": None}) + ) + teacher_mlp_ctx = ( + capture_module_output(teacher_mlp) + if teacher_mlp is not None + else nullcontext({"output": None}) + ) + with torch.no_grad(): + with teacher_attn_ctx as teacher_attn_cache, teacher_mlp_ctx as teacher_mlp_cache: + teacher_hidden = forward_truncated( + teacher_parent, + teacher_layer_attr, + teacher_layers, + teacher_depth, + teacher_ids, + attention_mask=teacher_mask, + ) + + student_attn_ctx = ( + capture_module_output(student_attn) + if student_attn is not None + else nullcontext({"output": None}) + ) + student_mlp_ctx = ( + capture_module_output(student_mlp) + if student_mlp is not None + else nullcontext({"output": None}) + ) + with student_attn_ctx as student_attn_cache, student_mlp_ctx as student_mlp_cache: + student_hidden = forward_truncated( + student_parent, + student_layer_attr, + virtual_layers, + student_depth, + input_ids, + attention_mask=attention_mask, + ) + + if teacher_hidden.device != student_hidden.device: + teacher_hidden = teacher_hidden.to(student_hidden.device) + + mse_loss = None + if hidden_mse_weight > 0.0: + diff = student_hidden - teacher_hidden + mse_loss = _masked_hidden_mse(diff, attention_mask) + if mse_loss is None: + continue + + attn_aux_loss = None + if attn_mse_weight > 0.0: + teacher_attn_hidden = teacher_attn_cache.get("output") + student_attn_hidden = student_attn_cache.get("output") + if teacher_attn_hidden is None or student_attn_hidden is None: + raise RuntimeError( + "Attention-output preservation is enabled, but the forward " + "hook did not capture attention outputs." + ) + if teacher_attn_hidden.device != student_attn_hidden.device: + teacher_attn_hidden = teacher_attn_hidden.to(student_attn_hidden.device) + attn_aux_loss = _masked_hidden_mse( + student_attn_hidden - teacher_attn_hidden, + attention_mask, + ) + if attn_aux_loss is None: + continue + + mlp_aux_loss = None + if mlp_mse_weight > 0.0: + teacher_mlp_hidden = teacher_mlp_cache.get("output") + student_mlp_hidden = student_mlp_cache.get("output") + if teacher_mlp_hidden is None or student_mlp_hidden is None: + raise RuntimeError( + "MLP-output preservation is enabled, but the forward hook " + "did not capture MLP outputs." + ) + if teacher_mlp_hidden.device != student_mlp_hidden.device: + teacher_mlp_hidden = teacher_mlp_hidden.to(student_mlp_hidden.device) + mlp_aux_loss = _masked_hidden_mse( + student_mlp_hidden - teacher_mlp_hidden, + attention_mask, + ) + if mlp_aux_loss is None: + continue + + kl_loss = None + if kl_weight > 0.0: + with torch.no_grad(): + teacher_outputs = teacher_model( + input_ids=teacher_ids, + attention_mask=teacher_mask, + use_cache=False, + ) + teacher_logits = teacher_outputs.logits + + virtual_container = torch.nn.ModuleList(virtual_layers) + with temporary_layers( + student_parent, student_layer_attr, virtual_container + ): + student_outputs = student_model( + input_ids=input_ids, + attention_mask=attention_mask, + use_cache=False, + ) + student_logits = student_outputs.logits + kl_loss = _masked_kl( + teacher_logits, + student_logits, + attention_mask, + temp=kl_temp, + detach_p=True, + chunk_size=int(getattr(args, "kl_chunk_size", 16384)), + ) + if kl_loss is None: + continue + + lambda_reg = None + if eta > 0.0: + reg_sum: Optional[torch.Tensor] = None + reg_elems = 0 + for orig, safe in reparam_layer._name_map.items(): + if safe not in trainable_safe_names: + continue + lam = torch.sigmoid(reparam_layer.gates[safe]).float() + target = gate_lambdas.get(orig) + if target is None: + target_t = 0.5 + elif isinstance(target, torch.Tensor): + target_t = target.to(device=lam.device, dtype=lam.dtype) + else: + target_t = float(target) + diff_lam = lam - target_t + family = _classify_param_family(orig) + scale = _family_reg_scale( + family, + attn_scale=attn_reg_scale, + mlp_scale=mlp_reg_scale, + ) + if scale <= 0.0: + continue + part = diff_lam.pow(2).sum() * scale + reg_sum = part if reg_sum is None else reg_sum + part + reg_elems += int(float(diff_lam.numel()) * scale) + if reg_elems > 0 and reg_sum is not None: + lambda_reg = reg_sum / float(reg_elems) + + u_reg = None + if gamma > 0.0: + reg_sum: Optional[torch.Tensor] = None + reg_elems = 0 + for orig, safe in reparam_layer._name_map.items(): + if safe not in trainable_safe_names: + continue + u = reparam_layer.u[safe].float() + param_a = params_a.get(orig) + param_b = params_b.get(orig) + if param_a is None or param_b is None or param_b.shape != param_a.shape: + continue + u0 = ( + torch.zeros_like(u) + if sequential_rho or additive_u + else _initial_reparam_u(param_a, param_b, u.device) + ) + diff_u = u - u0 + family = _classify_param_family(orig) + scale = _family_reg_scale( + family, + attn_scale=attn_reg_scale, + mlp_scale=mlp_reg_scale, + ) + if scale <= 0.0: + continue + part = diff_u.pow(2).sum() * scale + reg_sum = part if reg_sum is None else reg_sum + part + reg_elems += int(float(diff_u.numel()) * scale) + if reg_elems > 0 and reg_sum is not None: + u_reg = reg_sum / float(reg_elems) + + total_loss = None + total_loss = _add_weighted_loss(total_loss, mse_loss, hidden_mse_weight) + total_loss = _add_weighted_loss(total_loss, attn_aux_loss, attn_mse_weight) + total_loss = _add_weighted_loss(total_loss, mlp_aux_loss, mlp_mse_weight) + total_loss = _add_weighted_loss(total_loss, kl_loss, kl_weight * (kl_temp ** 2)) + total_loss = _add_weighted_loss(total_loss, lambda_reg, eta) + total_loss = _add_weighted_loss(total_loss, u_reg, gamma) + if total_loss is None: + continue + + rho_loss = None + rho_grads = None + if rho_enabled and (not sequential_rho or phase == "rho"): + if rho_objective in {"full", "hidden_kl"}: + rho_loss = _add_weighted_loss( + rho_loss, mse_loss, hidden_mse_weight + ) + if rho_objective == "full": + rho_loss = _add_weighted_loss( + rho_loss, mlp_aux_loss, mlp_mse_weight + ) + rho_loss = _add_weighted_loss( + rho_loss, kl_loss, kl_weight * (kl_temp ** 2) + ) + if rho_loss is None: + raise RuntimeError( + f"rho objective {rho_objective!r} has no active loss term" + ) + if not sequential_rho: + rho_grads = torch.autograd.grad( + rho_loss, + trainable_rho_params, + retain_graph=True, + allow_unused=False, + ) + + backward_loss = rho_loss if sequential_rho and phase == "rho" else total_loss + if backward_loss is None: + raise RuntimeError(f"no active backward loss for phase {phase!r}") + if grad_accum > 1: + backward_loss = backward_loss / grad_accum + if use_scaler: + scaler.scale(backward_loss).backward() + else: + backward_loss.backward() + + if rho_grads is not None: + for rho_param, rho_grad in zip(trainable_rho_params, rho_grads): + rho_param.grad = rho_grad.detach() + + if (step + 1) % grad_accum == 0: + if use_scaler: + scaler.unscale_(optimizer) + if phase not in first_grad_summary: + trainable_gates = [ + param + for safe, param in reparam_layer.gates.items() + if safe in trainable_safe_names + ] + trainable_u = [ + param + for safe, param in reparam_layer.u.items() + if safe in trainable_safe_names + ] + trainable_rho = list(reparam_layer.rho.parameters()) + phase_grad_summary = { + "step": step + 1, + "phase": phase, + "gate": _grad_debug_summary(trainable_gates), + "u": _grad_debug_summary(trainable_u), + "rho": _grad_debug_summary(trainable_rho), + } + first_grad_summary[phase] = phase_grad_summary + print( + "[reparam] first_grad " + f"phase={phase} step={phase_grad_summary['step']} " + f"gate_l2={phase_grad_summary['gate']['l2']:.6e} " + f"gate_mean_abs={phase_grad_summary['gate']['mean_abs']} " + f"gate_max_abs={phase_grad_summary['gate']['max_abs']:.6e} " + f"u_l2={phase_grad_summary['u']['l2']:.6e} " + f"u_mean_abs={phase_grad_summary['u']['mean_abs']} " + f"u_max_abs={phase_grad_summary['u']['max_abs']:.6e} " + f"rho_l2={phase_grad_summary['rho']['l2']:.6e}" + ) + if max_grad_norm is not None: + if trainable_base_params and (not sequential_rho or phase == "u"): + torch.nn.utils.clip_grad_norm_( + trainable_base_params, + float(max_grad_norm), + ) + if trainable_rho_params and (not sequential_rho or phase == "rho"): + torch.nn.utils.clip_grad_norm_( + trainable_rho_params, + float(max_grad_norm), + ) + if use_scaler: + scaler.step(optimizer) + scaler.update() + else: + optimizer.step() + if rho_enabled and (not sequential_rho or phase == "rho"): + with torch.no_grad(): + for rho in reparam_layer.rho.values(): + rho.clamp_(rho_min, rho_max) + optimizer.zero_grad(set_to_none=True) + + if log_steps and (step == 0 or (step + 1) % log_steps == 0): + log_parts = [f"phase={phase}", f"loss={total_loss.item():.6e}"] + if rho_loss is not None: + log_parts.append(f"rho_loss={rho_loss.item():.6e}") + if mse_loss is not None: + log_parts.append(f"mse={mse_loss.item():.6e}") + else: + log_parts.append("mse=disabled") + if attn_aux_loss is not None: + log_parts.append(f"attn_mse={attn_aux_loss.item():.6e}") + elif attn_mse_weight > 0.0: + log_parts.append("attn_mse=nan") + if mlp_aux_loss is not None: + log_parts.append(f"mlp_mse={mlp_aux_loss.item():.6e}") + elif mlp_mse_weight > 0.0: + log_parts.append("mlp_mse=nan") + if kl_loss is not None: + log_parts.append(f"kl={kl_loss.item():.6e}") + if lambda_reg is not None: + log_parts.append(f"lam_reg={lambda_reg.item():.6e}") + if u_reg is not None: + log_parts.append(f"u_reg={u_reg.item():.6e}") + lambda_now = _lambda_summary_from_gates( + reparam_layer._name_map, + reparam_layer.gates, + ) + log_parts.append(f"lambda_mean={lambda_now.get('mean')}") + log_parts.append(f"lambda_std={lambda_now.get('std')}") + log_parts.append( + f"lambda_abs0.5={lambda_now.get('mean_abs_from_0_5')}" + ) + if rho_enabled: + log_parts.append(f"rho={reparam_layer.rho_values()}") + print( + f"[reparam] epoch={epoch_idx+1} step={step+1} " + " ".join(log_parts) + ) + # Release graph-heavy batch tensors before the next forward. On 70B + # reparam runs, AdamW state leaves little headroom, so carrying the + # previous logits/outputs into the next batch can trip OOM. + teacher_outputs = None + teacher_logits = None + student_outputs = None + student_logits = None + teacher_hidden = None + student_hidden = None + teacher_attn_hidden = None + student_attn_hidden = None + teacher_mlp_hidden = None + student_mlp_hidden = None + teacher_attn_cache = None + teacher_mlp_cache = None + student_attn_cache = None + student_mlp_cache = None + diff = None + mse_loss = None + attn_aux_loss = None + mlp_aux_loss = None + kl_loss = None + lambda_reg = None + u_reg = None + rho_loss = None + rho_grads = None + total_loss = None + if device_type == "cuda" and torch.cuda.is_available(): + gc.collect() + torch.cuda.empty_cache() + + step += 1 + + final_lambdas = reparam_layer.gate_lambdas() + lambda_final_summary = _tensor_debug_summary(final_lambdas) + lambda_delta_from_init = _lambda_delta_summary(final_lambdas, gate_lambdas) + u_delta_summary = _u_delta_debug_summary( + reparam_layer._name_map, + reparam_layer.u, + params_a, + params_b, + initial_scale=0.0 if sequential_rho or additive_u else 1.0, + ) + u_fisher_orthogonality = _sequential_u_fisher_orthogonality(reparam_layer) + merged = reparam_layer.materialize_into_layer_a() + stats: Dict[str, object] = { + "enabled": True, + "epochs": total_epochs, + "requested_epochs": requested_epochs, + "skip_train": skip_train, + "trained": bool(do_train), + "lr": float(args.distill_lr), + "hidden_mse_weight": hidden_mse_weight, + "attn_mse_weight": attn_mse_weight, + "mlp_mse_weight": mlp_mse_weight, + "eta": eta, + "gamma": gamma, + "attn_reg_scale": attn_reg_scale, + "mlp_reg_scale": mlp_reg_scale, + "param_subset": param_subset, + "train_subset": train_subset, + "num_gates": len(final_lambdas), + "num_attn_gates": family_counts["attn"], + "num_mlp_gates": family_counts["mlp"], + "num_other_gates": family_counts["other"], + "num_trainable_attn_gates": train_family_counts["attn"], + "num_trainable_mlp_gates": train_family_counts["mlp"], + "num_trainable_other_gates": train_family_counts["other"], + "lambda_init_summary": lambda_init_summary, + "lambda_final_summary": lambda_final_summary, + "lambda_delta_from_init": lambda_delta_from_init, + "first_grad_summary": first_grad_summary, + "u_delta_summary": u_delta_summary, + "rho_objective": rho_objective, + "rho_schedule": rho_schedule, + "additive_u": additive_u, + "rho_epochs": rho_epochs if sequential_rho else 0.0, + "rho_lr": rho_lr if rho_enabled else None, + "rho_bounds": [rho_min, rho_max] if rho_enabled else None, + "rho_after_phase": rho_after_phase, + "rho_final": reparam_layer.rho_values(), + "u_fisher_orthogonality": u_fisher_orthogonality, + } + return merged, final_lambdas, stats + + +class LoRALinear(torch.nn.Module): + def __init__( + self, + base: torch.nn.Linear, + rank: int, + alpha: float, + dropout: float, + ) -> None: + super().__init__() + if rank <= 0: + raise ValueError("LoRA rank must be positive") + self.base = base + self.rank = int(rank) + self.alpha = float(alpha) + self.scaling = self.alpha / float(self.rank) + self.enabled = True + if dropout > 0: + self.dropout = torch.nn.Dropout(dropout) + else: + self.dropout = torch.nn.Identity() + + self.lora_A = torch.nn.Linear(base.in_features, self.rank, bias=False) + self.lora_B = torch.nn.Linear(self.rank, base.out_features, bias=False) + torch.nn.init.kaiming_uniform_(self.lora_A.weight, a=math.sqrt(5)) + torch.nn.init.zeros_(self.lora_B.weight) + + self.lora_A.to(device=base.weight.device, dtype=base.weight.dtype) + self.lora_B.to(device=base.weight.device, dtype=base.weight.dtype) + self.merged = False + + def lora_parameters(self) -> List[torch.nn.Parameter]: + return [*self.lora_A.parameters(), *self.lora_B.parameters()] + + def forward(self, x: torch.Tensor) -> torch.Tensor: + result = self.base(x) + if self.merged or not self.enabled: + return result + lora_out = self.lora_B(self.lora_A(self.dropout(x))) + return result + lora_out * self.scaling + + def merge(self) -> None: + if self.merged: + return + delta = torch.matmul(self.lora_B.weight, self.lora_A.weight) + delta = delta.to(dtype=self.base.weight.dtype) * self.scaling + self.base.weight.data.add_(delta) + self.merged = True + + +def _get_child_module(parent: torch.nn.Module, part: str) -> torch.nn.Module: + if isinstance(parent, (torch.nn.ModuleList, torch.nn.Sequential)) and part.isdigit(): + return parent[int(part)] + if isinstance(parent, torch.nn.ModuleDict): + return parent[part] + return getattr(parent, part) + + +def _set_child_module(parent: torch.nn.Module, part: str, module: torch.nn.Module) -> None: + if isinstance(parent, (torch.nn.ModuleList, torch.nn.Sequential)) and part.isdigit(): + parent[int(part)] = module + return + if isinstance(parent, torch.nn.ModuleDict): + parent[part] = module + return + setattr(parent, part, module) + + +def _resolve_parent_module( + root: torch.nn.Module, module_name: str +) -> Optional[tuple]: + if not module_name: + return None + parts = module_name.split(".") + parent = root + for part in parts[:-1]: + parent = _get_child_module(parent, part) + return parent, parts[-1] + + +def _resolve_module_by_path(root: torch.nn.Module, module_path: str) -> Optional[torch.nn.Module]: + if not module_path: + return None + parts = [part for part in module_path.split(".") if part] + node = root + for part in parts: + try: + node = _get_child_module(node, part) + except Exception: + return None + return node + + +def _resolve_layer_container_for_lora( + model: torch.nn.Module, layer_path: Optional[str] +) -> Tuple[Optional[str], Optional[object]]: + """Resolve transformer layer container with optional auto-detection. + + Mirrors the candidate path strategy used elsewhere, so LoRA filtering can work + even when --layer_path is not provided. + """ + if isinstance(layer_path, str) and layer_path and layer_path.lower() != "none": + container = _resolve_module_by_path(model, layer_path) + if container is not None: + try: + list(container) + return layer_path, container + except TypeError: + pass + + candidate_paths = [ + "model.layers", # LLaMA, Mistral, Qwen2, Gemma + "model.decoder.layers", # OPT + "transformer.h", # GPT-2, GPT-J, Bloom, Falcon + "transformer.blocks", # MPT + "gpt_neox.layers", # GPT-NeoX + "layers", # fallback + ] + for path in candidate_paths: + container = _resolve_module_by_path(model, path) + if container is None: + continue + try: + list(container) + except TypeError: + continue + return path, container + + return None, None + + +def _parse_exclude_pairs_local(raw_values, num_pairs: int) -> Set[int]: + if not raw_values or num_pairs <= 0: + return set() + exclude: Set[int] = set() + for item in raw_values: + if item is None: + continue + for part in str(item).split(","): + part = part.strip() + if not part: + continue + try: + idx = int(part) + except ValueError as exc: + raise SystemExit("--exclude_pairs must contain integers.") from exc + if idx < 0: + idx = num_pairs + idx + if 0 <= idx < num_pairs: + exclude.add(idx) + return exclude + + +def _extract_layer_index_from_module_name( + module_name: str, layer_path: str +) -> Optional[int]: + if not layer_path: + return None + prefix = f"{layer_path}." + if not module_name.startswith(prefix): + return None + rest = module_name[len(prefix) :] + if not rest: + return None + idx_text = rest.split(".", 1)[0] + if not idx_text.isdigit(): + return None + return int(idx_text) + + +def _select_linear_modules_for_lora_targets( + model: torch.nn.Module, + args: argparse.Namespace, + *, + log_tag: str, +) -> Tuple[List[Tuple[str, torch.nn.Linear]], Optional[Set[str]], Set[int], Optional[str]]: + raw_targets = getattr(args, "lora_target_modules", None) + target_modules: Optional[Set[str]] = None + if raw_targets: + target_modules = {str(item) for item in raw_targets if str(item)} + + exclude_layer_indices: Set[int] = set() + resolved_layer_path: Optional[str] = None + if bool(getattr(args, "lora_respect_exclude_pairs", False)): + requested_layer_path = getattr(args, "layer_path", None) + resolved_layer_path, layer_container = _resolve_layer_container_for_lora( + model, requested_layer_path + ) + if isinstance(layer_container, (torch.nn.ModuleList, list, tuple)): + num_pairs = max(len(layer_container) - 1, 0) + exclude_pairs = _parse_exclude_pairs_local( + getattr(args, "exclude_pairs", None), num_pairs + ) + for pair_idx in exclude_pairs: + exclude_layer_indices.add(pair_idx) + exclude_layer_indices.add(pair_idx + 1) + else: + print( + f"[{log_tag}] Warning: --lora_respect_exclude_pairs enabled, but " + f"could not resolve layer path '{requested_layer_path}'." + ) + + linear_modules = [ + (name, module) + for name, module in model.named_modules() + if isinstance(module, torch.nn.Linear) + and (target_modules is None or name.split(".")[-1] in target_modules) + and ( + not exclude_layer_indices + or _extract_layer_index_from_module_name(name, resolved_layer_path or "") + not in exclude_layer_indices + ) + ] + return linear_modules, target_modules, exclude_layer_indices, resolved_layer_path + + +def apply_lora_adapters( + model: torch.nn.Module, args: argparse.Namespace +) -> List[LoRALinear]: + if args.lora_rank <= 0: + raise SystemExit("--lora_rank must be > 0 when --lora_epochs > 0") + linear_modules, target_modules, exclude_layer_indices, _ = ( + _select_linear_modules_for_lora_targets(model, args, log_tag="lora") + ) + if not linear_modules: + raise SystemExit( + "No Linear modules found for LoRA adapters " + "(check --lora_target_modules / --exclude_pairs / --lora_respect_exclude_pairs)." + ) + + lora_modules: List[LoRALinear] = [] + for name, module in linear_modules: + resolved = _resolve_parent_module(model, name) + if resolved is None: + continue + parent, attr = resolved + wrapped = LoRALinear( + base=module, + rank=args.lora_rank, + alpha=args.lora_alpha, + dropout=args.lora_dropout, + ) + _set_child_module(parent, attr, wrapped) + lora_modules.append(wrapped) + + for param in model.parameters(): + param.requires_grad_(False) + for lora_module in lora_modules: + for param in lora_module.lora_parameters(): + param.requires_grad_(True) + + total_params = sum(p.numel() for p in model.parameters()) + trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) + percent = 100.0 * trainable_params / max(total_params, 1) + target_note = "" + if target_modules is not None: + target_note = f" target={sorted(target_modules)}" + exclude_note = "" + if exclude_layer_indices: + exclude_note = f" excluded_layers={sorted(exclude_layer_indices)}" + print( + "[lora] Applied adapters to " + f"{len(lora_modules)} linear modules " + f"({trainable_params}/{total_params} trainable, {percent:.4f}%)." + f"{target_note}{exclude_note}" + ) + return lora_modules + + +def merge_lora_adapters(model: torch.nn.Module) -> None: + lora_entries = [ + (name, module) + for name, module in model.named_modules() + if isinstance(module, LoRALinear) + ] + for name, module in lora_entries: + module.merge() + resolved = _resolve_parent_module(model, name) + if resolved is None: + continue + parent, attr = resolved + _set_child_module(parent, attr, module.base) + + +def set_lora_enabled(lora_modules: List[LoRALinear], enabled: bool) -> None: + for module in lora_modules: + module.enabled = enabled + + +def lora_ce_finetune( + model: torch.nn.Module, + dataloader, + eval_tokenizer, + eval_datasets: List[str], + eval_configs: List[Optional[str]], + eval_history: List[Dict[str, object]], + args: argparse.Namespace, + eval_dataloaders: Optional[Dict[str, object]] = None, + progressive_cycle: Optional[int] = None, + progressive_total: Optional[int] = None, +) -> None: + total_epochs = float(args.lora_epochs) + if total_epochs <= 0: + return + + use_kl = bool(getattr(args, "lora_kl_enabled", False)) + kl_weight = float(getattr(args, "lora_kl_weight", 0.0)) + kl_temp = float(getattr(args, "lora_kl_temp", 1.0)) + if use_kl: + if kl_weight < 0.0: + raise SystemExit("--lora_kl_weight must be >= 0") + if kl_temp <= 0.0: + raise SystemExit("--lora_kl_temp must be > 0") + if kl_weight == 0.0: + use_kl = False + + lora_modules = apply_lora_adapters(model, args) + if not lora_modules: + return + + model.train() + + lora_params = [] + for module in lora_modules: + lora_params.extend(module.lora_parameters()) + + optimizer = torch.optim.AdamW( + lora_params, + lr=args.lora_lr, + weight_decay=args.lora_weight_decay, + ) + + device_type = torch.device(args.device).type + amp_dtype = None + if args.dtype == "float16": + amp_dtype = torch.float16 + elif args.dtype == "bfloat16": + amp_dtype = torch.bfloat16 + use_amp = amp_dtype is not None and device_type == "cuda" + use_scaler = use_amp and amp_dtype == torch.float16 + scaler = torch.cuda.amp.GradScaler() if use_scaler else None + + full_epochs = int(total_epochs) + fractional = total_epochs - full_epochs + if fractional < 1e-8: + fractional = 0.0 + + epoch_plan = [(epoch_idx, None) for epoch_idx in range(full_epochs)] + if fractional > 0: + try: + batches_per_epoch = len(dataloader) + except TypeError as exc: + raise SystemExit( + "Fractional lora epochs require a dataloader with finite length." + ) from exc + if batches_per_epoch > 0: + frac_batches = int(round(fractional * batches_per_epoch)) + if frac_batches <= 0: + frac_batches = 1 + epoch_plan.append((full_epochs, frac_batches)) + + step = 0 + for epoch_idx, max_batches in epoch_plan: + if max_batches is None: + epoch_iter = dataloader + else: + epoch_iter = itertools.islice(dataloader, max_batches) + iterator = epoch_iter + if tqdm is not None and _tqdm_enabled(): + if progressive_cycle is not None: + if progressive_total is not None: + desc = ( + f"LoRA (cycle {progressive_cycle}/{progressive_total}, " + f"epoch {epoch_idx+1})" + ) + else: + desc = f"LoRA (cycle {progressive_cycle}, epoch {epoch_idx+1})" + else: + desc = f"LoRA (epoch {epoch_idx+1})" + iterator = tqdm( + epoch_iter, + desc=desc, + unit="batch", + total=max_batches, + ) + for batch in iterator: + input_ids = batch[0].to(args.device) + attention_mask = batch[1].to(args.device) + autocast_ctx = ( + torch.autocast(device_type=device_type, dtype=amp_dtype) + if use_amp + else nullcontext() + ) + with autocast_ctx: + outputs = model( + input_ids=input_ids, + attention_mask=attention_mask, + use_cache=False, + ) + logits = outputs.logits + shift_logits = logits[:, :-1, :].contiguous() + shift_labels = input_ids[:, 1:].contiguous() + shift_mask = attention_mask[:, 1:].contiguous() + ce_flat = F.cross_entropy( + shift_logits.view(-1, shift_logits.size(-1)), + shift_labels.view(-1), + reduction="none", + ) + ce_denom = shift_mask.sum() + if ce_denom.item() == 0: + continue + ce_loss = ( + ce_flat * shift_mask.view(-1).to(ce_flat.dtype) + ).sum() / ce_denom + kl_loss = None + if use_kl: + set_lora_enabled(lora_modules, False) + with torch.no_grad(): + base_outputs = model( + input_ids=input_ids, + attention_mask=attention_mask, + use_cache=False, + ) + base_logits = base_outputs.logits + set_lora_enabled(lora_modules, True) + if base_logits.device != shift_logits.device: + base_logits = base_logits.to(shift_logits.device) + shift_base_logits = base_logits[:, :-1, :].contiguous() + log_p_pre = F.log_softmax(shift_base_logits / kl_temp, dim=-1) + log_p_post = F.log_softmax(shift_logits / kl_temp, dim=-1) + p_pre = log_p_pre.exp() + kl_flat = (p_pre * (log_p_pre - log_p_post)).sum(dim=-1) + kl_loss = ( + kl_flat * shift_mask.to(kl_flat.dtype) + ).sum() / ce_denom + + total_loss = ce_loss + if kl_loss is not None: + total_loss = total_loss + (kl_weight * (kl_temp ** 2) * kl_loss) + + if args.lora_grad_accum_steps > 1: + total_loss = total_loss / args.lora_grad_accum_steps + if use_scaler: + scaler.scale(total_loss).backward() + else: + total_loss.backward() + + if (step + 1) % args.lora_grad_accum_steps == 0: + if args.lora_max_grad_norm is not None: + if use_scaler: + scaler.unscale_(optimizer) + torch.nn.utils.clip_grad_norm_( + lora_params, + args.lora_max_grad_norm, + ) + if use_scaler: + scaler.step(optimizer) + scaler.update() + else: + optimizer.step() + optimizer.zero_grad(set_to_none=True) + + if args.lora_eval_every and (step + 1) % args.lora_eval_every == 0: + prev_mode = model.training + model.eval() + eval_device = args.eval_device or args.device + if eval_dataloaders is not None: + results = ppl_eval.evaluate_ppl_dataloaders( + model, + eval_dataloaders, + eval_device, + max_batches=args.lora_eval_max_batches, + ) + else: + results = ppl_eval.evaluate_ppl_datasets( + model, + eval_tokenizer, + datasets=eval_datasets, + configs=eval_configs, + split=args.eval_split, + text_field=args.eval_text_field, + num_samples=args.eval_num_samples, + seq_len=args.eval_seq_len, + batch_size=args.eval_batch_size or args.batch_size, + device=eval_device, + seed=args.seed, + shuffle=False, + model_family=args.eval_model_family, + add_bos=args.eval_add_bos, + max_batches=args.lora_eval_max_batches, + cache_dir=args.eval_cache_dir, + num_workers=args.eval_num_workers, + ) + eval_history.append({"step": step + 1, "ppl": results}) + print(f"[lora] eval step={step+1}: {results}") + if prev_mode: + model.train() + + if args.lora_log_steps and ( + step == 0 or (step + 1) % args.lora_log_steps == 0 + ): + log_parts = [f"loss={total_loss.item():.6f}"] + if kl_loss is not None: + log_parts.append(f"kl={kl_loss.item():.6f}") + print( + f"[lora] epoch={epoch_idx+1} step={step+1} " + + " ".join(log_parts) + ) + step += 1 + + merge_lora_adapters(model) + + +def _masked_kl( + logits_p: torch.Tensor, + logits_q: torch.Tensor, + attention_mask: torch.Tensor, + temp: float, + detach_p: bool = True, + chunk_size: int = 16384, +) -> Optional[torch.Tensor]: + if chunk_size <= 0: + raise ValueError("chunk_size must be positive") + shift_mask = attention_mask[:, 1:].contiguous() + denom = shift_mask.sum() + if denom.item() == 0: + return None + + # Avoid materializing a full shifted logits copy on GPU. We stream over the + # vocab dimension below, so the sliced view is sufficient and lowers peak + # memory for sharded comm preconditioning. + p = logits_p[:, :-1, :] + q = logits_q[:, :-1, :] + q_device = q.device + q_dtype = q.dtype + + if (not detach_p) and p.device != q_device: + p = p.to(q_device) + + def _streaming_logsumexp( + logits: torch.Tensor, + target_device: torch.device, + target_dtype: torch.dtype, + ) -> torch.Tensor: + max_logits = logits.amax(dim=-1, keepdim=True) + max_scaled = max_logits / temp + sum_exp = None + vocab = logits.size(-1) + for start in range(0, vocab, chunk_size): + end = min(start + chunk_size, vocab) + chunk = logits[..., start:end] + if chunk.device != target_device or chunk.dtype != target_dtype: + chunk = chunk.to(device=target_device, dtype=target_dtype) + else: + chunk = chunk.to(dtype=target_dtype) + chunk_scaled = chunk / temp + partial = (chunk_scaled - max_scaled.to(device=chunk_scaled.device, dtype=chunk_scaled.dtype)).exp().sum( + dim=-1, + keepdim=True, + ) + sum_exp = partial if sum_exp is None else sum_exp + partial + return max_scaled.to(device=target_device, dtype=target_dtype) + sum_exp.log() + + logsumexp_q = _streaming_logsumexp(q, q_device, q_dtype) + logsumexp_p = _streaming_logsumexp( + p, + q_device if detach_p else p.device, + q_dtype if detach_p else p.dtype, + ) + if detach_p: + logsumexp_p = logsumexp_p.detach() + + kl_flat = None + vocab = q.size(-1) + for start in range(0, vocab, chunk_size): + end = min(start + chunk_size, vocab) + q_chunk = q[..., start:end].to(dtype=q_dtype) + log_q_chunk = (q_chunk / temp) - logsumexp_q + + p_chunk = p[..., start:end] + if p_chunk.device != q_device or p_chunk.dtype != q_dtype: + p_chunk = p_chunk.to(device=q_device, dtype=q_dtype) + else: + p_chunk = p_chunk.to(dtype=q_dtype) + log_p_chunk = (p_chunk / temp) - logsumexp_p.to(device=q_device, dtype=q_dtype) + if detach_p: + log_p_chunk = log_p_chunk.detach() + p_probs_chunk = log_p_chunk.exp() + chunk_kl = (p_probs_chunk * (log_p_chunk - log_q_chunk)).sum(dim=-1) + kl_flat = chunk_kl if kl_flat is None else kl_flat + chunk_kl + + mask = shift_mask.to(device=kl_flat.device, dtype=kl_flat.dtype) + denom = denom.to(device=kl_flat.device, dtype=kl_flat.dtype) + return (kl_flat * mask).sum() / denom + + +def _extract_hidden_tensor(output: object) -> Optional[torch.Tensor]: + if isinstance(output, torch.Tensor): + return output + if isinstance(output, (tuple, list)) and output: + first = output[0] + if isinstance(first, torch.Tensor): + return first + return None + + +def _grad_l2_norm(grads: List[Optional[torch.Tensor]]) -> float: + total = 0.0 + for grad in grads: + if grad is None: + continue + total += float(grad.detach().float().pow(2).sum().item()) + if total <= 0.0: + return 0.0 + return float(math.sqrt(total)) + + +def _register_forward_pre_hook_with_optional_kwargs(layer, hook): + try: + handle = layer.register_forward_pre_hook(hook, with_kwargs=True) + return handle + except TypeError: + def wrapper(module, inputs): + return hook(module, inputs, None) + + return layer.register_forward_pre_hook(wrapper) + + +def _batch_input_ids_attention(batch) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor]]: + if isinstance(batch, torch.Tensor): + return batch, None + if isinstance(batch, dict): + input_ids = batch.get("input_ids") + attention_mask = batch.get("attention_mask") + return input_ids, attention_mask + if ( + isinstance(batch, (tuple, list)) + and len(batch) == 1 + and isinstance(batch[0], torch.Tensor) + ): + return batch[0], None + if isinstance(batch, (tuple, list)) and len(batch) >= 2: + return batch[0], batch[1] + return None, None + + +def _new_gap_accumulator() -> Dict[str, float]: + return { + "mse_sum": 0.0, + "relative_sum": 0.0, + "cosine_sum": 0.0, + "r1_norm_sum": 0.0, + "r0_norm_sum": 0.0, + "token_count": 0.0, + "elem_count": 0.0, + "batches": 0.0, + } + + +def _accumulate_gap_component( + acc: Dict[str, float], + r1_like: torch.Tensor, + r0_like: torch.Tensor, + attention_mask: torch.Tensor, + interaction_eps: float, +) -> bool: + r1 = r1_like.float() + r0 = r0_like.float() + if r0.device != r1.device: + r0 = r0.to(r1.device) + if r0.shape != r1.shape or r1.dim() < 3: + return False + + mask = attention_mask.to(device=r1.device, dtype=torch.float32) + mask_sum = float(mask.sum().item()) + if mask_sum <= 0.0: + return False + + hidden_dim = int(r1.size(-1)) + mask_3d = mask.unsqueeze(-1) + gap = r1 - r0 + gap_sq = gap.pow(2).sum(dim=-1) + r1_sq = r1.pow(2).sum(dim=-1) + r0_sq = r0.pow(2).sum(dim=-1) + relative = gap_sq / (r1_sq + float(interaction_eps)) + cosine = F.cosine_similarity(r1, r0, dim=-1, eps=float(interaction_eps)) + + acc["mse_sum"] += float((gap.pow(2) * mask_3d).sum().item()) + acc["relative_sum"] += float((relative * mask).sum().item()) + acc["cosine_sum"] += float((cosine * mask).sum().item()) + acc["r1_norm_sum"] += float((r1_sq * mask).sum().item()) + acc["r0_norm_sum"] += float((r0_sq * mask).sum().item()) + acc["token_count"] += mask_sum + acc["elem_count"] += mask_sum * hidden_dim + acc["batches"] += 1.0 + return True + + +def _finalize_gap_component(acc: Dict[str, float]) -> Optional[Dict[str, object]]: + token_count = float(acc.get("token_count", 0.0)) + elem_count = float(acc.get("elem_count", 0.0)) + if token_count <= 0.0 or elem_count <= 0.0: + return None + mean_cosine = float(acc["cosine_sum"] / token_count) + return { + "batches": int(acc.get("batches", 0.0)), + "tokens": int(token_count), + "mse": float(acc["mse_sum"] / elem_count), + "relative": float(acc["relative_sum"] / token_count), + "cosine": mean_cosine, + "cosine_distance": float(1.0 - mean_cosine), + "r1_norm_mean": float(acc["r1_norm_sum"] / token_count), + "r0_norm_mean": float(acc["r0_norm_sum"] / token_count), + } + + +def _format_comm_gap_stats(stats: Dict[str, object]) -> str: + parts = [ + f"relative={stats.get('relative'):.6e}", + f"mse={stats.get('mse'):.6e}", + f"cos_dist={stats.get('cosine_distance'):.6e}", + ] + components = stats.get("components") + if isinstance(components, dict): + for name in ("attn", "mlp", "mlp.gate_proj", "mlp.up_proj", "mlp.down_proj"): + value = components.get(name) + if isinstance(value, dict) and "relative" in value: + parts.append(f"{name}_relative={value.get('relative'):.6e}") + if "cosine_distance" in value: + parts.append(f"{name}_cos_dist={value.get('cosine_distance'):.6e}") + return " ".join(parts) + + +def _safe_ratio(numer: object, denom: object) -> Optional[float]: + try: + n = float(numer) + d = float(denom) + except (TypeError, ValueError): + return None + if not math.isfinite(n) or not math.isfinite(d) or d == 0.0: + return None + return n / d + + +def _comm_gap_ratio(pre_stats: Dict[str, object], post_stats: Dict[str, object]) -> Dict[str, object]: + ratio: Dict[str, object] = {} + for key in ("mse", "relative", "cosine_distance"): + if key not in pre_stats or key not in post_stats: + continue + value = _safe_ratio(post_stats.get(key), pre_stats.get(key)) + if value is not None: + ratio[key] = value + mse_ratio = ratio.get("mse") + if isinstance(mse_ratio, float) and mse_ratio >= 0.0: + ratio["l2_norm_from_mse"] = math.sqrt(mse_ratio) + + pre_components = pre_stats.get("components") + post_components = post_stats.get("components") + if isinstance(pre_components, dict) and isinstance(post_components, dict): + component_ratios = {} + for name, pre_value in pre_components.items(): + post_value = post_components.get(name) + if not isinstance(pre_value, dict) or not isinstance(post_value, dict): + continue + one_component: Dict[str, float] = {} + for key in ("mse", "relative", "cosine_distance"): + if key not in pre_value or key not in post_value: + continue + value = _safe_ratio(post_value.get(key), pre_value.get(key)) + if value is not None: + one_component[key] = value + mse_ratio = one_component.get("mse") + if isinstance(mse_ratio, float) and mse_ratio >= 0.0: + one_component["l2_norm_from_mse"] = math.sqrt(mse_ratio) + if one_component: + component_ratios[name] = one_component + if component_ratios: + ratio["components"] = component_ratios + return ratio + + +def _measure_commutator_gap( + student_model: torch.nn.Module, + student_layers: List[torch.nn.Module], + dataloader, + pair_idx: int, + args: argparse.Namespace, + max_batches: int, + interaction_eps: float, +) -> Dict[str, object]: + """Measure r1-r0 on a fixed pair without updating model weights.""" + if dataloader is None: + return {"enabled": False, "reason": "no_dataloader"} + if pair_idx < 0 or pair_idx >= len(student_layers) - 1: + return {"enabled": False, "reason": "invalid_pair"} + + was_training = student_model.training + student_model.eval() + + device_type = torch.device(args.device).type + amp_dtype = None + if args.dtype == "float16": + amp_dtype = torch.float16 + elif args.dtype == "bfloat16": + amp_dtype = torch.bfloat16 + use_amp = amp_dtype is not None and device_type == "cuda" + autocast_ctx = ( + torch.autocast(device_type=device_type, dtype=amp_dtype) + if use_amp + else nullcontext() + ) + + block_acc = _new_gap_accumulator() + component_accs: Dict[str, Dict[str, float]] = {} + batches = 0 + skipped = 0 + receiver_attn = None + receiver_mlp = None + try: + receiver_attn = find_attention_module(student_layers[pair_idx + 1]) + except Exception: + receiver_attn = None + try: + receiver_mlp = find_mlp_module(student_layers[pair_idx + 1]) + except Exception: + receiver_mlp = None + if receiver_attn is not None: + component_accs["attn"] = _new_gap_accumulator() + mlp_submodules: Dict[str, torch.nn.Module] = {} + if receiver_mlp is not None: + component_accs["mlp"] = _new_gap_accumulator() + for sub_name in ("gate_proj", "up_proj", "down_proj"): + submodule = getattr(receiver_mlp, sub_name, None) + if isinstance(submodule, torch.nn.Module): + component_name = f"mlp.{sub_name}" + mlp_submodules[component_name] = submodule + component_accs[component_name] = _new_gap_accumulator() + + limit = int(max_batches) + try: + iterator = iter(dataloader) + with torch.no_grad(): + for batch in iterator: + if limit > 0 and batches >= limit: + break + input_ids, attention_mask = _batch_input_ids_attention(batch) + if input_ids is None: + skipped += 1 + continue + input_ids = input_ids.to(args.device) + if attention_mask is None: + attention_mask = torch.ones_like(input_ids) + attention_mask = attention_mask.to(args.device) + + capture: Dict[str, object] = { + "h_l": None, + "h_lp1": None, + "y1": None, + "attn1": None, + "mlp1": None, + "recv_args": None, + "recv_kwargs": None, + } + + def _hook_l(_module, inputs, _output): + if inputs and isinstance(inputs[0], torch.Tensor): + capture["h_l"] = inputs[0] + + def _hook_recv_pre(_module, inputs, kwargs): + capture["recv_args"] = inputs + capture["recv_kwargs"] = kwargs + + def _hook_recv(_module, inputs, output): + if inputs and isinstance(inputs[0], torch.Tensor): + capture["h_lp1"] = inputs[0] + capture["y1"] = _extract_hidden_tensor(output) + + def _hook_attn1(_module, _inputs, output): + capture["attn1"] = _extract_hidden_tensor(output) + + def _hook_mlp1(_module, _inputs, output): + capture["mlp1"] = _extract_hidden_tensor(output) + + def _make_component_hook(storage: Dict[str, object], key: str): + def _hook(_module, _inputs, output): + storage[key] = _extract_hidden_tensor(output) + + return _hook + + handles: List[object] = [ + student_layers[pair_idx].register_forward_hook(_hook_l), + _register_forward_pre_hook_with_optional_kwargs( + student_layers[pair_idx + 1], _hook_recv_pre + ), + student_layers[pair_idx + 1].register_forward_hook(_hook_recv), + ] + if receiver_attn is not None: + handles.append(receiver_attn.register_forward_hook(_hook_attn1)) + if receiver_mlp is not None: + handles.append(receiver_mlp.register_forward_hook(_hook_mlp1)) + for name, module in mlp_submodules.items(): + handles.append( + module.register_forward_hook( + _make_component_hook(capture, f"{name}1") + ) + ) + try: + with autocast_ctx: + student_model( + input_ids=input_ids, + attention_mask=attention_mask, + use_cache=False, + ) + finally: + for handle in handles: + try: + handle.remove() + except Exception: + pass + + h_l = capture.get("h_l") + h_lp1 = capture.get("h_lp1") + y1 = capture.get("y1") + recv_args = capture.get("recv_args") + recv_kwargs = capture.get("recv_kwargs") + if not ( + isinstance(h_l, torch.Tensor) + and isinstance(h_lp1, torch.Tensor) + and isinstance(y1, torch.Tensor) + and isinstance(recv_args, tuple) + and len(recv_args) > 0 + and isinstance(recv_args[0], torch.Tensor) + ): + skipped += 1 + continue + + first_hidden = recv_args[0] + receiver_device = first_hidden.device + call_args = list(_move_tensor_tree_to_device(recv_args, receiver_device)) + call_args[0] = h_l.detach().to( + device=receiver_device, + dtype=first_hidden.dtype, + ) + call_kwargs = ( + _move_tensor_tree_to_device(dict(recv_kwargs), receiver_device) + if isinstance(recv_kwargs, dict) + else {} + ) + y0_capture: Dict[str, object] = {"attn0": None, "mlp0": None} + + def _hook_attn0(_module, _inputs, output): + y0_capture["attn0"] = _extract_hidden_tensor(output) + + def _hook_mlp0(_module, _inputs, output): + y0_capture["mlp0"] = _extract_hidden_tensor(output) + + y0_handles: List[object] = [] + if receiver_attn is not None: + y0_handles.append(receiver_attn.register_forward_hook(_hook_attn0)) + if receiver_mlp is not None: + y0_handles.append(receiver_mlp.register_forward_hook(_hook_mlp0)) + for name, module in mlp_submodules.items(): + y0_handles.append( + module.register_forward_hook( + _make_component_hook(y0_capture, f"{name}0") + ) + ) + with autocast_ctx: + try: + y0_raw = student_layers[pair_idx + 1](*tuple(call_args), **call_kwargs) + finally: + for handle in y0_handles: + try: + handle.remove() + except Exception: + pass + y0 = _extract_hidden_tensor(y0_raw) + if not isinstance(y0, torch.Tensor): + skipped += 1 + continue + + if y0.device != y1.device: + y0 = y0.to(y1.device) + h_lp1_detached = h_lp1.detach().to(device=y1.device, dtype=y1.dtype) + h_l_for_res = h_l.detach().to(device=y0.device, dtype=y0.dtype) + r1 = (y1 - h_lp1_detached).float() + r0 = (y0 - h_l_for_res).float() + if not _accumulate_gap_component( + block_acc, + r1, + r0, + attention_mask, + interaction_eps, + ): + skipped += 1 + continue + + attn1 = capture.get("attn1") + attn0 = y0_capture.get("attn0") + if isinstance(attn1, torch.Tensor) and isinstance(attn0, torch.Tensor): + _accumulate_gap_component( + component_accs["attn"], + attn1, + attn0, + attention_mask, + interaction_eps, + ) + mlp1 = capture.get("mlp1") + mlp0 = y0_capture.get("mlp0") + if isinstance(mlp1, torch.Tensor) and isinstance(mlp0, torch.Tensor): + _accumulate_gap_component( + component_accs["mlp"], + mlp1, + mlp0, + attention_mask, + interaction_eps, + ) + for name in mlp_submodules: + sub1 = capture.get(f"{name}1") + sub0 = y0_capture.get(f"{name}0") + if isinstance(sub1, torch.Tensor) and isinstance(sub0, torch.Tensor): + _accumulate_gap_component( + component_accs[name], + sub1, + sub0, + attention_mask, + interaction_eps, + ) + batches += 1 + finally: + if was_training: + student_model.train() + + block_stats = _finalize_gap_component(block_acc) + if block_stats is None: + return { + "enabled": False, + "reason": "no_valid_batches", + "batches": int(batches), + "skipped_batches": int(skipped), + } + + components = {} + for name, acc in component_accs.items(): + component_stats = _finalize_gap_component(acc) + if component_stats is not None: + components[name] = component_stats + + return { + "enabled": True, + "pair": int(pair_idx), + "batches": int(batches), + "skipped_batches": int(skipped), + "tokens": block_stats["tokens"], + "mse": block_stats["mse"], + "relative": block_stats["relative"], + "cosine": block_stats["cosine"], + "cosine_distance": block_stats["cosine_distance"], + "r1_norm_mean": block_stats["r1_norm_mean"], + "r0_norm_mean": block_stats["r0_norm_mean"], + "components": components, + } + + +def commutator_precondition( + student_model: torch.nn.Module, + student_layers: List[torch.nn.Module], + teacher_model: torch.nn.Module, + dataloader, + dwce_scores: Optional[List[float]], + args: argparse.Namespace, + exclude_pairs: Optional[Set[int]] = None, + progressive_cycle: Optional[int] = None, + progressive_total: Optional[int] = None, + measure_dataloader=None, +) -> Dict[str, object]: + """Run commutator-style preconditioning before pair fusion. + + Objective on each sampled pair i: + L = T^2 * KL(p_teacher || p_student) + mu * L_interaction(i) + + Interaction loss is computed locally on block (i+1): + r1 = B_{i+1}(h_{i+1}) - h_{i+1} + r0 = B_{i+1}(h_i) - h_i + L_interaction = ||r1-r0||^2 (or relative form). + """ + if not bool(getattr(args, "comm_enabled", False)): + return {"enabled": False} + if not student_layers or len(student_layers) < 2: + return {"enabled": False, "reason": "need_at_least_2_layers"} + + temp = float(getattr(args, "comm_temp", 2.0)) + steps_ratio = float(getattr(args, "comm_steps_ratio", 0.1)) + lr_scale = float(getattr(args, "comm_lr_scale", 0.1)) + sample_eta = float(getattr(args, "comm_sample_eta", 0.5)) + sample_dwce_scale = float(getattr(args, "comm_sample_dwce_scale", 1.0)) + top_k = int(getattr(args, "comm_topk", 1)) + interaction_mode = str(getattr(args, "comm_interaction_mode", "relative")).strip().lower() + interaction_eps = float(getattr(args, "comm_interaction_eps", 1e-8)) + mu_cfg = getattr(args, "comm_mu", None) + mu_auto = bool(getattr(args, "comm_mu_auto", False)) + mu_auto_rho = float(getattr(args, "comm_mu_auto_rho", 0.1)) + mu_auto_eps = float(getattr(args, "comm_mu_auto_eps", 1e-8)) + comm_train_mode = str(getattr(args, "comm_train_mode", "lora")).strip().lower() + log_steps = int(getattr(args, "comm_log_steps", 50)) + + if temp <= 0.0: + raise SystemExit("--comm_temp must be > 0") + if steps_ratio < 0.0: + raise SystemExit("--comm_steps_ratio must be >= 0") + if lr_scale <= 0.0: + raise SystemExit("--comm_lr_scale must be > 0") + if not (0.0 <= sample_eta <= 1.0): + raise SystemExit("--comm_sample_eta must be in [0, 1]") + if top_k <= 0: + raise SystemExit("--comm_topk must be >= 1") + if interaction_mode not in {"mse", "relative"}: + raise SystemExit("--comm_interaction_mode must be one of: mse, relative") + if comm_train_mode not in {"lora", "full"}: + raise SystemExit("--comm_train_mode must be one of: lora, full") + if interaction_eps <= 0.0: + raise SystemExit("--comm_interaction_eps must be > 0") + if mu_auto_rho < 0.0: + raise SystemExit("--comm_mu_auto_rho must be >= 0") + if mu_auto_eps <= 0.0: + raise SystemExit("--comm_mu_auto_eps must be > 0") + + if mu_cfg is None: + base_mu = 0.5 if interaction_mode == "relative" else 0.1 + else: + base_mu = float(mu_cfg) + if base_mu < 0.0: + raise SystemExit("--comm_mu must be >= 0") + + distill_epochs = float(getattr(args, "distill_epochs", 1.0)) + if distill_epochs <= 0.0: + distill_epochs = 1.0 + grad_accum = int(getattr(args, "distill_grad_accum_steps", 1)) + if grad_accum <= 0: + grad_accum = 1 + + try: + batches_per_epoch = len(dataloader) + except TypeError as exc: + raise SystemExit( + "Commutator preconditioning requires a finite-length distillation dataloader." + ) from exc + if batches_per_epoch <= 0: + return {"enabled": False, "reason": "empty_dataloader"} + + full_epochs = int(distill_epochs) + fractional = distill_epochs - full_epochs + if fractional < 1e-8: + fractional = 0.0 + total_batches = full_epochs * batches_per_epoch + if fractional > 0.0: + frac_batches = int(round(fractional * batches_per_epoch)) + if frac_batches <= 0: + frac_batches = 1 + total_batches += frac_batches + + distill_opt_steps = int(math.ceil(total_batches / float(grad_accum))) + target_opt_steps = int(round(steps_ratio * distill_opt_steps)) + if target_opt_steps <= 0: + target_opt_steps = 1 + + num_pairs = max(len(student_layers) - 1, 0) + exclude_set = { + int(idx) + for idx in (exclude_pairs or set()) + if isinstance(idx, int) and 0 <= int(idx) < num_pairs + } + allowed_pairs = [i for i in range(num_pairs) if i not in exclude_set] + if not allowed_pairs: + return {"enabled": False, "reason": "all_pairs_excluded"} + + ranked_pairs = list(allowed_pairs) + if dwce_scores is not None and len(dwce_scores) >= num_pairs: + finite_pairs = [] + for idx in allowed_pairs: + value = float(dwce_scores[idx]) + if math.isfinite(value): + finite_pairs.append(idx) + if finite_pairs: + ranked_pairs = sorted(finite_pairs, key=lambda i: float(dwce_scores[i])) + else: + ranked_pairs = list(allowed_pairs) + candidate_pairs = ranked_pairs[: min(top_k, len(ranked_pairs))] + if not candidate_pairs: + return {"enabled": False, "reason": "no_candidate_pairs"} + + layer_trainable_params: List[List[torch.nn.Parameter]] = [] + trainable_params: List[torch.nn.Parameter] = [] + if comm_train_mode == "lora": + # LoRA comm preconditioning: update LoRA adapters on receiver layer (i+1). + lora_modules = apply_lora_adapters(student_model, args) + if not lora_modules: + return {"enabled": False, "reason": "no_lora_modules"} + + trainable_seen: Set[int] = set() + for module in lora_modules: + for param in module.lora_parameters(): + pid = id(param) + if pid in trainable_seen: + continue + trainable_seen.add(pid) + trainable_params.append(param) + + for layer in student_layers: + seen: Set[int] = set() + params: List[torch.nn.Parameter] = [] + for module in layer.modules(): + if not isinstance(module, LoRALinear): + continue + for param in module.lora_parameters(): + pid = id(param) + if pid in seen: + continue + seen.add(pid) + params.append(param) + layer_trainable_params.append(params) + else: + # Full-weight comm preconditioning: update full receiver-layer weights. + for layer in student_layers: + seen: Set[int] = set() + params: List[torch.nn.Parameter] = [] + for param in layer.parameters(): + if not isinstance(param, torch.nn.Parameter): + continue + pid = id(param) + if pid in seen: + continue + seen.add(pid) + params.append(param) + layer_trainable_params.append(params) + + candidate_pairs = [ + i + for i in candidate_pairs + if (i + 1) < len(layer_trainable_params) and layer_trainable_params[i + 1] + ] + if not candidate_pairs: + if comm_train_mode == "lora": + merge_lora_adapters(student_model) + return {"enabled": False, "reason": "no_trainable_receiver_layers"} + + if comm_train_mode == "full": + trainable_seen: Set[int] = set() + for pair_idx in candidate_pairs: + for param in layer_trainable_params[pair_idx + 1]: + pid = id(param) + if pid in trainable_seen: + continue + trainable_seen.add(pid) + trainable_params.append(param) + if not trainable_params: + return {"enabled": False, "reason": "no_trainable_receiver_layers"} + + # Freeze non-comm params to reduce grad memory. + for param in student_model.parameters(): + param.requires_grad_(False) + for param in trainable_params: + param.requires_grad_(True) + + if not trainable_params: + if comm_train_mode == "lora": + merge_lora_adapters(student_model) + return {"enabled": False, "reason": "no_trainable_params"} + + candidate_probs = torch.full( + (len(candidate_pairs),), + 1.0 / float(len(candidate_pairs)), + dtype=torch.float32, + ) + if dwce_scores is not None and len(dwce_scores) >= num_pairs and sample_eta > 0.0: + score_vec = torch.tensor( + [float(dwce_scores[i]) for i in candidate_pairs], dtype=torch.float32 + ) + score_vec = torch.nan_to_num(score_vec, nan=1e9, posinf=1e9, neginf=-1e9) + biased = torch.softmax(-float(sample_dwce_scale) * score_vec, dim=0) + candidate_probs = (1.0 - sample_eta) * candidate_probs + sample_eta * biased + candidate_probs = candidate_probs / candidate_probs.sum() + + probs_by_pair = [0.0 for _ in range(num_pairs)] + for pos, pair_idx in enumerate(candidate_pairs): + probs_by_pair[pair_idx] = float(candidate_probs[pos].item()) + + measured_pair = int(candidate_pairs[0]) + gap_pre = None + if bool(getattr(args, "comm_measure_gap", False)): + max_gap_batches = int(getattr(args, "comm_gap_max_batches", 8)) + gap_pre = _measure_commutator_gap( + student_model=student_model, + student_layers=student_layers, + dataloader=measure_dataloader if measure_dataloader is not None else dataloader, + pair_idx=measured_pair, + args=args, + max_batches=max_gap_batches, + interaction_eps=interaction_eps, + ) + if gap_pre.get("enabled"): + print( + "[comm-gap] pre " + f"pair={measured_pair}-{measured_pair + 1} " + f"{_format_comm_gap_stats(gap_pre)} " + f"batches={gap_pre.get('batches')}" + ) + else: + print(f"[comm-gap] pre measurement skipped: {gap_pre.get('reason')}") + + lr = float(getattr(args, "distill_lr", 1e-4)) * lr_scale + optimizer = torch.optim.AdamW( + trainable_params, + lr=lr, + weight_decay=float(getattr(args, "distill_weight_decay", 0.0)), + ) + + device_type = torch.device(args.device).type + amp_dtype = None + if args.dtype == "float16": + amp_dtype = torch.float16 + elif args.dtype == "bfloat16": + amp_dtype = torch.bfloat16 + use_amp = amp_dtype is not None and device_type == "cuda" + use_scaler = use_amp and amp_dtype == torch.float16 + scaler = torch.cuda.amp.GradScaler() if use_scaler else None + + teacher_device = next(teacher_model.parameters()).device + teacher_model.eval() + student_model.train() + + gen = torch.Generator(device="cpu") + seed = int(getattr(args, "seed", 0)) + if progressive_cycle is not None: + seed += int(progressive_cycle) * 100003 + gen.manual_seed(seed) + + opt_step = 0 + total_loss_sum = 0.0 + anchor_sum = 0.0 + interaction_sum = 0.0 + mu_sum = 0.0 + counted = 0 + pair_counts = [0 for _ in range(num_pairs)] + + desc = "Comm" + if progressive_cycle is not None: + if progressive_total is not None: + desc = f"Comm (cycle {progressive_cycle}/{progressive_total})" + else: + desc = f"Comm (cycle {progressive_cycle})" + iterator = range(target_opt_steps) + if tqdm is not None and _tqdm_enabled(): + iterator = tqdm(iterator, desc=desc, unit="step") + + data_iter = iter(dataloader) + autocast_ctx = ( + torch.autocast(device_type=device_type, dtype=amp_dtype) + if use_amp + else nullcontext() + ) + + for _ in iterator: + optimizer.zero_grad(set_to_none=True) + accum_done = 0 + while accum_done < grad_accum: + try: + batch = next(data_iter) + except StopIteration: + data_iter = iter(dataloader) + batch = next(data_iter) + + input_ids = batch[0].to(args.device) + attention_mask = batch[1].to(args.device) + sampled_pos = int(torch.multinomial(candidate_probs, 1, generator=gen).item()) + pair_idx = int(candidate_pairs[sampled_pos]) + pair_counts[pair_idx] += 1 + + receiver_params = layer_trainable_params[pair_idx + 1] + receiver_param_ids = {id(param) for param in receiver_params} + + teacher_ids = input_ids.to(teacher_device) + teacher_mask = attention_mask.to(teacher_device) + with torch.no_grad(), autocast_ctx: + teacher_outputs = teacher_model( + input_ids=teacher_ids, + attention_mask=teacher_mask, + use_cache=False, + ) + teacher_logits = teacher_outputs.logits + + capture: Dict[str, object] = { + "h_l": None, + "h_lp1": None, + "y1": None, + "recv_args": None, + "recv_kwargs": None, + } + + def _hook_l(_module, inputs, _output): + if inputs and isinstance(inputs[0], torch.Tensor): + capture["h_l"] = inputs[0] + + def _hook_recv_pre(_module, inputs, kwargs): + capture["recv_args"] = inputs + capture["recv_kwargs"] = kwargs + + def _hook_recv(_module, inputs, output): + if inputs and isinstance(inputs[0], torch.Tensor): + capture["h_lp1"] = inputs[0] + capture["y1"] = _extract_hidden_tensor(output) + + handles: List[object] = [ + student_layers[pair_idx].register_forward_hook(_hook_l), + _register_forward_pre_hook_with_optional_kwargs( + student_layers[pair_idx + 1], _hook_recv_pre + ), + student_layers[pair_idx + 1].register_forward_hook(_hook_recv), + ] + try: + with autocast_ctx: + student_outputs = student_model( + input_ids=input_ids, + attention_mask=attention_mask, + use_cache=False, + ) + student_logits = student_outputs.logits + finally: + for handle in handles: + try: + handle.remove() + except Exception: + pass + + with autocast_ctx: + anchor_kl = _masked_kl( + teacher_logits, + student_logits, + attention_mask, + temp=temp, + detach_p=True, + chunk_size=int(getattr(args, "kl_chunk_size", 16384)), + ) + if anchor_kl is None: + continue + anchor_loss = (temp ** 2) * anchor_kl + + interaction_loss = None + h_l = capture.get("h_l") + h_lp1 = capture.get("h_lp1") + y1 = capture.get("y1") + recv_args = capture.get("recv_args") + recv_kwargs = capture.get("recv_kwargs") + if ( + isinstance(h_l, torch.Tensor) + and isinstance(h_lp1, torch.Tensor) + and isinstance(y1, torch.Tensor) + and isinstance(recv_args, tuple) + and len(recv_args) > 0 + and isinstance(recv_args[0], torch.Tensor) + ): + first_hidden = recv_args[0] + receiver_device = first_hidden.device + call_args = list( + _move_tensor_tree_to_device(recv_args, receiver_device) + ) + h_l_detached = h_l.detach().to( + device=receiver_device, + dtype=first_hidden.dtype, + ) + call_args[0] = h_l_detached + call_kwargs = ( + _move_tensor_tree_to_device(dict(recv_kwargs), receiver_device) + if isinstance(recv_kwargs, dict) + else {} + ) + + y0_raw = student_layers[pair_idx + 1](*tuple(call_args), **call_kwargs) + y0 = _extract_hidden_tensor(y0_raw) + if isinstance(y0, torch.Tensor): + if y0.device != y1.device: + y0 = y0.to(y1.device) + h_lp1_detached = h_lp1.detach().to(device=y1.device, dtype=y1.dtype) + h_l_for_res = h_l.detach().to(device=y0.device, dtype=y0.dtype) + r1 = y1 - h_lp1_detached + r0 = y0 - h_l_for_res + mask = attention_mask.to(device=r1.device, dtype=r1.dtype) + mask_sum = mask.sum() + if mask_sum.item() > 0: + if interaction_mode == "relative": + num = (r1 - r0).float().pow(2).sum(dim=-1) + den = r1.float().pow(2).sum(dim=-1) + float(interaction_eps) + ratio = (num / den) * mask.to(num.dtype) + interaction_loss = ratio.sum() / (mask_sum + 1e-8) + else: + denom = mask_sum * r1.size(-1) + if denom.item() > 0: + interaction_loss = ( + (r1 - r0).pow(2) * mask.unsqueeze(-1) + ).sum() / denom + + mu_effective = float(base_mu) + if ( + mu_auto + and interaction_loss is not None + and receiver_params + and mu_auto_rho > 0.0 + ): + anchor_grads = torch.autograd.grad( + anchor_loss, + receiver_params, + retain_graph=True, + allow_unused=True, + ) + interaction_grads = torch.autograd.grad( + interaction_loss, + receiver_params, + retain_graph=True, + allow_unused=True, + ) + anchor_norm = _grad_l2_norm(list(anchor_grads)) + interaction_norm = _grad_l2_norm(list(interaction_grads)) + if interaction_norm > 0.0: + mu_effective = float( + mu_auto_rho + * (anchor_norm / (interaction_norm + float(mu_auto_eps))) + ) + else: + mu_effective = float(base_mu) + if not math.isfinite(mu_effective): + mu_effective = float(base_mu) + + total_loss = anchor_loss + if interaction_loss is not None: + if interaction_loss.device != total_loss.device: + interaction_loss = interaction_loss.to(total_loss.device) + total_loss = total_loss + (float(mu_effective) * interaction_loss) + + if grad_accum > 1: + total_loss = total_loss / float(grad_accum) + + if use_scaler: + scaler.scale(total_loss).backward() + else: + total_loss.backward() + + # Only the sampled receiver layer updates on this micro-batch. + for param in trainable_params: + if id(param) in receiver_param_ids: + continue + if param.grad is not None: + if comm_train_mode == "lora": + param.grad.zero_() + else: + param.grad = None + + total_loss_sum += float(total_loss.detach().float().item()) + anchor_sum += float(anchor_loss.detach().float().item()) + if interaction_loss is not None: + interaction_sum += float(interaction_loss.detach().float().item()) + mu_sum += float(mu_effective) + counted += 1 + accum_done += 1 + + if args.distill_max_grad_norm is not None: + if use_scaler: + scaler.unscale_(optimizer) + torch.nn.utils.clip_grad_norm_( + trainable_params, + float(args.distill_max_grad_norm), + ) + + if use_scaler: + scaler.step(optimizer) + scaler.update() + else: + optimizer.step() + + opt_step += 1 + if log_steps and (opt_step == 1 or opt_step % log_steps == 0): + denom = max(counted, 1) + print( + f"[comm] step={opt_step}/{target_opt_steps} " + f"loss={total_loss_sum/denom:.6f} " + f"anchor={anchor_sum/denom:.6f} " + f"int={interaction_sum/denom:.6f} " + f"mu={mu_sum/denom:.6f}" + ) + + if comm_train_mode == "lora": + merge_lora_adapters(student_model) + + gap_post = None + if bool(getattr(args, "comm_measure_gap", False)): + max_gap_batches = int(getattr(args, "comm_gap_max_batches", 8)) + gap_post = _measure_commutator_gap( + student_model=student_model, + student_layers=student_layers, + dataloader=measure_dataloader if measure_dataloader is not None else dataloader, + pair_idx=measured_pair, + args=args, + max_batches=max_gap_batches, + interaction_eps=interaction_eps, + ) + if gap_post.get("enabled"): + print( + "[comm-gap] post " + f"pair={measured_pair}-{measured_pair + 1} " + f"{_format_comm_gap_stats(gap_post)} " + f"batches={gap_post.get('batches')}" + ) + else: + print(f"[comm-gap] post measurement skipped: {gap_post.get('reason')}") + + stats: Dict[str, object] = { + "enabled": True, + "train_mode": comm_train_mode, + "opt_steps": int(target_opt_steps), + "grad_accum_steps": int(grad_accum), + "lr": float(lr), + "temp": float(temp), + "steps_ratio": float(steps_ratio), + "lr_scale": float(lr_scale), + "interaction_mode": interaction_mode, + "interaction_eps": float(interaction_eps), + "mu": float(base_mu), + "mu_auto": bool(mu_auto), + "mu_auto_rho": float(mu_auto_rho), + "mu_auto_eps": float(mu_auto_eps), + "sample_eta": float(sample_eta), + "sample_dwce_scale": float(sample_dwce_scale), + "topk": int(top_k), + "candidate_pairs": [int(i) for i in candidate_pairs], + "trainable_params": int(sum(int(param.numel()) for param in trainable_params)), + } + if gap_pre is not None or gap_post is not None: + stats["gap_pair"] = int(measured_pair) + stats["gap_pre"] = gap_pre + stats["gap_post"] = gap_post + if ( + isinstance(gap_pre, dict) + and isinstance(gap_post, dict) + and gap_pre.get("enabled") + and gap_post.get("enabled") + ): + stats["gap_delta"] = { + key: float(gap_post[key] - gap_pre[key]) + for key in ("mse", "relative", "cosine_distance") + if key in gap_pre and key in gap_post + } + pre_components = gap_pre.get("components") + post_components = gap_post.get("components") + if isinstance(pre_components, dict) and isinstance(post_components, dict): + component_delta = {} + for name, pre_value in pre_components.items(): + post_value = post_components.get(name) + if not isinstance(pre_value, dict) or not isinstance(post_value, dict): + continue + component_delta[name] = { + key: float(post_value[key] - pre_value[key]) + for key in ("mse", "relative", "cosine_distance") + if key in pre_value and key in post_value + } + if component_delta: + stats["gap_delta"]["components"] = component_delta + stats["gap_ratio_post_over_pre"] = _comm_gap_ratio(gap_pre, gap_post) + total_samples = int(sum(pair_counts)) + probs_list = [float(x) for x in probs_by_pair] + freqs = ( + [float(c) / float(total_samples) for c in pair_counts] + if total_samples > 0 + else [0.0 for _ in pair_counts] + ) + top_show = min(10, num_pairs) + top_indices = sorted(range(num_pairs), key=lambda i: pair_counts[i], reverse=True)[:top_show] + top_pairs = [ + { + "pair": int(i), + "count": int(pair_counts[i]), + "freq": float(freqs[i]), + "prob": float(probs_list[i]) if i < len(probs_list) else None, + } + for i in top_indices + if pair_counts[i] > 0 + ] + stats["pair_selection"] = { + "num_pairs": int(num_pairs), + "excluded_pairs": sorted(exclude_set), + "candidate_pairs": [int(i) for i in candidate_pairs], + "total_samples": total_samples, + "unique_pairs": int(sum(1 for c in pair_counts if c > 0)), + "counts": [int(c) for c in pair_counts], + "freqs": freqs, + "probs": probs_list, + "top_pairs": top_pairs, + } + + if total_samples > 0 and top_pairs: + top_str = ", ".join( + f"{entry['pair']}-{entry['pair'] + 1}: {entry['count']} " + f"(obs={entry['freq']:.3f}, exp={entry['prob']:.3f})" + for entry in top_pairs + if entry.get("prob") is not None + ) + if not top_str: + top_str = ", ".join( + f"{entry['pair']}-{entry['pair'] + 1}: {entry['count']} " + f"(obs={entry['freq']:.3f})" + for entry in top_pairs + ) + print( + f"[comm] Pair sampling stats: total={total_samples} " + f"unique={stats['pair_selection']['unique_pairs']}/{num_pairs} " + f"top={top_str}" + ) + + if counted > 0: + stats["avg_loss"] = float(total_loss_sum / float(counted)) + stats["avg_anchor"] = float(anchor_sum / float(counted)) + stats["avg_interaction"] = float(interaction_sum / float(counted)) + stats["avg_mu"] = float(mu_sum / float(counted)) + return stats diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/launch_llama31_come_fit2.sh b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/launch_llama31_come_fit2.sh new file mode 100644 index 0000000000000000000000000000000000000000..2938bb8d096198d567bab00619cc2bcf4f979c4d --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/launch_llama31_come_fit2.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash +set -euo pipefail +project="$1"; external="$2"; root="$3"; base_model="$4"; inst_model="$5"; alias="$6" +scope="${7:-full}"; fit=(--fit-full-block); experiment=20261008-llama31-come-fullblock-fit2 +protocol=exp_md/2026-10-08_llama31-come-stagewise-fullblock-fit2.md +if [[ "$scope" == mlp ]]; then + fit=(--fit-come-mlp); experiment=20261008-llama31-come-mlp-fit2 + protocol=exp_md/2026-10-08_llama31-come-stagewise-mlp-fit2.md +elif [[ "$scope" != full ]]; then exit 2; fi +export HF_HOME=/workspace/.hf_home HF_TOKEN_PATH=/root/.cache/huggingface/token +export HF_DATASETS_CACHE=/workspace/.hf_datasets36 HF_DATASETS_TRUST_REMOTE_CODE=1 +export PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false OMP_NUM_THREADS=4 +export PYTHONPATH="$project/src:$external/src" +mkdir -p "$root" +trap 'rc=$?; if ((rc)); then touch "$root/FAILED"; fi' EXIT +while [[ ! -f "$root/DEPS_READY" ]]; do [[ ! -f "$root/BOOTSTRAP_FAILED" ]] || exit 1; sleep 3; done +python -m pytest -q "$project/tests/test_come.py" > "$root/unit_tests.log" 2>&1 +python "$project/scripts/run_llama31_base_fit_ablation.py" --external-root "$external" \ + --initializer come "${fit[@]}" --audit-root "$root/algebra" --self-test >> "$root/unit_tests.log" 2>&1 +# Evaluation preparation runs independently: it must never block fitting or PPL. +prepare_eval() ( + [[ ! -f "$root/EVAL_READY" ]] || exit 0 + trap 'rc=$?; if ((rc)); then touch "$root/EVAL_PREP_FAILED"; fi' EXIT + mkdir -p "$root/eval_data" + while [[ ! -f "$root/EVAL_ASSETS_READY" ]]; do sleep 3; done + tar -xzf "$root/opencompass5-data.tar.gz" -C "$root/eval_data" + if [[ -f "$root/lmeval-cache-131.tar.gz" ]]; then + mkdir -p "$root/lmeval_cache" + tar -xzf "$root/lmeval-cache-131.tar.gz" -C "$root/lmeval_cache" + else + # Slow SSH cache transfers must not turn into GPU-idle serialization. + # Warm common archives once, then materialize identical task definitions in + # parallel. Retry preserves completed source.json caches after extraction races. + python - <<'PY' +import datasets +from concurrent.futures import ThreadPoolExecutor +jobs=[('cais/mmlu','anatomy'),('haonan-li/cmmlu','anatomy'),('Salesforce/wikitext','wikitext-2-raw-v1')] +with ThreadPoolExecutor(max_workers=3) as p: + for f in [p.submit(datasets.load_dataset,*j,trust_remote_code=True) for j in jobs]:f.result() +PY + for attempt in 1 2 3; do + python "$project/scripts/prepare_lmeval9_local_cache.py" "$root/lmeval_cache" --workers 8 && break + [[ "$attempt" -lt 3 ]] || exit 1 + done + fi + HF_HUB_OFFLINE=1 HF_DATASETS_OFFLINE=1 python "$project/scripts/prepare_lmeval9_local_cache.py" \ + "$root/lmeval_cache" --validate-local + python "$project/scripts/prepare_offline_ppl_cache.py" "$root" + touch "$root/EVAL_READY" +) +prepare_eval > "$root/eval_prepare.log" 2>&1 & eval_pid=$! +run_job() ( + family="$1"; gpu="$2"; model="$base_model"; revision=d04e592bb4f6aa9cfee91e2e20afa771667e1d4b + if [[ "$family" == instruct ]]; then model="$inst_model"; revision=0e9e39f249a16976918f6564b8830bc894c89659; fi + ready="${family^^}_READY" + trap 'rc=$?; if ((rc)); then touch "$root/FAILED" "$root/${family}_FAILED"; fi' EXIT + while [[ ! -f "$root/$ready" ]]; do [[ ! -f "$root/BOOTSTRAP_FAILED" ]] || exit 1; sleep 3; done + smoke="$root/smoke/$family" + if [[ ! -f "$smoke/SMOKE_VERIFIED" ]]; then + if [[ ! -f "$smoke/TRAIN_COMPLETE" ]]; then + bash "$project/scripts/run_llama31_come_fit_arm.sh" "$project" "$external" "$smoke" "$model" "$family" "$gpu" smoke "$scope" + fi + python - "$smoke" "$scope" <<'PY' +import json,sys +from pathlib import Path +r=Path(sys.argv[1]) +mlp=sys.argv[2]=='mlp' +for c in (1,2): + f=json.loads((r/f'audit/cycle_{c:02d}_fit.json').read_text()); ab=f['ablation'] + assert f['trained'] and f['additive_u'] and ab['fit_scope']==('mlp' if mlp else 'full_block_including_norms') + assert ab['attention_initialization']=='CoMe_channel_merge' and ab['norms_trainable']==(not mlp) + assert not ab['fisher_computed'] and not ab['source_feature_transport'] + count=3 if mlp else 9 + 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) + for phase in f['first_grad_summary'].values(): + assert phase['u']['num_tensors']==count and phase['u']['num_tensors_without_grad']==0 and phase['u']['l2']>0 + d=f['u_delta_summary']['per_tensor'] + assert len(d)==count and all(v['rms']>0 for v in d.values()), d + assert sum('layernorm' in k for k in d)==(0 if mlp else 2) + if mlp: + assert len(ab['frozen_CoMe_parameters'])==6 +print('TWO_CYCLES_FIT_SCOPE_UPDATES_VERIFIED',sys.argv[2],flush=True) +PY + touch "$smoke/SMOKE_VERIFIED" + fi + output="$root/full/$family" + if [[ ! -f "$output/TRAIN_COMPLETE" ]]; then + bash "$project/scripts/run_llama31_come_fit_arm.sh" "$project" "$external" "$output" "$model" "$family" "$gpu" full "$scope" + fi + mkdir -p "$output/eval" + export MODEL_REVISION="$revision" + if [[ ! -f "$output/eval/final_ppl.json" ]]; then + CUDA_VISIBLE_DEVICES="$gpu" python "$project/scripts/evaluate_abprune_compact_ppl.py" \ + --model "$model" --revision "$revision" --compact-stage "$output/compact/stage_08" \ + --anchor 21 --cycles 8 --original-layers 32 --seq-len 2048 --batch-size 8 \ + --output "$output/eval/final_ppl.json" > "$output/logs/ppl.log" 2>&1 + fi + while [[ ! -f "$root/EVAL_READY" ]]; do [[ ! -f "$root/EVAL_PREP_FAILED" ]] || exit 1; sleep 3; done + export LMEVAL_LOCAL_CACHE="$root/lmeval_cache" + bash "$project/scripts/eval_llama31_fit_ablation_one.sh" "$project" "$output" "$model" \ + "$root/eval_data/data" "$(command -v python)" 21 8 "$gpu" + touch "$output/EVAL_COMPLETE" + backup="$root/backup/$family" + if [[ ! -d "$backup" ]]; then + python "$project/scripts/package_final_fit_backup.py" "$output" "$backup" "$project" "$external" --protocol "$protocol" + git -C "$project" rev-parse HEAD > "$backup/code/project_commit.txt" + python "$project/scripts/write_tree_manifest.py" "$backup" + fi + # Evaluation stays offline; uploading must explicitly override inherited flags. + HF_HUB_OFFLINE=0 HF_DATASETS_OFFLINE=0 TRANSFORMERS_OFFLINE=0 \ + python "$project/scripts/upload_verified_hf_tree.py" "$backup" --repo-id LJYAI/paper_revision \ + --path-in-repo "runs/$alias/$experiment/$family" \ + --commit-message "Llama31 $family CoMe stagewise $scope FiT final weights PPL bench14" > "$root/${family}_backup.json" + touch "$output/BACKUP_COMPLETE" +) +run_job base 0 > "$root/base_pipeline.log" 2>&1 & base_pid=$! +run_job instruct 1 > "$root/instruct_pipeline.log" 2>&1 & inst_pid=$! +failed=0 +for pid in "$base_pid" "$inst_pid" "$eval_pid"; do wait "$pid" || failed=1; done +((failed == 0)) || exit 1 +python "$project/scripts/collect_llama31_come_fit2.py" "$root" +touch "$root/COMPLETE" +echo "CoMe $scope FiT evaluated/backed up; retain instance pending user instruction." diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/launch_mka_batch_comparison.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/launch_mka_batch_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..a068bf264eaffe2cd1108e057ca808229a38ceda --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/launch_mka_batch_comparison.py @@ -0,0 +1,268 @@ +"""Run native-MKA MLP-only FiT on an existing host, keeping the host running.""" +import argparse +from concurrent.futures import ThreadPoolExecutor +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import threading +import time + + +FIT_IDS = "2b2d044c8c040f67891817ecc110f0fa0de2f469db4c6731114ff7816bbf1cd0" +FIT_MASK = "c8e7f8e30cd532b82e6af4b98d596bc7106f29f9fb2b398b44355e624898a30d" +REVISION = "d04e592bb4f6aa9cfee91e2e20afa771667e1d4b" + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--project", type=Path, required=True) + p.add_argument("--external", type=Path, required=True) + p.add_argument("--root", type=Path, required=True) + p.add_argument("--model", required=True) + p.add_argument("--session", required=True) + p.add_argument("--selection-data", type=Path, required=True) + p.add_argument("--selection-metadata", type=Path) + p.add_argument("--expected-selection-hash", required=True) + p.add_argument("--eval-root", type=Path, required=True, + help="Existing completed run with eval_data, lmeval_cache and offline WikiText policy") + p.add_argument("--larger-batch", type=int, default=8) + p.add_argument("--profile-only", action="store_true", + help="Stop after validated probes so the controller can audit native first-stage selection") + p.add_argument("--experiment-id", default="20261126-llama31-mka-mlp-batch") + p.add_argument("--protocol", default="exp_md/2026-11-26_llama31-mka-mlp-batch-comparison.md") + a = p.parse_args() + root = a.root.resolve() + root.mkdir(parents=True, exist_ok=True) + env = dict(os.environ, HF_HOME="/workspace/.hf_home", + HF_TOKEN_PATH="/root/.cache/huggingface/token", + HF_DATASETS_CACHE="/workspace/.hf_datasets36", HF_DATASETS_TRUST_REMOTE_CODE="1", + HF_HUB_OFFLINE="1", HF_DATASETS_OFFLINE="1", TRANSFORMERS_OFFLINE="1", + PYTHONUNBUFFERED="1", TOKENIZERS_PARALLELISM="false", OMP_NUM_THREADS="4", + PYTHONPATH=f"{a.project}/src:{a.external}/src") + state = {"experiment": a.experiment_id, "session": a.session, "fit_scope": "mlp", + "method": "native MKA + MLP-only FiT", "phase": "validation", "arms": {}, + "instance_return_policy": "explicit_user_instruction_only", "auto_return": False} + lock = threading.RLock() + + def save(): + with lock: + state["updated_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + temporary = root / "status.partial" + temporary.write_text(json.dumps(state, indent=2) + "\n") + temporary.replace(root / "status.json") + + def run(command, log, gpu=None, check=True): + child_env = dict(env) + if gpu is not None: + child_env["CUDA_VISIBLE_DEVICES"] = str(gpu) + log.parent.mkdir(parents=True, exist_ok=True) + with log.open("a") as stream: + result = subprocess.run([str(x) for x in command], env=child_env, cwd=a.project, + stdout=stream, stderr=subprocess.STDOUT) + if check and result.returncode: + raise RuntimeError(f"Command failed ({result.returncode}); see {log}") + return result.returncode + + def validate_fit(fit, batch, tokens, require_gradients=False): + assert fit["trained"] and fit["num_trainable_mlp_gates"] == 3 + assert fit["num_trainable_attn_gates"] == 0 and fit["num_trainable_other_gates"] == 0 + audit = fit["ablation"] + assert audit["fit_scope"] == "mlp" and audit["attention_initialization"] == "MKA_merge" + assert not audit["norms_trainable"] and audit["frozen_attention_norm_unchanged"] + expected = audit["frozen_attention_norm_expected_sha256"] + assert len(expected) == 6 + assert audit["frozen_attention_norm_before_sha256"] == expected + assert audit["frozen_attention_norm_after_sha256"] == expected + assert not audit["source_feature_transport"] + assert fit["runtime"]["batch_size"] == batch + assert fit["runtime"]["dataset_tokens"] == tokens + if require_gradients: + assert fit["first_grad_summary"]["joint"]["u"]["num_tensors_without_grad"] == 0 + changes = fit["u_delta_summary"]["per_tensor"] + assert len(changes) == 3 and all(v["rms"] > 0 for v in changes.values()) + + selection = root / "calibration/selection.pt" + + def train_command(out, batch, gpu, cycles=8, tokens=524288): + return ["bash", a.project / "scripts/run_mka_batch_arm.sh", a.project, a.external, + out, a.model, selection, batch, gpu, cycles, tokens, a.expected_selection_hash] + + def complete_arm(name, batch, gpu): + out = root / "full" / name + out.mkdir(parents=True, exist_ok=True) + with lock: + state["arms"][name] = {"phase": "training", "batch_size": batch, "gpu": gpu, + "started_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + save() + if not (out / "TRAIN_COMPLETE").exists(): + started = time.time() + run(train_command(out, batch, gpu), root / f"{name}_pipeline.log") + (out / "training_elapsed.json").write_text(json.dumps({ + "wall_seconds": time.time() - started, + "completed_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}, indent=2) + "\n") + for cycle in range(1, 9): + validate_fit(json.loads((out / "audit" / f"cycle_{cycle:02d}_fit.json").read_text()), + batch, 524288, require_gradients=True) + fingerprints = json.loads((out / "audit/data_fingerprints.json").read_text()) + assert fingerprints["distill_loader"]["sha256"] == FIT_IDS + assert fingerprints["distill_loader"]["attention_mask_sha256"] == FIT_MASK + native = json.loads((out / "audit/selection_inputs.json").read_text()) + assert native["input_ids_sha256"] == a.expected_selection_hash and native["sequences"] == 100 + with lock: + state["arms"][name]["phase"] = "evaluation" + save() + (out / "eval").mkdir(exist_ok=True) + if not (out / "eval/final_ppl.json").exists(): + run([sys.executable, a.project / "scripts/evaluate_abprune_compact_ppl.py", + "--model", a.model, "--revision", REVISION, + "--compact-stage", out / "compact/stage_08", "--anchor", 21, "--cycles", 8, + "--original-layers", 32, "--seq-len", 2048, "--batch-size", 8, + "--output", out / "eval/final_ppl.json"], root / f"{name}_ppl.log", gpu) + eval_env = dict(env, LMEVAL_LOCAL_CACHE=str(a.eval_root / "lmeval_cache"), MODEL_REVISION=REVISION) + with (root / f"{name}_eval.log").open("a") as stream: + subprocess.run(["bash", str(a.project / "scripts/eval_llama31_fit_ablation_one.sh"), + str(a.project), str(out), a.model, str(a.eval_root / "eval_data/data"), + sys.executable, "21", "8", str(gpu)], env=eval_env, check=True, + stdout=stream, stderr=subprocess.STDOUT) + (out / "EVAL_COMPLETE").touch() + with lock: + state["arms"][name]["phase"] = "backup" + save() + backup = root / "backup" / name + if not backup.exists(): + run([sys.executable, a.project / "scripts/package_final_fit_backup.py", out, backup, + a.project, a.external, "--protocol", a.protocol], root / f"{name}_backup.log") + for filename in ("launch_mka_batch_comparison.py", "run_mka_batch_arm.sh", + "collect_mka_batch_comparison.py", "prepare_mka_batch_calibration.py", + "validate_mka_first_selection.py", "validate_mka_runtime_geometry.py", + "finalize_mka_batch_report.py"): + shutil.copy2(a.project / "scripts" / filename, backup / "code" / filename) + shutil.copy2(a.project / "src/fusegpt/fit_ablation_mka.py", backup / "code/fit_ablation_mka.py") + shutil.copy2(a.project / "src/fusegpt/mka.py", backup / "code/mka.py") + for filename in ("selection_provenance.json", "batch_profile.json", "native_first_selection.json"): + shutil.copy2(root / filename, backup / filename) + shutil.copy2(out / "training_elapsed.json", backup / "training_elapsed.json") + (backup / "code/project_commit.txt").write_text(subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=a.project, text=True)) + run([sys.executable, a.project / "scripts/write_tree_manifest.py", backup], + root / f"{name}_backup.log") + upload_env = dict(env, HF_HUB_OFFLINE="0", HF_DATASETS_OFFLINE="0", TRANSFORMERS_OFFLINE="0") + with (root / f"{name}_backup.json").open("w") as stream: + subprocess.run([sys.executable, str(a.project / "scripts/upload_verified_hf_tree.py"), str(backup), + "--repo-id", "LJYAI/paper_revision", "--path-in-repo", + f"runs/{a.session}/{a.experiment_id}/{name}", "--commit-message", + f"Native MKA Llama Base MLP-only FiT {name}"], + env=upload_env, stdout=stream, check=True) + (out / "BACKUP_COMPLETE").touch() + with lock: + state["arms"][name]["phase"] = "complete" + save() + + save() + try: + # Inspect only frozen inputs; never regenerate native geometry samples. + import torch + batches = torch.load(a.selection_data, weights_only=True, map_location="cpu") + assert len(batches) == 100 + ids_hash, masks_hash = hashlib.sha256(), hashlib.sha256() + for batch in batches: + ids, mask = batch["input_ids"], batch["attention_mask"] + assert tuple(ids.shape) == (1, 512) and ids.shape == mask.shape and bool(mask.any()) + ids_hash.update(ids.numpy().astype(" 1 + and r["memory_margin_bytes"] >= 4 * 1024**3] + if a.larger_batch not in {r["batch_size"] for r in eligible}: + raise RuntimeError("Required larger batch failed profile/memory gates; do not reduce silently") + profile = {"profiles": profiles, "selected_larger_batch": a.larger_batch, + "selection_rule": "Required user comparison batch, profiled with >=4GiB margin", + "training_updates_per_stage": {"batch1": 512, "batch_large": 512 // a.larger_batch}} + (root / "batch_profile.json").write_text(json.dumps(profile, indent=2) + "\n") + if a.profile_only: + state["phase"] = "profile_complete" + state["larger_batch"] = a.larger_batch + save() + (root / "PROFILE_COMPLETE").touch() + return + native_check = json.loads((root / "native_first_selection.json").read_text()) + assert native_check["passed"], "Historical pre-FiT MKA selection must pass before production" + state["phase"] = "production" + state["larger_batch"] = a.larger_batch + save() + with ThreadPoolExecutor(max_workers=2) as pool: + jobs = [pool.submit(complete_arm, "batch1", 1, 0), + pool.submit(complete_arm, "batch_large", a.larger_batch, 1)] + for job in jobs: + job.result() + state["phase"] = "complete" + save() + (root / "COMPLETE").touch() + except Exception as error: + state["phase"] = "failed" + state["error"] = str(error) + save() + (root / "FAILED").touch() + raise + + +if __name__ == "__main__": + main() diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/mka.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/mka.py new file mode 100644 index 0000000000000000000000000000000000000000..a06594bd33dfbea70c54093a43d7cb65e8abb9a1 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/mka.py @@ -0,0 +1,505 @@ +"""Corrected MKA variant: adjacent NPIB selection, upstream lambda, real fusion. + +Not an exact reproduction of the paper: use sequence-level pooled activations, +recompute geometry after every merge, and resolve NPIB ties back-to-front. +The seven projection weights are fused; residual and Q/K norms stay at anchor. +""" + +from __future__ import annotations + +import hashlib +import math +import random +import time +from collections.abc import Callable, Iterable, Sequence +from dataclasses import asdict, dataclass + +import numpy as np +import torch +from scipy.linalg import eigh +from scipy.spatial.distance import pdist, squareform +from sklearn.feature_selection import mutual_info_regression +from sklearn.neighbors import NearestNeighbors +from torch import Tensor, nn + +PROJECTION_WEIGHTS = ( + "mlp.down_proj.weight", + "mlp.up_proj.weight", + "mlp.gate_proj.weight", + "self_attn.k_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_proj.weight", + "self_attn.v_proj.weight", +) +UPSTREAM = "https://github.com/SempraETY/Pruning-via-Merging" +UPSTREAM_COMMIT = "3b60b002a0963266e2f4ca78f133b4e091bc607a" + + +@dataclass(frozen=True) +class GeometryConfig: + sigma: float = 8.0 + alpha: float = 0.5 + dimensions: int = 2 + mi_neighbors: int = 5 + entropy_neighbors: int = 50 + beta: float = 1.0 + seed: int = 0 + pooling: str = "mean" + + def validate(self) -> None: + if not math.isfinite(self.sigma) or self.sigma <= 0: + raise ValueError("sigma must be positive and finite") + if not math.isfinite(self.alpha) or not 0 <= self.alpha <= 1: + raise ValueError("alpha must be finite and in [0, 1]") + if self.dimensions < 1 or min(self.mi_neighbors, self.entropy_neighbors) < 1: + raise ValueError("dimensions and neighbor counts must be positive") + if not math.isfinite(self.beta) or self.beta < 0: + raise ValueError("beta must be non-negative and finite") + if self.pooling not in {"mean", "last"}: + raise ValueError("pooling must be 'mean' or 'last'") + + +def sample_slimpajama( + tokenizer, + *, + samples: int = 100, + sequence_length: int = 512, + seed: int = 0, + revision: str = "b5f90f419b7489cdba26fdbc8c022fcb5562f968", + shuffle_buffer: int = 10000, + max_documents: int = 100000, + documents: Iterable[dict] | None = None, +) -> tuple[list[dict[str, Tensor]], dict]: + """Exactly one random fixed-length, no-BOS window from each distinct document. + + Unlike CoMe's row-packing loader, ``samples`` is the number of sequences. + Persist returned IDs and provenance; do not sample again between stages. + """ + if min(samples, sequence_length, shuffle_buffer, max_documents) < 1: + raise ValueError("sampling counts, length and buffer must be positive") + if documents is None: + from datasets import load_dataset + + documents = load_dataset( + "DKYoon/SlimPajama-6B", revision=revision, split="train", streaming=True + ).shuffle(seed=seed, buffer_size=shuffle_buffer) + rng = random.Random(seed) + batches, records, seen = [], [], set() + iterator = iter(documents) + try: + for row_index, row in enumerate(iterator): + if row_index >= max_documents: + break + text = row.get("text") + if not isinstance(text, str) or not text.strip(): + continue + digest = hashlib.sha256(text.encode("utf-8")).hexdigest() + if digest in seen: + continue + seen.add(digest) + ids = tokenizer.encode(text, add_special_tokens=False) + if len(ids) < sequence_length: + continue + start = rng.randrange(len(ids) - sequence_length + 1) + tensor = torch.tensor( + ids[start : start + sequence_length], dtype=torch.long + )[None, :] + batches.append( + {"input_ids": tensor, "attention_mask": torch.ones_like(tensor)} + ) + records.append( + { + "stream_row": row_index, + "document_sha256": digest, + "document_tokens": len(ids), + "window_start": start, + } + ) + if len(batches) == samples: + break + finally: + close = getattr(iterator, "close", None) + if close is not None: + close() + if len(batches) != samples: + raise RuntimeError( + f"Only found {len(batches)}/{samples} distinct sufficiently long documents" + ) + checksum = hashlib.sha256() + for batch in batches: + checksum.update(batch["input_ids"].numpy().astype(" list[np.ndarray]: + """One backbone forward per batch; block hooks avoid hidden-state off-by-one. + + Collect outputs *before* the final backbone norm, including the final block. + Pool only valid tokens; activations are CPU float32 after pooling. + """ + if pooling not in {"mean", "last"} or not batches: + raise ValueError("valid pooling and nonempty calibration batches are required") + layers = model.model.layers + features: list[list[Tensor]] = [[] for _ in layers] + current_mask: Tensor | None = None + + def hook(index): + def capture(module, inputs, output): + hidden = output[0] if isinstance(output, (tuple, list)) else output + mask = current_mask.to(hidden.device, dtype=torch.bool) + if hidden.shape[:2] != mask.shape or (mask.sum(-1) == 0).any(): + raise ValueError("block output and valid-token mask do not match") + if pooling == "mean": + value = (hidden.float() * mask[:, :, None]).sum(1) / mask.sum(1)[ + :, None + ] + else: + positions = torch.arange(mask.shape[1], device=mask.device)[None, :] + last = positions.expand_as(mask).masked_fill(~mask, -1).max(1).values + value = hidden[ + torch.arange(hidden.shape[0], device=hidden.device), last + ].float() + if not torch.isfinite(value).all(): + raise FloatingPointError(f"nonfinite activation in block {index}") + features[index].append(value.cpu()) + + return capture + + handles = [layer.register_forward_hook(hook(i)) for i, layer in enumerate(layers)] + was_training = model.training + model.eval() + try: + device = model.get_input_embeddings().weight.device + for batch in batches: + prepared = {key: value.to(device) for key, value in batch.items()} + current_mask = prepared.get( + "attention_mask", torch.ones_like(prepared["input_ids"]) + ) + model.model(**prepared, use_cache=False, return_dict=True) + finally: + for handle in handles: + handle.remove() + model.train(was_training) + expected = sum(batch["input_ids"].shape[0] for batch in batches) + arrays = [torch.cat(parts, dim=0).numpy() for parts in features] + if any(array.shape[0] != expected for array in arrays): + raise RuntimeError("not all calibration examples reached each decoder block") + return arrays + + +def diffusion_embedding( + features: np.ndarray, config: GeometryConfig +) -> tuple[np.ndarray, dict]: + """Correctly shaped sample-by-sample diffusion kernel, following upstream SVD geometry.""" + config.validate() + x = np.asarray(features, dtype=np.float64) + if x.ndim != 2 or not np.isfinite(x).all() or len(x) <= config.dimensions + 1: + raise ValueError( + "features must be finite [samples, features], samples > dimensions + 1" + ) + distance = squareform(pdist(x, metric="euclidean")) + if distance.max() <= np.finfo(float).eps: + raise ValueError( + "constant calibration features: cannot estimate manifold geometry" + ) + kernel = np.exp(-np.sqrt(distance / config.sigma)) + p = kernel.sum(0) + normalized = kernel / np.outer(p, p) ** config.alpha + v = np.sqrt(normalized.sum(0)) + operator = normalized / np.outer(v, v) + condition = float(np.linalg.cond(operator)) + regularization = 1e-6 if not math.isfinite(condition) or condition > 1e12 else 0.0 + if regularization: + operator += regularization * np.eye(len(x)) + values, vectors = eigh( + operator, subset_by_index=(len(x) - config.dimensions - 1, len(x) - 1) + ) + values, vectors = values[::-1], vectors[:, ::-1] + # Fix arbitrary eigenvector signs; the leading vector of this positive kernel is positive. + for dim in range(vectors.shape[1]): + if vectors[np.argmax(np.abs(vectors[:, dim])), dim] < 0: + vectors[:, dim] *= -1 + if np.any(np.abs(vectors[:, 0]) < 1e-12): + raise FloatingPointError( + "diffusion normalization has a near-zero leading eigenvector" + ) + embedding = vectors[:, 1:] / vectors[:, :1] + if not np.isfinite(embedding).all(): + raise FloatingPointError("nonfinite diffusion embedding") + # Upstream uses per-axis rank normalization before its KNN estimators. + embedding = np.argsort( + np.argsort(embedding, axis=0, kind="stable"), axis=0, kind="stable" + ) / len(x) + return embedding, { + "samples": len(x), + "condition_number": condition if math.isfinite(condition) else None, + "regularization": regularization, + "eigenvalues": values.tolist(), + } + + +def entropy_knn(x: np.ndarray, neighbors: int) -> float: + """Upstream differential-entropy estimator, evaluated in log space.""" + n, dimensions = x.shape + k = min(neighbors, n - 1) + distances = NearestNeighbors(n_neighbors=k + 1).fit(x).kneighbors(x)[0][:, -1] + if np.any(distances <= 0) or not np.isfinite(distances).all(): + raise FloatingPointError( + "duplicate/degenerate manifold points in entropy estimator" + ) + return float(math.log(n / k) + dimensions * np.log(distances).mean()) + + +def npib_matrix( + embeddings: Sequence[np.ndarray], config: GeometryConfig +) -> tuple[np.ndarray, list[float]]: + """Match upstream axis-wise MI average and symmetric sqrt(H_i*H_j) normalization. + + Differential entropies can be negative. Preserve upstream's formula when + their product is positive; fail clearly for zero/negative products or NaNs. + This estimator is a heuristic, not a guaranteed [0, 1] similarity. + """ + config.validate() + if not embeddings or len({x.shape for x in embeddings}) != 1: + raise ValueError("embeddings must have identical sample/coordinate shapes") + n = len(embeddings[0]) + if n < 3 or any(not np.isfinite(x).all() for x in embeddings): + raise ValueError("need at least three finite manifold points") + entropies = [entropy_knn(x, config.entropy_neighbors) for x in embeddings] + scores = np.empty((len(embeddings), len(embeddings)), dtype=np.float64) + for i, left in enumerate(embeddings): + for j in range(i, len(embeddings)): + right = embeddings[j] + product = entropies[i] * entropies[j] + if not math.isfinite(product) or product <= 1e-12: + raise FloatingPointError( + f"invalid entropy product at ({i}, {j}): {entropies[i]}, {entropies[j]}" + ) + mi = np.mean( + [ + np.mean( + mutual_info_regression( + left, + right[:, dim], + n_neighbors=min(config.mi_neighbors, n - 1), + random_state=config.seed, + ) + ) + for dim in range(right.shape[1]) + ] + ) + scores[i, j] = scores[j, i] = mi / math.sqrt(product) + if not np.isfinite(scores).all(): + raise FloatingPointError("NPIB contains nonfinite scores") + return scores, entropies + + +def upstream_lambda( + scores: np.ndarray, left: int, right: int, beta: float = 1.0 +) -> float: + """Exactly upstream's sigmoid(beta * row_mean_i / (row_mean_i + row_mean_j)).""" + means = np.mean(scores[[left, right]], axis=1) + total = float(means.sum()) + if not np.isfinite(means).all() or (means < 0).any() or total <= 1e-12: + raise FloatingPointError( + "cannot compute upstream lambda from nonpositive/nonfinite row means" + ) + if not math.isfinite(beta) or beta < 0: + raise ValueError("beta must be non-negative and finite") + value = beta * float(means[0]) / total + return 1.0 / (1.0 + math.exp(-value)) + + +def select_pair( + scores: np.ndarray, + *, + selection: str = "npib", + protected_first: int = 0, + protected_last: int = 0, +) -> int: + """Adjacent pairs only; NPIB descending, and deeper pair wins exact ties.""" + n = len(scores) + if scores.shape != (n, n) or not np.isfinite(scores).all(): + raise ValueError("scores must be a finite square matrix") + if min(protected_first, protected_last) < 0: + raise ValueError("protected layer counts must be non-negative") + candidates = range(protected_first, n - protected_last - 1) + if not candidates: + raise ValueError("no eligible adjacent pair remains") + if selection == "back-to-front": + return candidates[-1] + if selection != "npib": + raise ValueError("selection must be 'npib' or 'back-to-front'") + return max(candidates, key=lambda i: (float(scores[i, i + 1]), i)) + + +@torch.inference_mode() +def merge_pair(model: nn.Module, left: int, ratio: float) -> int: + """FP32 weighted sum copied into real parameters, then delete the right block.""" + layers = model.model.layers + if ( + not 0 <= left < len(layers) - 1 + or not math.isfinite(ratio) + or not 0 <= ratio <= 1 + ): + raise ValueError("invalid adjacent pair or merge ratio") + destination, source = layers[left], layers[left + 1] + pairs = [] + for name in PROJECTION_WEIGHTS: + pairs.append((destination.get_parameter(name), source.get_parameter(name))) + # Qwen2.5 has Q/K/V biases. Fuse them with the same coefficient; + # Llama and Qwen3 (bias-free projections) retain their existing behavior. + module_name = name.rsplit('.', 1)[0] + a_bias = getattr(destination.get_submodule(module_name), 'bias', None) + b_bias = getattr(source.get_submodule(module_name), 'bias', None) + if (a_bias is None) != (b_bias is None): + raise ValueError('projection bias presence differs between merge layers') + if a_bias is not None: + pairs.append((a_bias, b_bias)) + # Validate all shapes/values/config before any model mutation. + if any(a.shape != b.shape for a, b in pairs): + raise ValueError("projection shapes differ between merge layers") + if any(not torch.isfinite(p).all() for pair in pairs for p in pair): + raise FloatingPointError("nonfinite source weight") + configs = [model.config, model.model.config] + for config in configs: + types = getattr(config, "layer_types", None) + if types is not None and len(types) != len(layers): + raise ValueError("config.layer_types length does not match decoder depth") + changed = 0 + for target, other in pairs: + merged = torch.lerp( + other.detach().to(target.device, dtype=torch.float32), target.float(), ratio + ) + merged = merged.to(target.dtype) + if not torch.isfinite(merged).all(): + raise FloatingPointError("merge overflow after conversion to model dtype") + changed += int(not torch.equal(target, merged)) + target.copy_(merged) + del layers[left + 1] + handled = set() + for config in configs: + if id(config) in handled: + continue + handled.add(id(config)) + config.num_hidden_layers = len(layers) + if getattr(config, "layer_types", None) is not None: + config.layer_types = list(config.layer_types[: left + 1]) + list( + config.layer_types[left + 2 :] + ) + for index, layer in enumerate(layers): + if hasattr(layer.self_attn, "layer_idx"): + layer.self_attn.layer_idx = index + return changed + + +def progressive_prune( + model: nn.Module, + batches: Sequence[dict[str, Tensor]], + *, + target_layers: int, + geometry: GeometryConfig | None = None, + selection: str = "npib", + protected_first: int = 0, + protected_last: int = 0, + on_stage: Callable[[nn.Module, dict], None] | None = None, + transport: bool = False, + transport_ridge: float = 1e-3, + transport_fit_fraction: float = 0.8, + initial_lineage: Sequence[Sequence[int]] | None = None, +) -> list[dict]: + """Recompute activations/manifolds/NPIB on fixed data after every accepted merge. + + No threshold or forced fallbacks; stop at the requested exact depth. Repeated + merging of a previously merged block is allowed and recorded in its lineage. + """ + geometry = geometry or GeometryConfig() + geometry.validate() + depth = len(model.model.layers) + if min(protected_first, protected_last) < 0 or not 1 <= target_layers <= depth: + raise ValueError("invalid target depth or protected counts") + if target_layers < protected_first + protected_last + 1: + raise ValueError("target depth would remove protected layers") + if selection not in {"npib", "back-to-front"}: + raise ValueError("invalid selection mode") + lineage = ([list(group) for group in initial_lineage] if initial_lineage is not None + else [[i] for i in range(depth)]) + flattened = [index for group in lineage for index in group] + if (len(lineage) != depth or any(not group for group in lineage) + or any(type(index) is not int for index in flattened) + or flattened != list(range(len(flattened)))): + raise ValueError("initial lineage must partition original layers in order") + stage_offset = len(flattened) - depth + records = [] + model.eval() + while len(model.model.layers) > target_layers: + started = time.monotonic() + step = stage_offset + len(records) + 1 + print( + f"MKA stage {step}: collecting features for {len(lineage)} layers", + flush=True, + ) + features = collect_features(model, batches, pooling=geometry.pooling) + results = [diffusion_embedding(x, geometry) for x in features] + del features + scores, entropies = npib_matrix([x[0] for x in results], geometry) + left = select_pair( + scores, + selection=selection, + protected_first=protected_first, + protected_last=protected_last, + ) + ratio = upstream_lambda(scores, left, left + 1, geometry.beta) + record = { + "step": step, + "selection": selection, + "left_index": left, + "source_layers": [lineage[left][:], lineage[left + 1][:]], + "pair_npib": float(scores[left, left + 1]), + "lambda_left": ratio, + "lambda_right": 1 - ratio, + "row_means": scores.mean(1).tolist(), + "npib_matrix": scores.tolist(), + "entropies": entropies, + "geometry": asdict(geometry), + "manifolds": [x[1] for x in results], + } + if transport: + from .mka_transport import transport_merge_pair + changed, diagnostic = transport_merge_pair( + model, batches, left, ratio, ridge_relative=transport_ridge, + fit_fraction=transport_fit_fraction, + ) + record["changed_parameter_tensors"] = changed + record["transport"] = diagnostic + else: + record["changed_parameter_tensors"] = merge_pair(model, left, ratio) + lineage[left] += lineage.pop(left + 1) + record["lineage_after"] = [x[:] for x in lineage] + record["remaining_layers"] = len(lineage) + record["elapsed_seconds"] = time.monotonic() - started + records.append(record) + print( + f"MKA stage {step}: merge {left}/{left + 1}, NPIB={record['pair_npib']:.6g}, " + f"lambda={ratio:.6g}, remaining={len(lineage)}", + flush=True, + ) + if on_stage is not None: + on_stage(model, record) + return records diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/offline_eval_policy.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/offline_eval_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..44cb57cdff81cc7b2d738749364bfca9c156bd47 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/offline_eval_policy.py @@ -0,0 +1,26 @@ +"""Run-local offline policy, applied before importing Hugging Face libraries.""" +import json +import os +from pathlib import Path + + +def apply_run_offline_policy(argv): + output = None + for index, value in enumerate(argv): + if value == '--output' and index + 1 < len(argv): + output = argv[index + 1] + elif value.startswith('--output='): + output = value.split('=', 1)[1] + if output is None: + return None + policy_path = Path(output).parent.parent / 'offline_eval.json' + if not policy_path.is_file(): + return None + policy = json.loads(policy_path.read_text()) + cache = Path(policy['wikitext_cache']) + if not (cache / 'dataset_dict.json').is_file(): + raise FileNotFoundError(f'Offline WikiText cache missing: {cache}; no online fallback') + for key in ('HF_HUB_OFFLINE', 'HF_DATASETS_OFFLINE', 'TRANSFORMERS_OFFLINE'): + os.environ[key] = '1' + print('STRICT_OFFLINE_RUN_POLICY_APPLIED', flush=True) + return policy diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/package_final_fit_backup.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/package_final_fit_backup.py new file mode 100644 index 0000000000000000000000000000000000000000..06d34901f355b2c778bae7707f045a2c68680020 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/package_final_fit_backup.py @@ -0,0 +1,60 @@ +"""Final compact reconstruction only; exclude intermediate/duplicate weights.""" +import argparse +import json +from pathlib import Path +import shutil + +p = argparse.ArgumentParser() +p.add_argument("run", type=Path) +p.add_argument("output", type=Path) +p.add_argument("project", type=Path) +p.add_argument("external", type=Path) +p.add_argument("--protocol", default="exp_md/2026-10-08_llama31-come-stagewise-fullblock-fit2.md") +p.add_argument("--cycles", type=int, default=8) +p.add_argument("--original-layers", type=int, default=32) +a = p.parse_args() +if a.output.exists(): + raise FileExistsError(a.output) +stage_name = f"stage_{a.cycles:02d}" +stage = a.run / "compact" / stage_name +meta = json.loads((stage / "metadata.json").read_text()) +assert meta["stage"] == a.cycles and meta["removed_count"] == a.cycles +if meta.get("format") == "abprune_compact_stage_v2": + assert len(meta["active_original_layers"]) == a.original_layers - a.cycles + expected = {s["state_file"] for s in meta["retained_layer_states"]} +else: + assert meta["format"] == "abprune_compact_stage_v1" + anchor = int(meta["anchor_index"]) + assert meta["removed_original_layers"] == list(range(anchor + 1, anchor + 1 + a.cycles)) + assert anchor + a.cycles < a.original_layers + expected = {meta["anchor_state_file"]} +assert expected == {f.name for f in stage.glob("*.pt")} +assert len(expected) >= 1 +shutil.copytree(stage, a.output / "compact" / stage_name) +if (a.run / "offline_eval.json").is_file(): + shutil.copy2(a.run / "offline_eval.json", a.output / "offline_eval.json") +if (a.run.parent.parent / "offline_preflight.json").is_file(): + shutil.copy2(a.run.parent.parent / "offline_preflight.json", a.output / "offline_preflight.json") +for folder in ("audit", "eval", "logs"): + shutil.copytree(a.run / folder, a.output / folder) +for f in (a.run / "run").glob("cycle_*/cycle_metadata.json"): + d = a.output / "stage_metadata" / f.parent.name + d.mkdir(parents=True, exist_ok=True) + shutil.copy2(f, d / f.name) +code = a.output / "code" +code.mkdir() +for name in ("run_llama31_base_fit_ablation.py", "run_llama31_come_fit_arm.sh", + "bootstrap_llama31_come_fit2.sh", "launch_llama31_come_fit2.sh", + "package_final_fit_backup.py", "run_external_abprune_instruct_order.py", + "offline_eval_policy.py", "evaluate_abprune_compact_ppl.py", + "evaluate_hchc_wikitext2_ppl.py", "eval_llama31_fit_ablation_one.sh", + "eval_llama31_8b_12bench.py", "prepare_lmeval9_local_cache.py", + "prepare_offline_ppl_cache.py"): + shutil.copy2(a.project / "scripts" / name, code / name) +for name in ("come.py", "fit_ablation_come.py", "abprune_compact.py"): + shutil.copy2(a.project / "src/fusegpt" / name, code / name) +for name in ("fuse_layers.py", "fuse_layers_distill.py", "source_feature_transport.py"): + shutil.copy2(a.external / "src" / name, code / name) +shutil.copy2(a.project / a.protocol, a.output / "protocol.md") +assert set(a.output.rglob("*.pt")) == {a.output / "compact" / stage_name / n for n in expected} +print("FINAL_ONLY_BACKUP", len(expected), "retained blocks", flush=True) diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/prepare_lmeval9_local_cache.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/prepare_lmeval9_local_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..0c169eca6c555cbd1fdb7fd1dd9bd9a085806b09 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/prepare_lmeval9_local_cache.py @@ -0,0 +1,108 @@ +"""Materialize the exact harness datasets once, without changing task definitions.""" +import argparse +from concurrent.futures import ThreadPoolExecutor, as_completed +import hashlib +import json +from pathlib import Path +import time + +import datasets +from lm_eval.tasks import TaskManager + + +def cache_key(path, name, kwargs): + return hashlib.sha256(json.dumps([path, name, kwargs], sort_keys=True).encode()).hexdigest() + + +def specs(): + manager = TaskManager() + names = ["piqa", "winogrande", "hellaswag", "arc_challenge", "arc_easy", "openbookqa", "sciq"] + entries = [manager.task_index[n] for n in names] + entries += [e for e in manager.task_index.values() + if e.yaml_path and e.yaml_path.parent.name == "default" + and (e.cfg or {}).get("dataset_path") == "cais/mmlu"] + entries += [e for e in manager.task_index.values() + if (e.cfg or {}).get("dataset_path") == "haonan-li/cmmlu"] + unique = {} + for entry in entries: + cfg = entry.cfg + path, name, kwargs = cfg["dataset_path"], cfg.get("dataset_name"), cfg.get("dataset_kwargs") or {} + unique[cache_key(path, name, kwargs)] = {"path": path, "name": name, "kwargs": kwargs} + assert len(unique) == 131, len(unique) + return unique + + +def materialize(root, key, spec, offline): + target = root / key + metadata = target / "source.json" + if metadata.is_file(): + return key, json.loads(metadata.read_text()) + start = time.monotonic() + try: + data = datasets.load_dataset(spec["path"], spec["name"], **spec["kwargs"]) + except Exception: + if offline: + return key, None + raise + data.save_to_disk(str(target)) + report = {**spec, "splits": {k: {"rows": len(v), "fingerprint": v._fingerprint} + for k, v in data.items()}} + metadata.write_text(json.dumps(report, indent=2) + "\n") + restored = datasets.load_from_disk(str(target)) + assert {k: len(v) for k, v in restored.items()} == {k: len(v) for k, v in data.items()} + assert all(restored[k].features == data[k].features for k in data) + assert all(restored[k].data.table.equals(data[k].data.table) for k in data) + print("READY", spec["path"], spec["name"], round(time.monotonic() - start, 2), flush=True) + return key, report + + +def install_local_loader(root): + manifest = json.loads((root / "manifest.json").read_text()) + assert len(manifest) == 131 + memo = {} + + def local_load(path, name=None, **kwargs): + key = cache_key(path, name, kwargs) + if key not in manifest: + raise RuntimeError(f"Unprepared dataset request: {path}/{name}; no online fallback") + if key not in memo: + memo[key] = datasets.load_from_disk(str(root / key)) + print("LOCAL_DATASET", path, name, flush=True) + return memo[key] + + datasets.load_dataset = local_load + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path) + parser.add_argument("--offline-export", action="store_true") + parser.add_argument("--validate-local", action="store_true", + help="Validate a complete transferred cache without Hub requests") + parser.add_argument("--workers", type=int, default=8) + args = parser.parse_args() + args.root.mkdir(parents=True, exist_ok=True) + sources = specs() + if args.validate_local: + manifest = json.loads((args.root / "manifest.json").read_text()) + assert set(manifest) == set(sources), "Task configuration mismatch" + for key, spec in sources.items(): + report = manifest[key] + assert all(report[k] == v for k, v in spec.items()) + assert json.loads((args.root / key / "source.json").read_text()) == report + data = datasets.load_from_disk(str(args.root / key)) + assert {k: len(v) for k, v in data.items()} == { + k: v["rows"] for k, v in report["splits"].items()} + print("VALIDATED_LOCAL", len(manifest), "NO_HUB_REQUESTS", flush=True) + raise SystemExit(0) + completed = {} + with ThreadPoolExecutor(max_workers=1 if args.offline_export else args.workers) as executor: + futures = [executor.submit(materialize, args.root, k, v, args.offline_export) + for k, v in sources.items()] + for future in as_completed(futures): + key, result = future.result() + if result is not None: + completed[key] = result + print("PREPARED", len(completed), "OF", len(sources), flush=True) + if len(completed) == len(sources): + (args.root / "manifest.json").write_text(json.dumps(completed, indent=2) + "\n") diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/prepare_mka_batch_calibration.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/prepare_mka_batch_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..a138adf3561acd2639f9457a3bdfc03eb412aece --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/prepare_mka_batch_calibration.py @@ -0,0 +1,108 @@ +"""Convert the immutable historical native MKA cache without resampling data.""" + +import argparse +import hashlib +import json +from pathlib import Path + +import torch + + +SOURCE_REVISION = "1bc4be66370f487b1c2ba4e7a2b4b35ae76758a3" +SOURCE_PREFIX = ( + "runs/vast-paper_revision-mka-all-small-5090x8-ca-54482709/" + "20261006-mka-small-13checkpoints/llama31_base_remove8/model" +) +RAW_SHA256 = "8e893e97e0a1f277802a6993588a8fe083cdb0d7579359da789fbf8871f2d08b" +INPUT_SHA256 = "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075" +MODEL = "meta-llama/Llama-3.1-8B" +MODEL_REVISION = "d04e592bb4f6aa9cfee91e2e20afa771667e1d4b" +VOCAB_SHA256 = "869dd26a7a4c36e0324cb1011416f764302d33093f5c0f5c06d6615cc017010f" + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", type=Path, required=True, + help="Downloaded original calibration_ids.pt") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--model", type=Path, + help="Optional local model/tokenizer directory for vocabulary verification") + args = parser.parse_args() + + raw_hash = hashlib.sha256(args.source.read_bytes()).hexdigest() + require(raw_hash == RAW_SHA256, "Source file does not match the immutable native MKA cache") + bundle = torch.load(args.source, map_location="cpu", weights_only=True) + metadata, chunks = bundle["metadata"], bundle["input_ids"] + require(metadata["tokenizer"] == MODEL, "Native cache tokenizer identity differs") + require(metadata["tokenizer_revision"] == MODEL_REVISION, "Native cache tokenizer revision differs") + require(metadata["tokenizer_vocab_sha256"] == VOCAB_SHA256, "Native cache vocabulary hash differs") + require(metadata["input_ids_sha256"] == INPUT_SHA256, "Native cache declared token hash differs") + require(metadata["samples"] == 100 and metadata["sequence_length"] == 512 + and metadata["seed"] == 0, "Expected the historical 100x512 seed0 cache") + require(len(metadata["records"]) == 100, "Native document provenance is incomplete") + require(isinstance(chunks, (list, tuple)) and len(chunks) == 100, + "Expected exactly 100 native calibration sequences") + require(all(isinstance(ids, torch.Tensor) and ids.dtype == torch.long + and tuple(ids.shape) == (512,) for ids in chunks), + "Native calibration IDs must be int64 vectors of length512") + + tokenizer_verified = False + if args.model is not None: + from transformers import AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained(str(args.model), local_files_only=True) + serialized = json.dumps(tokenizer.get_vocab(), sort_keys=True, ensure_ascii=False) + actual_vocab = hashlib.sha256(serialized.encode("utf-8")).hexdigest() + require(actual_vocab == VOCAB_SHA256, "Local tokenizer vocabulary differs from native MKA") + require(all(bool((ids >= 0).all()) and bool((ids < len(tokenizer)).all()) + for ids in chunks), "Native cache contains out-of-vocabulary IDs") + tokenizer_verified = True + + inputs_hash, masks_hash = hashlib.sha256(), hashlib.sha256() + batches = [] + for chunk in chunks: + ids = chunk.contiguous().unsqueeze(0) + mask = torch.ones_like(ids) + inputs_hash.update(ids.numpy().astype(" str: + return "\n\n".join( + f"{str(message.get('role', '')).strip().title() or 'User'}: " + f"{str(message.get('content', '')).strip()}" + for message in messages + if str(message.get("content", "")).strip() + ) + + +def _slimorca_record(row: Dict[str, object]) -> Optional[Dict[str, object]]: + conversations = row.get("conversations") + if not isinstance(conversations, list) or len(conversations) < 2: + return None + start = 0 if str(conversations[0].get("from", "")).lower() == "human" else 1 + if start + 1 >= len(conversations): + return None + user = conversations[start] + assistant = conversations[start + 1] + if str(user.get("from", "")).lower() != "human": + return None + if str(assistant.get("from", "")).lower() != "gpt": + return None + user_text = str(user.get("value", "")).strip() + assistant_text = str(assistant.get("value", "")).strip() + if not user_text or not assistant_text: + return None + messages = [ + {"role": "user", "content": user_text}, + {"role": "assistant", "content": assistant_text}, + ] + return {"messages": messages, "text": _messages_text(messages)} + + +def load_slimorca_records( + args: argparse.Namespace, + num_samples: int, + manifest_env_var: str = "ABPRUNE_DATA_INDICES_FILE", +) -> List[Dict[str, object]]: + if args.instruction_dataset != "Open-Orca/SlimOrca": + raise SystemExit( + "The instruction transport adapter requires Open-Orca/SlimOrca" + ) + dataset = data.load_dataset(**data._instruction_dataset_kwargs(args)) + rows = ( + data._sample_dataset_rows(dataset, num_samples, args.seed, manifest_env_var) + if num_samples > 0 + else dataset + ) + records: List[Dict[str, object]] = [] + for row in rows: + if not isinstance(row, dict): + continue + record = _slimorca_record(row) + if record is not None: + records.append(record) + return records + + +def build_instruction_calibration(args: argparse.Namespace, tokenizer): + records = load_slimorca_records( + args, args.num_samples, "ABPRUNE_CALIB_DATA_INDICES_FILE" + ) + if not records: + raise SystemExit("No SlimOrca instruction calibration records were built") + dataset = base.FixedSeqDataset(records, tokenizer, args.seq_len) + chunks = [dataset[index][0] for index in range(len(dataset))] + masks = [dataset[index][1] for index in range(len(dataset))] + loader = torch.utils.data.DataLoader( + torch.utils.data.TensorDataset(torch.stack(chunks), torch.stack(masks)), + batch_size=args.batch_size, + shuffle=False, + ) + return [], chunks, loader + + +original_parse_args = base.parse_args + + +def parse_args() -> argparse.Namespace: + args = original_parse_args() + args.instruction_format = "slimorca" + args.calibration_source = "instruction" + return args + + +base.parse_args = parse_args +base.load_instruction_records = load_slimorca_records +base.build_calibration_dataloader = build_instruction_calibration +data.load_instruction_records = load_slimorca_records + +original_prepare_distillation_data = base.prepare_distillation_data + + +def prepare_instruction_distillation(args, tokenizer, include_instruction=True): + # The generic LM entrypoint deliberately suppresses instruction records for + # reparameterization and enables them only for LoRA. This adapter is the + # instruction-model entrypoint, so both calibration and reparameterization + # must consume the requested SlimOrca records. + del include_instruction + return original_prepare_distillation_data( + args, tokenizer, include_instruction=True + ) + + +base.prepare_distillation_data = prepare_instruction_distillation + +import fuse_layers_order as ordered # noqa: E402 + + +if __name__ == "__main__": + ordered.main() diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/run_llama31_base_fit_ablation.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/run_llama31_base_fit_ablation.py new file mode 100644 index 0000000000000000000000000000000000000000..7e1673773897a8988913fb8a4dc0896a625120b4 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/run_llama31_base_fit_ablation.py @@ -0,0 +1,869 @@ +#!/usr/bin/env python3 +"""Non-Fisher initialization controls on the historical additive-U FiT engine. + +Wa/Wb/average use the fixed anchor. MKA uses the corrected, committed MKA +selector; --fit-mka-mlp freezes its merged attention and anchor norms while +fitting only the three MLP weights. The existing default MKA scope is unchanged. +The opt-in fixed-span-merge-only mode instead retains our selection/transport, +replaces just the three MLP initializers, and freezes anchor attention/norms. +No fake Fisher tensor is used to derive initialization; empty placeholders +only satisfy the unmodified engine's call signature. Audits mark this clearly. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import os +import sys +import time +from pathlib import Path + + +def install_exact_layer(distill, torch, state): + original = distill.ReparamMergedLayer + + class ExactInitializationLayer(original): + def __init__(self, layer_a, layer_b, targets, **kwargs): + assert kwargs.get("additive_u"), "Controls require additive-U" + assert not kwargs.get("tensor_rho") + super().__init__(layer_a, layer_b, targets, **kwargs) + self.exact_lambda = float(state["lambda"]) + self.initialization_errors = {} + self.fit_attention = bool(state.get("fit_attention", False)) + self.fit_full_block = bool(state.get("fit_full_block", False)) + self.fit_come_mlp = bool(state.get("fit_come_mlp", False)) + self.fit_come_attention = bool(state.get("fit_come_attention", False)) + self.fit_mka_mlp = bool(state.get("fit_mka_mlp", False)) + fixed_merge_only = bool(state.get("fixed_span_merge_only", False)) + fixed_initial = None + if fixed_merge_only: + from fusegpt.fixed_span_merge_init import MLP_NAMES, build_initialization + assert set(self._name_map) == set(MLP_NAMES), self._name_map + assert state.get("transport_completed"), "Initialize only after transport" + fixed_initial, fixed_audit = build_initialization( + layer_a, layer_b, state["initializer"], state["merge_payload"]) + if ((state["initializer"] == "mka" and not fixed_merge_only) or + self.fit_attention or self.fit_come_attention): + from fusegpt.fit_ablation_mka import PROJECTION_WEIGHTS + for name, safe in list(self._name_map.items()): + if name not in PROJECTION_WEIGHTS: + del self._name_map[name] + del self.u[safe] + del self.gates[safe] + mka_frozen_initial = {} + if self.fit_mka_mlp: + assert state["initializer"] == "mka" and not fixed_merge_only + assert len(self._name_map) == 3 and all(n.startswith("mlp.") for n in self._name_map) + # Native MKA merges all seven projections in FP32, rounds into + # the model dtype, and leaves both RMSNorms at the left anchor. + # A narrower FiT scope must still materialize that attention merge. + for name, param in layer_a.named_parameters(): + if name in self._name_map: + continue + projection_weight = name in PROJECTION_WEIGHTS + projection_bias = name.endswith(".bias") and name[:-4] + "weight" in PROJECTION_WEIGHTS + initial = (torch.lerp(layer_b.get_parameter(name).detach().float(), + param.detach().float(), self.exact_lambda) + if projection_weight or projection_bias else param.detach().clone()) + initial = initial.to(param.dtype) + mka_frozen_initial[name] = initial.detach().clone() + self.register_buffer("frozen_initial__" + name.replace(".", "__"), + initial.detach().clone(), persistent=False) + if (self.fit_come_mlp or self.fit_come_attention) and not fixed_merge_only: + assert len(self._name_map) == (7 if self.fit_come_attention else 3) + if self.fit_come_mlp: + assert all(n.startswith("mlp.") for n in self._name_map) + for name, initial in state["come_initial"].items(): + if name not in self._name_map: + self.register_buffer("frozen_initial__" + name.replace(".", "__"), + initial.to(layer_a.get_parameter(name).device).clone(), persistent=False) + with torch.no_grad(): + for name, safe in self._name_map.items(): + a = layer_a.get_parameter(name).detach().float() + b = layer_b.get_parameter(name).detach().float() + # This is a fitting-scope ablation, not an attention merge. + # Keep anchor attention exactly; only MLP uses Wa/Wb lambda. + ratio = 1. if self.fit_attention and name.startswith("self_attn.") else self.exact_lambda + if fixed_merge_only: + initial = fixed_initial[name].to(a.device).clone() + elif state["initializer"] == "come": + initial = state["come_initial"][name].to(a.device).clone() + elif ratio == 1: + initial = a.clone() + elif ratio == 0: + initial = b.clone() + else: + initial = torch.lerp(b, a, ratio) + self.register_buffer("initial__" + safe, initial, persistent=False) + self.u[safe].zero_() + assert torch.isfinite(initial).all(), name + self.initialization_errors[name] = 0.0 + state["initialization_audit"] = { + "lambda": self.exact_lambda, "endpoint_clamping": False, + "initial_u_nonzero": 0, "merged_parameters": list(self._name_map), + "parameterization": "W_initial + U_add", "fisher_computed": False, + "fit_scope": "full_block_including_norms" if self.fit_full_block else ( + "attention_and_mlp" if self.fit_attention or self.fit_come_attention else "mlp"), + "attention_initialization": "CoMe_channel_merge" if state["initializer"] == "come" else ( + "anchor_Wa" if self.fit_attention else ( + "MKA_merge" if state["initializer"] == "mka" else "anchor_Wa") + ), + } + if fixed_merge_only: + state["initialization_audit"].update({"fixed_span_merge_only": True, + "attention_initialization": "anchor_Wa", "norm_initialization": "anchor_Wa", + "norms_trainable": False, "initialized_parameters": list(self._name_map), + "selection_policy": state.get("selection_policy", "fixed_anchor21_remove_original_22_30"), + "merge_rule_audit": fixed_audit}) + state.pop("merge_payload") + elif state["initializer"] == "come": + assert len(state["come_initial"]) == 9, "Pinned Llama block has7 projections and2 norms" + if self.fit_full_block: + assert set(self._name_map) == set(state["come_initial"]), "All block parameters must have U" + state["initialization_audit"].update({"lambda": None, "norm_initialization": "CoMe_pair_mean", + "CoMe": state["come_audit"], "norms_trainable": self.fit_full_block, + "initialized_parameters": list(state["come_initial"]), + "frozen_CoMe_parameters": [n for n in state["come_initial"] if n not in self._name_map]}) + if self.fit_come_attention: + state["initialization_audit"]["frozen_norm_expected_sha256"] = { + n: hashlib.sha256(initial.to(dtype=layer_a.get_parameter(n).dtype).cpu().contiguous() + .view(torch.uint8).numpy().tobytes()).hexdigest() + for n, initial in state["come_initial"].items() if n not in self._name_map + } + assert len(state["initialization_audit"]["frozen_norm_expected_sha256"]) == 2 + state.pop("come_initial") + elif self.fit_mka_mlp: + hashes = {n: hashlib.sha256(p.cpu().contiguous().view(torch.uint8).numpy().tobytes()).hexdigest() + for n, p in mka_frozen_initial.items()} + actual = self._merged_params() + measured = {n: hashlib.sha256(actual[n].detach().cpu().contiguous() + .view(torch.uint8).numpy().tobytes()).hexdigest() for n in hashes} + assert measured == hashes, "MKA frozen initialization does not match native merge" + state["initialization_audit"].update({ + "fit_scope": "mlp", "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", "norms_trainable": False, + "frozen_MKA_parameters": list(mka_frozen_initial), + "frozen_attention_norm_expected_sha256": hashes, + "frozen_attention_norm_before_sha256": measured, + }) + + def gate_lambdas(self): + return {name: torch.tensor( + 1. if self.fit_attention and name.startswith("self_attn.") else self.exact_lambda, + device=self.u[safe].device) + for name, safe in self._name_map.items()} + + def _merged_params(self): + result = {} + for name, param in self.layer_a.named_parameters(): + safe = self._name_map.get(name) + frozen = getattr(self, "frozen_initial__" + name.replace(".", "__"), param.detach()) + result[name] = (frozen.to(param.dtype) if safe is None else + (getattr(self, "initial__" + safe) + self.u[safe]).to(param.dtype)) + return result + + def materialize_into_layer_a(self): + with torch.no_grad(): + for name, param in self.layer_a.named_parameters(): + frozen = getattr(self, "frozen_initial__" + name.replace(".", "__"), None) + if frozen is not None: + param.copy_(frozen.to(param.dtype)) + for name, safe in self._name_map.items(): + param = self.layer_a.get_parameter(name) + param.copy_((getattr(self, "initial__" + safe) + self.u[safe]).to(param.dtype)) + return len(self._name_map) + + distill.ReparamMergedLayer = ExactInitializationLayer + # The old diagnostic names its reference "Fisher displacement". That is + # not the reference direction in these controls, so do not emit it. + distill._sequential_u_fisher_orthogonality = lambda layer: {} + return ExactInitializationLayer + + +def algebra_test(torch, distill): + class Layer(torch.nn.Module): + def __init__(self): + super().__init__() + self.mlp = torch.nn.Module() + self.mlp.up_proj = torch.nn.Linear(4, 5, bias=False) + + torch.manual_seed(42) + state = {"initializer": "average", "lambda": .5} + cls = install_exact_layer(distill, torch, state) + a, b = Layer(), Layer() + for ratio in (0., .5, 1.): + state["lambda"] = ratio + layer = cls(a, b, {"mlp.up_proj.weight": ratio}, + param_subset="mlp", additive_u=True) + actual = layer._merged_params()["mlp.up_proj.weight"] + expected = a.mlp.up_proj.weight if ratio == 1 else ( + b.mlp.up_proj.weight if ratio == 0 else + torch.lerp(b.mlp.up_proj.weight, a.mlp.up_proj.weight, ratio)) + expected = expected.detach().clone() + assert torch.equal(actual, expected) + actual.sum().backward() + u = layer.u["mlp__up_proj__weight"] + assert torch.equal(u.grad, torch.ones_like(u)), "Average must not mask FiT gradients" + with torch.no_grad(): + u.add_(.01) + layer.materialize_into_layer_a() + assert torch.equal(a.mlp.up_proj.weight, expected + .01) + print("EXACT_INITIALIZATION_AND_AVERAGE_U_GRADIENT_OK", flush=True) + + +def attention_algebra_test(torch, distill): + class Layer(torch.nn.Module): + def __init__(self): + super().__init__() + self.self_attn = torch.nn.Module() + self.mlp = torch.nn.Module() + for name in ("q_proj", "k_proj", "v_proj", "o_proj"): + setattr(self.self_attn, name, torch.nn.Linear(4, 4, bias=False)) + for name in ("gate_proj", "up_proj", "down_proj"): + setattr(self.mlp, name, torch.nn.Linear(4, 4, bias=False)) + self.input_layernorm = torch.nn.LayerNorm(4) + + state = {"initializer": "wa", "lambda": 1., "fit_attention": True} + cls = install_exact_layer(distill, torch, state) + for ratio in (0., 1.): + state["lambda"] = ratio + a, b = Layer(), Layer() + targets = {name: ratio for name, _ in a.named_parameters()} + layer = cls(a, b, targets, param_subset="all", additive_u=True) + assert len(layer._name_map) == 7 + merged = layer._merged_params() + for name, safe in layer._name_map.items(): + expected = (a if name.startswith("self_attn.") or ratio == 1 else b).get_parameter(name) + assert torch.equal(merged[name], expected.detach()), name + assert torch.equal(merged["input_layernorm.weight"], a.input_layernorm.weight) + sum(merged[name].sum() for name in layer._name_map).backward() + assert all(torch.equal(u.grad, torch.ones_like(u)) for u in layer.u.values()) + print("ATTENTION_FIT_EXACT_ANCHOR_ATTENTION_MLP_ENDPOINTS_7_U_GRADIENTS_OK", flush=True) + + +def come_algebra_test(torch, distill, mlp_only=False, attention_and_mlp=False): + from types import SimpleNamespace + from fusegpt import come + + class Layer(torch.nn.Module): + def __init__(self): + super().__init__() + self.self_attn = torch.nn.Module() + self.self_attn.config = SimpleNamespace(num_attention_heads=2, num_key_value_heads=2) + self.self_attn.head_dim = 2 + for n in ("q_proj", "k_proj", "v_proj", "o_proj"): + setattr(self.self_attn, n, torch.nn.Linear(4, 4, bias=False)) + self.mlp = torch.nn.Module() + self.mlp.gate_proj = torch.nn.Linear(4, 6, bias=False) + self.mlp.up_proj = torch.nn.Linear(4, 6, bias=False) + self.mlp.down_proj = torch.nn.Linear(6, 4, bias=False) + self.input_layernorm = torch.nn.RMSNorm(4) + self.post_attention_layernorm = torch.nn.RMSNorm(4) + + import copy + a, b = Layer(), Layer() + with torch.no_grad(): + a.input_layernorm.weight.fill_(2) + b.input_layernorm.weight.fill_(4) + untouched = {n: p.detach().clone() for n, p in a.named_parameters()} + pair = [copy.deepcopy(a), copy.deepcopy(b)] + come.merge_attention(pair, [.5, .5], [torch.tensor([0., 1.]), torch.tensor([1., 0.])]) + come.merge_mlp(pair, [.5, .5], [torch.arange(6.), torch.arange(6.).flip(0)]) + come.merge_norms(pair) + expected = {n: p.detach().clone() for n, p in pair[0].named_parameters()} + state = {"initializer": "come", "lambda": 1., "fit_full_block": not (mlp_only or attention_and_mlp), + "fit_come_mlp": mlp_only, + "fit_come_attention": attention_and_mlp, + "come_initial": expected, "come_audit": {"self_test": True}} + cls = install_exact_layer(distill, torch, state) + layer = cls(a, b, {n: 1. for n in expected}, param_subset="mlp" if mlp_only else "all", additive_u=True) + merged = layer._merged_params() + assert len(layer._name_map) == (3 if mlp_only else (7 if attention_and_mlp else 9)) + assert all(torch.equal(merged[n], expected[n]) for n in expected) + assert all(torch.equal(p, untouched[n]) for n, p in a.named_parameters()) + assert bool((merged["input_layernorm.weight"] == 3).all()) + sum(v.sum() for v in merged.values()).backward() + assert all(torch.equal(u.grad, torch.ones_like(u)) for u in layer.u.values()) + assert state["initialization_audit"]["attention_initialization"] == "CoMe_channel_merge" + if mlp_only or attention_and_mlp: + assert not state["initialization_audit"]["norms_trainable"] + assert len(state["initialization_audit"]["frozen_CoMe_parameters"]) == (2 if attention_and_mlp else 6) + with torch.no_grad(): + for u in layer.u.values(): + u.add_(.01) + layer.materialize_into_layer_a() + for n, p in a.named_parameters(): + trainable = n in layer._name_map + assert torch.equal(p, expected[n] + .01 if trainable else expected[n]), n + print("COME_NATIVE_MERGE_MLP3_U_FROZEN_ATTN_NORMS_OK" if mlp_only else ( + "COME_NATIVE_MERGE_ATTN4_MLP3_U_FROZEN_NORMS_TEACHER_UNCHANGED_OK" if attention_and_mlp else + "COME_NATIVE_MERGE_9_U_GRADIENTS_NORMS_TEACHER_UNCHANGED_OK"), flush=True) + + +def mka_algebra_test(torch, distill, mlp_only=False): + """Compare with the real native merger, including BF16 rounding and frozen attention.""" + import copy + from types import SimpleNamespace + from fusegpt import fit_ablation_mka as mka + original = distill.ReparamMergedLayer + + class Layer(torch.nn.Module): + def __init__(self): + super().__init__() + self.self_attn = torch.nn.Module() + self.mlp = torch.nn.Module() + for name in ("q_proj", "k_proj", "v_proj", "o_proj"): + setattr(self.self_attn, name, torch.nn.Linear(4, 4, bias=False)) + for name in ("gate_proj", "up_proj", "down_proj"): + setattr(self.mlp, name, torch.nn.Linear(4, 4, bias=False)) + self.input_layernorm = torch.nn.RMSNorm(4) + self.post_attention_layernorm = torch.nn.RMSNorm(4) + + for dtype in (torch.float32, torch.bfloat16): + for ratio in (0., .623, 1.): + a, b = Layer().to(dtype), Layer().to(dtype) + with torch.no_grad(): + a.input_layernorm.weight.fill_(2) + b.input_layernorm.weight.fill_(4) + a.post_attention_layernorm.weight.fill_(3) + b.post_attention_layernorm.weight.fill_(5) + teacher = [{n: p.detach().clone() for n, p in layer.named_parameters()} for layer in (a, b)] + model = torch.nn.Module() + model.config = SimpleNamespace(num_hidden_layers=2) + model.model = torch.nn.Module() + model.model.config = model.config + model.model.layers = torch.nn.ModuleList([copy.deepcopy(a), copy.deepcopy(b)]) + mka.merge_pair(model, 0, ratio) + expected = {n: p.detach().clone() for n, p in model.model.layers[0].named_parameters()} + state = {"initializer": "mka", "lambda": ratio, "fit_mka_mlp": mlp_only} + distill.ReparamMergedLayer = original + cls = install_exact_layer(distill, torch, state) + layer = cls(a, b, {n: ratio for n, _ in a.named_parameters()}, + param_subset="mlp" if mlp_only else "all", additive_u=True) + merged = layer._merged_params() + assert len(layer._name_map) == (3 if mlp_only else 7) + assert all(torch.equal(merged[n], expected[n]) for n in expected) + assert all(torch.equal(p, saved[n]) for source, saved in zip((a, b), teacher) + for n, p in source.named_parameters()), "Initialization mutated the teacher" + sum(merged[n].float().sum() for n in layer._name_map).backward() + assert all(u.grad is not None and torch.equal(u.grad, torch.ones_like(u)) for u in layer.u.values()) + with torch.no_grad(): + for u in layer.u.values(): + u.add_(.01) + layer.materialize_into_layer_a() + for n, p in a.named_parameters(): + after = (expected[n].float() + .01).to(dtype) if n in layer._name_map else expected[n] + # Trainable BF16 native initialization keeps its unrounded FP32 + # weighted sum until materialization, as in the existing engine. + if n in layer._name_map: + initial = torch.lerp(teacher[1][n].float(), teacher[0][n].float(), ratio) + after = (initial + .01).to(dtype) + assert torch.equal(p, after), n + if mlp_only: + audit = state["initialization_audit"] + assert len(audit["frozen_attention_norm_expected_sha256"]) == 6 + assert audit["frozen_attention_norm_before_sha256"] == audit["frozen_attention_norm_expected_sha256"] + assert not audit["norms_trainable"] and audit["attention_initialization"] == "MKA_merge" + # Historical MKA uses a seven-projection map but the external + # fitter trains only MLP U (reparam_train_subset=mlp). Confirm + # narrowing the map preserves that initialization and update. + old_a, old_b = Layer().to(dtype), Layer().to(dtype) + old_a.load_state_dict(teacher[0]) + old_b.load_state_dict(teacher[1]) + distill.ReparamMergedLayer = original + old_cls = install_exact_layer(distill, torch, {"initializer": "mka", "lambda": ratio}) + old = old_cls(old_a, old_b, {n: ratio for n, _ in old_a.named_parameters()}, + param_subset="all", additive_u=True) + assert len(old._name_map) == 7 + for name, safe in old._name_map.items(): + u = old.u[safe] + u.requires_grad_(name.startswith("mlp.")) + if name.startswith("mlp."): + with torch.no_grad(): + u.add_(.01) + old.materialize_into_layer_a() + assert all(torch.equal(p, old_a.get_parameter(n)) for n, p in a.named_parameters()), ( + "New three-MLP map differs from historical seven-map/MLP-only-update MKA") + distill.ReparamMergedLayer = original + print("MKA_NATIVE_MERGE_MLP3_U_FROZEN_ATTN_NORMS_TEACHER_UNCHANGED_OK" if mlp_only else + "MKA_NATIVE_MERGE_DEFAULT7_U_REGRESSION_OK", flush=True) + + +def main(): + parser = argparse.ArgumentParser(allow_abbrev=False) + parser.add_argument("--external-root", type=Path, required=True) + parser.add_argument("--initializer", choices=("wa", "wb", "average", "mka", "come"), required=True) + parser.add_argument("--fixed-anchor", type=int, default=21) + parser.add_argument("--original-layers", type=int, default=32, + help="Original decoder depth; defaults preserve the Llama controls") + parser.add_argument("--audit-root", type=Path, required=True) + parser.add_argument("--mka-data", type=Path) + parser.add_argument("--selection-data", type=Path, + help="Frozen native calibration batches; separate from FiT inputs") + parser.add_argument("--selection-hash", + help="Required input_ids SHA256 for frozen selection batches") + parser.add_argument("--record-fit-runtime", action="store_true") + parser.add_argument("--mka-samples", type=int, default=100) + parser.add_argument("--self-test", action="store_true") + parser.add_argument("--model-id", default="meta-llama/Llama-3.1-8B") + parser.add_argument("--base-revision", default="d04e592bb4f6aa9cfee91e2e20afa771667e1d4b") + parser.add_argument("--instruction-data", action="store_true") + parser.add_argument("--fit-attention", action="store_true", + help="Train seven projection U tensors; initialize attention from anchor Wa") + parser.add_argument("--fit-full-block", action="store_true", + help="CoMe initialization; train all9 block weights including both norms") + parser.add_argument("--fit-come-mlp", action="store_true", + help="CoMe initializes all9 weights; fit only3 MLP weights, freeze merged attention/norms") + parser.add_argument("--fit-come-attention", action="store_true", + help="CoMe initializes all9 weights; fit7 attention/MLP projections, freeze merged norms") + parser.add_argument("--fit-mka-mlp", action="store_true", + help="Native dynamic MKA initializes7 projections; fit3 MLP weights, freeze merged attention/anchor norms") + parser.add_argument("--fixed-span-merge-only", action="store_true", + help="Fixed our span, transport ON, replace ONLY3 MLP initial weights with CoMe/MKA") + parser.add_argument("--come-minimum-retention", type=float, default=.97) + parser.add_argument("--come-power", type=float, default=1.) + parser.add_argument("--one-shot", type=int, default=1, + help="Absorb this many blocks in a single cycle (Wa only).") + opt, forwarded = parser.parse_known_args() + if opt.fit_attention: + assert opt.initializer in ("wa", "wb") and opt.one_shot == 1 + if opt.fit_mka_mlp: + assert opt.initializer == "mka" and not opt.fixed_span_merge_only and opt.one_shot == 1 + assert not (opt.fit_attention or opt.fit_full_block or opt.fit_come_mlp or opt.fit_come_attention) + assert "--source_feature_transport" not in forwarded + if not opt.self_test: + assert opt.selection_data or opt.mka_data, "MLP-only MKA requires explicitly saved native geometry inputs" + assert opt.selection_hash, "MLP-only MKA requires a native geometry input hash" + for key in ("--reparam_param_subset", "--reparam_train_subset"): + assert forwarded[forwarded.index(key) + 1] == "mlp" + assert sum((opt.fit_full_block, opt.fit_come_mlp, opt.fit_come_attention)) == int( + opt.initializer == "come" and not opt.fixed_span_merge_only) + if opt.fixed_span_merge_only: + assert opt.initializer in ("come", "mka") and opt.one_shot == 1 + count = int(forwarded[forwarded.index("--num_progressive") + 1]) + assert opt.original_layers > 1 and 0 <= opt.fixed_anchor < opt.original_layers - 1 + assert 1 <= count <= opt.original_layers - opt.fixed_anchor - 1 + assert int(forwarded[forwarded.index("--layer") + 1]) == opt.fixed_anchor + assert not (opt.fit_attention or opt.fit_full_block or opt.fit_come_mlp or opt.fit_come_attention or opt.self_test) + assert "--source_feature_transport" in forwarded + for key in ("--reparam_param_subset", "--reparam_train_subset"): + assert forwarded[forwarded.index(key) + 1] == "mlp" + elif opt.initializer == "come": + assert not opt.fit_attention and opt.one_shot == 1 + assert "--source_feature_transport" not in forwarded + if not opt.self_test: + subset = "mlp" if opt.fit_come_mlp else "all" + assert forwarded[forwarded.index("--reparam_param_subset") + 1] == subset + assert forwarded[forwarded.index("--reparam_train_subset") + 1] == subset + if opt.one_shot != 1: + assert opt.initializer == "wa" and opt.one_shot == 8 + assert forwarded[forwarded.index("--num_progressive") + 1] == "1" + assert forwarded[forwarded.index("--redistrib_teacher_source") + 1] == "base_model" + assert forwarded[forwarded.index("--reparam_absorb_count") + 1] == "8" + assert "--source_feature_transport" not in forwarded + sys.path.insert(0, str(opt.external_root / "src")) + sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) + import torch + import fuse_layers as base + import fuse_layers_distill as distill + if opt.self_test: + if opt.initializer == "come": + come_algebra_test(torch, distill, mlp_only=opt.fit_come_mlp, + attention_and_mlp=opt.fit_come_attention) + elif opt.initializer == "mka": + mka_algebra_test(torch, distill, mlp_only=opt.fit_mka_mlp) + else: + (attention_algebra_test if opt.fit_attention else algebra_test)(torch, distill) + return + if opt.instruction_data: + assert opt.model_id in ("meta-llama/Llama-3.1-8B-Instruct", "Qwen/Qwen3-8B") + os.environ["ABPRUNE_EXTERNAL_SRC"] = str(opt.external_root / "src") + import run_external_abprune_instruct_order as instruction + + opt.audit_root.mkdir(parents=True, exist_ok=True) + selection_batches = None + if opt.selection_data: + if opt.initializer not in ("come", "mka") or opt.fixed_span_merge_only: + raise ValueError("Frozen selection inputs require native CoMe or MKA") + selection_batches = torch.load(opt.selection_data, weights_only=True, map_location="cpu") + checksum = hashlib.sha256() + count = 0 + for batch in selection_batches: + ids, mask = batch["input_ids"], batch["attention_mask"] + if ids.ndim != 2 or ids.shape != mask.shape or not bool(mask.bool().any(dim=1).all()): + raise ValueError("Frozen native inputs require matching nonempty valid-token masks") + if opt.initializer == "come" and not bool(mask.all()): + raise ValueError("Frozen native CoMe inputs must be unpadded matrices") + checksum.update(ids.numpy().astype(" 1 and fingerprints["distill_loader"]["sequences"] == 512: + assert fingerprints["calib_loader"]["sha256"] == "fa4a6219f7a7b17364eef6b5b7771533b57a407f1d26db1d483bbd955814ce38" + assert fingerprints["distill_loader"]["sha256"] == "2b2d044c8c040f67891817ecc110f0fa0de2f469db4c6731114ff7816bbf1cd0" + print("ONE_SHOT_DATA_MATCHES_PREVIOUS_PROGRESSIVE", flush=True) + return data + + base.prepare_all_data = prepare + geometry_batches = None + + def select(args, model, layers, dataloader, cosine_loader, scores, start, excluded): + nonlocal geometry_batches + if opt.fixed_span_merge_only: + from fusegpt.fit_ablation_come import valid_calibration_batches + index = opt.fixed_anchor + assert state["active"][index] == opt.fixed_anchor + assert state["active"][index + 1] == opt.fixed_anchor + 1 + len(state["records"]) + state["transport_completed"] = False + batches = valid_calibration_batches(dataloader) + if opt.initializer == "come": + from fusegpt import come + measured = come.collect_calibration_scores(model, batches, sbi_metric="angular_last") + leaves = len(state["lineage"][index]) + len(state["lineage"][index + 1]) + minimum = opt.come_minimum_retention ** (1 / (leaves - 1)) + ratios = come.compute_retention_ratios( + measured.block_importance[index:index+2], power=opt.come_power, minimum=minimum) + state["merge_payload"] = {"ratios": ratios, + "neuron_scores": measured.mlp_neurons[index:index+2]} + extra = {"minimum_retention": opt.come_minimum_retention, + "adjusted_minimum": minimum, "power": opt.come_power, + "retention_ratios": ratios, "block_importance": measured.block_importance[index:index+2]} + del measured + else: + from fusegpt import fit_ablation_mka as mka + config = mka.GeometryConfig() + assert len(batches) >= 64, "MKA geometry requires the matched64-record calibration view" + features = mka.collect_features(model, batches, pooling=config.pooling) + manifolds = [mka.diffusion_embedding(x, config) for x in features] + del features + matrix, entropies = mka.npib_matrix([x[0] for x in manifolds], config) + state["lambda"] = mka.upstream_lambda(matrix, index, index+1, config.beta) + state["merge_payload"] = {"lambda_left": state["lambda"]} + extra = {"npib_matrix": matrix.tolist(), "entropies": entropies, + "row_means": matrix.mean(1).tolist(), "geometry_samples": len(batches), + "geometry_sequence_length": int(batches[0]["input_ids"].shape[1])} + del manifolds, matrix + extra.update({"selection_policy": f"fixed_anchor{opt.fixed_anchor}", "source_lineage": + [state["lineage"][index][:], state["lineage"][index+1][:]], + "score_data": "same_calib_loader_as_transport", "data_seed": 42, + "mka_mi_seed": 0 if opt.initializer == "mka" else None, + "initializer_weights_after_transport": True}) + del batches + elif opt.initializer == "come": + from fusegpt.fit_ablation_come import select_and_initialize + index, initial, extra = select_and_initialize( + model, selection_batches if selection_batches is not None else dataloader, state["lineage"], + minimum=opt.come_minimum_retention, power=opt.come_power) + state["come_initial"] = initial + state["come_audit"] = extra + elif opt.initializer == "mka": + from fusegpt import fit_ablation_mka as mka + if geometry_batches is None: + if selection_batches is not None: + geometry_batches = selection_batches + elif opt.mka_data and opt.mka_data.is_file(): + geometry_batches = torch.load(opt.mka_data, weights_only=True) + else: + from transformers import AutoTokenizer + tokenizer = AutoTokenizer.from_pretrained(args.model) + if opt.instruction_data: + import copy + geometry_args = copy.copy(args) + geometry_args.seed = 0 + records = instruction.load_slimorca_records(geometry_args, opt.mka_samples, + "ABPRUNE_MKA_DATA_INDICES_FILE") + dataset = base.FixedSeqDataset(records, tokenizer, 512) + geometry_batches = [{"input_ids": ids[None, :], "attention_mask": mask[None, :]} + for ids, mask in dataset] + assert len(geometry_batches) == opt.mka_samples + checksum = hashlib.sha256() + for batch in geometry_batches: + checksum.update(batch["input_ids"].numpy().astype(" 1: + assert len(kwargs["teacher_layers"]) == 32 + assert len(kwargs["student_layers"]) == 32 + assert kwargs["layer_idx"] == 21 and kwargs["absorb_count"] == 8 + print("ONE_SHOT_FIXED_DENSE_TEACHER_BOUNDARY=29 STUDENT_BOUNDARY=21 DROP=22:30", flush=True) + if opt.record_fit_runtime: + forward_shapes = {} + hooks = [] + def trace_forward(label): + def capture(module, positional, named): + ids = named.get("input_ids") + if ids is None and positional: + ids = positional[0] + if torch.is_tensor(ids): + key = label + ":" + "x".join(str(v) for v in ids.shape) + forward_shapes[key] = forward_shapes.get(key, 0) + 1 + return capture + for label in ("student", "teacher"): + hooks.append(kwargs[label + "_model"].register_forward_pre_hook( + trace_forward(label), with_kwargs=True)) + torch.cuda.synchronize() + torch.cuda.reset_peak_memory_stats() + fit_started = time.perf_counter() + try: + merged, gates, stats = original_fit(**kwargs) + finally: + if opt.record_fit_runtime: + for hook in hooks: + hook.remove() + if opt.record_fit_runtime: + torch.cuda.synchronize() + elapsed = time.perf_counter() - fit_started + loader = kwargs["dataloader"] + tokens = sum(int(item[1].sum()) for item in loader.dataset) + stats["runtime"] = { + "seconds": elapsed, "dataset_tokens": tokens, + "tokens_per_second": tokens * float(kwargs["args"].distill_epochs) / elapsed, + "batch_size": int(kwargs["args"].distill_batch_size), + "batches_per_epoch": len(loader), + "grad_accumulation": int(kwargs["args"].distill_grad_accum_steps), + "peak_allocated_bytes": torch.cuda.max_memory_allocated(), + "peak_reserved_bytes": torch.cuda.max_memory_reserved(), + "gpu_total_bytes": torch.cuda.get_device_properties(0).total_memory, + "actual_forward_shapes": forward_shapes, + } + if opt.fit_come_attention: + layer = kwargs["student_layers"][kwargs["layer_idx"]] + expected = state["initialization_audit"]["frozen_norm_expected_sha256"] + measured = {n: hashlib.sha256(layer.get_parameter(n).detach().cpu().contiguous() + .view(torch.uint8).numpy().tobytes()).hexdigest() for n in expected} + assert measured == expected, "CoMe-initialized norms changed during attention+MLP FiT" + state["initialization_audit"]["frozen_norm_after_sha256"] = measured + state["initialization_audit"]["frozen_norms_unchanged"] = True + if opt.fit_mka_mlp: + layer = kwargs["student_layers"][kwargs["layer_idx"]] + expected = state["initialization_audit"]["frozen_attention_norm_expected_sha256"] + measured = {n: hashlib.sha256(layer.get_parameter(n).detach().cpu().contiguous() + .view(torch.uint8).numpy().tobytes()).hexdigest() for n in expected} + assert measured == expected, "Native MKA merged attention/anchor norms changed during MLP-only FiT" + state["initialization_audit"]["frozen_attention_norm_after_sha256"] = measured + state["initialization_audit"]["frozen_attention_norm_unchanged"] = True + if opt.fixed_span_merge_only: + frozen_after = frozen_hashes(anchor_layer) + assert frozen_after == frozen_before, "Attention/norm changed during MLP-only FiT" + audit = state["initialization_audit"]["merge_rule_audit"] + assert audit["transported_source_mlp_sha256"] == state["transport_operands"]["after"] + state["initialization_audit"].update({"frozen_attention_norm_unchanged": True, + "transport_operands": state["transport_operands"]}) + stats["ablation"] = {**state["initialization_audit"], + "source_feature_transport": bool(kwargs["args"].source_feature_transport), + "initializer": opt.initializer, + "removed_count_per_cycle": opt.one_shot, + "teacher_boundary_current_layer": kwargs["layer_idx"] + opt.one_shot, + "teacher_boundary_original_layer": state["records"][-1]["removed_original_layers"][-1]} + (opt.audit_root / f"cycle_{kwargs['progressive_cycle']:02d}_fit.json").write_text( + json.dumps(stats, indent=2) + "\n") + return merged, gates, stats + + base.distill_reparam_merge = fit + sys.argv = [sys.argv[0], *forwarded] + base.main() + # Correct legacy Fisher-specific labels and add reconstructible topology. + output = Path(forwarded[forwarded.index("--output_dir") + 1]) + for record in state["records"]: + path = output / f"cycle_{record['cycle']}" / "cycle_metadata.json" + data = json.loads(path.read_text()) + data.update({k: record[k] for k in ("recipient_original_layer", "removed_original_layer", "recipient_side", "active_original_layers")}) + data["fisher_computed"] = False + data["merge_initializer"] = opt.initializer + data["fixed_span_merge_only"] = opt.fixed_span_merge_only + data["removed_original_layers"] = record["removed_original_layers"] + data["same_anchor_contextual_fisher"] = {"computed": False} + if data.get("source_feature_transport"): + data["source_feature_transport"]["fisher_order"] = "source transport; non-Fisher initialization; additive-U FiT" + reparam = data.get("distill", {}).get("reparam_stats") + if reparam: + reparam["lambda_init"] = opt.initializer + path.write_text(json.dumps(data, indent=2) + "\n") + if opt.one_shot > 1: + import subprocess + subprocess.run([sys.executable, str(Path(__file__).with_name("package_qwen3_1_7b_one_shot_compact.py")), + "--run-root", str(output), "--output-root", str(opt.audit_root.parent / "compact"), + "--model", opt.model_id, "--base-revision", opt.base_revision, + "--run-id", "llama31_base_wa_oneshot_8block", "--anchor", str(opt.fixed_anchor), + "--removed-count", str(opt.one_shot)], check=True) + else: + from fusegpt.abprune_compact import package + package(argparse.Namespace(run_root=output, output_root=opt.audit_root.parent / "compact", + model=opt.model_id, base_revision=opt.base_revision, + 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"]), + start_cycle=1, layer_order=" ".join(str(r["pair_index"]) for r in state["records"]))) + (opt.audit_root.parent / "TRAIN_COMPLETE").touch() + + +if __name__ == "__main__": + main() diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/run_llama31_come_fit_arm.sh b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/run_llama31_come_fit_arm.sh new file mode 100644 index 0000000000000000000000000000000000000000..5b0eb22829f449efa7d265d04fda982e2a509b58 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/run_llama31_come_fit_arm.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +set -euo pipefail +project="$1"; external="$2"; root="$3"; model="$4"; family="$5"; gpu="$6"; mode="${7:-full}" +scope="${8:-full}"; subset=all; fit=(--fit-full-block) +if [[ "$scope" == mlp ]]; then subset=mlp; fit=(--fit-come-mlp); elif [[ "$scope" != full ]]; then exit 2; fi +export CUDA_VISIBLE_DEVICES="$gpu" HF_HOME=/workspace/.hf_home HF_TOKEN_PATH=/root/.cache/huggingface/token +export HF_DATASETS_CACHE=/workspace/.hf_datasets36 HF_DATASETS_TRUST_REMOTE_CODE=1 +export HF_HUB_OFFLINE=1 HF_DATASETS_OFFLINE=1 +export PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false OMP_NUM_THREADS=4 +export PYTHONPATH="$external/src:$project/src${PYTHONPATH:+:$PYTHONPATH}" +mkdir -p "$root/logs" "$root/audit" "$root/run" +cycles=8; records=500; calib=64; tokens=524288 +if [[ "$mode" == smoke ]]; then cycles=2; records=20; calib=4; tokens=20480; fi +if [[ "$family" == instruct ]]; then + export ABPRUNE_DATASET_REVISION=ce9ed009ef3292bac33d3520afaf5ec804066120 + wrapper=(--model-id meta-llama/Llama-3.1-8B-Instruct --base-revision 0e9e39f249a16976918f6564b8830bc894c89659 --instruction-data) + data=(--target_tokens 0 --distill_calib_samples 0 --instruction_dataset Open-Orca/SlimOrca + --instruction_config none --instruction_split train --distill_inst_samples "$records") +elif [[ "$family" == base ]]; then + export ABPRUNE_DATASET_REVISION=b5f90f419b7489cdba26fdbc8c022fcb5562f968 + wrapper=(--model-id meta-llama/Llama-3.1-8B --base-revision d04e592bb4f6aa9cfee91e2e20afa771667e1d4b) + data=(--dataset slimpajama --dataset_config none --target_tokens "$tokens") +else exit 2; fi +python "$project/scripts/run_llama31_base_fit_ablation.py" \ + --external-root "$external" --initializer come "${fit[@]}" --audit-root "$root/audit" \ + --come-minimum-retention .97 --come-power 1 "${wrapper[@]}" --model "$model" --output_dir "$root/run" \ + --layer 21 --num_progressive "$cycles" "${data[@]}" --num_samples "$calib" \ + --seq_len 1024 --batch_size 2 --distill_seq_len 1024 --distill_batch_size 1 \ + --distill_epochs 1 --distill_lr 1e-4 --distill_weight_decay 0 --distill_max_grad_norm 1 \ + --distill_grad_accum_steps 1 --distill_kl_weight .02 --distill_kl_temp 4 \ + --distill_hidden_mse_weight 1 --distill_mlp_mse_weight 1 --distill_attn_mse_weight 0 \ + --reparam_eta 0 --reparam_gamma 0 --reparam_param_subset "$subset" \ + --reparam_fisher_init_subset same --reparam_train_subset "$subset" --reparam_rho_objective none \ + --reparam_additive_u --redistrib_teacher_source previous_cycle --fisher_mode param --eps 0 \ + --no_head_permute_merge --no_head_permute_select --dtype bfloat16 --eval_dtype bfloat16 \ + --lora_epochs 0 --skip_eval --skip_final_model_save --distill_log_steps 20 --seed 42 \ + >> "$root/logs/train.log" 2>&1 diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/run_mka_batch_arm.sh b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/run_mka_batch_arm.sh new file mode 100644 index 0000000000000000000000000000000000000000..9d13eedd81901ddbb3ba1ff766c0b4462b02ea80 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/run_mka_batch_arm.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +set -euo pipefail +project="$1"; external="$2"; root="$3"; model="$4"; selection="$5"; batch="$6"; gpu="$7" +cycles="${8:-8}"; tokens="${9:-524288}"; selection_hash="${10:?frozen MKA input hash required}" +export CUDA_VISIBLE_DEVICES="$gpu" HF_HOME=/workspace/.hf_home HF_TOKEN_PATH=/root/.cache/huggingface/token +export HF_DATASETS_CACHE=/workspace/.hf_datasets36 HF_DATASETS_TRUST_REMOTE_CODE=1 +export HF_HUB_OFFLINE=1 HF_DATASETS_OFFLINE=1 TRANSFORMERS_OFFLINE=1 +export PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false OMP_NUM_THREADS=4 +export PYTHONPATH="$external/src:$project/src${PYTHONPATH:+:$PYTHONPATH}" +export ABPRUNE_DATASET_REVISION=b5f90f419b7489cdba26fdbc8c022fcb5562f968 +[[ -s "$selection" ]] || { echo 'Frozen historical MKA inputs are required; no resampling'; exit 1; } +mkdir -p "$root/logs" "$root/audit" "$root/run" +python "$project/scripts/run_llama31_base_fit_ablation.py" \ + --external-root "$external" --initializer mka --fit-mka-mlp --audit-root "$root/audit" \ + --mka-data "$selection" --selection-hash "$selection_hash" --mka-samples 100 --record-fit-runtime \ + --model-id meta-llama/Llama-3.1-8B --base-revision d04e592bb4f6aa9cfee91e2e20afa771667e1d4b \ + --model "$model" --output_dir "$root/run" --layer 21 --num_progressive "$cycles" \ + --dataset slimpajama --dataset_config none --target_tokens "$tokens" \ + --num_samples 64 --seq_len 1024 --batch_size 2 \ + --distill_seq_len 1024 --distill_batch_size "$batch" --distill_epochs 1 --distill_lr 1e-4 \ + --distill_weight_decay 0 --distill_max_grad_norm 1 --distill_grad_accum_steps 1 \ + --distill_kl_weight .02 --distill_kl_temp 4 --distill_hidden_mse_weight 1 \ + --distill_mlp_mse_weight 1 --distill_attn_mse_weight 0 --reparam_eta 0 --reparam_gamma 0 \ + --reparam_param_subset mlp --reparam_fisher_init_subset same --reparam_train_subset mlp \ + --reparam_rho_objective none --reparam_additive_u --redistrib_teacher_source previous_cycle \ + --fisher_mode param --eps 0 --no_head_permute_merge --no_head_permute_select \ + --dtype bfloat16 --eval_dtype bfloat16 --lora_epochs 0 --skip_eval --skip_final_model_save \ + --distill_log_steps 10 --seed 42 >> "$root/logs/train.log" 2>&1 diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/source_feature_transport.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/source_feature_transport.py new file mode 100644 index 0000000000000000000000000000000000000000..242e2e52572627622decabcc62b7e24a1b7f0046 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/source_feature_transport.py @@ -0,0 +1,342 @@ +"""Stage-local source MLP transport into the anchor MLP input coordinate. + +The fitted map ``T`` satisfies ``X_anchor @ T ~= X_source``. For linear +input projections stored as ``W`` (PyTorch convention ``y = x @ W.T``), the +equivalent source projection in the anchor coordinate is ``W @ T.T``. + +This module intentionally transports only ``gate_proj`` and ``up_proj``. +``down_proj`` consumes the SwiGLU intermediate representation rather than the +decoder hidden coordinate and is therefore left unchanged. +""" + +from __future__ import annotations + +import math +from typing import Dict, List, Tuple + +import torch + + +class _StopAfterSource(RuntimeError): + """Abort a model forward once both MLP inputs have been captured.""" + + +def _capture_mlp_inputs(model, layer_a, layer_b, input_ids, attention_mask=None): + captured: Dict[str, torch.Tensor] = {} + + def capture_anchor(_module, inputs): + captured["anchor"] = inputs[0].detach() + + def capture_source(_module, inputs): + captured["source"] = inputs[0].detach() + raise _StopAfterSource() + + handles = ( + layer_a.mlp.register_forward_pre_hook(capture_anchor), + layer_b.mlp.register_forward_pre_hook(capture_source), + ) + try: + kwargs = {"input_ids": input_ids, "use_cache": False} + if attention_mask is not None: + kwargs["attention_mask"] = attention_mask + try: + model(**kwargs) + except _StopAfterSource: + pass + finally: + for handle in handles: + handle.remove() + + if set(captured) != {"anchor", "source"}: + raise RuntimeError( + "Failed to capture anchor/source MLP inputs; " + f"captured={sorted(captured)}" + ) + return captured["anchor"], captured["source"] + + +def solve_transport_from_statistics( + gram_sum: torch.Tensor, + cross_sum: torch.Tensor, + source_sq_sum: float, + token_count: int, + ridge_relative: float, +) -> Tuple[torch.Tensor, Dict[str, float]]: + """Solve ridge OLS and return its calibration-set reconstruction metrics.""" + if token_count <= 0: + raise ValueError("token_count must be positive") + if ridge_relative < 0.0: + raise ValueError("ridge_relative must be non-negative") + + gram = gram_sum / float(token_count) + cross = cross_sum / float(token_count) + target_sq = float(source_sq_sum) / float(token_count) + mean_diagonal = float(torch.diagonal(gram).mean().item()) + ridge = float(ridge_relative) * mean_diagonal + regularized = gram.clone() + regularized.diagonal().add_(ridge) + chol, info = torch.linalg.cholesky_ex(regularized) + if int(info.max().item()) != 0: + raise RuntimeError( + "Source-feature transport Cholesky failed: " + f"info={int(info.max().item())}" + ) + solution = torch.cholesky_solve(cross, chol) + + # Since (G + ridge I) T = C, tr(T' G T) can be computed without another + # O(d^3) multiply as - ridge ||T||^2. + dot = float((solution.double() * cross.double()).sum().item()) + solution_sq = float(solution.double().square().sum().item()) + predicted_sq = max(0.0, dot - ridge * solution_sq) + error_sq = max(0.0, target_sq + predicted_sq - 2.0 * dot) + denominator = math.sqrt(max(predicted_sq, 0.0) * max(target_sq, 0.0)) + identity = torch.eye( + solution.shape[0], dtype=solution.dtype, device=solution.device + ) + relative_identity_distance = float( + torch.linalg.vector_norm((solution - identity).float()).item() + / math.sqrt(float(solution.shape[0])) + ) + del identity + + stats = { + "tokens": int(token_count), + "ridge_relative": float(ridge_relative), + "ridge_absolute": ridge, + "gram_mean_diagonal": mean_diagonal, + "calibration_nmse": error_sq / target_sq if target_sq > 0.0 else float("nan"), + "calibration_cosine": dot / denominator if denominator > 0.0 else float("nan"), + "calibration_norm_ratio": ( + math.sqrt(predicted_sq / target_sq) if target_sq > 0.0 else float("nan") + ), + "transport_relative_identity_distance": relative_identity_distance, + } + return solution, stats + + +def _apply_transport_to_source_mlp(source_mlp, solution, row_chunk: int) -> None: + if row_chunk <= 0: + raise ValueError("row_chunk must be positive") + with torch.no_grad(): + for projection_name in ("gate_proj", "up_proj"): + projection = getattr(source_mlp, projection_name) + original = projection.weight.detach().clone() + if original.ndim != 2 or original.shape[1] != solution.shape[0]: + raise ValueError( + f"Unexpected {projection_name} shape {tuple(original.shape)} " + f"for transport {tuple(solution.shape)}" + ) + for start in range(0, original.shape[0], row_chunk): + end = min(start + row_chunk, original.shape[0]) + transported = original[start:end].float() @ solution.transpose(0, 1) + projection.weight[start:end].copy_(transported.to(projection.weight.dtype)) + del original + + +def fit_and_apply_source_feature_transport( + model, + layer_a, + layer_b, + dataloader, + device: str, + ridge_relative: float = 1e-3, + max_batches: int = 0, + row_chunk: int = 128, +) -> Dict[str, object]: + """Fit ``X_a T ~= X_b`` and rewrite source MLP input projections.""" + if dataloader is None: + raise ValueError("Source-feature transport requires a dataloader") + + previous_training = model.training + model.eval() + gram_sum = None + cross_sum = None + source_sq_sum = 0.0 + token_count = 0 + batches = 0 + try: + with torch.no_grad(): + for batch in dataloader: + if max_batches > 0 and batches >= max_batches: + break + input_ids = batch[0].to(device, non_blocking=True) + attention_mask = ( + batch[1].to(device, non_blocking=True) if len(batch) > 1 else None + ) + x_a, x_b = _capture_mlp_inputs( + model, layer_a, layer_b, input_ids, attention_mask + ) + x_a = x_a.reshape(-1, x_a.shape[-1]).float() + x_b = x_b.reshape(-1, x_b.shape[-1]).float() + if attention_mask is not None: + valid = attention_mask.reshape(-1).to(dtype=torch.bool) + if valid.numel() != x_a.shape[0]: + raise RuntimeError( + "Attention mask does not align with captured MLP inputs" + ) + x_a = x_a[valid] + x_b = x_b[valid] + if gram_sum is None: + width = x_a.shape[-1] + gram_sum = torch.zeros( + (width, width), dtype=torch.float32, device=x_a.device + ) + cross_sum = torch.zeros_like(gram_sum) + gram_sum.addmm_(x_a.transpose(0, 1), x_a) + cross_sum.addmm_(x_a.transpose(0, 1), x_b) + source_sq_sum += float(x_b.double().square().sum().item()) + token_count += int(x_a.shape[0]) + batches += 1 + finally: + model.train(previous_training) + + if gram_sum is None or cross_sum is None or batches == 0: + raise RuntimeError("No batches were processed for source-feature transport") + solution, stats = solve_transport_from_statistics( + gram_sum, + cross_sum, + source_sq_sum, + token_count, + ridge_relative, + ) + _apply_transport_to_source_mlp(layer_b.mlp, solution, row_chunk=row_chunk) + stats.update( + { + "enabled": True, + "batches": int(batches), + "coordinate_fit": "X_anchor @ T ~= X_source", + "weight_rewrite": [ + "mlp.gate_proj.weight <- W_source @ T.T", + "mlp.up_proj.weight <- W_source @ T.T", + ], + "down_proj_transported": False, + } + ) + del solution, gram_sum, cross_sum + if torch.cuda.is_available(): + torch.cuda.empty_cache() + return stats + + +def _drop_container_layer(container, index: int): + if isinstance(container, torch.nn.ModuleList): + return torch.nn.ModuleList( + [layer for layer_index, layer in enumerate(container) if layer_index != index] + ) + if isinstance(container, list): + return [layer for layer_index, layer in enumerate(container) if layer_index != index] + raise TypeError(f"Unsupported layer container: {type(container)}") + + +def compute_same_anchor_contextual_fisher( + model, + parent, + layer_attr: str, + container, + layer_idx: int, + layer_a, + layer_b, + dataloader, + device: str, + fisher_mode: str, +) -> Tuple[List[Dict[str, object]], int, List[Dict[str, int]], Dict[str, float]]: + """Measure both candidate MLPs in the same post-pruning anchor topology. + + The source MLP must already be feature-transported. Two virtual pruned + models are evaluated on every calibration batch: one uses the native + anchor MLP and one replaces it with the transported source MLP. The source + decoder block is absent in both arms, so the gradients describe the actual + deployment coordinate/topology rather than the source's old depth. + """ + if fisher_mode != "param": + raise ValueError("Same-anchor contextual Fisher currently requires fisher_mode=param") + + anchor_mlp = layer_a.mlp + source_mlp = layer_b.mlp + previous_container = container + pruned_container = _drop_container_layer(container, layer_idx + 1) + previous_training = model.training + + names_a = dict(layer_a.named_parameters()) + names_b = dict(layer_b.named_parameters()) + fisher_a: Dict[str, object] = {} + fisher_b: Dict[str, object] = {} + numels_a: Dict[str, int] = {} + numels_b: Dict[str, int] = {} + for name, parameter in names_a.items(): + if name.startswith("mlp."): + fisher_a[name] = torch.zeros_like(parameter, dtype=torch.float32, device="cpu") + else: + fisher_a[name] = 0.0 + numels_a[name] = int(parameter.numel()) + for name, parameter in names_b.items(): + if name.startswith("mlp."): + fisher_b[name] = torch.zeros_like(parameter, dtype=torch.float32, device="cpu") + else: + fisher_b[name] = 0.0 + numels_b[name] = int(parameter.numel()) + + for parameter in model.parameters(): + parameter.requires_grad_(False) + + anchor_loss_sum = 0.0 + source_loss_sum = 0.0 + num_batches = 0 + + def run_arm(candidate_mlp, fisher_target, input_ids, attention_mask): + layer_a.mlp = candidate_mlp + for parameter in candidate_mlp.parameters(): + parameter.requires_grad_(True) + model.zero_grad(set_to_none=True) + labels = input_ids + if attention_mask is not None: + labels = input_ids.masked_fill(attention_mask == 0, -100) + kwargs = {"input_ids": input_ids, "labels": labels, "use_cache": False} + if attention_mask is not None: + kwargs["attention_mask"] = attention_mask + output = model(**kwargs) + output.loss.backward() + for local_name, parameter in candidate_mlp.named_parameters(): + full_name = f"mlp.{local_name}" + if parameter.grad is not None: + fisher_target[full_name] += parameter.grad.detach().float().square().cpu() + loss = float(output.loss.detach().item()) + model.zero_grad(set_to_none=True) + for parameter in candidate_mlp.parameters(): + parameter.requires_grad_(False) + return loss + + try: + setattr(parent, layer_attr, pruned_container) + model.eval() + for batch in dataloader: + input_ids = batch[0].to(device, non_blocking=True) + attention_mask = ( + batch[1].to(device, non_blocking=True) if len(batch) > 1 else None + ) + anchor_loss_sum += run_arm( + anchor_mlp, fisher_a, input_ids, attention_mask + ) + source_loss_sum += run_arm( + source_mlp, fisher_b, input_ids, attention_mask + ) + num_batches += 1 + finally: + layer_a.mlp = anchor_mlp + setattr(parent, layer_attr, previous_container) + model.train(previous_training) + + if num_batches == 0: + raise RuntimeError("No batches were processed for same-anchor contextual Fisher") + stats = { + "num_batches": int(num_batches), + "anchor_candidate_mean_nll": anchor_loss_sum / float(num_batches), + "transported_source_candidate_mean_nll": source_loss_sum / float(num_batches), + "source_minus_anchor_mean_nll": ( + source_loss_sum - anchor_loss_sum + ) / float(num_batches), + "topology": "source block dropped; candidate MLP evaluated at anchor slot", + "shared_input_coordinate": True, + "scope": "mlp gate/up/down diagonal empirical Fisher", + } + return [fisher_a, fisher_b], num_batches, [numels_a, numels_b], stats diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/validate_mka_first_selection.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/validate_mka_first_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..4302b9ca17110e1491cb241463d3d5cd890b847a --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/validate_mka_first_selection.py @@ -0,0 +1,57 @@ +"""Compare the pre-FiT MKA selection against its immutable historical reference.""" +import argparse +import json +from pathlib import Path + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--reference", type=Path, required=True) + p.add_argument("--selection", type=Path, required=True) + p.add_argument("--output", type=Path, required=True) + p.add_argument("--historical-reference", type=Path, + help="Preserve cross-environment historical differences separately from the native implementation gate") + p.add_argument("--atol", type=float, default=1e-6) + p.add_argument("--rtol", type=float, default=1e-5) + a = p.parse_args() + source = json.loads(a.reference.read_text()) + ref = source["merges"][0] if "merges" in source else source + observed = json.loads(a.selection.read_text())[0] + left, right = ref["npib_matrix"], observed["npib_matrix"] + assert len(left) == len(right) == 32 + assert all(len(x) == len(y) == 32 for x, y in zip(left, right)) + differences = [abs(x - y) for xs, ys in zip(left, right) for x, y in zip(xs, ys)] + close = all(abs(x - y) <= a.atol + a.rtol * abs(x) + for xs, ys in zip(left, right) for x, y in zip(xs, ys)) + ratio_close = abs(ref["lambda_left"] - observed["lambda_left"]) <= a.atol + reference_index = ref.get("left_index", ref.get("pair_index")) + source_lineage = ref.get("source_layers", [[reference_index], [reference_index + 1]]) + passed = (reference_index == observed["pair_index"] and close and ratio_close + and source_lineage == observed["source_lineage"]) + result = {"passed": passed, "validation_scope": "first pre-FiT selection only; no eight-stage replay claimed", + "atol": a.atol, "rtol": a.rtol, "matrix_allclose": close, + "matrix_max_absolute_difference": max(differences), + "reference_path": str(a.reference), + "reference_implementation": source.get("implementation", "historical native MKA"), + "expected_pair_index": reference_index, "observed_pair_index": observed["pair_index"], + "expected_lambda": ref["lambda_left"], "observed_lambda": observed["lambda_left"], + "expected_pair_npib": ref["pair_npib"], "observed_pair_npib": observed["pair_npib"]} + if a.historical_reference: + old = json.loads(a.historical_reference.read_text())["merges"][0] + result["historical_reference_comparison"] = { + "path": str(a.historical_reference), + "pair_agrees": old["left_index"] == observed["pair_index"], + "expected_lambda": old["lambda_left"], "observed_lambda": observed["lambda_left"], + "matrix_max_absolute_difference": max(abs(x-y) for xs, ys in zip(old["npib_matrix"], right) + for x, y in zip(xs, ys)), + "exact_historical_reproduction_claimed": False, + "qualification": "Same frozen tokens and native algorithm; historical execution environment differs. Current runtime native implementation is validated independently."} + a.output.parent.mkdir(parents=True, exist_ok=True) + a.output.write_text(json.dumps(result, indent=2) + "\n") + print(json.dumps(result, indent=2)) + if not passed: + raise SystemExit("Native reference differs; inspect runtime/input fidelity before production") + + +if __name__ == "__main__": + main() diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/validate_mka_runtime_geometry.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/validate_mka_runtime_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..e42c3b1994ac474295201b75f68aaffa078b7134 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/code/validate_mka_runtime_geometry.py @@ -0,0 +1,174 @@ +"""Split native MKA activation collection from CPU geometry for runtime diagnosis. + +Pooled feature caches are private diagnostic artifacts, never public payloads. +No model weights or calibration tokens are written by this script. +""" +from __future__ import annotations + +import argparse +from dataclasses import asdict +import hashlib +import importlib.metadata +import json +from pathlib import Path +import platform +import sys +import time + + +def versions(): + result = {"python": platform.python_version()} + for name in ("torch", "transformers", "numpy", "scipy", "scikit-learn"): + try: + result[name] = importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError: + result[name] = None + return result + + +def file_hash(path): + digest = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(8 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def first_reference(path): + item = json.loads(path.read_text()) + if isinstance(item, list): + return item[0] + if "merges" in item: + return item["merges"][0] + return item + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--model", help="Local dense model directory; not needed with --features-input") + p.add_argument("--selection", type=Path, help="Frozen native MKA100x512 list of input/mask dictionaries") + p.add_argument("--output", type=Path, required=True) + p.add_argument("--features-output", type=Path) + p.add_argument("--features-input", type=Path) + p.add_argument("--features-only", action="store_true") + p.add_argument("--reference", type=Path) + p.add_argument("--implementation", choices=("native", "fit"), default="native", + help="Independent native implementation or the FiT selector helper") + p.add_argument("--device", default="cuda:0") + p.add_argument("--attn-implementation", default="sdpa", choices=("sdpa", "eager", "flash_attention_2")) + p.add_argument("--atol", type=float, default=1e-6) + p.add_argument("--rtol", type=float, default=1e-5) + a = p.parse_args() + if a.features_only and (not a.features_output or a.features_input): + p.error("--features-only requires --features-output and collects new model features") + if not a.features_input and (not a.model or not a.selection): + p.error("Collecting features requires both --model and --selection") + + sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) + import numpy as np + import torch + if a.implementation == "native": + from fusegpt import mka + else: + from fusegpt import fit_ablation_mka as mka + + started = time.monotonic() + config = mka.GeometryConfig() + result = {"runtime_versions": versions(), "geometry_config": asdict(config), + "implementation": a.implementation, "implementation_module": str(Path(mka.__file__).resolve()), + "implementation_source_sha256": file_hash(Path(mka.__file__)), + "private_feature_cache": True, "public_upload_allowed": False, + "validation_scope": "dense original model, first pre-FiT MKA geometry only"} + if a.features_input: + features = np.load(a.features_input, allow_pickle=False) + result["features_source"] = str(a.features_input) + result["features_sha256"] = file_hash(a.features_input) + sidecar = a.features_input.with_suffix(a.features_input.suffix + ".json") + if sidecar.is_file(): + result["feature_collection_provenance"] = json.loads(sidecar.read_text()) + else: + from transformers import AutoModelForCausalLM + + batches = torch.load(a.selection, weights_only=True, map_location="cpu") + if len(batches) != 100: + raise ValueError("Expected the frozen native100x512 MKA geometry") + ids_hash, masks_hash = hashlib.sha256(), hashlib.sha256() + for batch in batches: + ids, mask = batch["input_ids"], batch["attention_mask"] + if tuple(ids.shape) != (1, 512) or mask.shape != ids.shape: + raise ValueError("Native MKA input shape must be1x512") + if not bool(((mask == 0) | (mask == 1)).all()) or not bool(mask.any()): + raise ValueError("Invalid native attention mask") + ids_hash.update(ids.numpy().astype("= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2) +/opt/conda/lib/python3.11/site-packages/torch/nn/modules/linear.py:125: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return F.linear(input, self.weight, self.bias) +[fit-ablation] selection {"cycle": 1, "pair_index": 21, "initializer": "mka", "lambda_left": 0.6240301169976673, "recipient_original_layer": 21, "recipient_side": "left", "removed_original_layer": 22, "entropies": [-0.6315610607587784, -0.627416009583068, -0.5861614941870391, -0.6016038763611488, -0.6130674217530055, -0.6121981385094227, -0.6033131501980972, -0.5924187613341422, -0.6069171484092294, -0.6132380808987886, -0.5909367743402253, -0.590407987771964, -0.5917503747664402, -0.5967832540390615, -0.6130424939063307, -0.5930475051215599, -0.6093573556090445, -0.5989470593654461, -0.5676289381777201, -0.5608694521216201, -0.5743625477527975, -0.5557850271201213, -0.5616113594268438, -0.5596460325149003, -0.5734106113048131, -0.5980103347467473, -0.585848842395306, -0.6006940220260183, -0.6040359784607082, -0.596804905704757, -0.6565548704092264, -0.6440389208735767], "pair_npib": 1.928525358648791, "source_lineage": [[21], [22]], "geometry_samples": 100, "geometry_sequence_length": 512, "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", "selection_policy": "native_dynamic_adjacent_NPIB", "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", "removed_original_layers": [22], "active_original_layers": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31]} +[fuse] Head permutation disabled; merging with original head order. +[fit-ablation] Fisher bypassed: non-Fisher initializer + Loading weights: 0%| | 0/291 [00:00= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2) +/opt/conda/lib/python3.11/site-packages/torch/nn/modules/linear.py:125: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return F.linear(input, self.weight, self.bias) +/opt/conda/lib/python3.11/site-packages/torch/autograd/graph.py:829: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass +/opt/conda/lib/python3.11/site-packages/torch/autograd/graph.py:829: UserWarning: Flash Attention defaults to a non-deterministic algorithm. To explicitly enable determinism call torch.use_deterministic_algorithms(True, warn_only=False). (Triggered internally at /pytorch/aten/src/ATen/native/transformers/cuda/attention_backward.cu:110.) + return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass +[reparam] first_grad phase=joint step=1 gate_l2=0.000000e+00 gate_mean_abs=None gate_max_abs=0.000000e+00 u_l2=2.846570e-02 u_mean_abs=1.2423996893284355e-06 u_max_abs=6.942749e-04 rho_l2=0.000000e+00 +[reparam] epoch=1 step=1 phase=joint loss=4.626257e-02 mse=2.555933e-02 mlp_mse=1.181081e-02 kl=2.778883e-02 lambda_mean=0.6240300536155701 lambda_std=0.0 lambda_abs0.5=0.12403005361557007 + Reparam (cycle 1/8, epoch 1): 2%|▏ | 1/64 [00:02<03:04, 2.93s/batch] Reparam (cycle 1/8, epoch 1): 3%|▎ | 2/64 [00:05<02:51, 2.77s/batch] Reparam (cycle 1/8, epoch 1): 5%|▍ | 3/64 [00:08<02:45, 2.72s/batch] Reparam (cycle 1/8, epoch 1): 6%|▋ | 4/64 [00:10<02:41, 2.70s/batch] Reparam (cycle 1/8, epoch 1): 8%|▊ | 5/64 [00:13<02:38, 2.69s/batch] Reparam (cycle 1/8, epoch 1): 9%|▉ | 6/64 [00:16<02:35, 2.68s/batch] Reparam (cycle 1/8, epoch 1): 11%|█ | 7/64 [00:18<02:32, 2.68s/batch] Reparam (cycle 1/8, epoch 1): 12%|█▎ | 8/64 [00:21<02:29, 2.68s/batch] Reparam (cycle 1/8, epoch 1): 14%|█▍ | 9/64 [00:24<02:27, 2.67s/batch][reparam] epoch=1 step=10 phase=joint loss=4.208330e-02 mse=2.228688e-02 mlp_mse=1.389042e-02 kl=1.845625e-02 lambda_mean=0.6240300536155701 lambda_std=0.0 lambda_abs0.5=0.12403005361557007 + Reparam (cycle 1/8, epoch 1): 16%|█▌ | 10/64 [00:27<02:27, 2.73s/batch] Reparam (cycle 1/8, epoch 1): 17%|█▋ | 11/64 [00:29<02:23, 2.71s/batch] Reparam (cycle 1/8, epoch 1): 19%|█▉ | 12/64 [00:32<02:20, 2.70s/batch] Reparam (cycle 1/8, epoch 1): 20%|██ | 13/64 [00:35<02:17, 2.69s/batch] Reparam (cycle 1/8, epoch 1): 22%|██▏ | 14/64 [00:37<02:14, 2.69s/batch] Reparam (cycle 1/8, epoch 1): 23%|██▎ | 15/64 [00:40<02:11, 2.69s/batch] Reparam (cycle 1/8, epoch 1): 25%|██▌ | 16/64 [00:43<02:08, 2.69s/batch] Reparam (cycle 1/8, epoch 1): 27%|██▋ | 17/64 [00:45<02:06, 2.69s/batch] Reparam (cycle 1/8, epoch 1): 28%|██▊ | 18/64 [00:48<02:03, 2.69s/batch] Reparam (cycle 1/8, epoch 1): 30%|██▉ | 19/64 [00:51<02:01, 2.69s/batch][reparam] epoch=1 step=20 phase=joint loss=4.226455e-02 mse=2.374206e-02 mlp_mse=1.360305e-02 kl=1.537328e-02 lambda_mean=0.6240300536155701 lambda_std=0.0 lambda_abs0.5=0.12403005361557007 + Reparam (cycle 1/8, epoch 1): 31%|███▏ | 20/64 [00:54<02:00, 2.73s/batch] Reparam (cycle 1/8, epoch 1): 33%|███▎ | 21/64 [00:56<01:56, 2.72s/batch] Reparam (cycle 1/8, epoch 1): 34%|███▍ | 22/64 [00:59<01:54, 2.72s/batch] Reparam (cycle 1/8, epoch 1): 36%|███▌ | 23/64 [01:02<01:51, 2.72s/batch] Reparam (cycle 1/8, epoch 1): 38%|███▊ | 24/64 [01:04<01:48, 2.71s/batch] Reparam (cycle 1/8, epoch 1): 39%|███▉ | 25/64 [01:07<01:45, 2.70s/batch] Reparam (cycle 1/8, epoch 1): 41%|████ | 26/64 [01:10<01:42, 2.70s/batch] Reparam (cycle 1/8, epoch 1): 42%|████▏ | 27/64 [01:12<01:39, 2.70s/batch] Reparam (cycle 1/8, epoch 1): 44%|████▍ | 28/64 [01:15<01:37, 2.70s/batch] Reparam (cycle 1/8, epoch 1): 45%|████▌ | 29/64 [01:18<01:34, 2.70s/batch][reparam] epoch=1 step=30 phase=joint loss=3.898781e-02 mse=2.087840e-02 mlp_mse=1.257739e-02 kl=1.728754e-02 lambda_mean=0.6240300536155701 lambda_std=0.0 lambda_abs0.5=0.12403005361557007 + Reparam (cycle 1/8, epoch 1): 47%|████▋ | 30/64 [01:21<01:33, 2.75s/batch] Reparam (cycle 1/8, epoch 1): 48%|████▊ | 31/64 [01:23<01:30, 2.73s/batch] Reparam (cycle 1/8, epoch 1): 50%|█████ | 32/64 [01:26<01:27, 2.72s/batch] Reparam (cycle 1/8, epoch 1): 52%|█████▏ | 33/64 [01:29<01:24, 2.72s/batch] Reparam (cycle 1/8, epoch 1): 53%|█████▎ | 34/64 [01:32<01:22, 2.73s/batch] Reparam (cycle 1/8, epoch 1): 55%|█████▍ | 35/64 [01:34<01:19, 2.73s/batch] Reparam (cycle 1/8, epoch 1): 56%|█████▋ | 36/64 [01:37<01:16, 2.72s/batch] Reparam (cycle 1/8, epoch 1): 58%|█████▊ | 37/64 [01:40<01:13, 2.71s/batch] Reparam (cycle 1/8, epoch 1): 59%|█████▉ | 38/64 [01:42<01:10, 2.71s/batch] Reparam (cycle 1/8, epoch 1): 61%|██████ | 39/64 [01:45<01:07, 2.71s/batch][reparam] epoch=1 step=40 phase=joint loss=3.852619e-02 mse=2.089170e-02 mlp_mse=1.279375e-02 kl=1.512731e-02 lambda_mean=0.6240300536155701 lambda_std=0.0 lambda_abs0.5=0.12403005361557007 + Reparam (cycle 1/8, epoch 1): 62%|██████▎ | 40/64 [01:48<01:05, 2.75s/batch] Reparam (cycle 1/8, epoch 1): 64%|██████▍ | 41/64 [01:51<01:02, 2.73s/batch] Reparam (cycle 1/8, epoch 1): 66%|██████▌ | 42/64 [01:53<00:59, 2.72s/batch] Reparam (cycle 1/8, epoch 1): 67%|██████▋ | 43/64 [01:56<00:57, 2.72s/batch] Reparam (cycle 1/8, epoch 1): 69%|██████▉ | 44/64 [01:59<00:54, 2.71s/batch] Reparam (cycle 1/8, epoch 1): 70%|███████ | 45/64 [02:01<00:51, 2.71s/batch] Reparam (cycle 1/8, epoch 1): 72%|███████▏ | 46/64 [02:04<00:48, 2.70s/batch] Reparam (cycle 1/8, epoch 1): 73%|███████▎ | 47/64 [02:07<00:45, 2.70s/batch] Reparam (cycle 1/8, epoch 1): 75%|███████▌ | 48/64 [02:10<00:43, 2.70s/batch] Reparam (cycle 1/8, epoch 1): 77%|███████▋ | 49/64 [02:12<00:40, 2.70s/batch][reparam] epoch=1 step=50 phase=joint loss=3.784364e-02 mse=1.934929e-02 mlp_mse=1.188456e-02 kl=2.065559e-02 lambda_mean=0.6240300536155701 lambda_std=0.0 lambda_abs0.5=0.12403005361557007 + Reparam (cycle 1/8, epoch 1): 78%|███████▊ | 50/64 [02:15<00:38, 2.74s/batch] Reparam (cycle 1/8, epoch 1): 80%|███████▉ | 51/64 [02:18<00:35, 2.72s/batch] Reparam (cycle 1/8, epoch 1): 81%|████████▏ | 52/64 [02:20<00:32, 2.71s/batch] Reparam (cycle 1/8, epoch 1): 83%|████████▎ | 53/64 [02:23<00:29, 2.71s/batch] Reparam (cycle 1/8, epoch 1): 84%|████████▍ | 54/64 [02:26<00:27, 2.70s/batch] Reparam (cycle 1/8, epoch 1): 86%|████████▌ | 55/64 [02:29<00:24, 2.70s/batch] Reparam (cycle 1/8, epoch 1): 88%|████████▊ | 56/64 [02:31<00:21, 2.70s/batch] Reparam (cycle 1/8, epoch 1): 89%|████████▉ | 57/64 [02:34<00:18, 2.70s/batch] Reparam (cycle 1/8, epoch 1): 91%|█████████ | 58/64 [02:37<00:16, 2.70s/batch] Reparam (cycle 1/8, epoch 1): 92%|█████████▏| 59/64 [02:39<00:13, 2.70s/batch][reparam] epoch=1 step=60 phase=joint loss=4.205791e-02 mse=2.195370e-02 mlp_mse=1.367152e-02 kl=2.010213e-02 lambda_mean=0.6240300536155701 lambda_std=0.0 lambda_abs0.5=0.12403005361557007 + Reparam (cycle 1/8, epoch 1): 94%|█████████▍| 60/64 [02:42<00:10, 2.74s/batch] Reparam (cycle 1/8, epoch 1): 95%|█████████▌| 61/64 [02:45<00:08, 2.73s/batch] Reparam (cycle 1/8, epoch 1): 97%|█████████▋| 62/64 [02:48<00:05, 2.72s/batch] Reparam (cycle 1/8, epoch 1): 98%|█████████▊| 63/64 [02:50<00:02, 2.71s/batch] Reparam (cycle 1/8, epoch 1): 100%|██████████| 64/64 [02:53<00:00, 2.71s/batch] Reparam (cycle 1/8, epoch 1): 100%|██████████| 64/64 [02:53<00:00, 2.71s/batch] +[timing] Cycle 1 component wall-clock: +[timing] selection: 10.747s (5.70% of cycle) +[timing] rebase: 0.000s (0.00% of cycle) +[timing] fisher: 0.000s (0.00% of cycle) +[timing] fit: 176.811s (93.85% of cycle) +[timing] materialize_save_layer: 0.473s (0.25% of cycle) +[timing] metadata_write: 0.001s (0.00% of cycle) +[timing] teacher_snapshot: 0.217s (0.12% of cycle) +[timing] cycle_cleanup: 0.147s (0.08% of cycle) +[timing] cycle_total: 188.397s +[timing] tracked_components_total: 188.396s +[progressive] Cycle 2/8 +[fit-ablation] MKA geometry: 31 layers +[fit-ablation] selection {"cycle": 2, "pair_index": 18, "initializer": "mka", "lambda_left": 0.6243720763232038, "recipient_original_layer": 18, "recipient_side": "left", "removed_original_layer": 19, "entropies": [-0.6315610607587784, -0.627416009583068, -0.5861614941870391, -0.6016038763611488, -0.6130674217530055, -0.6121981385094227, -0.6033131501980972, -0.5924187613341422, -0.6069171484092294, -0.6132380808987886, -0.5909367743402253, -0.590407987771964, -0.5917503747664402, -0.5967832540390615, -0.6130424939063307, -0.5930475051215599, -0.6093573556090445, -0.5989470593654461, -0.5676289381777201, -0.5608694521216201, -0.5743625477527975, -0.5758816773281742, -0.5801409806126402, -0.5913668641359654, -0.6097472828545235, -0.6083570027802482, -0.6274904600708421, -0.6306152827921306, -0.6120070175682731, -0.6667256627105463, -0.6619341659869157], "pair_npib": 1.8411160089685985, "source_lineage": [[18], [19]], "geometry_samples": 100, "geometry_sequence_length": 512, "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", "selection_policy": "native_dynamic_adjacent_NPIB", "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", "removed_original_layers": [19], "active_original_layers": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31]} +[fuse] Head permutation disabled; merging with original head order. +[fit-ablation] Fisher bypassed: non-Fisher initializer +[reparam] fisher_prior_inputs fa_mean=None fb_mean=None active_ratio=None rel_contrast=None prior_mean=0.6243720763232038 prior_active_mean=None +[reparam] Cycle 2: training U + gates for pair 18-19 (epochs=1.0, skip_train=False, hidden_mse_w=1.0, attn_mse_w=0.0, mlp_mse_w=1.0, eta=0.0, gamma=0.0, attn_reg_scale=1.0, mlp_reg_scale=1.0, param_subset=mlp, fisher_init_subset=same, train_subset=mlp, lambda_init=fisher_prior). +[reparam] subset=mlp gates=3 (attn=0, mlp=3, other=0) train_subset=mlp (attn=0, mlp=3, other=0) elems=3 (~0.0 MiB), U_elems=176160768 (~672.0 MiB; +optimizer state) +[reparam] lambda_init mean=0.6243720054626465 std=0.0 min=0.6243720054626465 max=0.6243720054626465 mean_abs_from_0.5=0.12437200546264648 +[reparam] additive_u enabled: W = W_F + U_add, U_add initialized at zero + Reparam (cycle 2/8, epoch 1): 0%| | 0/64 [00:00= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2) +/opt/conda/lib/python3.11/site-packages/torch/nn/modules/linear.py:125: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return F.linear(input, self.weight, self.bias) +/opt/conda/lib/python3.11/site-packages/torch/autograd/graph.py:829: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass +[reparam] first_grad phase=joint step=1 gate_l2=0.000000e+00 gate_mean_abs=None gate_max_abs=0.000000e+00 u_l2=1.556976e-02 u_mean_abs=4.0223484834963787e-07 u_max_abs=2.388239e-03 rho_l2=0.000000e+00 +[reparam] epoch=1 step=1 phase=joint loss=3.559173e-02 mse=1.892366e-02 mlp_mse=1.033176e-02 kl=1.980096e-02 lambda_mean=0.6243720054626465 lambda_std=0.0 lambda_abs0.5=0.12437200546264648 + Reparam (cycle 2/8, epoch 1): 2%|▏ | 1/64 [00:03<03:30, 3.34s/batch] Reparam (cycle 2/8, epoch 1): 3%|▎ | 2/64 [00:05<02:59, 2.90s/batch] Reparam (cycle 2/8, epoch 1): 5%|▍ | 3/64 [00:08<02:48, 2.76s/batch] Reparam (cycle 2/8, epoch 1): 6%|▋ | 4/64 [00:11<02:41, 2.69s/batch] Reparam (cycle 2/8, epoch 1): 8%|▊ | 5/64 [00:13<02:36, 2.66s/batch] Reparam (cycle 2/8, epoch 1): 9%|▉ | 6/64 [00:16<02:32, 2.63s/batch] Reparam (cycle 2/8, epoch 1): 11%|█ | 7/64 [00:18<02:29, 2.62s/batch] Reparam (cycle 2/8, epoch 1): 12%|█▎ | 8/64 [00:21<02:26, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 14%|█▍ | 9/64 [00:24<02:23, 2.61s/batch][reparam] epoch=1 step=10 phase=joint loss=2.994476e-02 mse=1.507062e-02 mlp_mse=1.028300e-02 kl=1.434733e-02 lambda_mean=0.6243720054626465 lambda_std=0.0 lambda_abs0.5=0.12437200546264648 + Reparam (cycle 2/8, epoch 1): 16%|█▌ | 10/64 [00:26<02:23, 2.65s/batch] Reparam (cycle 2/8, epoch 1): 17%|█▋ | 11/64 [00:29<02:19, 2.63s/batch] Reparam (cycle 2/8, epoch 1): 19%|█▉ | 12/64 [00:32<02:16, 2.63s/batch] Reparam (cycle 2/8, epoch 1): 20%|██ | 13/64 [00:34<02:13, 2.62s/batch] Reparam (cycle 2/8, epoch 1): 22%|██▏ | 14/64 [00:37<02:10, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 23%|██▎ | 15/64 [00:39<02:07, 2.60s/batch] Reparam (cycle 2/8, epoch 1): 25%|██▌ | 16/64 [00:42<02:04, 2.60s/batch] Reparam (cycle 2/8, epoch 1): 27%|██▋ | 17/64 [00:45<02:02, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 28%|██▊ | 18/64 [00:47<01:59, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 30%|██▉ | 19/64 [00:50<01:57, 2.60s/batch][reparam] epoch=1 step=20 phase=joint loss=2.988833e-02 mse=1.448838e-02 mlp_mse=9.616310e-03 kl=1.807389e-02 lambda_mean=0.6243720054626465 lambda_std=0.0 lambda_abs0.5=0.12437200546264648 + Reparam (cycle 2/8, epoch 1): 31%|███▏ | 20/64 [00:52<01:56, 2.65s/batch] Reparam (cycle 2/8, epoch 1): 33%|███▎ | 21/64 [00:55<01:53, 2.63s/batch] Reparam (cycle 2/8, epoch 1): 34%|███▍ | 22/64 [00:58<01:50, 2.62s/batch] Reparam (cycle 2/8, epoch 1): 36%|███▌ | 23/64 [01:00<01:47, 2.62s/batch] Reparam (cycle 2/8, epoch 1): 38%|███▊ | 24/64 [01:03<01:44, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 39%|███▉ | 25/64 [01:05<01:41, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 41%|████ | 26/64 [01:08<01:38, 2.60s/batch] Reparam (cycle 2/8, epoch 1): 42%|████▏ | 27/64 [01:11<01:36, 2.60s/batch] Reparam (cycle 2/8, epoch 1): 44%|████▍ | 28/64 [01:13<01:33, 2.60s/batch] Reparam (cycle 2/8, epoch 1): 45%|████▌ | 29/64 [01:16<01:31, 2.60s/batch][reparam] epoch=1 step=30 phase=joint loss=3.174837e-02 mse=1.419403e-02 mlp_mse=9.467350e-03 kl=2.527183e-02 lambda_mean=0.6243720054626465 lambda_std=0.0 lambda_abs0.5=0.12437200546264648 + Reparam (cycle 2/8, epoch 1): 47%|████▋ | 30/64 [01:19<01:29, 2.64s/batch] Reparam (cycle 2/8, epoch 1): 48%|████▊ | 31/64 [01:21<01:26, 2.63s/batch] Reparam (cycle 2/8, epoch 1): 50%|█████ | 32/64 [01:24<01:23, 2.62s/batch] Reparam (cycle 2/8, epoch 1): 52%|█████▏ | 33/64 [01:26<01:21, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 53%|█████▎ | 34/64 [01:29<01:18, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 55%|█████▍ | 35/64 [01:32<01:15, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 56%|█████▋ | 36/64 [01:34<01:12, 2.60s/batch] Reparam (cycle 2/8, epoch 1): 58%|█████▊ | 37/64 [01:37<01:10, 2.60s/batch] Reparam (cycle 2/8, epoch 1): 59%|█████▉ | 38/64 [01:39<01:07, 2.60s/batch] Reparam (cycle 2/8, epoch 1): 61%|██████ | 39/64 [01:42<01:05, 2.60s/batch][reparam] epoch=1 step=40 phase=joint loss=2.712386e-02 mse=1.379031e-02 mlp_mse=9.673781e-03 kl=1.143678e-02 lambda_mean=0.6243720054626465 lambda_std=0.0 lambda_abs0.5=0.12437200546264648 + Reparam (cycle 2/8, epoch 1): 62%|██████▎ | 40/64 [01:45<01:03, 2.64s/batch] Reparam (cycle 2/8, epoch 1): 64%|██████▍ | 41/64 [01:47<01:00, 2.63s/batch] Reparam (cycle 2/8, epoch 1): 66%|██████▌ | 42/64 [01:50<00:57, 2.62s/batch] Reparam (cycle 2/8, epoch 1): 67%|██████▋ | 43/64 [01:53<00:54, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 69%|██████▉ | 44/64 [01:55<00:52, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 70%|███████ | 45/64 [01:58<00:49, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 72%|███████▏ | 46/64 [02:00<00:46, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 73%|███████▎ | 47/64 [02:03<00:44, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 75%|███████▌ | 48/64 [02:06<00:41, 2.60s/batch] Reparam (cycle 2/8, epoch 1): 77%|███████▋ | 49/64 [02:08<00:39, 2.60s/batch][reparam] epoch=1 step=50 phase=joint loss=2.915584e-02 mse=1.321197e-02 mlp_mse=9.275235e-03 kl=2.083950e-02 lambda_mean=0.6243720054626465 lambda_std=0.0 lambda_abs0.5=0.12437200546264648 + Reparam (cycle 2/8, epoch 1): 78%|███████▊ | 50/64 [02:11<00:36, 2.64s/batch] Reparam (cycle 2/8, epoch 1): 80%|███████▉ | 51/64 [02:13<00:34, 2.63s/batch] Reparam (cycle 2/8, epoch 1): 81%|████████▏ | 52/64 [02:16<00:31, 2.62s/batch] Reparam (cycle 2/8, epoch 1): 83%|████████▎ | 53/64 [02:19<00:28, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 84%|████████▍ | 54/64 [02:21<00:26, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 86%|████████▌ | 55/64 [02:24<00:23, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 88%|████████▊ | 56/64 [02:27<00:20, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 89%|████████▉ | 57/64 [02:29<00:18, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 91%|█████████ | 58/64 [02:32<00:15, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 92%|█████████▏| 59/64 [02:34<00:13, 2.60s/batch][reparam] epoch=1 step=60 phase=joint loss=2.817599e-02 mse=1.380061e-02 mlp_mse=9.811766e-03 kl=1.426130e-02 lambda_mean=0.6243720054626465 lambda_std=0.0 lambda_abs0.5=0.12437200546264648 + Reparam (cycle 2/8, epoch 1): 94%|█████████▍| 60/64 [02:37<00:10, 2.65s/batch] Reparam (cycle 2/8, epoch 1): 95%|█████████▌| 61/64 [02:40<00:07, 2.63s/batch] Reparam (cycle 2/8, epoch 1): 97%|█████████▋| 62/64 [02:42<00:05, 2.62s/batch] Reparam (cycle 2/8, epoch 1): 98%|█████████▊| 63/64 [02:45<00:02, 2.62s/batch] Reparam (cycle 2/8, epoch 1): 100%|██████████| 64/64 [02:47<00:00, 2.61s/batch] Reparam (cycle 2/8, epoch 1): 100%|██████████| 64/64 [02:47<00:00, 2.62s/batch] +[timing] Cycle 2 component wall-clock: +[timing] selection: 9.864s (5.50% of cycle) +[timing] rebase: 0.000s (0.00% of cycle) +[timing] fisher: 0.000s (0.00% of cycle) +[timing] fit: 168.418s (93.94% of cycle) +[timing] materialize_save_layer: 0.488s (0.27% of cycle) +[timing] metadata_write: 0.001s (0.00% of cycle) +[timing] teacher_snapshot: 0.367s (0.20% of cycle) +[timing] cycle_cleanup: 0.140s (0.08% of cycle) +[timing] cycle_total: 179.279s +[timing] tracked_components_total: 179.278s +[progressive] Cycle 3/8 +[fit-ablation] MKA geometry: 30 layers +[fit-ablation] selection {"cycle": 3, "pair_index": 21, "initializer": "mka", "lambda_left": 0.6243202778643895, "recipient_original_layer": 23, "recipient_side": "left", "removed_original_layer": 24, "entropies": [-0.6315610607587784, -0.627416009583068, -0.5861614941870391, -0.6016038763611488, -0.6130674217530055, -0.6121981385094227, -0.6033131501980972, -0.5924187613341422, -0.6069171484092294, -0.6132380808987886, -0.5909367743402253, -0.590407987771964, -0.5917503747664402, -0.5967832540390615, -0.6130424939063307, -0.5930475051215599, -0.6093573556090445, -0.5989470593654461, -0.5845659494901442, -0.6006742712305501, -0.5705183361386409, -0.5802214835165794, -0.5813144789491883, -0.5945462750297424, -0.6060665316489774, -0.6338224312205408, -0.6133413857874385, -0.6456504390068377, -0.6696087275441559, -0.6286190472747107], "pair_npib": 1.8433488761948427, "source_lineage": [[23], [24]], "geometry_samples": 100, "geometry_sequence_length": 512, "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", "selection_policy": "native_dynamic_adjacent_NPIB", "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", "removed_original_layers": [24], "active_original_layers": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 23, 25, 26, 27, 28, 29, 30, 31]} +[fuse] Head permutation disabled; merging with original head order. +[fit-ablation] Fisher bypassed: non-Fisher initializer +[reparam] fisher_prior_inputs fa_mean=None fb_mean=None active_ratio=None rel_contrast=None prior_mean=0.6243202778643895 prior_active_mean=None +[reparam] Cycle 3: training U + gates for pair 21-22 (epochs=1.0, skip_train=False, hidden_mse_w=1.0, attn_mse_w=0.0, mlp_mse_w=1.0, eta=0.0, gamma=0.0, attn_reg_scale=1.0, mlp_reg_scale=1.0, param_subset=mlp, fisher_init_subset=same, train_subset=mlp, lambda_init=fisher_prior). +[reparam] subset=mlp gates=3 (attn=0, mlp=3, other=0) train_subset=mlp (attn=0, mlp=3, other=0) elems=3 (~0.0 MiB), U_elems=176160768 (~672.0 MiB; +optimizer state) +[reparam] lambda_init mean=0.6243202686309814 std=0.0001216652134970651 min=0.6243202686309814 max=0.6243202686309814 mean_abs_from_0.5=0.12432026863098145 +[reparam] additive_u enabled: W = W_F + U_add, U_add initialized at zero + Reparam (cycle 3/8, epoch 1): 0%| | 0/64 [00:00= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2) +/opt/conda/lib/python3.11/site-packages/torch/nn/modules/linear.py:125: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return F.linear(input, self.weight, self.bias) +/opt/conda/lib/python3.11/site-packages/torch/autograd/graph.py:829: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass +[reparam] first_grad phase=joint step=1 gate_l2=0.000000e+00 gate_mean_abs=None gate_max_abs=0.000000e+00 u_l2=3.029337e-02 u_mean_abs=7.845224315263164e-07 u_max_abs=3.115654e-03 rho_l2=0.000000e+00 +[reparam] epoch=1 step=1 phase=joint loss=5.814354e-02 mse=3.497943e-02 mlp_mse=1.403110e-02 kl=2.854066e-02 lambda_mean=0.6243202686309814 lambda_std=0.0001216652134970651 lambda_abs0.5=0.12432026863098145 + Reparam (cycle 3/8, epoch 1): 2%|▏ | 1/64 [00:02<02:56, 2.80s/batch] Reparam (cycle 3/8, epoch 1): 3%|▎ | 2/64 [00:05<02:44, 2.66s/batch] Reparam (cycle 3/8, epoch 1): 5%|▍ | 3/64 [00:07<02:40, 2.63s/batch] Reparam (cycle 3/8, epoch 1): 6%|▋ | 4/64 [00:10<02:36, 2.60s/batch] Reparam (cycle 3/8, epoch 1): 8%|▊ | 5/64 [00:13<02:32, 2.59s/batch] Reparam (cycle 3/8, epoch 1): 9%|▉ | 6/64 [00:15<02:29, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 11%|█ | 7/64 [00:18<02:26, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 12%|█▎ | 8/64 [00:20<02:24, 2.57s/batch] Reparam (cycle 3/8, epoch 1): 14%|█▍ | 9/64 [00:23<02:21, 2.57s/batch][reparam] epoch=1 step=10 phase=joint loss=4.274534e-02 mse=2.261686e-02 mlp_mse=1.500342e-02 kl=1.601584e-02 lambda_mean=0.6243202686309814 lambda_std=0.0001216652134970651 lambda_abs0.5=0.12432026863098145 + Reparam (cycle 3/8, epoch 1): 16%|█▌ | 10/64 [00:26<02:21, 2.61s/batch] Reparam (cycle 3/8, epoch 1): 17%|█▋ | 11/64 [00:28<02:17, 2.60s/batch] Reparam (cycle 3/8, epoch 1): 19%|█▉ | 12/64 [00:31<02:14, 2.59s/batch] Reparam (cycle 3/8, epoch 1): 20%|██ | 13/64 [00:33<02:11, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 22%|██▏ | 14/64 [00:36<02:09, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 23%|██▎ | 15/64 [00:38<02:06, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 25%|██▌ | 16/64 [00:41<02:03, 2.57s/batch] Reparam (cycle 3/8, epoch 1): 27%|██▋ | 17/64 [00:44<02:01, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 28%|██▊ | 18/64 [00:46<01:59, 2.60s/batch] Reparam (cycle 3/8, epoch 1): 30%|██▉ | 19/64 [00:49<01:56, 2.60s/batch][reparam] epoch=1 step=20 phase=joint loss=4.294283e-02 mse=2.357874e-02 mlp_mse=1.345279e-02 kl=1.847279e-02 lambda_mean=0.6243202686309814 lambda_std=0.0001216652134970651 lambda_abs0.5=0.12432026863098145 + Reparam (cycle 3/8, epoch 1): 31%|███▏ | 20/64 [00:52<01:55, 2.63s/batch] Reparam (cycle 3/8, epoch 1): 33%|███▎ | 21/64 [00:54<01:52, 2.62s/batch] Reparam (cycle 3/8, epoch 1): 34%|███▍ | 22/64 [00:57<01:49, 2.60s/batch] Reparam (cycle 3/8, epoch 1): 36%|███▌ | 23/64 [00:59<01:46, 2.59s/batch] Reparam (cycle 3/8, epoch 1): 38%|███▊ | 24/64 [01:02<01:43, 2.59s/batch] Reparam (cycle 3/8, epoch 1): 39%|███▉ | 25/64 [01:04<01:40, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 41%|████ | 26/64 [01:07<01:38, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 42%|████▏ | 27/64 [01:10<01:35, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 44%|████▍ | 28/64 [01:12<01:32, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 45%|████▌ | 29/64 [01:15<01:30, 2.58s/batch][reparam] epoch=1 step=30 phase=joint loss=4.270542e-02 mse=2.339978e-02 mlp_mse=1.374218e-02 kl=1.738583e-02 lambda_mean=0.6243202686309814 lambda_std=0.0001216652134970651 lambda_abs0.5=0.12432026863098145 + Reparam (cycle 3/8, epoch 1): 47%|████▋ | 30/64 [01:17<01:28, 2.62s/batch] Reparam (cycle 3/8, epoch 1): 48%|████▊ | 31/64 [01:20<01:25, 2.60s/batch] Reparam (cycle 3/8, epoch 1): 50%|█████ | 32/64 [01:23<01:23, 2.60s/batch] Reparam (cycle 3/8, epoch 1): 52%|█████▏ | 33/64 [01:25<01:20, 2.59s/batch] Reparam (cycle 3/8, epoch 1): 53%|█████▎ | 34/64 [01:28<01:17, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 55%|█████▍ | 35/64 [01:30<01:14, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 56%|█████▋ | 36/64 [01:33<01:12, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 58%|█████▊ | 37/64 [01:35<01:09, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 59%|█████▉ | 38/64 [01:38<01:06, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 61%|██████ | 39/64 [01:41<01:04, 2.57s/batch][reparam] epoch=1 step=40 phase=joint loss=4.028462e-02 mse=2.083962e-02 mlp_mse=1.324400e-02 kl=1.937815e-02 lambda_mean=0.6243202686309814 lambda_std=0.0001216652134970651 lambda_abs0.5=0.12432026863098145 + Reparam (cycle 3/8, epoch 1): 62%|██████▎ | 40/64 [01:43<01:02, 2.61s/batch] Reparam (cycle 3/8, epoch 1): 64%|██████▍ | 41/64 [01:46<00:59, 2.60s/batch] Reparam (cycle 3/8, epoch 1): 66%|██████▌ | 42/64 [01:48<00:57, 2.60s/batch] Reparam (cycle 3/8, epoch 1): 67%|██████▋ | 43/64 [01:51<00:54, 2.59s/batch] Reparam (cycle 3/8, epoch 1): 69%|██████▉ | 44/64 [01:54<00:51, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 70%|███████ | 45/64 [01:56<00:49, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 72%|███████▏ | 46/64 [01:59<00:48, 2.69s/batch] Reparam (cycle 3/8, epoch 1): 73%|███████▎ | 47/64 [02:02<00:45, 2.65s/batch] Reparam (cycle 3/8, epoch 1): 75%|███████▌ | 48/64 [02:04<00:42, 2.63s/batch] Reparam (cycle 3/8, epoch 1): 77%|███████▋ | 49/64 [02:07<00:39, 2.61s/batch][reparam] epoch=1 step=50 phase=joint loss=3.896519e-02 mse=2.137364e-02 mlp_mse=1.296852e-02 kl=1.444696e-02 lambda_mean=0.6243202686309814 lambda_std=0.0001216652134970651 lambda_abs0.5=0.12432026863098145 + Reparam (cycle 3/8, epoch 1): 78%|███████▊ | 50/64 [02:10<00:36, 2.64s/batch] Reparam (cycle 3/8, epoch 1): 80%|███████▉ | 51/64 [02:12<00:34, 2.62s/batch] Reparam (cycle 3/8, epoch 1): 81%|████████▏ | 52/64 [02:15<00:31, 2.61s/batch] Reparam (cycle 3/8, epoch 1): 83%|████████▎ | 53/64 [02:17<00:28, 2.59s/batch] Reparam (cycle 3/8, epoch 1): 84%|████████▍ | 54/64 [02:20<00:25, 2.59s/batch] Reparam (cycle 3/8, epoch 1): 86%|████████▌ | 55/64 [02:22<00:23, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 88%|████████▊ | 56/64 [02:25<00:20, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 89%|████████▉ | 57/64 [02:28<00:18, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 91%|█████████ | 58/64 [02:30<00:15, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 92%|█████████▏| 59/64 [02:33<00:12, 2.57s/batch][reparam] epoch=1 step=60 phase=joint loss=4.030695e-02 mse=2.163081e-02 mlp_mse=1.346477e-02 kl=1.628554e-02 lambda_mean=0.6243202686309814 lambda_std=0.0001216652134970651 lambda_abs0.5=0.12432026863098145 + Reparam (cycle 3/8, epoch 1): 94%|█████████▍| 60/64 [02:35<00:10, 2.61s/batch] Reparam (cycle 3/8, epoch 1): 95%|█████████▌| 61/64 [02:38<00:07, 2.60s/batch] Reparam (cycle 3/8, epoch 1): 97%|█████████▋| 62/64 [02:40<00:05, 2.59s/batch] Reparam (cycle 3/8, epoch 1): 98%|█████████▊| 63/64 [02:43<00:02, 2.59s/batch] Reparam (cycle 3/8, epoch 1): 100%|██████████| 64/64 [02:46<00:00, 2.58s/batch] Reparam (cycle 3/8, epoch 1): 100%|██████████| 64/64 [02:46<00:00, 2.60s/batch] +[timing] Cycle 3 component wall-clock: +[timing] selection: 9.434s (5.33% of cycle) +[timing] rebase: 0.000s (0.00% of cycle) +[timing] fisher: 0.000s (0.00% of cycle) +[timing] fit: 166.534s (94.14% of cycle) +[timing] materialize_save_layer: 0.440s (0.25% of cycle) +[timing] metadata_write: 0.001s (0.00% of cycle) +[timing] teacher_snapshot: 0.357s (0.20% of cycle) +[timing] cycle_cleanup: 0.138s (0.08% of cycle) +[timing] cycle_total: 176.905s +[timing] tracked_components_total: 176.904s +[progressive] Cycle 4/8 +[fit-ablation] MKA geometry: 29 layers +[fit-ablation] selection {"cycle": 4, "pair_index": 24, "initializer": "mka", "lambda_left": 0.6214287991453509, "recipient_original_layer": 27, "recipient_side": "left", "removed_original_layer": 28, "entropies": [-0.6315610607587784, -0.627416009583068, -0.5861614941870391, -0.6016038763611488, -0.6130674217530055, -0.6121981385094227, -0.6033131501980972, -0.5924187613341422, -0.6069171484092294, -0.6132380808987886, -0.5909367743402253, -0.590407987771964, -0.5917503747664402, -0.5967832540390615, -0.6130424939063307, -0.5930475051215599, -0.6093573556090445, -0.5989470593654461, -0.5845659494901442, -0.6006742712305501, -0.5705183361386409, -0.566425003102157, -0.5875409475739463, -0.6165914355649426, -0.6481007302498619, -0.6388713218255503, -0.6641428062353042, -0.6250859027743988, -0.6166829740327132], "pair_npib": 1.79552158793285, "source_lineage": [[27], [28]], "geometry_samples": 100, "geometry_sequence_length": 512, "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", "selection_policy": "native_dynamic_adjacent_NPIB", "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", "removed_original_layers": [28], "active_original_layers": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 23, 25, 26, 27, 29, 30, 31]} +[fuse] Head permutation disabled; merging with original head order. +[fit-ablation] Fisher bypassed: non-Fisher initializer +[reparam] fisher_prior_inputs fa_mean=None fb_mean=None active_ratio=None rel_contrast=None prior_mean=0.6214287991453509 prior_active_mean=None +[reparam] Cycle 4: training U + gates for pair 24-25 (epochs=1.0, skip_train=False, hidden_mse_w=1.0, attn_mse_w=0.0, mlp_mse_w=1.0, eta=0.0, gamma=0.0, attn_reg_scale=1.0, mlp_reg_scale=1.0, param_subset=mlp, fisher_init_subset=same, train_subset=mlp, lambda_init=fisher_prior). +[reparam] subset=mlp gates=3 (attn=0, mlp=3, other=0) train_subset=mlp (attn=0, mlp=3, other=0) elems=3 (~0.0 MiB), U_elems=176160768 (~672.0 MiB; +optimizer state) +[reparam] lambda_init mean=0.6214288473129272 std=4.7565402832764544e-05 min=0.6214288473129272 max=0.6214288473129272 mean_abs_from_0.5=0.12142884731292725 +[reparam] additive_u enabled: W = W_F + U_add, U_add initialized at zero + Reparam (cycle 4/8, epoch 1): 0%| | 0/64 [00:00= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2) +/opt/conda/lib/python3.11/site-packages/torch/nn/modules/linear.py:125: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return F.linear(input, self.weight, self.bias) +/opt/conda/lib/python3.11/site-packages/torch/autograd/graph.py:829: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass +[reparam] first_grad phase=joint step=1 gate_l2=0.000000e+00 gate_mean_abs=None gate_max_abs=0.000000e+00 u_l2=6.622738e-02 u_mean_abs=1.1644387671237512e-06 u_max_abs=1.046371e-02 rho_l2=0.000000e+00 +[reparam] epoch=1 step=1 phase=joint loss=9.718529e-02 mse=6.288653e-02 mlp_mse=2.303299e-02 kl=3.520554e-02 lambda_mean=0.6214288473129272 lambda_std=4.7565402832764544e-05 lambda_abs0.5=0.12142884731292725 + Reparam (cycle 4/8, epoch 1): 2%|▏ | 1/64 [00:02<02:55, 2.78s/batch] Reparam (cycle 4/8, epoch 1): 3%|▎ | 2/64 [00:05<02:43, 2.64s/batch] Reparam (cycle 4/8, epoch 1): 5%|▍ | 3/64 [00:07<02:38, 2.59s/batch] Reparam (cycle 4/8, epoch 1): 6%|▋ | 4/64 [00:10<02:34, 2.57s/batch] Reparam (cycle 4/8, epoch 1): 8%|▊ | 5/64 [00:12<02:30, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 9%|▉ | 6/64 [00:15<02:28, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 11%|█ | 7/64 [00:18<02:25, 2.55s/batch] Reparam (cycle 4/8, epoch 1): 12%|█▎ | 8/64 [00:20<02:22, 2.55s/batch] Reparam (cycle 4/8, epoch 1): 14%|█▍ | 9/64 [00:23<02:20, 2.55s/batch][reparam] epoch=1 step=10 phase=joint loss=7.192578e-02 mse=3.925940e-02 mlp_mse=2.779630e-02 kl=1.521898e-02 lambda_mean=0.6214288473129272 lambda_std=4.7565402832764544e-05 lambda_abs0.5=0.12142884731292725 + Reparam (cycle 4/8, epoch 1): 16%|█▌ | 10/64 [00:25<02:21, 2.62s/batch] Reparam (cycle 4/8, epoch 1): 17%|█▋ | 11/64 [00:28<02:17, 2.60s/batch] Reparam (cycle 4/8, epoch 1): 19%|█▉ | 12/64 [00:30<02:14, 2.58s/batch] Reparam (cycle 4/8, epoch 1): 20%|██ | 13/64 [00:33<02:11, 2.57s/batch] Reparam (cycle 4/8, epoch 1): 22%|██▏ | 14/64 [00:36<02:08, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 23%|██▎ | 15/64 [00:38<02:05, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 25%|██▌ | 16/64 [00:41<02:02, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 27%|██▋ | 17/64 [00:43<02:00, 2.55s/batch] Reparam (cycle 4/8, epoch 1): 28%|██▊ | 18/64 [00:46<01:57, 2.55s/batch] Reparam (cycle 4/8, epoch 1): 30%|██▉ | 19/64 [00:48<01:54, 2.55s/batch][reparam] epoch=1 step=20 phase=joint loss=6.712705e-02 mse=3.776370e-02 mlp_mse=2.424238e-02 kl=1.600304e-02 lambda_mean=0.6214288473129272 lambda_std=4.7565402832764544e-05 lambda_abs0.5=0.12142884731292725 + Reparam (cycle 4/8, epoch 1): 31%|███▏ | 20/64 [00:51<01:54, 2.61s/batch] Reparam (cycle 4/8, epoch 1): 33%|███▎ | 21/64 [00:54<01:51, 2.59s/batch] Reparam (cycle 4/8, epoch 1): 34%|███▍ | 22/64 [00:56<01:48, 2.57s/batch] Reparam (cycle 4/8, epoch 1): 36%|███▌ | 23/64 [00:59<01:45, 2.57s/batch] Reparam (cycle 4/8, epoch 1): 38%|███▊ | 24/64 [01:01<01:42, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 39%|███▉ | 25/64 [01:04<01:39, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 41%|████ | 26/64 [01:06<01:37, 2.55s/batch] Reparam (cycle 4/8, epoch 1): 42%|████▏ | 27/64 [01:09<01:34, 2.55s/batch] Reparam (cycle 4/8, epoch 1): 44%|████▍ | 28/64 [01:11<01:31, 2.55s/batch] Reparam (cycle 4/8, epoch 1): 45%|████▌ | 29/64 [01:14<01:29, 2.55s/batch][reparam] epoch=1 step=30 phase=joint loss=6.518345e-02 mse=3.690217e-02 mlp_mse=2.381637e-02 kl=1.395284e-02 lambda_mean=0.6214288473129272 lambda_std=4.7565402832764544e-05 lambda_abs0.5=0.12142884731292725 + Reparam (cycle 4/8, epoch 1): 47%|████▋ | 30/64 [01:17<01:28, 2.59s/batch] Reparam (cycle 4/8, epoch 1): 48%|████▊ | 31/64 [01:19<01:25, 2.58s/batch] Reparam (cycle 4/8, epoch 1): 50%|█████ | 32/64 [01:22<01:22, 2.57s/batch] Reparam (cycle 4/8, epoch 1): 52%|█████▏ | 33/64 [01:24<01:19, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 53%|█████▎ | 34/64 [01:27<01:16, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 55%|█████▍ | 35/64 [01:29<01:14, 2.57s/batch] Reparam (cycle 4/8, epoch 1): 56%|█████▋ | 36/64 [01:32<01:11, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 58%|█████▊ | 37/64 [01:35<01:09, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 59%|█████▉ | 38/64 [01:37<01:06, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 61%|██████ | 39/64 [01:40<01:03, 2.55s/batch][reparam] epoch=1 step=40 phase=joint loss=6.529596e-02 mse=3.625731e-02 mlp_mse=2.524313e-02 kl=1.186102e-02 lambda_mean=0.6214288473129272 lambda_std=4.7565402832764544e-05 lambda_abs0.5=0.12142884731292725 + Reparam (cycle 4/8, epoch 1): 62%|██████▎ | 40/64 [01:42<01:02, 2.61s/batch] Reparam (cycle 4/8, epoch 1): 64%|██████▍ | 41/64 [01:45<00:59, 2.59s/batch] Reparam (cycle 4/8, epoch 1): 66%|██████▌ | 42/64 [01:48<00:56, 2.58s/batch] Reparam (cycle 4/8, epoch 1): 67%|██████▋ | 43/64 [01:50<00:53, 2.57s/batch] Reparam (cycle 4/8, epoch 1): 69%|██████▉ | 44/64 [01:53<00:51, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 70%|███████ | 45/64 [01:55<00:48, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 72%|███████▏ | 46/64 [01:58<00:46, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 73%|███████▎ | 47/64 [02:00<00:43, 2.55s/batch] Reparam (cycle 4/8, epoch 1): 75%|███████▌ | 48/64 [02:03<00:40, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 77%|███████▋ | 49/64 [02:05<00:38, 2.55s/batch][reparam] epoch=1 step=50 phase=joint loss=6.012936e-02 mse=3.362731e-02 mlp_mse=2.234545e-02 kl=1.298940e-02 lambda_mean=0.6214288473129272 lambda_std=4.7565402832764544e-05 lambda_abs0.5=0.12142884731292725 + Reparam (cycle 4/8, epoch 1): 78%|███████▊ | 50/64 [02:08<00:36, 2.60s/batch] Reparam (cycle 4/8, epoch 1): 80%|███████▉ | 51/64 [02:11<00:33, 2.58s/batch] Reparam (cycle 4/8, epoch 1): 81%|████████▏ | 52/64 [02:13<00:30, 2.57s/batch] Reparam (cycle 4/8, epoch 1): 83%|████████▎ | 53/64 [02:16<00:28, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 84%|████████▍ | 54/64 [02:18<00:25, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 86%|████████▌ | 55/64 [02:21<00:23, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 88%|████████▊ | 56/64 [02:23<00:20, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 89%|████████▉ | 57/64 [02:26<00:17, 2.55s/batch] Reparam (cycle 4/8, epoch 1): 91%|█████████ | 58/64 [02:28<00:15, 2.55s/batch] Reparam (cycle 4/8, epoch 1): 92%|█████████▏| 59/64 [02:31<00:12, 2.55s/batch][reparam] epoch=1 step=60 phase=joint loss=7.559325e-02 mse=3.835394e-02 mlp_mse=2.608557e-02 kl=3.485539e-02 lambda_mean=0.6214288473129272 lambda_std=4.7565402832764544e-05 lambda_abs0.5=0.12142884731292725 + Reparam (cycle 4/8, epoch 1): 94%|█████████▍| 60/64 [02:34<00:10, 2.59s/batch] Reparam (cycle 4/8, epoch 1): 95%|█████████▌| 61/64 [02:36<00:07, 2.58s/batch] Reparam (cycle 4/8, epoch 1): 97%|█████████▋| 62/64 [02:39<00:05, 2.57s/batch] Reparam (cycle 4/8, epoch 1): 98%|█████████▊| 63/64 [02:41<00:02, 2.57s/batch] Reparam (cycle 4/8, epoch 1): 100%|██████████| 64/64 [02:44<00:00, 2.56s/batch] Reparam (cycle 4/8, epoch 1): 100%|██████████| 64/64 [02:44<00:00, 2.57s/batch] +[timing] Cycle 4 component wall-clock: +[timing] selection: 8.977s (5.14% of cycle) +[timing] rebase: 0.000s (0.00% of cycle) +[timing] fisher: 0.000s (0.00% of cycle) +[timing] fit: 164.832s (94.31% of cycle) +[timing] materialize_save_layer: 0.494s (0.28% of cycle) +[timing] metadata_write: 0.001s (0.00% of cycle) +[timing] teacher_snapshot: 0.330s (0.19% of cycle) +[timing] cycle_cleanup: 0.149s (0.08% of cycle) +[timing] cycle_total: 174.784s +[timing] tracked_components_total: 174.783s +[progressive] Cycle 5/8 +[fit-ablation] MKA geometry: 28 layers +[fit-ablation] selection {"cycle": 5, "pair_index": 21, "initializer": "mka", "lambda_left": 0.6221970199569331, "recipient_original_layer": 23, "recipient_side": "left", "removed_original_layer": 25, "entropies": [-0.6315610607587784, -0.627416009583068, -0.5861614941870391, -0.6016038763611488, -0.6130674217530055, -0.6121981385094227, -0.6033131501980972, -0.5924187613341422, -0.6069171484092294, -0.6132380808987886, -0.5909367743402253, -0.590407987771964, -0.5917503747664402, -0.5967832540390615, -0.6130424939063307, -0.5930475051215599, -0.6093573556090445, -0.5989470593654461, -0.5845659494901442, -0.6006742712305501, -0.5705183361386409, -0.566425003102157, -0.5875409475739463, -0.6165914355649426, -0.6507573345616348, -0.6501803103780216, -0.6403402608026175, -0.5992278924805038], "pair_npib": 1.7846382378202132, "source_lineage": [[23, 24], [25]], "geometry_samples": 100, "geometry_sequence_length": 512, "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", "selection_policy": "native_dynamic_adjacent_NPIB", "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", "removed_original_layers": [25], "active_original_layers": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 23, 26, 27, 29, 30, 31]} +[fuse] Head permutation disabled; merging with original head order. +[fit-ablation] Fisher bypassed: non-Fisher initializer +[reparam] fisher_prior_inputs fa_mean=None fb_mean=None active_ratio=None rel_contrast=None prior_mean=0.6221970199569331 prior_active_mean=None +[reparam] Cycle 5: training U + gates for pair 21-22 (epochs=1.0, skip_train=False, hidden_mse_w=1.0, attn_mse_w=0.0, mlp_mse_w=1.0, eta=0.0, gamma=0.0, attn_reg_scale=1.0, mlp_reg_scale=1.0, param_subset=mlp, fisher_init_subset=same, train_subset=mlp, lambda_init=fisher_prior). +[reparam] subset=mlp gates=3 (attn=0, mlp=3, other=0) train_subset=mlp (attn=0, mlp=3, other=0) elems=3 (~0.0 MiB), U_elems=176160768 (~672.0 MiB; +optimizer state) +[reparam] lambda_init mean=0.6221969723701477 std=0.0 min=0.6221969723701477 max=0.6221969723701477 mean_abs_from_0.5=0.1221969723701477 +[reparam] additive_u enabled: W = W_F + U_add, U_add initialized at zero + Reparam (cycle 5/8, epoch 1): 0%| | 0/64 [00:00= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2) +/opt/conda/lib/python3.11/site-packages/torch/nn/modules/linear.py:125: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return F.linear(input, self.weight, self.bias) +/opt/conda/lib/python3.11/site-packages/torch/autograd/graph.py:829: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass +[reparam] first_grad phase=joint step=1 gate_l2=0.000000e+00 gate_mean_abs=None gate_max_abs=0.000000e+00 u_l2=1.724474e-02 u_mean_abs=5.998026067356391e-07 u_max_abs=1.410484e-03 rho_l2=0.000000e+00 +[reparam] epoch=1 step=1 phase=joint loss=4.686308e-02 mse=2.670278e-02 mlp_mse=1.294601e-02 kl=2.254465e-02 lambda_mean=0.6221969723701477 lambda_std=0.0 lambda_abs0.5=0.1221969723701477 + Reparam (cycle 5/8, epoch 1): 2%|▏ | 1/64 [00:02<02:47, 2.67s/batch] Reparam (cycle 5/8, epoch 1): 3%|▎ | 2/64 [00:05<02:37, 2.53s/batch] Reparam (cycle 5/8, epoch 1): 5%|▍ | 3/64 [00:07<02:31, 2.49s/batch] Reparam (cycle 5/8, epoch 1): 6%|▋ | 4/64 [00:09<02:28, 2.47s/batch] Reparam (cycle 5/8, epoch 1): 8%|▊ | 5/64 [00:12<02:25, 2.47s/batch] Reparam (cycle 5/8, epoch 1): 9%|▉ | 6/64 [00:14<02:22, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 11%|█ | 7/64 [00:17<02:20, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 12%|█▎ | 8/64 [00:19<02:17, 2.45s/batch] Reparam (cycle 5/8, epoch 1): 14%|█▍ | 9/64 [00:22<02:14, 2.45s/batch][reparam] epoch=1 step=10 phase=joint loss=3.710741e-02 mse=1.878885e-02 mlp_mse=1.370071e-02 kl=1.443077e-02 lambda_mean=0.6221969723701477 lambda_std=0.0 lambda_abs0.5=0.1221969723701477 + Reparam (cycle 5/8, epoch 1): 16%|█▌ | 10/64 [00:24<02:14, 2.50s/batch] Reparam (cycle 5/8, epoch 1): 17%|█▋ | 11/64 [00:27<02:11, 2.48s/batch] Reparam (cycle 5/8, epoch 1): 19%|█▉ | 12/64 [00:29<02:08, 2.47s/batch] Reparam (cycle 5/8, epoch 1): 20%|██ | 13/64 [00:32<02:05, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 22%|██▏ | 14/64 [00:34<02:02, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 23%|██▎ | 15/64 [00:37<02:00, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 25%|██▌ | 16/64 [00:39<01:57, 2.45s/batch] Reparam (cycle 5/8, epoch 1): 27%|██▋ | 17/64 [00:41<01:55, 2.45s/batch] Reparam (cycle 5/8, epoch 1): 28%|██▊ | 18/64 [00:44<01:53, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 30%|██▉ | 19/64 [00:46<01:50, 2.45s/batch][reparam] epoch=1 step=20 phase=joint loss=3.346872e-02 mse=1.669140e-02 mlp_mse=1.275896e-02 kl=1.255741e-02 lambda_mean=0.6221969723701477 lambda_std=0.0 lambda_abs0.5=0.1221969723701477 + Reparam (cycle 5/8, epoch 1): 31%|███▏ | 20/64 [00:49<01:49, 2.50s/batch] Reparam (cycle 5/8, epoch 1): 33%|███▎ | 21/64 [00:51<01:46, 2.48s/batch] Reparam (cycle 5/8, epoch 1): 34%|███▍ | 22/64 [00:54<01:43, 2.47s/batch] Reparam (cycle 5/8, epoch 1): 36%|███▌ | 23/64 [00:56<01:41, 2.47s/batch] Reparam (cycle 5/8, epoch 1): 38%|███▊ | 24/64 [00:59<01:38, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 39%|███▉ | 25/64 [01:01<01:35, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 41%|████ | 26/64 [01:04<01:33, 2.45s/batch] Reparam (cycle 5/8, epoch 1): 42%|████▏ | 27/64 [01:06<01:30, 2.45s/batch] Reparam (cycle 5/8, epoch 1): 44%|████▍ | 28/64 [01:09<01:28, 2.45s/batch] Reparam (cycle 5/8, epoch 1): 45%|████▌ | 29/64 [01:11<01:25, 2.45s/batch][reparam] epoch=1 step=30 phase=joint loss=3.472550e-02 mse=1.760061e-02 mlp_mse=1.284318e-02 kl=1.338034e-02 lambda_mean=0.6221969723701477 lambda_std=0.0 lambda_abs0.5=0.1221969723701477 + Reparam (cycle 5/8, epoch 1): 47%|████▋ | 30/64 [01:14<01:24, 2.50s/batch] Reparam (cycle 5/8, epoch 1): 48%|████▊ | 31/64 [01:16<01:21, 2.48s/batch] Reparam (cycle 5/8, epoch 1): 50%|█████ | 32/64 [01:19<01:19, 2.47s/batch] Reparam (cycle 5/8, epoch 1): 52%|█████▏ | 33/64 [01:21<01:16, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 53%|█████▎ | 34/64 [01:23<01:13, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 55%|█████▍ | 35/64 [01:26<01:11, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 56%|█████▋ | 36/64 [01:28<01:08, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 58%|█████▊ | 37/64 [01:31<01:06, 2.45s/batch] Reparam (cycle 5/8, epoch 1): 59%|█████▉ | 38/64 [01:33<01:03, 2.45s/batch] Reparam (cycle 5/8, epoch 1): 61%|██████ | 39/64 [01:36<01:01, 2.45s/batch][reparam] epoch=1 step=40 phase=joint loss=3.047964e-02 mse=1.550421e-02 mlp_mse=1.169740e-02 kl=1.024385e-02 lambda_mean=0.6221969723701477 lambda_std=0.0 lambda_abs0.5=0.1221969723701477 + Reparam (cycle 5/8, epoch 1): 62%|██████▎ | 40/64 [01:38<00:59, 2.49s/batch] Reparam (cycle 5/8, epoch 1): 64%|██████▍ | 41/64 [01:41<00:57, 2.48s/batch] Reparam (cycle 5/8, epoch 1): 66%|██████▌ | 42/64 [01:43<00:54, 2.47s/batch] Reparam (cycle 5/8, epoch 1): 67%|██████▋ | 43/64 [01:46<00:51, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 69%|██████▉ | 44/64 [01:48<00:49, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 70%|███████ | 45/64 [01:50<00:46, 2.45s/batch] Reparam (cycle 5/8, epoch 1): 72%|███████▏ | 46/64 [01:53<00:44, 2.45s/batch] Reparam (cycle 5/8, epoch 1): 73%|███████▎ | 47/64 [01:55<00:41, 2.45s/batch] Reparam (cycle 5/8, epoch 1): 75%|███████▌ | 48/64 [01:58<00:39, 2.45s/batch] Reparam (cycle 5/8, epoch 1): 77%|███████▋ | 49/64 [02:00<00:36, 2.45s/batch][reparam] epoch=1 step=50 phase=joint loss=3.450762e-02 mse=1.691662e-02 mlp_mse=1.295301e-02 kl=1.449372e-02 lambda_mean=0.6221969723701477 lambda_std=0.0 lambda_abs0.5=0.1221969723701477 + Reparam (cycle 5/8, epoch 1): 78%|███████▊ | 50/64 [02:03<00:34, 2.50s/batch] Reparam (cycle 5/8, epoch 1): 80%|███████▉ | 51/64 [02:05<00:32, 2.49s/batch] Reparam (cycle 5/8, epoch 1): 81%|████████▏ | 52/64 [02:08<00:29, 2.48s/batch] Reparam (cycle 5/8, epoch 1): 83%|████████▎ | 53/64 [02:10<00:27, 2.47s/batch] Reparam (cycle 5/8, epoch 1): 84%|████████▍ | 54/64 [02:13<00:24, 2.47s/batch] Reparam (cycle 5/8, epoch 1): 86%|████████▌ | 55/64 [02:15<00:22, 2.47s/batch] Reparam (cycle 5/8, epoch 1): 88%|████████▊ | 56/64 [02:18<00:19, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 89%|████████▉ | 57/64 [02:20<00:17, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 91%|█████████ | 58/64 [02:23<00:14, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 92%|█████████▏| 59/64 [02:25<00:12, 2.46s/batch][reparam] epoch=1 step=60 phase=joint loss=3.022534e-02 mse=1.557726e-02 mlp_mse=1.175153e-02 kl=9.051709e-03 lambda_mean=0.6221969723701477 lambda_std=0.0 lambda_abs0.5=0.1221969723701477 + Reparam (cycle 5/8, epoch 1): 94%|█████████▍| 60/64 [02:28<00:10, 2.50s/batch] Reparam (cycle 5/8, epoch 1): 95%|█████████▌| 61/64 [02:30<00:07, 2.48s/batch] Reparam (cycle 5/8, epoch 1): 97%|█████████▋| 62/64 [02:32<00:04, 2.47s/batch] Reparam (cycle 5/8, epoch 1): 98%|█████████▊| 63/64 [02:35<00:02, 2.47s/batch] Reparam (cycle 5/8, epoch 1): 100%|██████████| 64/64 [02:37<00:00, 2.46s/batch] Reparam (cycle 5/8, epoch 1): 100%|██████████| 64/64 [02:37<00:00, 2.47s/batch] +[timing] Cycle 5 component wall-clock: +[timing] selection: 8.613s (5.13% of cycle) +[timing] rebase: 0.000s (0.00% of cycle) +[timing] fisher: 0.000s (0.00% of cycle) +[timing] fit: 158.336s (94.28% of cycle) +[timing] materialize_save_layer: 0.496s (0.30% of cycle) +[timing] metadata_write: 0.001s (0.00% of cycle) +[timing] teacher_snapshot: 0.358s (0.21% of cycle) +[timing] cycle_cleanup: 0.145s (0.09% of cycle) +[timing] cycle_total: 167.950s +[timing] tracked_components_total: 167.949s +[progressive] Cycle 6/8 +[fit-ablation] MKA geometry: 27 layers +[fit-ablation] selection {"cycle": 6, "pair_index": 10, "initializer": "mka", "lambda_left": 0.6211211480841742, "recipient_original_layer": 10, "recipient_side": "left", "removed_original_layer": 11, "entropies": [-0.6315610607587784, -0.627416009583068, -0.5861614941870391, -0.6016038763611488, -0.6130674217530055, -0.6121981385094227, -0.6033131501980972, -0.5924187613341422, -0.6069171484092294, -0.6132380808987886, -0.5909367743402253, -0.590407987771964, -0.5917503747664402, -0.5967832540390615, -0.6130424939063307, -0.5930475051215599, -0.6093573556090445, -0.5989470593654461, -0.5845659494901442, -0.6006742712305501, -0.5705183361386409, -0.5843026773437968, -0.6082050236179576, -0.6400439647853179, -0.6563589513748683, -0.621065842292377, -0.6347100964603006], "pair_npib": 1.6929237795968073, "source_lineage": [[10], [11]], "geometry_samples": 100, "geometry_sequence_length": 512, "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", "selection_policy": "native_dynamic_adjacent_NPIB", "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", "removed_original_layers": [11], "active_original_layers": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 20, 21, 23, 26, 27, 29, 30, 31]} +[fuse] Head permutation disabled; merging with original head order. +[fit-ablation] Fisher bypassed: non-Fisher initializer +[reparam] fisher_prior_inputs fa_mean=None fb_mean=None active_ratio=None rel_contrast=None prior_mean=0.6211211480841742 prior_active_mean=None +[reparam] Cycle 6: training U + gates for pair 10-11 (epochs=1.0, skip_train=False, hidden_mse_w=1.0, attn_mse_w=0.0, mlp_mse_w=1.0, eta=0.0, gamma=0.0, attn_reg_scale=1.0, mlp_reg_scale=1.0, param_subset=mlp, fisher_init_subset=same, train_subset=mlp, lambda_init=fisher_prior). +[reparam] subset=mlp gates=3 (attn=0, mlp=3, other=0) train_subset=mlp (attn=0, mlp=3, other=0) elems=3 (~0.0 MiB), U_elems=176160768 (~672.0 MiB; +optimizer state) +[reparam] lambda_init mean=0.6211211681365967 std=6.954265765167942e-05 min=0.6211211681365967 max=0.6211211681365967 mean_abs_from_0.5=0.12112116813659668 +[reparam] additive_u enabled: W = W_F + U_add, U_add initialized at zero + Reparam (cycle 6/8, epoch 1): 0%| | 0/64 [00:00= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2) +/opt/conda/lib/python3.11/site-packages/torch/nn/modules/linear.py:125: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return F.linear(input, self.weight, self.bias) +/opt/conda/lib/python3.11/site-packages/torch/autograd/graph.py:829: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass +[reparam] first_grad phase=joint step=1 gate_l2=0.000000e+00 gate_mean_abs=None gate_max_abs=0.000000e+00 u_l2=1.532551e-02 u_mean_abs=5.175094256195561e-07 u_max_abs=3.411174e-04 rho_l2=0.000000e+00 +[reparam] epoch=1 step=1 phase=joint loss=1.210001e-02 mse=5.238143e-03 mlp_mse=4.050871e-03 kl=8.784349e-03 lambda_mean=0.6211211681365967 lambda_std=6.954265765167942e-05 lambda_abs0.5=0.12112116813659668 + Reparam (cycle 6/8, epoch 1): 2%|▏ | 1/64 [00:02<03:05, 2.94s/batch] Reparam (cycle 6/8, epoch 1): 3%|▎ | 2/64 [00:05<02:36, 2.53s/batch] Reparam (cycle 6/8, epoch 1): 5%|▍ | 3/64 [00:07<02:26, 2.40s/batch] Reparam (cycle 6/8, epoch 1): 6%|▋ | 4/64 [00:09<02:20, 2.35s/batch] Reparam (cycle 6/8, epoch 1): 8%|▊ | 5/64 [00:11<02:16, 2.31s/batch] Reparam (cycle 6/8, epoch 1): 9%|▉ | 6/64 [00:14<02:12, 2.29s/batch] Reparam (cycle 6/8, epoch 1): 11%|█ | 7/64 [00:16<02:09, 2.28s/batch] Reparam (cycle 6/8, epoch 1): 12%|█▎ | 8/64 [00:18<02:07, 2.27s/batch] Reparam (cycle 6/8, epoch 1): 14%|█▍ | 9/64 [00:20<02:04, 2.26s/batch][reparam] epoch=1 step=10 phase=joint loss=1.033009e-02 mse=4.902764e-03 mlp_mse=3.858429e-03 kl=4.902809e-03 lambda_mean=0.6211211681365967 lambda_std=6.954265765167942e-05 lambda_abs0.5=0.12112116813659668 + Reparam (cycle 6/8, epoch 1): 16%|█▌ | 10/64 [00:23<02:04, 2.30s/batch] Reparam (cycle 6/8, epoch 1): 17%|█▋ | 11/64 [00:25<02:01, 2.29s/batch] Reparam (cycle 6/8, epoch 1): 19%|█▉ | 12/64 [00:27<01:58, 2.28s/batch] Reparam (cycle 6/8, epoch 1): 20%|██ | 13/64 [00:30<01:55, 2.27s/batch] Reparam (cycle 6/8, epoch 1): 22%|██▏ | 14/64 [00:32<01:53, 2.26s/batch] Reparam (cycle 6/8, epoch 1): 23%|██▎ | 15/64 [00:34<01:50, 2.26s/batch] Reparam (cycle 6/8, epoch 1): 25%|██▌ | 16/64 [00:36<01:48, 2.26s/batch] Reparam (cycle 6/8, epoch 1): 27%|██▋ | 17/64 [00:39<01:46, 2.26s/batch] Reparam (cycle 6/8, epoch 1): 28%|██▊ | 18/64 [00:41<01:43, 2.26s/batch] Reparam (cycle 6/8, epoch 1): 30%|██▉ | 19/64 [00:43<01:41, 2.26s/batch][reparam] epoch=1 step=20 phase=joint loss=1.024509e-02 mse=4.731753e-03 mlp_mse=3.783118e-03 kl=5.406932e-03 lambda_mean=0.6211211681365967 lambda_std=6.954265765167942e-05 lambda_abs0.5=0.12112116813659668 + Reparam (cycle 6/8, epoch 1): 31%|███▏ | 20/64 [00:46<01:41, 2.30s/batch] Reparam (cycle 6/8, epoch 1): 33%|███▎ | 21/64 [00:48<01:38, 2.29s/batch] Reparam (cycle 6/8, epoch 1): 34%|███▍ | 22/64 [00:50<01:35, 2.28s/batch] Reparam (cycle 6/8, epoch 1): 36%|███▌ | 23/64 [00:52<01:32, 2.27s/batch] Reparam (cycle 6/8, epoch 1): 38%|███▊ | 24/64 [00:55<01:30, 2.26s/batch] Reparam (cycle 6/8, epoch 1): 39%|███▉ | 25/64 [00:57<01:28, 2.26s/batch] Reparam (cycle 6/8, epoch 1): 41%|████ | 26/64 [00:59<01:26, 2.27s/batch] Reparam (cycle 6/8, epoch 1): 42%|████▏ | 27/64 [01:01<01:24, 2.27s/batch] Reparam (cycle 6/8, epoch 1): 44%|████▍ | 28/64 [01:04<01:21, 2.27s/batch] Reparam (cycle 6/8, epoch 1): 45%|████▌ | 29/64 [01:06<01:19, 2.28s/batch][reparam] epoch=1 step=30 phase=joint loss=1.041611e-02 mse=4.640253e-03 mlp_mse=3.716339e-03 kl=6.435983e-03 lambda_mean=0.6211211681365967 lambda_std=6.954265765167942e-05 lambda_abs0.5=0.12112116813659668 + Reparam (cycle 6/8, epoch 1): 47%|████▋ | 30/64 [01:08<01:20, 2.36s/batch] Reparam (cycle 6/8, epoch 1): 48%|████▊ | 31/64 [01:11<01:16, 2.33s/batch] Reparam (cycle 6/8, epoch 1): 50%|█████ | 32/64 [01:13<01:15, 2.35s/batch] Reparam (cycle 6/8, epoch 1): 52%|█████▏ | 33/64 [01:15<01:11, 2.32s/batch] Reparam (cycle 6/8, epoch 1): 53%|█████▎ | 34/64 [01:18<01:09, 2.30s/batch] Reparam (cycle 6/8, epoch 1): 55%|█████▍ | 35/64 [01:20<01:06, 2.30s/batch] Reparam (cycle 6/8, epoch 1): 56%|█████▋ | 36/64 [01:22<01:04, 2.29s/batch] Reparam (cycle 6/8, epoch 1): 58%|█████▊ | 37/64 [01:24<01:01, 2.29s/batch] Reparam (cycle 6/8, epoch 1): 59%|█████▉ | 38/64 [01:27<00:59, 2.28s/batch] Reparam (cycle 6/8, epoch 1): 61%|██████ | 39/64 [01:29<00:57, 2.30s/batch][reparam] epoch=1 step=40 phase=joint loss=1.034515e-02 mse=4.681095e-03 mlp_mse=3.697897e-03 kl=6.144259e-03 lambda_mean=0.6211211681365967 lambda_std=6.954265765167942e-05 lambda_abs0.5=0.12112116813659668 + Reparam (cycle 6/8, epoch 1): 62%|██████▎ | 40/64 [01:32<00:56, 2.37s/batch] Reparam (cycle 6/8, epoch 1): 64%|██████▍ | 41/64 [01:34<00:53, 2.34s/batch] Reparam (cycle 6/8, epoch 1): 66%|██████▌ | 42/64 [01:36<00:50, 2.31s/batch] Reparam (cycle 6/8, epoch 1): 67%|██████▋ | 43/64 [01:38<00:48, 2.30s/batch] Reparam (cycle 6/8, epoch 1): 69%|██████▉ | 44/64 [01:41<00:45, 2.29s/batch] Reparam (cycle 6/8, epoch 1): 70%|███████ | 45/64 [01:43<00:43, 2.28s/batch] Reparam (cycle 6/8, epoch 1): 72%|███████▏ | 46/64 [01:45<00:40, 2.27s/batch] Reparam (cycle 6/8, epoch 1): 73%|███████▎ | 47/64 [01:48<00:39, 2.32s/batch] Reparam (cycle 6/8, epoch 1): 75%|███████▌ | 48/64 [01:50<00:37, 2.34s/batch] Reparam (cycle 6/8, epoch 1): 77%|███████▋ | 49/64 [01:52<00:34, 2.31s/batch][reparam] epoch=1 step=50 phase=joint loss=9.696410e-03 mse=4.493625e-03 mlp_mse=3.579800e-03 kl=5.071830e-03 lambda_mean=0.6211211681365967 lambda_std=6.954265765167942e-05 lambda_abs0.5=0.12112116813659668 + Reparam (cycle 6/8, epoch 1): 78%|███████▊ | 50/64 [01:55<00:33, 2.38s/batch] Reparam (cycle 6/8, epoch 1): 80%|███████▉ | 51/64 [01:57<00:30, 2.34s/batch] Reparam (cycle 6/8, epoch 1): 81%|████████▏ | 52/64 [01:59<00:27, 2.32s/batch] Reparam (cycle 6/8, epoch 1): 83%|████████▎ | 53/64 [02:02<00:25, 2.30s/batch] Reparam (cycle 6/8, epoch 1): 84%|████████▍ | 54/64 [02:04<00:22, 2.29s/batch] Reparam (cycle 6/8, epoch 1): 86%|████████▌ | 55/64 [02:06<00:20, 2.28s/batch] Reparam (cycle 6/8, epoch 1): 88%|████████▊ | 56/64 [02:08<00:18, 2.28s/batch] Reparam (cycle 6/8, epoch 1): 89%|████████▉ | 57/64 [02:11<00:15, 2.28s/batch] Reparam (cycle 6/8, epoch 1): 91%|█████████ | 58/64 [02:13<00:13, 2.27s/batch] Reparam (cycle 6/8, epoch 1): 92%|█████████▏| 59/64 [02:15<00:11, 2.27s/batch][reparam] epoch=1 step=60 phase=joint loss=9.840488e-03 mse=4.482965e-03 mlp_mse=3.547631e-03 kl=5.655918e-03 lambda_mean=0.6211211681365967 lambda_std=6.954265765167942e-05 lambda_abs0.5=0.12112116813659668 + Reparam (cycle 6/8, epoch 1): 94%|█████████▍| 60/64 [02:18<00:09, 2.35s/batch] Reparam (cycle 6/8, epoch 1): 95%|█████████▌| 61/64 [02:20<00:07, 2.35s/batch] Reparam (cycle 6/8, epoch 1): 97%|█████████▋| 62/64 [02:22<00:04, 2.33s/batch] Reparam (cycle 6/8, epoch 1): 98%|█████████▊| 63/64 [02:25<00:02, 2.31s/batch] Reparam (cycle 6/8, epoch 1): 100%|██████████| 64/64 [02:27<00:00, 2.29s/batch] Reparam (cycle 6/8, epoch 1): 100%|██████████| 64/64 [02:27<00:00, 2.30s/batch] +[timing] Cycle 6 component wall-clock: +[timing] selection: 8.204s (5.22% of cycle) +[timing] rebase: 0.000s (0.00% of cycle) +[timing] fisher: 0.000s (0.00% of cycle) +[timing] fit: 147.826s (94.12% of cycle) +[timing] materialize_save_layer: 0.523s (0.33% of cycle) +[timing] metadata_write: 0.001s (0.00% of cycle) +[timing] teacher_snapshot: 0.376s (0.24% of cycle) +[timing] cycle_cleanup: 0.137s (0.09% of cycle) +[timing] cycle_total: 157.067s +[timing] tracked_components_total: 157.067s +[progressive] Cycle 7/8 +[fit-ablation] MKA geometry: 26 layers +[fit-ablation] selection {"cycle": 7, "pair_index": 16, "initializer": "mka", "lambda_left": 0.6229176202047336, "recipient_original_layer": 17, "recipient_side": "left", "removed_original_layer": 18, "entropies": [-0.6315610607587784, -0.627416009583068, -0.5861614941870391, -0.6016038763611488, -0.6130674217530055, -0.6121981385094227, -0.6033131501980972, -0.5924187613341422, -0.6069171484092294, -0.6132380808987886, -0.607843819939205, -0.6085076526449892, -0.5918690386938749, -0.5995608511332241, -0.5767638850935354, -0.5998789692930665, -0.5994408320409431, -0.5950893317180167, -0.5982691857051824, -0.5578064876569259, -0.577818168115036, -0.6012980952371977, -0.6334446234704915, -0.6592623178960838, -0.6091736365869417, -0.616569194453633], "pair_npib": 1.5415356845175048, "source_lineage": [[17], [18, 19]], "geometry_samples": 100, "geometry_sequence_length": 512, "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", "selection_policy": "native_dynamic_adjacent_NPIB", "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", "removed_original_layers": [18], "active_original_layers": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 20, 21, 23, 26, 27, 29, 30, 31]} +[fuse] Head permutation disabled; merging with original head order. +[fit-ablation] Fisher bypassed: non-Fisher initializer +[reparam] fisher_prior_inputs fa_mean=None fb_mean=None active_ratio=None rel_contrast=None prior_mean=0.6229176202047336 prior_active_mean=None +[reparam] Cycle 7: training U + gates for pair 16-17 (epochs=1.0, skip_train=False, hidden_mse_w=1.0, attn_mse_w=0.0, mlp_mse_w=1.0, eta=0.0, gamma=0.0, attn_reg_scale=1.0, mlp_reg_scale=1.0, param_subset=mlp, fisher_init_subset=same, train_subset=mlp, lambda_init=fisher_prior). +[reparam] subset=mlp gates=3 (attn=0, mlp=3, other=0) train_subset=mlp (attn=0, mlp=3, other=0) elems=3 (~0.0 MiB), U_elems=176160768 (~672.0 MiB; +optimizer state) +[reparam] lambda_init mean=0.6229175925254822 std=0.0 min=0.6229175925254822 max=0.6229175925254822 mean_abs_from_0.5=0.12291759252548218 +[reparam] additive_u enabled: W = W_F + U_add, U_add initialized at zero + Reparam (cycle 7/8, epoch 1): 0%| | 0/64 [00:00= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2) +/opt/conda/lib/python3.11/site-packages/torch/nn/modules/linear.py:125: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return F.linear(input, self.weight, self.bias) +/opt/conda/lib/python3.11/site-packages/torch/autograd/graph.py:829: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass +[reparam] first_grad phase=joint step=1 gate_l2=0.000000e+00 gate_mean_abs=None gate_max_abs=0.000000e+00 u_l2=9.353721e-03 u_mean_abs=2.8153123193554903e-07 u_max_abs=1.277328e-03 rho_l2=0.000000e+00 +[reparam] epoch=1 step=1 phase=joint loss=1.769575e-02 mse=9.506442e-03 mlp_mse=4.384138e-03 kl=1.189115e-02 lambda_mean=0.6229175925254822 lambda_std=0.0 lambda_abs0.5=0.12291759252548218 + Reparam (cycle 7/8, epoch 1): 2%|▏ | 1/64 [00:02<02:53, 2.75s/batch] Reparam (cycle 7/8, epoch 1): 3%|▎ | 2/64 [00:05<02:32, 2.46s/batch] Reparam (cycle 7/8, epoch 1): 5%|▍ | 3/64 [00:07<02:24, 2.37s/batch] Reparam (cycle 7/8, epoch 1): 6%|▋ | 4/64 [00:09<02:19, 2.33s/batch] Reparam (cycle 7/8, epoch 1): 8%|▊ | 5/64 [00:11<02:16, 2.31s/batch] Reparam (cycle 7/8, epoch 1): 9%|▉ | 6/64 [00:14<02:12, 2.29s/batch] Reparam (cycle 7/8, epoch 1): 11%|█ | 7/64 [00:16<02:10, 2.28s/batch] Reparam (cycle 7/8, epoch 1): 12%|█▎ | 8/64 [00:18<02:07, 2.28s/batch] Reparam (cycle 7/8, epoch 1): 14%|█▍ | 9/64 [00:20<02:04, 2.27s/batch][reparam] epoch=1 step=10 phase=joint loss=1.445539e-02 mse=8.123785e-03 mlp_mse=3.268103e-03 kl=9.573457e-03 lambda_mean=0.6229175925254822 lambda_std=0.0 lambda_abs0.5=0.12291759252548218 + Reparam (cycle 7/8, epoch 1): 16%|█▌ | 10/64 [00:23<02:06, 2.34s/batch] Reparam (cycle 7/8, epoch 1): 17%|█▋ | 11/64 [00:25<02:02, 2.32s/batch] Reparam (cycle 7/8, epoch 1): 19%|█▉ | 12/64 [00:27<01:59, 2.30s/batch] Reparam (cycle 7/8, epoch 1): 20%|██ | 13/64 [00:30<01:56, 2.29s/batch] Reparam (cycle 7/8, epoch 1): 22%|██▏ | 14/64 [00:32<01:54, 2.29s/batch] Reparam (cycle 7/8, epoch 1): 23%|██▎ | 15/64 [00:34<01:51, 2.28s/batch] Reparam (cycle 7/8, epoch 1): 25%|██▌ | 16/64 [00:36<01:49, 2.28s/batch] Reparam (cycle 7/8, epoch 1): 27%|██▋ | 17/64 [00:39<01:46, 2.27s/batch] Reparam (cycle 7/8, epoch 1): 28%|██▊ | 18/64 [00:41<01:44, 2.27s/batch] Reparam (cycle 7/8, epoch 1): 30%|██▉ | 19/64 [00:44<01:53, 2.51s/batch][reparam] epoch=1 step=20 phase=joint loss=1.393633e-02 mse=7.833527e-03 mlp_mse=3.171532e-03 kl=9.160209e-03 lambda_mean=0.6229175925254822 lambda_std=0.0 lambda_abs0.5=0.12291759252548218 + Reparam (cycle 7/8, epoch 1): 31%|███▏ | 20/64 [00:47<01:50, 2.50s/batch] Reparam (cycle 7/8, epoch 1): 33%|███▎ | 21/64 [00:49<01:44, 2.43s/batch] Reparam (cycle 7/8, epoch 1): 34%|███▍ | 22/64 [00:51<01:39, 2.38s/batch] Reparam (cycle 7/8, epoch 1): 36%|███▌ | 23/64 [00:53<01:36, 2.34s/batch] Reparam (cycle 7/8, epoch 1): 38%|███▊ | 24/64 [00:56<01:32, 2.32s/batch] Reparam (cycle 7/8, epoch 1): 39%|███▉ | 25/64 [00:58<01:30, 2.31s/batch] Reparam (cycle 7/8, epoch 1): 41%|████ | 26/64 [01:00<01:27, 2.29s/batch] Reparam (cycle 7/8, epoch 1): 42%|████▏ | 27/64 [01:02<01:24, 2.28s/batch] Reparam (cycle 7/8, epoch 1): 44%|████▍ | 28/64 [01:05<01:21, 2.28s/batch] Reparam (cycle 7/8, epoch 1): 45%|████▌ | 29/64 [01:07<01:19, 2.27s/batch][reparam] epoch=1 step=30 phase=joint loss=1.364324e-02 mse=7.560027e-03 mlp_mse=3.104996e-03 kl=9.306912e-03 lambda_mean=0.6229175925254822 lambda_std=0.0 lambda_abs0.5=0.12291759252548218 + Reparam (cycle 7/8, epoch 1): 47%|████▋ | 30/64 [01:09<01:18, 2.32s/batch] Reparam (cycle 7/8, epoch 1): 48%|████▊ | 31/64 [01:12<01:16, 2.30s/batch] Reparam (cycle 7/8, epoch 1): 50%|█████ | 32/64 [01:14<01:13, 2.29s/batch] Reparam (cycle 7/8, epoch 1): 52%|█████▏ | 33/64 [01:16<01:10, 2.29s/batch] Reparam (cycle 7/8, epoch 1): 53%|█████▎ | 34/64 [01:19<01:09, 2.31s/batch] Reparam (cycle 7/8, epoch 1): 55%|█████▍ | 35/64 [01:21<01:06, 2.29s/batch] Reparam (cycle 7/8, epoch 1): 56%|█████▋ | 36/64 [01:23<01:04, 2.29s/batch] Reparam (cycle 7/8, epoch 1): 58%|█████▊ | 37/64 [01:25<01:01, 2.28s/batch] Reparam (cycle 7/8, epoch 1): 59%|█████▉ | 38/64 [01:28<00:59, 2.27s/batch] Reparam (cycle 7/8, epoch 1): 61%|██████ | 39/64 [01:30<00:56, 2.27s/batch][reparam] epoch=1 step=40 phase=joint loss=1.380874e-02 mse=7.064424e-03 mlp_mse=2.995700e-03 kl=1.171441e-02 lambda_mean=0.6229175925254822 lambda_std=0.0 lambda_abs0.5=0.12291759252548218 + Reparam (cycle 7/8, epoch 1): 62%|██████▎ | 40/64 [01:32<00:56, 2.34s/batch] Reparam (cycle 7/8, epoch 1): 64%|██████▍ | 41/64 [01:35<00:53, 2.31s/batch] Reparam (cycle 7/8, epoch 1): 66%|██████▌ | 42/64 [01:37<00:50, 2.30s/batch] Reparam (cycle 7/8, epoch 1): 67%|██████▋ | 43/64 [01:39<00:48, 2.29s/batch] Reparam (cycle 7/8, epoch 1): 69%|██████▉ | 44/64 [01:41<00:45, 2.28s/batch] Reparam (cycle 7/8, epoch 1): 70%|███████ | 45/64 [01:44<00:43, 2.28s/batch] Reparam (cycle 7/8, epoch 1): 72%|███████▏ | 46/64 [01:46<00:40, 2.28s/batch] Reparam (cycle 7/8, epoch 1): 73%|███████▎ | 47/64 [01:48<00:38, 2.27s/batch] Reparam (cycle 7/8, epoch 1): 75%|███████▌ | 48/64 [01:50<00:36, 2.27s/batch] Reparam (cycle 7/8, epoch 1): 77%|███████▋ | 49/64 [01:53<00:34, 2.27s/batch][reparam] epoch=1 step=50 phase=joint loss=1.279450e-02 mse=6.983085e-03 mlp_mse=3.200041e-03 kl=8.160553e-03 lambda_mean=0.6229175925254822 lambda_std=0.0 lambda_abs0.5=0.12291759252548218 + Reparam (cycle 7/8, epoch 1): 78%|███████▊ | 50/64 [01:55<00:32, 2.33s/batch] Reparam (cycle 7/8, epoch 1): 80%|███████▉ | 51/64 [01:57<00:30, 2.32s/batch] Reparam (cycle 7/8, epoch 1): 81%|████████▏ | 52/64 [02:00<00:27, 2.30s/batch] Reparam (cycle 7/8, epoch 1): 83%|████████▎ | 53/64 [02:02<00:25, 2.29s/batch] Reparam (cycle 7/8, epoch 1): 84%|████████▍ | 54/64 [02:04<00:22, 2.29s/batch] Reparam (cycle 7/8, epoch 1): 86%|████████▌ | 55/64 [02:07<00:20, 2.28s/batch] Reparam (cycle 7/8, epoch 1): 88%|████████▊ | 56/64 [02:09<00:18, 2.28s/batch] Reparam (cycle 7/8, epoch 1): 89%|████████▉ | 57/64 [02:11<00:15, 2.28s/batch] Reparam (cycle 7/8, epoch 1): 91%|█████████ | 58/64 [02:13<00:13, 2.28s/batch] Reparam (cycle 7/8, epoch 1): 92%|█████████▏| 59/64 [02:16<00:11, 2.28s/batch][reparam] epoch=1 step=60 phase=joint loss=1.306862e-02 mse=6.918347e-03 mlp_mse=3.276949e-03 kl=8.979149e-03 lambda_mean=0.6229175925254822 lambda_std=0.0 lambda_abs0.5=0.12291759252548218 + Reparam (cycle 7/8, epoch 1): 94%|█████████▍| 60/64 [02:18<00:09, 2.34s/batch] Reparam (cycle 7/8, epoch 1): 95%|█████████▌| 61/64 [02:20<00:06, 2.32s/batch] Reparam (cycle 7/8, epoch 1): 97%|█████████▋| 62/64 [02:23<00:04, 2.30s/batch] Reparam (cycle 7/8, epoch 1): 98%|█████████▊| 63/64 [02:25<00:02, 2.29s/batch] Reparam (cycle 7/8, epoch 1): 100%|██████████| 64/64 [02:27<00:00, 2.28s/batch] Reparam (cycle 7/8, epoch 1): 100%|██████████| 64/64 [02:27<00:00, 2.31s/batch] +[timing] Cycle 7 component wall-clock: +[timing] selection: 7.935s (5.04% of cycle) +[timing] rebase: 0.000s (0.00% of cycle) +[timing] fisher: 0.000s (0.00% of cycle) +[timing] fit: 148.182s (94.21% of cycle) +[timing] materialize_save_layer: 0.554s (0.35% of cycle) +[timing] metadata_write: 0.001s (0.00% of cycle) +[timing] teacher_snapshot: 0.394s (0.25% of cycle) +[timing] cycle_cleanup: 0.216s (0.14% of cycle) +[timing] cycle_total: 157.283s +[timing] tracked_components_total: 157.281s +[progressive] Cycle 8/8 +[fit-ablation] MKA geometry: 25 layers +[fit-ablation] selection {"cycle": 8, "pair_index": 16, "initializer": "mka", "lambda_left": 0.6223904334015297, "recipient_original_layer": 17, "recipient_side": "left", "removed_original_layer": 20, "entropies": [-0.6315610607587784, -0.627416009583068, -0.5861614941870391, -0.6016038763611488, -0.6130674217530055, -0.6121981385094227, -0.6033131501980972, -0.5924187613341422, -0.6069171484092294, -0.6132380808987886, -0.607843819939205, -0.6085076526449892, -0.5918690386938749, -0.5995608511332241, -0.5767638850935354, -0.5998789692930665, -0.6060303112437687, -0.5976469364022053, -0.5767187710745335, -0.5862940540626368, -0.6120057979779193, -0.6468870503045397, -0.6486871845158716, -0.601268769843721, -0.6931420893705896], "pair_npib": 1.7124458804253397, "source_lineage": [[17, 18, 19], [20]], "geometry_samples": 100, "geometry_sequence_length": 512, "geometry_input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", "selection_policy": "native_dynamic_adjacent_NPIB", "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", "removed_original_layers": [20], "active_original_layers": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 21, 23, 26, 27, 29, 30, 31]} +[fuse] Head permutation disabled; merging with original head order. +[fit-ablation] Fisher bypassed: non-Fisher initializer +[reparam] fisher_prior_inputs fa_mean=None fb_mean=None active_ratio=None rel_contrast=None prior_mean=0.6223904334015297 prior_active_mean=None +[reparam] Cycle 8: training U + gates for pair 16-17 (epochs=1.0, skip_train=False, hidden_mse_w=1.0, attn_mse_w=0.0, mlp_mse_w=1.0, eta=0.0, gamma=0.0, attn_reg_scale=1.0, mlp_reg_scale=1.0, param_subset=mlp, fisher_init_subset=same, train_subset=mlp, lambda_init=fisher_prior). +[reparam] subset=mlp gates=3 (attn=0, mlp=3, other=0) train_subset=mlp (attn=0, mlp=3, other=0) elems=3 (~0.0 MiB), U_elems=176160768 (~672.0 MiB; +optimizer state) +[reparam] lambda_init mean=0.6223904490470886 std=8.630744330786893e-06 min=0.6223904490470886 max=0.6223904490470886 mean_abs_from_0.5=0.12239044904708862 +[reparam] additive_u enabled: W = W_F + U_add, U_add initialized at zero + Reparam (cycle 8/8, epoch 1): 0%| | 0/64 [00:00= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2) +/opt/conda/lib/python3.11/site-packages/torch/nn/modules/linear.py:125: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return F.linear(input, self.weight, self.bias) +/opt/conda/lib/python3.11/site-packages/torch/autograd/graph.py:829: UserWarning: Deterministic behavior was enabled with either `torch.use_deterministic_algorithms(True)` or `at::Context::setDeterministicAlgorithms(true)`, but this operation is not deterministic because it uses CuBLAS and you have CUDA >= 10.2. To enable deterministic behavior in this case, you must set an environment variable before running your PyTorch application: CUBLAS_WORKSPACE_CONFIG=:4096:8 or CUBLAS_WORKSPACE_CONFIG=:16:8. For more information, go to https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility (Triggered internally at /pytorch/aten/src/ATen/Context.cpp:233.) + return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass +[reparam] first_grad phase=joint step=1 gate_l2=0.000000e+00 gate_mean_abs=None gate_max_abs=0.000000e+00 u_l2=9.576968e-03 u_mean_abs=2.923745363486454e-07 u_max_abs=9.045601e-04 rho_l2=0.000000e+00 +[reparam] epoch=1 step=1 phase=joint loss=2.820441e-02 mse=1.461516e-02 mlp_mse=8.210992e-03 kl=1.680707e-02 lambda_mean=0.6223904490470886 lambda_std=8.630744330786893e-06 lambda_abs0.5=0.12239044904708862 + Reparam (cycle 8/8, epoch 1): 2%|▏ | 1/64 [00:02<02:37, 2.49s/batch] Reparam (cycle 8/8, epoch 1): 3%|▎ | 2/64 [00:04<02:23, 2.32s/batch] Reparam (cycle 8/8, epoch 1): 5%|▍ | 3/64 [00:06<02:18, 2.26s/batch] Reparam (cycle 8/8, epoch 1): 6%|▋ | 4/64 [00:09<02:14, 2.24s/batch] Reparam (cycle 8/8, epoch 1): 8%|▊ | 5/64 [00:11<02:11, 2.23s/batch] Reparam (cycle 8/8, epoch 1): 9%|▉ | 6/64 [00:13<02:08, 2.22s/batch] Reparam (cycle 8/8, epoch 1): 11%|█ | 7/64 [00:15<02:06, 2.21s/batch] Reparam (cycle 8/8, epoch 1): 12%|█▎ | 8/64 [00:17<02:03, 2.21s/batch] Reparam (cycle 8/8, epoch 1): 14%|█▍ | 9/64 [00:20<02:01, 2.21s/batch][reparam] epoch=1 step=10 phase=joint loss=2.399264e-02 mse=1.097060e-02 mlp_mse=8.337954e-03 kl=1.463774e-02 lambda_mean=0.6223904490470886 lambda_std=8.630744330786893e-06 lambda_abs0.5=0.12239044904708862 + Reparam (cycle 8/8, epoch 1): 16%|█▌ | 10/64 [00:22<02:02, 2.27s/batch] Reparam (cycle 8/8, epoch 1): 17%|█▋ | 11/64 [00:24<01:59, 2.25s/batch] Reparam (cycle 8/8, epoch 1): 19%|█▉ | 12/64 [00:26<01:56, 2.24s/batch] Reparam (cycle 8/8, epoch 1): 20%|██ | 13/64 [00:29<01:53, 2.23s/batch] Reparam (cycle 8/8, epoch 1): 22%|██▏ | 14/64 [00:31<01:51, 2.22s/batch] Reparam (cycle 8/8, epoch 1): 23%|██▎ | 15/64 [00:33<01:48, 2.22s/batch] Reparam (cycle 8/8, epoch 1): 25%|██▌ | 16/64 [00:35<01:46, 2.22s/batch] Reparam (cycle 8/8, epoch 1): 27%|██▋ | 17/64 [00:37<01:43, 2.21s/batch] Reparam (cycle 8/8, epoch 1): 28%|██▊ | 18/64 [00:40<01:41, 2.21s/batch] Reparam (cycle 8/8, epoch 1): 30%|██▉ | 19/64 [00:42<01:39, 2.21s/batch][reparam] epoch=1 step=20 phase=joint loss=2.255853e-02 mse=1.095181e-02 mlp_mse=8.275382e-03 kl=1.041043e-02 lambda_mean=0.6223904490470886 lambda_std=8.630744330786893e-06 lambda_abs0.5=0.12239044904708862 + Reparam (cycle 8/8, epoch 1): 31%|███▏ | 20/64 [00:44<01:40, 2.27s/batch] Reparam (cycle 8/8, epoch 1): 33%|███▎ | 21/64 [00:47<01:36, 2.25s/batch] Reparam (cycle 8/8, epoch 1): 34%|███▍ | 22/64 [00:49<01:33, 2.24s/batch] Reparam (cycle 8/8, epoch 1): 36%|███▌ | 23/64 [00:51<01:31, 2.23s/batch] Reparam (cycle 8/8, epoch 1): 38%|███▊ | 24/64 [00:53<01:28, 2.22s/batch] Reparam (cycle 8/8, epoch 1): 39%|███▉ | 25/64 [00:55<01:26, 2.22s/batch] Reparam (cycle 8/8, epoch 1): 41%|████ | 26/64 [00:58<01:24, 2.22s/batch] Reparam (cycle 8/8, epoch 1): 42%|████▏ | 27/64 [01:00<01:23, 2.24s/batch] Reparam (cycle 8/8, epoch 1): 44%|████▍ | 28/64 [01:02<01:20, 2.23s/batch] Reparam (cycle 8/8, epoch 1): 45%|████▌ | 29/64 [01:04<01:17, 2.23s/batch][reparam] epoch=1 step=30 phase=joint loss=2.265448e-02 mse=1.026659e-02 mlp_mse=8.569840e-03 kl=1.193140e-02 lambda_mean=0.6223904490470886 lambda_std=8.630744330786893e-06 lambda_abs0.5=0.12239044904708862 + Reparam (cycle 8/8, epoch 1): 47%|████▋ | 30/64 [01:07<01:17, 2.28s/batch] Reparam (cycle 8/8, epoch 1): 48%|████▊ | 31/64 [01:10<01:22, 2.51s/batch] Reparam (cycle 8/8, epoch 1): 50%|█████ | 32/64 [01:12<01:17, 2.42s/batch] Reparam (cycle 8/8, epoch 1): 52%|█████▏ | 33/64 [01:14<01:12, 2.35s/batch] Reparam (cycle 8/8, epoch 1): 53%|█████▎ | 34/64 [01:16<01:09, 2.31s/batch] Reparam (cycle 8/8, epoch 1): 55%|█████▍ | 35/64 [01:19<01:06, 2.28s/batch] Reparam (cycle 8/8, epoch 1): 56%|█████▋ | 36/64 [01:21<01:03, 2.26s/batch] Reparam (cycle 8/8, epoch 1): 58%|█████▊ | 37/64 [01:23<01:00, 2.24s/batch] Reparam (cycle 8/8, epoch 1): 59%|█████▉ | 38/64 [01:25<00:58, 2.23s/batch] Reparam (cycle 8/8, epoch 1): 61%|██████ | 39/64 [01:27<00:55, 2.22s/batch][reparam] epoch=1 step=40 phase=joint loss=2.235165e-02 mse=1.049259e-02 mlp_mse=8.157967e-03 kl=1.156592e-02 lambda_mean=0.6223904490470886 lambda_std=8.630744330786893e-06 lambda_abs0.5=0.12239044904708862 + Reparam (cycle 8/8, epoch 1): 62%|██████▎ | 40/64 [01:30<00:54, 2.28s/batch] Reparam (cycle 8/8, epoch 1): 64%|██████▍ | 41/64 [01:32<00:51, 2.26s/batch] Reparam (cycle 8/8, epoch 1): 66%|██████▌ | 42/64 [01:34<00:49, 2.24s/batch] Reparam (cycle 8/8, epoch 1): 67%|██████▋ | 43/64 [01:36<00:46, 2.23s/batch] Reparam (cycle 8/8, epoch 1): 69%|██████▉ | 44/64 [01:39<00:44, 2.22s/batch] Reparam (cycle 8/8, epoch 1): 70%|███████ | 45/64 [01:41<00:42, 2.22s/batch] Reparam (cycle 8/8, epoch 1): 72%|███████▏ | 46/64 [01:43<00:40, 2.23s/batch] Reparam (cycle 8/8, epoch 1): 73%|███████▎ | 47/64 [01:45<00:37, 2.23s/batch] Reparam (cycle 8/8, epoch 1): 75%|███████▌ | 48/64 [01:48<00:35, 2.22s/batch] Reparam (cycle 8/8, epoch 1): 77%|███████▋ | 49/64 [01:50<00:33, 2.22s/batch][reparam] epoch=1 step=50 phase=joint loss=2.191285e-02 mse=1.014190e-02 mlp_mse=8.073809e-03 kl=1.155356e-02 lambda_mean=0.6223904490470886 lambda_std=8.630744330786893e-06 lambda_abs0.5=0.12239044904708862 + Reparam (cycle 8/8, epoch 1): 78%|███████▊ | 50/64 [01:52<00:31, 2.28s/batch] Reparam (cycle 8/8, epoch 1): 80%|███████▉ | 51/64 [01:54<00:29, 2.26s/batch] Reparam (cycle 8/8, epoch 1): 81%|████████▏ | 52/64 [01:57<00:26, 2.24s/batch] Reparam (cycle 8/8, epoch 1): 83%|████████▎ | 53/64 [01:59<00:24, 2.23s/batch] Reparam (cycle 8/8, epoch 1): 84%|████████▍ | 54/64 [02:01<00:22, 2.22s/batch] Reparam (cycle 8/8, epoch 1): 86%|████████▌ | 55/64 [02:03<00:19, 2.22s/batch] Reparam (cycle 8/8, epoch 1): 88%|████████▊ | 56/64 [02:05<00:17, 2.22s/batch] Reparam (cycle 8/8, epoch 1): 89%|████████▉ | 57/64 [02:08<00:15, 2.21s/batch] Reparam (cycle 8/8, epoch 1): 91%|█████████ | 58/64 [02:10<00:13, 2.21s/batch] Reparam (cycle 8/8, epoch 1): 92%|█████████▏| 59/64 [02:12<00:11, 2.21s/batch][reparam] epoch=1 step=60 phase=joint loss=2.275818e-02 mse=1.042443e-02 mlp_mse=8.169543e-03 kl=1.301316e-02 lambda_mean=0.6223904490470886 lambda_std=8.630744330786893e-06 lambda_abs0.5=0.12239044904708862 + Reparam (cycle 8/8, epoch 1): 94%|█████████▍| 60/64 [02:14<00:09, 2.27s/batch] Reparam (cycle 8/8, epoch 1): 95%|█████████▌| 61/64 [02:17<00:06, 2.25s/batch] Reparam (cycle 8/8, epoch 1): 97%|█████████▋| 62/64 [02:19<00:04, 2.24s/batch] Reparam (cycle 8/8, epoch 1): 98%|█████████▊| 63/64 [02:21<00:02, 2.23s/batch] Reparam (cycle 8/8, epoch 1): 100%|██████████| 64/64 [02:23<00:00, 2.22s/batch] Reparam (cycle 8/8, epoch 1): 100%|██████████| 64/64 [02:23<00:00, 2.25s/batch] +[timing] Cycle 8 component wall-clock: +[timing] selection: 7.680s (5.02% of cycle) +[timing] rebase: 0.000s (0.00% of cycle) +[timing] fisher: 0.000s (0.00% of cycle) +[timing] fit: 144.221s (94.23% of cycle) +[timing] materialize_save_layer: 0.560s (0.37% of cycle) +[timing] metadata_write: 0.001s (0.00% of cycle) +[timing] teacher_snapshot: 0.385s (0.25% of cycle) +[timing] cycle_cleanup: 0.209s (0.14% of cycle) +[timing] cycle_total: 153.057s +[timing] tracked_components_total: 153.056s +[save] Skipping final pre-LoRA weight save (compact_only). +[save] Skipping final model weight save (compact_only). +[progressive] Completed 8 cycles. Compact weights written to /workspace/mka-fit-batch-20261126/full/batch_large/run; final dense model save skipped. diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/manifest.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..7ef345a0fec96f0a1eccb3d729d78cb40a36b974 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/manifest.json @@ -0,0 +1,342 @@ +{ + "schema": "sha256-tree-v1", + "files": [ + { + "path": "audit/cycle_01_fit.json", + "size": 8267, + "sha256": "595d617518adcacf41c42e9c16cc1afa1c366e905530b1f4693f1dcb026aae97" + }, + { + "path": "audit/cycle_02_fit.json", + "size": 8264, + "sha256": "6e2b6e56304d395ac94c56a54869978c068df3363c4c8a25db73cbb67e2d6c54" + }, + { + "path": "audit/cycle_03_fit.json", + "size": 8337, + "sha256": "ba67ca570ab30ae7416691814c01c00b3b72ef7f8bccc7aae968338fdda7a081" + }, + { + "path": "audit/cycle_04_fit.json", + "size": 8269, + "sha256": "09841a0b6b19b457264bbb39c4df1ae741f8815169b127c20ceff78aa29993da" + }, + { + "path": "audit/cycle_05_fit.json", + "size": 8264, + "sha256": "3021dd47cb78088bae32aa810edaaa037ea6b61daeb1fa3ff82196e828b6da9c" + }, + { + "path": "audit/cycle_06_fit.json", + "size": 8343, + "sha256": "56f6ea0749791abef71c1eab513697da8b40bf2bac2929992499554fd987ac62" + }, + { + "path": "audit/cycle_07_fit.json", + "size": 8198, + "sha256": "8155daeead501defcdf39cecf90ea4a8884a2330e4401ff85130f14270e32455" + }, + { + "path": "audit/cycle_08_fit.json", + "size": 8338, + "sha256": "eb081d4269621220f51d6aa196652cd260d6da5e383f701d9334a2482cec67f4" + }, + { + "path": "audit/data_fingerprints.json", + "size": 509, + "sha256": "0a3902dc3badda0d88f08e0b1bbaa24c9257efabf1170fa2704d006da446d9ce" + }, + { + "path": "audit/selection.json", + "size": 201108, + "sha256": "36a0355a5ee1beb14e7fc30ef77701bd6927f8588b0bd862151a5bc88b1642d1" + }, + { + "path": "audit/selection_inputs.json", + "size": 436, + "sha256": "9b9324823aa6cb1bbb1e7ccb9cf4dc9410ed69d27eef962f38d858a4d749d33e" + }, + { + "path": "batch_profile.json", + "size": 2313, + "sha256": "fff8743dc7d254059433ab31b2831729530345ac5681a18aea57a20a8b92ce25" + }, + { + "path": "code/abprune_compact.py", + "size": 12360, + "sha256": "34f00dc3b96ea3c3dd6dafada682352e2b332e6b1c79fb2033e13f9585254ff3" + }, + { + "path": "code/bootstrap_llama31_come_fit2.sh", + "size": 3092, + "sha256": "53d76652e71b4ac0b4d8cf8e3444443acf59781e03311a102f8583e2a4597818" + }, + { + "path": "code/collect_mka_batch_comparison.py", + "size": 4125, + "sha256": "0920f2c22f6b7834dbdaf0cd17a05dddab969f45613d7c8fa84861f748b9b72c" + }, + { + "path": "code/come.py", + "size": 24499, + "sha256": "782e306e43f59e6fc1df28ba346ee57b03004c283376c661233b144f7491d9f8" + }, + { + "path": "code/eval_llama31_8b_12bench.py", + "size": 6694, + "sha256": "94f6ca3e633f10b5cdef756c1e88e32cdf1615a8f17d078918c0b412a445fb37" + }, + { + "path": "code/eval_llama31_fit_ablation_one.sh", + "size": 3118, + "sha256": "ae03668f8f4aae078813858b17aada4d0cc828a848d4321036736bf12ca665dd" + }, + { + "path": "code/evaluate_abprune_compact_ppl.py", + "size": 7038, + "sha256": "916db0545ee18ba39dbbb0af9ce4f379a1ddef0b54d0477caf402ee24421a050" + }, + { + "path": "code/evaluate_hchc_wikitext2_ppl.py", + "size": 5422, + "sha256": "a1c1c0bf8422ddc70cc5e9c0049830b9aa594742fdeffa110de7b3dcf30c1dd3" + }, + { + "path": "code/finalize_mka_batch_report.py", + "size": 14634, + "sha256": "761863e0e7cb55d5f2480a149b6a620f5a70c87255a9058d6012efd0455b549a" + }, + { + "path": "code/fit_ablation_come.py", + "size": 2615, + "sha256": "21345e899859f09745b008e6a77582a574a2ba66fa9b071634b16fd7969e3dbb" + }, + { + "path": "code/fit_ablation_mka.py", + "size": 19854, + "sha256": "05679b074c4e8dda5f902598c0115e538128da42dfe75c5402f4adf84262da03" + }, + { + "path": "code/fuse_layers.py", + "size": 131351, + "sha256": "d2bca0ca9b5bc42da7a29cd5a14f860821486625cebd9da60d01521f07a3f6dc" + }, + { + "path": "code/fuse_layers_distill.py", + "size": 148110, + "sha256": "d0f2ffcb021e486b9462b45fd7507d492a47ffa5f803768a9bc856721e4be16c" + }, + { + "path": "code/launch_llama31_come_fit2.sh", + "size": 6784, + "sha256": "0b8fa86012cc34ca690495d2fe99129237ce45b204e42cc343897a6d2411ebd8" + }, + { + "path": "code/launch_mka_batch_comparison.py", + "size": 15600, + "sha256": "8a7b8432da9aa1a20bd519f42baadbfe5df60a8ce76338f9540e35df50a6d208" + }, + { + "path": "code/mka.py", + "size": 21026, + "sha256": "ad9ea0af779cf5714e98f6872500f6059c8731635aae425b53d19fbfb7fecd0a" + }, + { + "path": "code/offline_eval_policy.py", + "size": 1001, + "sha256": "6d4b2b315573cc308ada19e24b81166d10a1dd4e2bcf0a1f3799229a6d58135a" + }, + { + "path": "code/package_final_fit_backup.py", + "size": 3144, + "sha256": "d70551361aa5e114912fe1b3a4ed7bae57da7f6addcc0c6ebec2b322172f3866" + }, + { + "path": "code/prepare_lmeval9_local_cache.py", + "size": 4706, + "sha256": "b9d7cfa46fa42cc017f53c5fffa34832756246377c3586484c0c54a53a00de8b" + }, + { + "path": "code/prepare_mka_batch_calibration.py", + "size": 5382, + "sha256": "d49f1b12da476b4a512d4a69be1e0c2110e2af382e1c839e179c1f954ac6067d" + }, + { + "path": "code/prepare_offline_ppl_cache.py", + "size": 1329, + "sha256": "b623ed2d4a71beda5427f86875bf5ee6364891f2e4854ff03539d3a94db22f2b" + }, + { + "path": "code/project_commit.txt", + "size": 41, + "sha256": "40909640cffcfb9ad7df26692150cfea179c486ab0a20ea837ba410507751e02" + }, + { + "path": "code/run_external_abprune_instruct_order.py", + "size": 4771, + "sha256": "c39736b64fd793a568ed2c4b3dcdfcb27f21123c28e7592392aef145336b0ecd" + }, + { + "path": "code/run_llama31_base_fit_ablation.py", + "size": 53815, + "sha256": "7450258dc87f45afd8cd7a1459982a4269d8314941aaaee422c07dbd34c1f17f" + }, + { + "path": "code/run_llama31_come_fit_arm.sh", + "size": 2729, + "sha256": "40c4febea4e215eae2598ca8fe09b5dbcf47b1b8d6fd9ab34d40a9c821c7544a" + }, + { + "path": "code/run_mka_batch_arm.sh", + "size": 2176, + "sha256": "c11f9bfb22ebb33dd6a2baae870bd7b9040604ac3f9e946c4c92a907d27d954a" + }, + { + "path": "code/source_feature_transport.py", + "size": 13200, + "sha256": "75809bdbbc9bf73f07adaf1f0c816fc9abd1d9b7c0b8a0d561c96cb0313e243f" + }, + { + "path": "code/validate_mka_first_selection.py", + "size": 3439, + "sha256": "241369686e13e22e8160cf87d029547a58308d4e3ac221e416ca9dc4be6f5d36" + }, + { + "path": "code/validate_mka_runtime_geometry.py", + "size": 9001, + "sha256": "5c1a0508ad881fb7f4e48e4f13c17bd29f4a620e1bf241a060f6d08898f6d498" + }, + { + "path": "compact/stage_08/layer_original_0010.pt", + "size": 436228357, + "sha256": "93a07137091b2b4587fa60bfb786d58eb76842968b5d6efece5bb3a90849d067" + }, + { + "path": "compact/stage_08/layer_original_0017.pt", + "size": 436228357, + "sha256": "83b10b64faa5600e82011c1da9d9e3adf511d06037e740d1972d2b81fc3cd846" + }, + { + "path": "compact/stage_08/layer_original_0021.pt", + "size": 436228357, + "sha256": "ae16abcc87a68b653f6373b534b9238427d570745efb67ec8adfdf0006669927" + }, + { + "path": "compact/stage_08/layer_original_0023.pt", + "size": 436228357, + "sha256": "c85398a3e06d9e37b36209e80a19b1ea98dcead03fdc5760afa8a5844764ce1b" + }, + { + "path": "compact/stage_08/layer_original_0027.pt", + "size": 436228357, + "sha256": "a51ec2f5c8f697b37647b30f364030d6f09a0c327a5e4064a396e13fd74aba6d" + }, + { + "path": "compact/stage_08/metadata.json", + "size": 2031, + "sha256": "360a3419b43d11d7b5f4e70b05603a9a24447770631191febdcedb5bac558517" + }, + { + "path": "eval/final_14bench.json", + "size": 889, + "sha256": "4df35975eca0111486b640691d7df8b0f193acfa18cfb98305a1ddf127377d09" + }, + { + "path": "eval/final_lmeval9.json", + "size": 42746, + "sha256": "cfac4b24e07595685bd6274b19df2887aa8f7edfa7e9b172e7d1f3b4b58bb23a" + }, + { + "path": "eval/final_opencompass5.json", + "size": 1111, + "sha256": "f020ce5cc7df5fbcefd9b4aadc92cea00be40899312f8670674f5f9ea4c9f8c2" + }, + { + "path": "eval/final_ppl.json", + "size": 1241, + "sha256": "67988c3c7249fd2f85af7c92495f0715bab00e0932e2140a0b33ab9d1e5a2a58" + }, + { + "path": "logs/eval14.log", + "size": 245533, + "sha256": "bd4bbab183be55dca1830cff44262ff7b6a4d4460192277c540645c8cc999769" + }, + { + "path": "logs/train.log", + "size": 106039, + "sha256": "7ec04dcb5e8396ed0a05085350c33cf297d2d7e8eb9f785910a9ba7314c0ae87" + }, + { + "path": "native_first_selection.json", + "size": 1095, + "sha256": "2dab51cc0100d587593fe035382e5ab47fecd71adf98f859f42447d77027d7a5" + }, + { + "path": "offline_eval.json", + "size": 352, + "sha256": "231aaa21c0395df1b82b97b396caca9795364ba35bf61fe085f300166f6bcd5e" + }, + { + "path": "offline_preflight.json", + "size": 514, + "sha256": "259080a1b450cb0797894c727765c6865c6f9eba0acf1757c3c23c694e8a2d4a" + }, + { + "path": "protocol.md", + "size": 9509, + "sha256": "40bfeb6a9a4f795c138d2d83003cca8392a0f154670036f783b9c001c3ee5ca7" + }, + { + "path": "selection_provenance.json", + "size": 21743, + "sha256": "c2172a199c76b6d19b165e81412f996cb8b58cec9d2ad46c33d123915c1c6ab9" + }, + { + "path": "stage_metadata/cycle_1/cycle_metadata.json", + "size": 13924, + "sha256": "2f85b1174487a0d3d4b628e3878d826f915241fe838da54f628c251456654214" + }, + { + "path": "stage_metadata/cycle_2/cycle_metadata.json", + "size": 13928, + "sha256": "05cd5b3aa1be5ee7daedbe877278c51d62a9eca345d62403bd8ea880c8bde45c" + }, + { + "path": "stage_metadata/cycle_3/cycle_metadata.json", + "size": 13991, + "sha256": "cbaef531daad1ed96c8693fb958563c01f1d76170f509c83f1505a7a470da225" + }, + { + "path": "stage_metadata/cycle_4/cycle_metadata.json", + "size": 13920, + "sha256": "129f64c5117b6ad0975c0d859fc85ae2694860708fde4d62a210481aa6e8b985" + }, + { + "path": "stage_metadata/cycle_5/cycle_metadata.json", + "size": 13904, + "sha256": "c93c77ca15986d37f0b4a9f156d5657c51c210012f0068274373e5cf987f281b" + }, + { + "path": "stage_metadata/cycle_6/cycle_metadata.json", + "size": 13973, + "sha256": "973ccf12a60554e9f17e8d88cfcf4987c5647555160858ad741807ec1f2ab024" + }, + { + "path": "stage_metadata/cycle_7/cycle_metadata.json", + "size": 13822, + "sha256": "2405263683cdccba2822182470d6315ae082643265e8b5c6784d3b504d556979" + }, + { + "path": "stage_metadata/cycle_8/cycle_metadata.json", + "size": 13954, + "sha256": "219a7eb0d3ba49d120f3662a366ba99418d95a2efd194c9cfeceffa43f63111b" + }, + { + "path": "training_elapsed.json", + "size": 84, + "sha256": "716745645e79fd305bb129796a1b2a1689c6c057b8a959265df4d3e7973c6cb3" + } + ], + "total_files": 67, + "total_bytes": 2182487790 +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/native_first_selection.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/native_first_selection.json new file mode 100644 index 0000000000000000000000000000000000000000..30d99675be5aff54936128adbcf4dcd4afa86149 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/native_first_selection.json @@ -0,0 +1,25 @@ +{ + "passed": true, + "validation_scope": "first pre-FiT selection only; no eight-stage replay claimed", + "atol": 1e-06, + "rtol": 1e-05, + "matrix_allclose": true, + "matrix_max_absolute_difference": 0.0, + "reference_path": "/workspace/mka-fit-batch-20261126/runtime_validation/current_native_geometry.json", + "reference_implementation": "native", + "expected_pair_index": 21, + "observed_pair_index": 21, + "expected_lambda": 0.6240301169976673, + "observed_lambda": 0.6240301169976673, + "expected_pair_npib": 1.928525358648791, + "observed_pair_npib": 1.928525358648791, + "historical_reference_comparison": { + "path": "/workspace/mka-fit-batch-20261126/calibration/mka_pruning.json", + "pair_agrees": true, + "expected_lambda": 0.6237227607228193, + "observed_lambda": 0.6240301169976673, + "matrix_max_absolute_difference": 0.04349728115905993, + "exact_historical_reproduction_claimed": false, + "qualification": "Same frozen tokens and native algorithm; historical execution environment differs. Current runtime native implementation is validated independently." + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/offline_eval.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/offline_eval.json new file mode 100644 index 0000000000000000000000000000000000000000..1970781d91bb49eeeb7feed9ba287a9738b90b1d --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/offline_eval.json @@ -0,0 +1,15 @@ +{ + "wikitext_cache": "/workspace/come-attn-fit-20261126/wikitext2_cache", + "dataset": "Salesforce/wikitext", + "config": "wikitext-2-raw-v1", + "splits": { + "test": 4358, + "train": 36718, + "validation": 3760 + }, + "fingerprints": { + "test": "a46124b21ac53738", + "train": "5d4fb603254a7a5b", + "validation": "51d84d52d095f90d" + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/offline_preflight.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/offline_preflight.json new file mode 100644 index 0000000000000000000000000000000000000000..b33b7e7528db6ea4be6088077180694890cd1c20 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/offline_preflight.json @@ -0,0 +1,20 @@ +{ + "eval_root": "/workspace/come-attn-fit-20261126", + "strict_offline": true, + "lmeval131_validated": true, + "wikitext_policy": { + "wikitext_cache": "/workspace/come-attn-fit-20261126/wikitext2_cache", + "dataset": "Salesforce/wikitext", + "config": "wikitext-2-raw-v1", + "splits": { + "test": 4358, + "train": 36718, + "validation": 3760 + }, + "fingerprints": { + "test": "a46124b21ac53738", + "train": "5d4fb603254a7a5b", + "validation": "51d84d52d095f90d" + } + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/protocol.md b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/protocol.md new file mode 100644 index 0000000000000000000000000000000000000000..121159ca603468b348b904f44cab768d93816677 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/protocol.md @@ -0,0 +1,138 @@ +# Llama-3.1-8B Base MKA + MLP-only FiT, 25% pruning + +User requested MKA with MLP-only FiT after the CoMe comparison. Continue +with Llama-3.1-8B Base, eight removals (32 to 24 layers), physical FiT +batch1 and batch8 on the existing retained two-A10080GB instance62646539. +Do not rent or restart a host. **Never return, destroy or stop this instance +without a new explicit user instruction**, even after all work and backups. + +Session/SSH alias: vast-paper_revision-come-attn-fit-20261126-62646539. +Remote branch: codex/vast-paper_revision-come-attn-fit-20261126-62646539. +Remote project: /workspace/paper_revision/sessions/vast-paper_revision-come-attn-fit-20261126-62646539. +New artifacts: /workspace/mka-fit-batch-20261126; existing CoMe outputs remain +intact. Model: /workspace/models/llama31-base-d04e592, pinned +meta-llama/Llama-3.1-8B@d04e592bb4f6aa9cfee91e2e20afa771667e1d4b. +External additive-U engine: /workspace/external/come-attn-fit. +Controlling local branch: codex/mka-mlp-fit-batch-20261126. + +This is the project's corrected local MKA variant, not a claim of exact +paper reproduction: sequence-mean pooled block outputs before final norm, +current-model geometry recomputed after each merge/FiT, adjacent maximum +NPIB with deeper tie-break, repeated merges allowed. Native geometry uses +100 distinct-document SlimPajama windows x512, seed0, sigma8, alpha.5, +diffusion dimensions2, MI neighbors5, entropy neighbors50, beta1. +All seven MKA projection weights are initialized using FP32 lerp followed +by model-dtype conversion. Freeze four merged attention projections and +the two left-anchor RMSNorm weights; train only gate/up/down MLP weights. +No imposed ABPrune span, Transport, Fisher, head permutation, rho or LoRA. + +FiT data and optimizer/loss match the completed CoMe controls: pinned +SlimPajama512x1024,524288tokens/stage,seed42,1epoch/stage,LR1e-4,WD0, +clip1,accumulation1; hiddenMSE1,MLPMSE1,attentionMSE0,KL.02/temp4; +previous-cycle teacher,BF16 model,zero-initialized additive FP32 U. +Expected FiT input SHA256: +2b2d044c8c040f67891817ecc110f0fa0de2f469db4c6731114ff7816bbf1cd0. +Expected mask SHA256: +c8e7f8e30cd532b82e6af4b98d596bc7106f29f9fb2b398b44355e624898a30d. +Native MKA selection data is intentionally separate from CoMe selection; +preserve its own saved tokens and provenance. Batch1 has512 optimizer +updates/stage, batch8 has64; later selection paths may diverge. + +Before production, validate exact seven-weight native initialization, +only3 MLP U gradients/updates, frozen merged attention/anchor norm hashes, +unchanged teacher, physical forward shapes, paired input/mask hashes, +and batch8 memory margin using64sequence probes. Reuse existing pinned +offline evaluation assets without downloading or publishing raw data. +Final metrics: packed WikiText2 PPL, full Bench12, MMLU and CMMLU separately. + +Public backup prefix: LJYAI/paper_revision/runs/ +vast-paper_revision-come-attn-fit-20261126-62646539/ +20261126-llama31-mka-mlp-batch/. +Back up only final reconstructible compact weights, metadata, raw results, +audits and code. Verify immutable file inventories and content hashes. +Move code/notes through SSH Git bundles; only local controller pushes GitHub. + +Initial SSH preflight at2026-11-26 17:04-17:06KST: existing instance reachable, +both A100-SXM4-80GB GPUs0%/0MiB with no compute processes,177GB disk free, +remote clean at695be5398afdc0af054394e225658a977186c4c1. Environment already +torch2.8.0+cu128/transformers5.15.1/datasets3.6.0/numpy2.3.2/scipy1.17.1/ +sklearn1.9.1. Current model, FiT dataset cache and all131benchmark caches +available. Model/host unchanged. Implementation/calibration audit pending; +no new MKA result is claimed at this checkpoint. + + +## Frozen inputs and runtime validation before production + +Recovered immutable native MKA100x512 calibration_ids.pt from +LJYAI/paper_revision@1bc4be66370f487b1c2ba4e7a2b4b35ae76758a3, +runs/vast-paper_revision-mka-all-small-5090x8-ca-54482709/ +20261006-mka-small-13checkpoints/llama31_base_remove8/model/. +Raw448967byte file SHA2568e893e97e0a1f277802a6993588a8fe083cdb0d7579359da789fbf8871f2d08b; +input SHA2563c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075; +mask SHA256ffe472b00e055e867ecb0129008048236f4d8f7a3730ec6fecda87fc1666dd88. +Local model vocabulary hash matches the immutable source. No resampling. + +Historical MKA+FiT was already MLP-only (all8audits attention0/MLP3/other0), +but used a different geometry token cache060a3e32a4fc62b480144f4f116345441444aec9b2a61f9d0f1b6dd7f71abaf8. +Its FiT512token/mask cache matches CoMe, but none of100same-position geometry +source documents matches the native cache. Do not attribute this difference +to a change in training scope, or reuse that model as a native-cache control. + +All23MKA/runner tests and MKA3MLP/old7-map+MLP-training equivalence, +CoMeMLP3/attention7/full9 regressions passed. Exact teacher preservation, +native projection initialization and frozen attention/norm checks passed. +The four physicalbatch1/2/4/8 probes completed without OOM. + +First selection under this host is pair21/22, lambda0.6240301169976673, +NPIB1.928525358648791. Historical native firstpair21/22 has +lambda0.6237227607228193, NPIB1.9396838291972136; maximum fullmatrix +absolute difference0.04349728115905993. Keep this difference explicitly. +Transformers4.52.1 and5.15.1 produced bitwise identical pooled feature +arrays on this A100 host (SHA2564538dbc17f803bafb0314c58928ec0ddfe99ccd81cb5d96a27cba2cdfcf48655). +Recomputing the same features with historical NumPy1.26.4/SciPy1.14.1/ +sklearn1.5.2 versus current2.3.2/1.17.1/1.9.1 produced identical matrices. +The exact historical cause was not established; cross-device BF16/SDPA +numerics are a possibility, not a verified explanation. Both source runs +use BF16 SDPA. Do not claim byte-identical historical8stage replay. + +Production gate instead requires exact agreement of the FiT selector with +an independent native MKA implementation on this host, plus the immutable +native input hash, unchanged geometry formulas and exact native merged +projection algebra. Preserve both this same-runtime check and the separate +historical mismatch audit; never force the historical coefficient/pair. +Private pooled feature arrays stay on the host and are excluded from backups. + + +## Validated production launch, 2026-11-26 17:21:33 KST + +Same-runtime independent native MKA versus FiT selector: entire32x32 NPIB +matrix max absolute difference0, exactpair21/22 and lambda0.6240301169976673. +Historical differences remain recorded separately. Sourcefea7ba11e; remote +controllerPID8826, GPU0batch1/GPU1batch8. Both production processes entered +stage1 and observed98/100% GPUutilization. Actual FiT token/mask hashes match +both each other and the completed CoMe controls exactly. No new rental, +host restart, data resampling or return. Existing rateUSD2.4137037037/hour +including allocated disk. Instance retained on explicit-user-instruction policy. + +Profile64sequence FiT seconds batch1/2/4/8:32.9771314/25.3771386/ +22.7327206/21.9561957. Batch8 peak reserved76701237248bytes of85094825984, +margin8393588736bytes (8.39GB). All4probes passed MLP3/attention0/other0, +nonzero threeU gradients and updates, native merged attention4 + anchor norm2 +exact before/after hashes. Profile memory/gates apply to the measured first +pair; production audits remain enabled at every stage. + +Exact controller command: +```bash +python scripts/launch_mka_batch_comparison.py --project /workspace/paper_revision/sessions/vast-paper_revision-come-attn-fit-20261126-62646539 --external /workspace/external/come-attn-fit --root /workspace/mka-fit-batch-20261126 --model /workspace/models/llama31-base-d04e592 --session vast-paper_revision-come-attn-fit-20261126-62646539 --selection-data /workspace/mka-fit-batch-20261126/calibration/selection.pt --selection-metadata /workspace/mka-fit-batch-20261126/calibration/selection.json --expected-selection-hash 3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075 --eval-root /workspace/come-attn-fit-20261126 --larger-batch 8 +``` +Local read-only monitor polls every300s; on completion it exits without +changing the running instance. Final full PPL/Bench12/MMLU/CMMLU and backups +are queued separately for each arm. No final quality result yet. + +## Batch8 pruning and PPL checkpoint + +Completed all8stages at2026-11-26T08:44:35Z (17:44:35KST). Pruning+FiT wall1382.1486237049103s (23m2.15s), WikiText2 PPL30.316944143609806, NLL3.411706768874581, 141sequences/288627predicted tokens. All8audits passed MLP3/attention0/other0 and six exact frozen attention/norm hashes. Final compact stage references5retained fitted layer states. Full14task evaluation active; no final accuracy claim. Batch1 training remains active; instance62646539 retained. + +## Both MKA MLP-only pruning arms completed + +Batch1 completed2026-11-26T08:55:57Z (17:55:57KST), wall2063.8316872119904s (34m23.83s), WikiText2 PPL25.82231846195682. Batch8 wall1382.1486237049103s (23m2.15s), PPL30.316944143609806. Both use141sequences/288627predictedtokens. All16production audits passed MLP3/attention0/other0 plus exact frozen mergedattention4/anchornorm2 hashes. Actual FiT input/mask hashes exactly match CoMe controls. Entire pruning+FiT wall saved681.6831s (11m21.68s,33.03%) bybatch8, with512versus64updates/stage; this excludessetup/profiling/evaluation/upload and does not establish quality equivalence. Both final Bench12/MMLU/CMMLU evaluations are active. No final accuracy claim. No instance return. diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/selection_provenance.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/selection_provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..e935b506119cf2708a25ad07f744aca53a066630 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/selection_provenance.json @@ -0,0 +1,640 @@ +{ + "input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", + "attention_mask_sha256": "ffe472b00e055e867ecb0129008048236f4d8f7a3730ec6fecda87fc1666dd88", + "sequences": 100, + "sequence_length": 512, + "seed": 0, + "source": "/workspace/mka-fit-batch-20261126/calibration/selection.pt", + "native_metadata": { + "dataset": "DKYoon/SlimPajama-6B", + "revision": "b5f90f419b7489cdba26fdbc8c022fcb5562f968", + "split": "train", + "samples": 100, + "sequence_length": 512, + "seed": 0, + "shuffle_buffer": 10000, + "add_special_tokens": false, + "sampling": "one random window per distinct document", + "input_ids_sha256": "3c44d7ad42e09c9eab2ab43ab160e823821739f682de53420a612fbe28e86075", + "records": [ + { + "stream_row": 7, + "document_sha256": "ac8f5a3f6a1b650d5f5c904320601f606c1c72b1f223d3e1769098dd14676f53", + "document_tokens": 870, + "window_start": 197 + }, + { + "stream_row": 9, + "document_sha256": "e7ebf1f41fda85fc9fe3abc20ab9b3230e7778740d71ebe744343a36118314aa", + "document_tokens": 1116, + "window_start": 430 + }, + { + "stream_row": 10, + "document_sha256": "f3a470d344261f8c757c32d506c3b5067df8fc3a91bdd92fd755526e0c1c0549", + "document_tokens": 799, + "window_start": 20 + }, + { + "stream_row": 14, + "document_sha256": "a874cf9d27742fa7a7eb51e37ac45a3246595e9984edfbadc144c8542f37cd98", + "document_tokens": 793, + "window_start": 132 + }, + { + "stream_row": 15, + "document_sha256": "39bf4b2abf97638a52ea61d8ca420e1219d0db31e682a52f5ecfb82670c8e300", + "document_tokens": 882, + "window_start": 261 + }, + { + "stream_row": 16, + "document_sha256": "9b453670291bfd6f9cced57fc1094c77caa5ca6cc370540bb242db5847c54e0d", + "document_tokens": 1410, + "window_start": 497 + }, + { + "stream_row": 18, + "document_sha256": "e085745d2b085e958c6fb0a061167c07b4a105acf2984df9000074e61a8fe431", + "document_tokens": 4728, + "window_start": 3317 + }, + { + "stream_row": 19, + "document_sha256": "61846a47c7366bc70861e4de60ef663305ecaed30363491fb755da985169bf6b", + "document_tokens": 766, + "window_start": 235 + }, + { + "stream_row": 27, + "document_sha256": "5f5f5dbea899373c49f9f7f99bec079aedb0884c7a872ec869b23d321d0b6998", + "document_tokens": 571, + "window_start": 50 + }, + { + "stream_row": 28, + "document_sha256": "ba37621eb085caf6a3d3acc584a3637ad5515ec9a9c2f186eb354fe408928600", + "document_tokens": 1810, + "window_start": 621 + }, + { + "stream_row": 29, + "document_sha256": "28e404de6977048dff9e6fdbd26104891c16e71fb0bb99cba2e22a322ef1fe1f", + "document_tokens": 1066, + "window_start": 488 + }, + { + "stream_row": 31, + "document_sha256": "9c87a61d98482a65d867adeffa221f43f82d0ccf370f36ffe545d9e7a5426e08", + "document_tokens": 930, + "window_start": 183 + }, + { + "stream_row": 32, + "document_sha256": "38caae31be8b4ae1c73a20badeead6019f84ab99e0604775ab555d1bc04bc548", + "document_tokens": 882, + "window_start": 298 + }, + { + "stream_row": 35, + "document_sha256": "17dc044eac594c2ea35e3bbb11f53b9895af962909ba2c9c29dab2a3cc90b50d", + "document_tokens": 1275, + "window_start": 223 + }, + { + "stream_row": 36, + "document_sha256": "31dd14a43e53f072ebc19f903b8a3ce00240c11a2f18cd3d37ecb3e1c2fb6f4d", + "document_tokens": 569, + "window_start": 32 + }, + { + "stream_row": 37, + "document_sha256": "7687dcdfd2228b3a40ee05588e34fe8ae32847c9f4352ba145df66ca1651f727", + "document_tokens": 6830, + "window_start": 1140 + }, + { + "stream_row": 38, + "document_sha256": "bafd2c425da5306cdcd1f6f0f98c72c056bf9f85d1ccc4041250e4d34a6c0f34", + "document_tokens": 2444, + "window_start": 577 + }, + { + "stream_row": 39, + "document_sha256": "a3b57c263d0241a65fd9801fabfa397a638b08ba5cb2404f7a012694c2941600", + "document_tokens": 518, + "window_start": 1 + }, + { + "stream_row": 41, + "document_sha256": "f3b1c751a067c70411a4505410a624ba5dea1656388f71b515ae7d3e106f41ba", + "document_tokens": 662, + "window_start": 24 + }, + { + "stream_row": 42, + "document_sha256": "7f228cc247a0e4b8419f878cd733f42f02b64c2fa579d2ed9875086168966093", + "document_tokens": 817, + "window_start": 128 + }, + { + "stream_row": 46, + "document_sha256": "de284cb2c03376538e0d8f5ef5fad5067290a3adb5c367d5ace76eda4ea1b1a0", + "document_tokens": 6302, + "window_start": 4362 + }, + { + "stream_row": 48, + "document_sha256": "d24468963a0957a4593f82d06244cc20984efd278dc1a955c9a004e1c0babe28", + "document_tokens": 591, + "window_start": 77 + }, + { + "stream_row": 51, + "document_sha256": "3f216a2a101412af8ddf477aee2e3817c8066dd800443a5f165c00fcd33c45d6", + "document_tokens": 1397, + "window_start": 150 + }, + { + "stream_row": 54, + "document_sha256": "4bea3ec348c6d9f45244f54914e9213e205e6af866955981d97ad96115ad786e", + "document_tokens": 767, + "window_start": 158 + }, + { + "stream_row": 57, + "document_sha256": "45f2e7f10bd217f4d05d713fc1a35b615dc2bc3fc8dc3c5cddb13444aa65c42e", + "document_tokens": 686, + "window_start": 25 + }, + { + "stream_row": 59, + "document_sha256": "99f31522002ab42befbe9f27c8f0fd800c737ee6a8fc5cdb92f605e64e21786e", + "document_tokens": 916, + "window_start": 373 + }, + { + "stream_row": 65, + "document_sha256": "dba1f1e2cf2f539e439afcb1887d85c1471066b6369c2e4f498a69a0e22e5f33", + "document_tokens": 617, + "window_start": 9 + }, + { + "stream_row": 68, + "document_sha256": "db7f48a6a54726f9d26c63feeabcb408811fdab46f783c71c3a119a189ce4eaa", + "document_tokens": 528, + "window_start": 10 + }, + { + "stream_row": 69, + "document_sha256": "964a9cdee6ae7edae357b5dd6e78bee0c7191015b9d2c264b0848997991bbbda", + "document_tokens": 2597, + "window_start": 1933 + }, + { + "stream_row": 72, + "document_sha256": "3363525f1892fa4c5861396ac3ff1f50cb0467ac9f62535661175f782126f2af", + "document_tokens": 1161, + "window_start": 573 + }, + { + "stream_row": 73, + "document_sha256": "6cee5651cfd4f572d4947575edf5b1c46d9eede1109803facc4d071ad5f69dd6", + "document_tokens": 709, + "window_start": 25 + }, + { + "stream_row": 75, + "document_sha256": "0742ae31108e5d9b935d774d7f279ccf8868598d730b6bbaba5d45bb645e22ed", + "document_tokens": 785, + "window_start": 181 + }, + { + "stream_row": 78, + "document_sha256": "61e6a936c26215c9299723c8bf7c153839a83ddada61eb920efc4f80158f7649", + "document_tokens": 1252, + "window_start": 444 + }, + { + "stream_row": 79, + "document_sha256": "d8782bc5106f420942824a2f496be7a8c572b4724a4b50c3136426cb27729739", + "document_tokens": 571, + "window_start": 20 + }, + { + "stream_row": 80, + "document_sha256": "a834ec2f3e3d86c0a1273ffc1e36ba4f52170c41f55e626b4523fe34fda2dded", + "document_tokens": 539, + "window_start": 19 + }, + { + "stream_row": 81, + "document_sha256": "787a6c5f80a4241a55126c45bd7eca61273e0b218d02f81af8d853e85f2ac29e", + "document_tokens": 1040, + "window_start": 209 + }, + { + "stream_row": 82, + "document_sha256": "3967691ef9bd4974968f5918fbc65346db671d66bdcc4a18c1bfbba3d7eb37d5", + "document_tokens": 943, + "window_start": 282 + }, + { + "stream_row": 83, + "document_sha256": "38b10f5054055c4c0c57fee6b480738a3492b1350622fd732d0790dcc6808e12", + "document_tokens": 538, + "window_start": 15 + }, + { + "stream_row": 84, + "document_sha256": "45a76e3f846e93b7835fbfe6221e6a9e21c28aaa1c94d0ca78117ac522deeafc", + "document_tokens": 2923, + "window_start": 1813 + }, + { + "stream_row": 86, + "document_sha256": "2ed365b0740b4c5f9baad5437d467ebe69eb824d0c6a8edc56e2a9e970317e1d", + "document_tokens": 1607, + "window_start": 1067 + }, + { + "stream_row": 87, + "document_sha256": "4bdf800f977234dea28671a9d23768fa30f66532f1600761e64ee90c86fd53a9", + "document_tokens": 1485, + "window_start": 266 + }, + { + "stream_row": 92, + "document_sha256": "eb93106c54737f50d673c29edf656f5178af3dbf413eb79dfa3f61c6f710a069", + "document_tokens": 1179, + "window_start": 63 + }, + { + "stream_row": 93, + "document_sha256": "3120d36379b208a8e4eaa02e3fd5015e9d958b7ed2ae6dba0221d3e88c2c7d7f", + "document_tokens": 513, + "window_start": 0 + }, + { + "stream_row": 95, + "document_sha256": "3e5db6ad1c2841d479024cd9b2a8b38ea93d3830915ab63a8436ffee00f139e0", + "document_tokens": 947, + "window_start": 47 + }, + { + "stream_row": 96, + "document_sha256": "221cccbf757dfeb0e3d0cc40110f75bbbc780ec0b9d206d3c1e1ca3813153bad", + "document_tokens": 714, + "window_start": 184 + }, + { + "stream_row": 99, + "document_sha256": "0c1ca5bf83aad68526b3d13a9e434a47bc4bf27e6b87a3bd5d082c3aee5a6c62", + "document_tokens": 894, + "window_start": 204 + }, + { + "stream_row": 100, + "document_sha256": "1bbc555069faa98706d13743ae017f19af8fc33043d8f4e62f1d855cf7bc79b7", + "document_tokens": 3306, + "window_start": 2736 + }, + { + "stream_row": 101, + "document_sha256": "83c257e5bc7f875f867c7fecb5e009bb02ef07755dce732253204347b6d34279", + "document_tokens": 1116, + "window_start": 1 + }, + { + "stream_row": 104, + "document_sha256": "18bae193a83cd9726ac9acf57ba8bdac90ea88d7d9bb6c3828cd9a806eb454cc", + "document_tokens": 1508, + "window_start": 626 + }, + { + "stream_row": 107, + "document_sha256": "8f76fb28b427752f0c9332c80680a860dee9d173d44cede21dfced6b4779e62d", + "document_tokens": 513, + "window_start": 1 + }, + { + "stream_row": 109, + "document_sha256": "c18430c70e629666b90bb2ef5bdd4ace00e2ed3b7ea0d8435e449ba56a25a373", + "document_tokens": 736, + "window_start": 211 + }, + { + "stream_row": 111, + "document_sha256": "200ec00054fefaae120ef97dbfbe549a22f4fbaa61ffdc968629acc3e3be8f24", + "document_tokens": 533, + "window_start": 10 + }, + { + "stream_row": 112, + "document_sha256": "761ec6fa54a210354cf704d0b57856957bfce1fb4a773121bc86c1c4b96d8b5b", + "document_tokens": 1464, + "window_start": 249 + }, + { + "stream_row": 114, + "document_sha256": "a7bec15db4d041cb3f705633b46a3563ccd59dd8f483ca3da19d52f2b812912e", + "document_tokens": 2706, + "window_start": 1332 + }, + { + "stream_row": 116, + "document_sha256": "dd0b8b22dada2f6d54f8cec7c4f7cec0626601e4102d4ab228c230fada5c1a8b", + "document_tokens": 1503, + "window_start": 720 + }, + { + "stream_row": 117, + "document_sha256": "b3f79c4a4087cc2a02ed5932cf7065e0d5e05430ff423ad20226695f20f463e7", + "document_tokens": 1157, + "window_start": 64 + }, + { + "stream_row": 122, + "document_sha256": "e254a6211037dd8ddc5b0cf1e0af8c1714f59f3faf6d55a5a4e670e4d53af90d", + "document_tokens": 1092, + "window_start": 195 + }, + { + "stream_row": 123, + "document_sha256": "cc1f8ed0ef69b4ec8fcd16d3bd51627f650b2350fb22a9bb49e6c4ff76589e44", + "document_tokens": 956, + "window_start": 290 + }, + { + "stream_row": 133, + "document_sha256": "c2d6e5e101653b8924ec02b7c8cd08df0fb7364ce23aac8279a537d0df9c30c3", + "document_tokens": 973, + "window_start": 113 + }, + { + "stream_row": 134, + "document_sha256": "fe588286dc9e9f94c84e85bed56b884593ab4e95006f1df1b80156e7896119b4", + "document_tokens": 4799, + "window_start": 1954 + }, + { + "stream_row": 136, + "document_sha256": "ef5743d7bf8b263b2b779577ee4868a1eba7029b3d8cb8e88c9dbc8309f1102f", + "document_tokens": 606, + "window_start": 18 + }, + { + "stream_row": 138, + "document_sha256": "8c204bb1fad0ecbc9af02f979558112a36919e9c445067473a2a80b905dd826b", + "document_tokens": 578, + "window_start": 57 + }, + { + "stream_row": 142, + "document_sha256": "d2300adfc617626fd5c6002c103a9e66fe1b97a06a6eac3bc77e52586a1ffc7c", + "document_tokens": 1001, + "window_start": 46 + }, + { + "stream_row": 143, + "document_sha256": "50fb87425312b4c122ff4fba823fe633affb9d71079df249d972be02aa224595", + "document_tokens": 970, + "window_start": 41 + }, + { + "stream_row": 145, + "document_sha256": "09ff974ba31eb969eec8386b34b141b57dbe1734534440ac0ba2abb863a4653c", + "document_tokens": 956, + "window_start": 163 + }, + { + "stream_row": 147, + "document_sha256": "810c56f4f2963a75381eb74236c11b72c5af6a450f0c822df24c5b28e712d0ed", + "document_tokens": 1437, + "window_start": 896 + }, + { + "stream_row": 148, + "document_sha256": "fe6318e204bf58d9b05ee4b791790aad966a51589a33d45859f63c1da11d5289", + "document_tokens": 551, + "window_start": 32 + }, + { + "stream_row": 149, + "document_sha256": "6b6881ed8c9cff458b1713575025d93557c7a848eeaaaaefd214c897c0b832ab", + "document_tokens": 1005, + "window_start": 477 + }, + { + "stream_row": 152, + "document_sha256": "47a668a81190f31ddf4d032bd43ae313351da66c7f8f702704a2baa9c46e4ad4", + "document_tokens": 531, + "window_start": 15 + }, + { + "stream_row": 154, + "document_sha256": "710b8937ad9077d5adba175c809252ac4baa7ca3bd1cc4226974577a4eacc5db", + "document_tokens": 789, + "window_start": 55 + }, + { + "stream_row": 155, + "document_sha256": "d9b32336230adab9d6152902ce065f56a32258c16984905acea5d8f870152efd", + "document_tokens": 553, + "window_start": 19 + }, + { + "stream_row": 156, + "document_sha256": "f53168b17d15cd4bb8919f334b5d9506207fb6d8a8a7580517e67399208c78be", + "document_tokens": 1908, + "window_start": 1128 + }, + { + "stream_row": 161, + "document_sha256": "b9cbc598151fe111acfd40ed8f2f2ec1be56ed64d74676b46b75d2c6d758269b", + "document_tokens": 842, + "window_start": 149 + }, + { + "stream_row": 162, + "document_sha256": "4b1d0ea5f0c919705d9738680a8ac4b4e4838f5cc6d456180fd091e66d152ec6", + "document_tokens": 849, + "window_start": 63 + }, + { + "stream_row": 164, + "document_sha256": "92825ee82231a7f7fa657e099045a3358d50318a0f3be57a80c406479c7ed718", + "document_tokens": 540, + "window_start": 17 + }, + { + "stream_row": 166, + "document_sha256": "763f108003221c14e9453aa571fa06e781de5ed014966d885a34070591a3f95e", + "document_tokens": 558, + "window_start": 21 + }, + { + "stream_row": 167, + "document_sha256": "41a85298c65411bd707b1334c5640ce1baa45351bf61dadc8e48c367196602ff", + "document_tokens": 515, + "window_start": 1 + }, + { + "stream_row": 169, + "document_sha256": "f005fdb48a62cd9721e7bf75e3d2063e6b1b94fa91b2eb98d066f4314c3584dc", + "document_tokens": 1028, + "window_start": 294 + }, + { + "stream_row": 170, + "document_sha256": "25fbbd49d00fc724ce7aa37c66dc7049b3623232e2aca591cfa1d6738fc5eb7a", + "document_tokens": 3267, + "window_start": 1822 + }, + { + "stream_row": 174, + "document_sha256": "350d16bb5744818cf0b571daad84f28952520db6ba912332facfd386e4b55797", + "document_tokens": 603, + "window_start": 11 + }, + { + "stream_row": 180, + "document_sha256": "76a7817b5df2ba303bd9f267b17f13d536cd70486cc2749a2d2ea3c047ef23d7", + "document_tokens": 1453, + "window_start": 610 + }, + { + "stream_row": 183, + "document_sha256": "5eea333eff35ef9159959130f6324bc4fc48c79653eef0ea2e7ae327c4953e2d", + "document_tokens": 652, + "window_start": 98 + }, + { + "stream_row": 184, + "document_sha256": "f70e79851a29ebaa170c88a406a1ae66b54f9fdd908240e66422a98236acfee0", + "document_tokens": 685, + "window_start": 81 + }, + { + "stream_row": 185, + "document_sha256": "894ee1d6c5c54fc87fd055f03db0e70b0e3ea992739a224559bca00352990522", + "document_tokens": 539, + "window_start": 18 + }, + { + "stream_row": 186, + "document_sha256": "ef035a5d5ac9731a04a871afe15ca61c46494558183c325148ed61de861eecca", + "document_tokens": 1506, + "window_start": 247 + }, + { + "stream_row": 194, + "document_sha256": "df983f275b9d6849f99e17382a1155ce8cdeb1373cf1ada1812153abc4f37513", + "document_tokens": 3071, + "window_start": 1189 + }, + { + "stream_row": 195, + "document_sha256": "482a63cc59d885c8e12220a545622adb1e220fe22aad3fbff061f35332183802", + "document_tokens": 738, + "window_start": 47 + }, + { + "stream_row": 197, + "document_sha256": "828d8df579d793b76867d769eec0786a277f0f0ba7b89d23c3d908b64a72fd6c", + "document_tokens": 6550, + "window_start": 1551 + }, + { + "stream_row": 198, + "document_sha256": "201105829879f989134e803f9ab7f1c7ef420ff6162005c95425a8e948dfec1a", + "document_tokens": 884, + "window_start": 95 + }, + { + "stream_row": 199, + "document_sha256": "123a4795b17fbaed2dde8918120bac5670f328b944863436f2ff29baf9114e44", + "document_tokens": 713, + "window_start": 8 + }, + { + "stream_row": 201, + "document_sha256": "a60c9991d65750a9de7fafca0720902a94359d160d48a35fc6f0e647d35ffce7", + "document_tokens": 718, + "window_start": 156 + }, + { + "stream_row": 203, + "document_sha256": "eebaa4e728a24c68cc584b4c82dd5cd8b8781e7dc6c2410ba8b0dd6c6a7e6ca8", + "document_tokens": 1055, + "window_start": 266 + }, + { + "stream_row": 211, + "document_sha256": "ee8a9c62150dd3921f428e93cb8fae6c244116b170c5acdb0c0e518305af61d3", + "document_tokens": 797, + "window_start": 243 + }, + { + "stream_row": 212, + "document_sha256": "2eda120c7738f2619b9101f61d7f72b3ec913075c0d96a854a9bf6b8b19bd820", + "document_tokens": 525, + "window_start": 1 + }, + { + "stream_row": 216, + "document_sha256": "995e06891a0dafef53cd75bdc365612ed91e9274cd6129576bb184f83b8a6c62", + "document_tokens": 853, + "window_start": 45 + }, + { + "stream_row": 217, + "document_sha256": "c5d55d18293389ea70f9528071a82fbdaf4890e1fea8a5901a98d7d4ab109ce2", + "document_tokens": 638, + "window_start": 86 + }, + { + "stream_row": 221, + "document_sha256": "5e7b9074e4d8ed846a796c32dcb97b509de1493492bef5bd626510460ce986d1", + "document_tokens": 766, + "window_start": 193 + }, + { + "stream_row": 228, + "document_sha256": "83718c91cb73096a48a712c05b0cf2e9e263e9969ebffb76cfcc92fafc812575", + "document_tokens": 992, + "window_start": 66 + }, + { + "stream_row": 230, + "document_sha256": "fbf88a5484bddd53b1096cda09692af34716716daad60a37071985230751123b", + "document_tokens": 522, + "window_start": 2 + }, + { + "stream_row": 231, + "document_sha256": "4eef10bef73b72af338e1c8d6184b4d8d0b173225e76c77bd2e0f294e4278602", + "document_tokens": 563, + "window_start": 2 + } + ], + "tokenizer": "meta-llama/Llama-3.1-8B", + "tokenizer_revision": "d04e592bb4f6aa9cfee91e2e20afa771667e1d4b", + "tokenizer_vocab_sha256": "869dd26a7a4c36e0324cb1011416f764302d33093f5c0f5c06d6615cc017010f", + "source": { + "repo_id": "LJYAI/paper_revision", + "revision": "1bc4be66370f487b1c2ba4e7a2b4b35ae76758a3", + "path_in_repo": "runs/vast-paper_revision-mka-all-small-5090x8-ca-54482709/20261006-mka-small-13checkpoints/llama31_base_remove8/model/calibration_ids.pt", + "local_path": "/workspace/mka-fit-batch-20261126/calibration/calibration_ids.pt", + "file_sha256": "8e893e97e0a1f277802a6993588a8fe083cdb0d7579359da789fbf8871f2d08b" + }, + "attention_mask_sha256": "ffe472b00e055e867ecb0129008048236f4d8f7a3730ec6fecda87fc1666dd88", + "sequences": 100, + "batch_size": 1, + "selection_file_sha256": "1488cf0291df7c90e92102855cc3c6a7fa2176aa6cef640ace02aefde0b4238f", + "local_tokenizer_vocabulary_verified": true, + "resampled": false, + "validation": "Immutable source file, tokenizer metadata, all native token IDs and masks verified" + }, + "independent_of_fit_loader": true +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_1/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_1/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..69fc5b5ba865842c647e278ccc94c999f7a5b177 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_1/cycle_metadata.json @@ -0,0 +1,456 @@ +{ + "cycle": 1, + "layer_merged": 21, + "num_layers_before": 32, + "num_layers_after": 31, + "fused_layer_state": "fused_layer.pt", + "profile_no_save": false, + "dwce_score": null, + "dwce_scores": null, + "dwce_meta": { + "method": "mka", + "fisher_computed": false + }, + "fisher_num_batches": 0, + "merge_method": "reparam", + "merged_params": 3, + "num_sequences": 64, + "teacher_source": "base_model", + "teacher_cycle": 0, + "eval": { + "datasets": [ + "wikitext2" + ], + "configs": [ + null + ], + "split": "test", + "num_samples": 0, + "seq_len": 1024, + "post_ppl": null, + "merge_only_ppl": null + }, + "comm": { + "enabled": false + }, + "distill": { + "enabled": true, + "method": "reparam", + "calib_samples": 256, + "inst_samples": 0, + "seq_len": 1024, + "batch_size": 8, + "epochs": 1.0, + "lr": 0.0001, + "kl_weight": 0.02, + "kl_temp": 4.0, + "kl_chunk_size": 16384, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "reparam_eta": 0.0, + "reparam_gamma": 0.0, + "reparam_attn_reg_scale": 1.0, + "reparam_mlp_reg_scale": 1.0, + "reparam_param_subset": "mlp", + "reparam_train_subset": "mlp", + "reparam_skip_train": false, + "reparam_stats": { + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6240300536155701, + "std": 0.0, + "min": 0.6240300536155701, + "max": 0.6240300536155701, + "mean_abs_from_0_5": 0.12403005361557007, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6240300536155701, + "std": 0.0, + "min": 0.6240300536155701, + "max": 0.6240300536155701, + "mean_abs_from_0_5": 0.12403005361557007 + }, + "mlp.up_proj.weight": { + "mean": 0.6240300536155701, + "std": 0.0, + "min": 0.6240300536155701, + "max": 0.6240300536155701, + "mean_abs_from_0_5": 0.12403005361557007 + }, + "mlp.down_proj.weight": { + "mean": 0.6240300536155701, + "std": 0.0, + "min": 0.6240300536155701, + "max": 0.6240300536155701, + "mean_abs_from_0_5": 0.12403005361557007 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6240301132202148, + "std": 0.00011399101194493286, + "min": 0.6240301132202148, + "max": 0.6240301132202148, + "mean_abs_from_0_5": 0.12403011322021484, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6240301132202148, + "std": 0.00011399101194493286, + "min": 0.6240301132202148, + "max": 0.6240301132202148, + "mean_abs_from_0_5": 0.12403011322021484 + }, + "mlp.up_proj.weight": { + "mean": 0.6240301132202148, + "std": 0.00011399101194493286, + "min": 0.6240301132202148, + "max": 0.6240301132202148, + "mean_abs_from_0_5": 0.12403011322021484 + }, + "mlp.down_proj.weight": { + "mean": 0.6240301132202148, + "std": 0.00011399101194493286, + "min": 0.6240301132202148, + "max": 0.6240301132202148, + "mean_abs_from_0_5": 0.12403011322021484 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.028465702459520677, + "mean_abs": 1.2423996893284355e-06, + "max_abs": 0.00069427490234375 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": 2.854910684661826e-06, + "std": 0.0009041833972203849, + "rms": 0.0009041879043229973, + "mean_abs": 0.0007286663610665571, + "min": -0.006496109068393707, + "max": 0.006071228068321943, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 8.477651655474411e-06, + "std": 0.0009155867578784959, + "rms": 0.0009156260054083475, + "mean_abs": 0.000737509091517755, + "min": -0.00588262639939785, + "max": 0.006071228068321943 + }, + "mlp.up_proj.weight": { + "mean": 1.699711284735323e-07, + "std": 0.0008917679378926515, + "rms": 0.000891767954090915, + "mean_abs": 0.0007192332829747881, + "min": -0.00567873427644372, + "max": 0.0057873912155628204 + }, + "mlp.down_proj.weight": { + "mean": -8.289072996246563e-08, + "std": 0.0009050117272044737, + "rms": 0.000905011731000487, + "mean_abs": 0.0007292567087071282, + "min": -0.006496109068393707, + "max": 0.0059011755511164665 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 173.79743414744735, + "dataset_tokens": 524288, + "tokens_per_second": 3016.6613366409156, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 64399123456, + "peak_reserved_bytes": 76701237248, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6240301169976673, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "4a1304ccf61920a97636331ade2fa8e57952e2592a59a3923abf20b5a1575c49", + "self_attn.k_proj.weight": "6710bf5362c49a99451481e33e0b3ce5e9cd9181d086d75a866e7f16b338c1e3", + "self_attn.v_proj.weight": "30b51dc5274bf74b3e6d4820f1b58e4aa9e2fe144a998c9fb9a5326d746d4e2f", + "self_attn.o_proj.weight": "d438bc8a8906f12fc134841c45241cf5847136143ba1f871b06c29b6eead7d34", + "input_layernorm.weight": "f856da6761e60707e41aac347e76b1e89f061b141683614d6d181ca7940c638c", + "post_attention_layernorm.weight": "392084c4b287c1be3dc86b898f84579f8145d981ccc71d02c85ae14a40da0e3f" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "4a1304ccf61920a97636331ade2fa8e57952e2592a59a3923abf20b5a1575c49", + "self_attn.k_proj.weight": "6710bf5362c49a99451481e33e0b3ce5e9cd9181d086d75a866e7f16b338c1e3", + "self_attn.v_proj.weight": "30b51dc5274bf74b3e6d4820f1b58e4aa9e2fe144a998c9fb9a5326d746d4e2f", + "self_attn.o_proj.weight": "d438bc8a8906f12fc134841c45241cf5847136143ba1f871b06c29b6eead7d34", + "input_layernorm.weight": "f856da6761e60707e41aac347e76b1e89f061b141683614d6d181ca7940c638c", + "post_attention_layernorm.weight": "392084c4b287c1be3dc86b898f84579f8145d981ccc71d02c85ae14a40da0e3f" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "4a1304ccf61920a97636331ade2fa8e57952e2592a59a3923abf20b5a1575c49", + "self_attn.k_proj.weight": "6710bf5362c49a99451481e33e0b3ce5e9cd9181d086d75a866e7f16b338c1e3", + "self_attn.v_proj.weight": "30b51dc5274bf74b3e6d4820f1b58e4aa9e2fe144a998c9fb9a5326d746d4e2f", + "self_attn.o_proj.weight": "d438bc8a8906f12fc134841c45241cf5847136143ba1f871b06c29b6eead7d34", + "input_layernorm.weight": "f856da6761e60707e41aac347e76b1e89f061b141683614d6d181ca7940c638c", + "post_attention_layernorm.weight": "392084c4b287c1be3dc86b898f84579f8145d981ccc71d02c85ae14a40da0e3f" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 22, + "teacher_boundary_original_layer": 22 + }, + "lambda_init": "mka", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "mka", + "prior_mean": 0.6240301169976673 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 0.6240301132202148, + "per_tensor_mean": { + "mlp.gate_proj.weight": 0.6240301132202148, + "mlp.up_proj.weight": 0.6240301132202148, + "mlp.down_proj.weight": 0.6240301132202148 + } + }, + "post_merge_nll_scale": null, + "merge_only_ppl": null, + "post_ppl": null, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "instruction_dataset": null, + "instruction_config": null, + "instruction_split": "train" + }, + "lora": { + "enabled": false, + "seq_len": 1024, + "batch_size": 8, + "epochs": 0.0, + "rank": 8, + "alpha": 16.0, + "dropout": 0.0, + "target_modules": [ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "down_proj", + "up_proj" + ], + "respect_exclude_pairs": false, + "kl_enabled": false, + "kl_weight": 0.1, + "kl_temp": 4.0, + "post_ppl": null, + "lr": 0.0001, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "log_steps": 100, + "eval_every": 0, + "eval_max_batches": null + }, + "norm_policy": "hybrid", + "source_feature_transport": null, + "same_anchor_contextual_fisher": { + "computed": false + }, + "full_model_saved": false, + "timing": { + "seconds": { + "selection": 10.747124980203807, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 4.064105451107025e-05, + "fit": 176.81124537065625, + "materialize_save_layer": 0.4729745336808264, + "metadata_write": 0.0008825138211250305, + "teacher_snapshot": 0.21684124413877726, + "cycle_cleanup": 0.1472184592857957, + "cycle_total": 188.39690309483558 + }, + "tracked_component_total_seconds": 188.3963277428411, + "cycle_total_seconds": 188.39690309483558, + "ratios_of_tracked_components": { + "selection": 0.05704529970920407, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 2.157210546404325e-07, + "fit": 0.938506856736622, + "materialize_save_layer": 0.002510529474472727, + "metadata_write": 4.684347257180364e-06, + "teacher_snapshot": 0.0011509844524929549, + "cycle_cleanup": 0.0007814295588964306 + }, + "ratios_of_cycle_total": { + "selection": 0.05704512549653696, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 2.15720395842241e-07, + "fit": 0.9385039905971951, + "materialize_save_layer": 0.002510521807477587, + "metadata_write": 4.68433295148588e-06, + "teacher_snapshot": 0.0011509809374606508, + "cycle_cleanup": 0.0007814271724609432 + } + }, + "recipient_original_layer": 21, + "removed_original_layer": 22, + "recipient_side": "left", + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31 + ], + "fisher_computed": false, + "merge_initializer": "mka", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 22 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_2/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_2/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..45f41343af9adf2c84e9707746bf55653f695131 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_2/cycle_metadata.json @@ -0,0 +1,455 @@ +{ + "cycle": 2, + "layer_merged": 18, + "num_layers_before": 31, + "num_layers_after": 30, + "fused_layer_state": "fused_layer.pt", + "profile_no_save": false, + "dwce_score": null, + "dwce_scores": null, + "dwce_meta": { + "method": "mka", + "fisher_computed": false + }, + "fisher_num_batches": 0, + "merge_method": "reparam", + "merged_params": 3, + "num_sequences": 64, + "teacher_source": "previous_cycle_memory", + "teacher_cycle": 1, + "eval": { + "datasets": [ + "wikitext2" + ], + "configs": [ + null + ], + "split": "test", + "num_samples": 0, + "seq_len": 1024, + "post_ppl": null, + "merge_only_ppl": null + }, + "comm": { + "enabled": false + }, + "distill": { + "enabled": true, + "method": "reparam", + "calib_samples": 256, + "inst_samples": 0, + "seq_len": 1024, + "batch_size": 8, + "epochs": 1.0, + "lr": 0.0001, + "kl_weight": 0.02, + "kl_temp": 4.0, + "kl_chunk_size": 16384, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "reparam_eta": 0.0, + "reparam_gamma": 0.0, + "reparam_attn_reg_scale": 1.0, + "reparam_mlp_reg_scale": 1.0, + "reparam_param_subset": "mlp", + "reparam_train_subset": "mlp", + "reparam_skip_train": false, + "reparam_stats": { + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6243720054626465, + "std": 0.0, + "min": 0.6243720054626465, + "max": 0.6243720054626465, + "mean_abs_from_0_5": 0.12437200546264648, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6243720054626465, + "std": 0.0, + "min": 0.6243720054626465, + "max": 0.6243720054626465, + "mean_abs_from_0_5": 0.12437200546264648 + }, + "mlp.up_proj.weight": { + "mean": 0.6243720054626465, + "std": 0.0, + "min": 0.6243720054626465, + "max": 0.6243720054626465, + "mean_abs_from_0_5": 0.12437200546264648 + }, + "mlp.down_proj.weight": { + "mean": 0.6243720054626465, + "std": 0.0, + "min": 0.6243720054626465, + "max": 0.6243720054626465, + "mean_abs_from_0_5": 0.12437200546264648 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6243720650672913, + "std": 8.960509203140518e-05, + "min": 0.6243720650672913, + "max": 0.6243720650672913, + "mean_abs_from_0_5": 0.12437206506729126, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6243720650672913, + "std": 8.960509203140518e-05, + "min": 0.6243720650672913, + "max": 0.6243720650672913, + "mean_abs_from_0_5": 0.12437206506729126 + }, + "mlp.up_proj.weight": { + "mean": 0.6243720650672913, + "std": 8.960509203140518e-05, + "min": 0.6243720650672913, + "max": 0.6243720650672913, + "mean_abs_from_0_5": 0.12437206506729126 + }, + "mlp.down_proj.weight": { + "mean": 0.6243720650672913, + "std": 8.960509203140518e-05, + "min": 0.6243720650672913, + "max": 0.6243720650672913, + "mean_abs_from_0_5": 0.12437206506729126 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.015569758067493491, + "mean_abs": 4.0223484834963787e-07, + "max_abs": 0.0023882389068603516 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": 4.247186996595008e-07, + "std": 0.0008837740109772068, + "rms": 0.0008837741130315563, + "mean_abs": 0.0007097784296742507, + "min": -0.006343320943415165, + "max": 0.00642724335193634, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.45962336059061e-06, + "std": 0.0009102086850955709, + "rms": 0.0009102098554310225, + "mean_abs": 0.0007322642819157668, + "min": -0.006002224050462246, + "max": 0.0061955866403877735 + }, + "mlp.up_proj.weight": { + "mean": -2.081775554480763e-07, + "std": 0.000854396591693673, + "rms": 0.0008543966170553695, + "mean_abs": 0.000685555993446282, + "min": -0.005236032418906689, + "max": 0.005667621269822121 + }, + "mlp.down_proj.weight": { + "mean": 2.2710293835968643e-08, + "std": 0.0008858298301135282, + "rms": 0.0008858298304046437, + "mean_abs": 0.0007115150136607033, + "min": -0.006343320943415165, + "max": 0.00642724335193634 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 168.2695588967763, + "dataset_tokens": 524288, + "tokens_per_second": 3115.7626099300624, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 65810608640, + "peak_reserved_bytes": 80729866240, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6243720763232038, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "6ea5e8782ac8684cc9bd9908f56e75b8947761a05a07420b37900ebba9bbbd06", + "self_attn.k_proj.weight": "915f27233c34e236f5bc3876c4e58174724759412dae919fffe0b0df7317bc47", + "self_attn.v_proj.weight": "2ffe3627c44e10d14be66a5ab2c7546c7173a8d4aa07788f1c2aafab18e8f7af", + "self_attn.o_proj.weight": "d9f7a05b16eea939da003c3fc5f8bd01175179a04eea9d49aeaa2686c3a00386", + "input_layernorm.weight": "2e51ae768cf6bf12d1903474b16741c383154686c8da264bfb44713bacaa0621", + "post_attention_layernorm.weight": "b3191d2dd3776ffff6f3dc74aebe2ddd40c82210ceba22c221eff83b1aeb1f95" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "6ea5e8782ac8684cc9bd9908f56e75b8947761a05a07420b37900ebba9bbbd06", + "self_attn.k_proj.weight": "915f27233c34e236f5bc3876c4e58174724759412dae919fffe0b0df7317bc47", + "self_attn.v_proj.weight": "2ffe3627c44e10d14be66a5ab2c7546c7173a8d4aa07788f1c2aafab18e8f7af", + "self_attn.o_proj.weight": "d9f7a05b16eea939da003c3fc5f8bd01175179a04eea9d49aeaa2686c3a00386", + "input_layernorm.weight": "2e51ae768cf6bf12d1903474b16741c383154686c8da264bfb44713bacaa0621", + "post_attention_layernorm.weight": "b3191d2dd3776ffff6f3dc74aebe2ddd40c82210ceba22c221eff83b1aeb1f95" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "6ea5e8782ac8684cc9bd9908f56e75b8947761a05a07420b37900ebba9bbbd06", + "self_attn.k_proj.weight": "915f27233c34e236f5bc3876c4e58174724759412dae919fffe0b0df7317bc47", + "self_attn.v_proj.weight": "2ffe3627c44e10d14be66a5ab2c7546c7173a8d4aa07788f1c2aafab18e8f7af", + "self_attn.o_proj.weight": "d9f7a05b16eea939da003c3fc5f8bd01175179a04eea9d49aeaa2686c3a00386", + "input_layernorm.weight": "2e51ae768cf6bf12d1903474b16741c383154686c8da264bfb44713bacaa0621", + "post_attention_layernorm.weight": "b3191d2dd3776ffff6f3dc74aebe2ddd40c82210ceba22c221eff83b1aeb1f95" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 19, + "teacher_boundary_original_layer": 19 + }, + "lambda_init": "mka", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "mka", + "prior_mean": 0.6243720763232038 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 0.6243720650672913, + "per_tensor_mean": { + "mlp.gate_proj.weight": 0.6243720650672913, + "mlp.up_proj.weight": 0.6243720650672913, + "mlp.down_proj.weight": 0.6243720650672913 + } + }, + "post_merge_nll_scale": null, + "merge_only_ppl": null, + "post_ppl": null, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "instruction_dataset": null, + "instruction_config": null, + "instruction_split": "train" + }, + "lora": { + "enabled": false, + "seq_len": 1024, + "batch_size": 8, + "epochs": 0.0, + "rank": 8, + "alpha": 16.0, + "dropout": 0.0, + "target_modules": [ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "down_proj", + "up_proj" + ], + "respect_exclude_pairs": false, + "kl_enabled": false, + "kl_weight": 0.1, + "kl_temp": 4.0, + "post_ppl": null, + "lr": 0.0001, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "log_steps": 100, + "eval_every": 0, + "eval_max_batches": null + }, + "norm_policy": "hybrid", + "source_feature_transport": null, + "same_anchor_contextual_fisher": { + "computed": false + }, + "full_model_saved": false, + "timing": { + "seconds": { + "selection": 9.864483243320137, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 3.661308437585831e-05, + "fit": 168.417955101002, + "materialize_save_layer": 0.488308307249099, + "metadata_write": 0.0008948273025453091, + "teacher_snapshot": 0.3665897366590798, + "cycle_cleanup": 0.13982499111443758, + "cycle_total": 179.27874472085387 + }, + "tracked_component_total_seconds": 179.27809281973168, + "cycle_total_seconds": 179.27874472085387, + "ratios_of_tracked_components": { + "selection": 0.055023361126666524, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 2.0422508852028908e-07, + "fit": 0.9394229515278825, + "materialize_save_layer": 0.0027237477796024103, + "metadata_write": 4.991280799964103e-06, + "teacher_snapshot": 0.0020448105560097315, + "cycle_cleanup": 0.0007799335039503955 + }, + "ratios_of_cycle_total": { + "selection": 0.05502316104834201, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 2.042243459081931e-07, + "fit": 0.9394195355575327, + "materialize_save_layer": 0.0027237378753929803, + "metadata_write": 4.9912626504530735e-06, + "teacher_snapshot": 0.002044803120581186, + "cycle_cleanup": 0.0007799306679224702 + } + }, + "recipient_original_layer": 18, + "removed_original_layer": 19, + "recipient_side": "left", + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 20, + 21, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31 + ], + "fisher_computed": false, + "merge_initializer": "mka", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 19 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_3/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_3/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..0f73a09226534abd7df4ab11c998dc3a9f359fc2 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_3/cycle_metadata.json @@ -0,0 +1,454 @@ +{ + "cycle": 3, + "layer_merged": 21, + "num_layers_before": 30, + "num_layers_after": 29, + "fused_layer_state": "fused_layer.pt", + "profile_no_save": false, + "dwce_score": null, + "dwce_scores": null, + "dwce_meta": { + "method": "mka", + "fisher_computed": false + }, + "fisher_num_batches": 0, + "merge_method": "reparam", + "merged_params": 3, + "num_sequences": 64, + "teacher_source": "previous_cycle_memory", + "teacher_cycle": 2, + "eval": { + "datasets": [ + "wikitext2" + ], + "configs": [ + null + ], + "split": "test", + "num_samples": 0, + "seq_len": 1024, + "post_ppl": null, + "merge_only_ppl": null + }, + "comm": { + "enabled": false + }, + "distill": { + "enabled": true, + "method": "reparam", + "calib_samples": 256, + "inst_samples": 0, + "seq_len": 1024, + "batch_size": 8, + "epochs": 1.0, + "lr": 0.0001, + "kl_weight": 0.02, + "kl_temp": 4.0, + "kl_chunk_size": 16384, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "reparam_eta": 0.0, + "reparam_gamma": 0.0, + "reparam_attn_reg_scale": 1.0, + "reparam_mlp_reg_scale": 1.0, + "reparam_param_subset": "mlp", + "reparam_train_subset": "mlp", + "reparam_skip_train": false, + "reparam_stats": { + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145 + }, + "mlp.up_proj.weight": { + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145 + }, + "mlp.down_proj.weight": { + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145 + }, + "mlp.up_proj.weight": { + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145 + }, + "mlp.down_proj.weight": { + "mean": 0.6243202686309814, + "std": 0.0001216652134970651, + "min": 0.6243202686309814, + "max": 0.6243202686309814, + "mean_abs_from_0_5": 0.12432026863098145 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.030293374457000595, + "mean_abs": 7.845224315263164e-07, + "max_abs": 0.0031156539916992188 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": 1.8650639470067853e-06, + "std": 0.0007761889496868795, + "rms": 0.0007761911904160905, + "mean_abs": 0.0006255472877195903, + "min": -0.006375117227435112, + "max": 0.006123701576143503, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 5.739701529299575e-06, + "std": 0.0007743511574451851, + "rms": 0.0007743724292679481, + "mean_abs": 0.0006252706183918885, + "min": -0.005891299806535244, + "max": 0.005949811544269323 + }, + "mlp.up_proj.weight": { + "mean": 3.181370849298608e-08, + "std": 0.0007656183632133441, + "rms": 0.000765618363874321, + "mean_abs": 0.000617578426109893, + "min": -0.006375117227435112, + "max": 0.005850381217896938 + }, + "mlp.down_proj.weight": { + "mean": -1.7632339677220443e-07, + "std": 0.0007884124065720728, + "rms": 0.0007884124262888732, + "mean_abs": 0.0006337928186569895, + "min": -0.00629733270034194, + "max": 0.006123701576143503 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 166.4453473757021, + "dataset_tokens": 524288, + "tokens_per_second": 3149.9108161706185, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 60370297344, + "peak_reserved_bytes": 83724599296, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6243202778643895, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "15ddc12b47e73aac3a13f47c90907b9b3ad9d2c2f3b6d92d18150d67a1177b91", + "self_attn.k_proj.weight": "25df896e1d40135244874d105e9d045ad3f36869bad85dac0c3fd644dac8e15d", + "self_attn.v_proj.weight": "8c132171150a34123ce0fe518880c3cbdf0ef21f50997cece69eccc1e61f9856", + "self_attn.o_proj.weight": "fc2860fcbdf78eec3494d3529ad628872ad3c6de62ed63c9c6a3f1d6f1a6d55a", + "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7", + "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "15ddc12b47e73aac3a13f47c90907b9b3ad9d2c2f3b6d92d18150d67a1177b91", + "self_attn.k_proj.weight": "25df896e1d40135244874d105e9d045ad3f36869bad85dac0c3fd644dac8e15d", + "self_attn.v_proj.weight": "8c132171150a34123ce0fe518880c3cbdf0ef21f50997cece69eccc1e61f9856", + "self_attn.o_proj.weight": "fc2860fcbdf78eec3494d3529ad628872ad3c6de62ed63c9c6a3f1d6f1a6d55a", + "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7", + "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "15ddc12b47e73aac3a13f47c90907b9b3ad9d2c2f3b6d92d18150d67a1177b91", + "self_attn.k_proj.weight": "25df896e1d40135244874d105e9d045ad3f36869bad85dac0c3fd644dac8e15d", + "self_attn.v_proj.weight": "8c132171150a34123ce0fe518880c3cbdf0ef21f50997cece69eccc1e61f9856", + "self_attn.o_proj.weight": "fc2860fcbdf78eec3494d3529ad628872ad3c6de62ed63c9c6a3f1d6f1a6d55a", + "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7", + "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 22, + "teacher_boundary_original_layer": 24 + }, + "lambda_init": "mka", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "mka", + "prior_mean": 0.6243202778643895 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 0.6243202686309814, + "per_tensor_mean": { + "mlp.gate_proj.weight": 0.6243202686309814, + "mlp.up_proj.weight": 0.6243202686309814, + "mlp.down_proj.weight": 0.6243202686309814 + } + }, + "post_merge_nll_scale": null, + "merge_only_ppl": null, + "post_ppl": null, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "instruction_dataset": null, + "instruction_config": null, + "instruction_split": "train" + }, + "lora": { + "enabled": false, + "seq_len": 1024, + "batch_size": 8, + "epochs": 0.0, + "rank": 8, + "alpha": 16.0, + "dropout": 0.0, + "target_modules": [ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "down_proj", + "up_proj" + ], + "respect_exclude_pairs": false, + "kl_enabled": false, + "kl_weight": 0.1, + "kl_temp": 4.0, + "post_ppl": null, + "lr": 0.0001, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "log_steps": 100, + "eval_every": 0, + "eval_max_batches": null + }, + "norm_policy": "hybrid", + "source_feature_transport": null, + "same_anchor_contextual_fisher": { + "computed": false + }, + "full_model_saved": false, + "timing": { + "seconds": { + "selection": 9.43434946378693, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 3.7173740565776825e-05, + "fit": 166.5340637974441, + "materialize_save_layer": 0.4399823029525578, + "metadata_write": 0.0008760690689086914, + "teacher_snapshot": 0.3565853899344802, + "cycle_cleanup": 0.13818733813241124, + "cycle_total": 176.90458634169772 + }, + "tracked_component_total_seconds": 176.90408153505996, + "cycle_total_seconds": 176.90458634169772, + "ratios_of_tracked_components": { + "selection": 0.0533303097470771, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 2.101350078709716e-07, + "fit": 0.9413805625758801, + "materialize_save_layer": 0.002487123525555058, + "metadata_write": 4.952226434272894e-06, + "teacher_snapshot": 0.0020156990547660703, + "cycle_cleanup": 0.0007811427352795385 + }, + "ratios_of_cycle_total": { + "selection": 0.05333015756620428, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 2.1013440823956015e-07, + "fit": 0.9413778762964202, + "materialize_save_layer": 0.002487116428415913, + "metadata_write": 4.952212302831605e-06, + "teacher_snapshot": 0.0020156933028617043, + "cycle_cleanup": 0.0007811405062472338 + } + }, + "recipient_original_layer": 23, + "removed_original_layer": 24, + "recipient_side": "left", + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 20, + 21, + 23, + 25, + 26, + 27, + 28, + 29, + 30, + 31 + ], + "fisher_computed": false, + "merge_initializer": "mka", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 24 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_4/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_4/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..10707969943642d11f31edebb45eeb7d668d8904 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_4/cycle_metadata.json @@ -0,0 +1,453 @@ +{ + "cycle": 4, + "layer_merged": 24, + "num_layers_before": 29, + "num_layers_after": 28, + "fused_layer_state": "fused_layer.pt", + "profile_no_save": false, + "dwce_score": null, + "dwce_scores": null, + "dwce_meta": { + "method": "mka", + "fisher_computed": false + }, + "fisher_num_batches": 0, + "merge_method": "reparam", + "merged_params": 3, + "num_sequences": 64, + "teacher_source": "previous_cycle_memory", + "teacher_cycle": 3, + "eval": { + "datasets": [ + "wikitext2" + ], + "configs": [ + null + ], + "split": "test", + "num_samples": 0, + "seq_len": 1024, + "post_ppl": null, + "merge_only_ppl": null + }, + "comm": { + "enabled": false + }, + "distill": { + "enabled": true, + "method": "reparam", + "calib_samples": 256, + "inst_samples": 0, + "seq_len": 1024, + "batch_size": 8, + "epochs": 1.0, + "lr": 0.0001, + "kl_weight": 0.02, + "kl_temp": 4.0, + "kl_chunk_size": 16384, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "reparam_eta": 0.0, + "reparam_gamma": 0.0, + "reparam_attn_reg_scale": 1.0, + "reparam_mlp_reg_scale": 1.0, + "reparam_param_subset": "mlp", + "reparam_train_subset": "mlp", + "reparam_skip_train": false, + "reparam_stats": { + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6214288473129272, + "std": 4.7565402832764544e-05, + "min": 0.6214288473129272, + "max": 0.6214288473129272, + "mean_abs_from_0_5": 0.12142884731292725, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6214288473129272, + "std": 4.7565402832764544e-05, + "min": 0.6214288473129272, + "max": 0.6214288473129272, + "mean_abs_from_0_5": 0.12142884731292725 + }, + "mlp.up_proj.weight": { + "mean": 0.6214288473129272, + "std": 4.7565402832764544e-05, + "min": 0.6214288473129272, + "max": 0.6214288473129272, + "mean_abs_from_0_5": 0.12142884731292725 + }, + "mlp.down_proj.weight": { + "mean": 0.6214288473129272, + "std": 4.7565402832764544e-05, + "min": 0.6214288473129272, + "max": 0.6214288473129272, + "mean_abs_from_0_5": 0.12142884731292725 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6214287877082825, + "std": 0.0, + "min": 0.6214287877082825, + "max": 0.6214287877082825, + "mean_abs_from_0_5": 0.12142878770828247, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6214287877082825, + "std": 0.0, + "min": 0.6214287877082825, + "max": 0.6214287877082825, + "mean_abs_from_0_5": 0.12142878770828247 + }, + "mlp.up_proj.weight": { + "mean": 0.6214287877082825, + "std": 0.0, + "min": 0.6214287877082825, + "max": 0.6214287877082825, + "mean_abs_from_0_5": 0.12142878770828247 + }, + "mlp.down_proj.weight": { + "mean": 0.6214287877082825, + "std": 0.0, + "min": 0.6214287877082825, + "max": 0.6214287877082825, + "mean_abs_from_0_5": 0.12142878770828247 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.06622738011610237, + "mean_abs": 1.1644387671237512e-06, + "max_abs": 0.010463714599609375 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": 3.683162882831918e-07, + "std": 0.0009767218954390667, + "rms": 0.0009767219648840562, + "mean_abs": 0.0007777905446432886, + "min": -0.0063410247676074505, + "max": 0.00635013822466135, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 9.061984980819813e-07, + "std": 0.0009685778717330229, + "rms": 0.0009685782956512034, + "mean_abs": 0.0007752220013311931, + "min": -0.006030924152582884, + "max": 0.005831782706081867 + }, + "mlp.up_proj.weight": { + "mean": 6.8289247272852145e-09, + "std": 0.0009665684278061907, + "rms": 0.0009665684278303143, + "mean_abs": 0.0007696717179247311, + "min": -0.00573101406916976, + "max": 0.005574765615165234 + }, + "mlp.down_proj.weight": { + "mean": 1.9192144204030877e-07, + "std": 0.0009947657577249627, + "rms": 0.0009947657762387882, + "mean_abs": 0.0007884779146739415, + "min": -0.0063410247676074505, + "max": 0.00635013822466135 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 164.69223202904686, + "dataset_tokens": 524288, + "tokens_per_second": 3183.440976788335, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 54929986048, + "peak_reserved_bytes": 78104231936, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6214287991453509, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "1483e52e20992c5b6111f4478ebc1b2701dbd0b645ccc86c234d6b4c54629bd7", + "self_attn.k_proj.weight": "4167b5b9d247abe59a84bbfc92234908c05f6680322139947a977d62b7a8de8c", + "self_attn.v_proj.weight": "18087bf6d3c06bf1d8233b679c2e146cc82b47e1dbfa85181da20197557b4f27", + "self_attn.o_proj.weight": "2bb782a492fa69fc1555d9d4d878be31196c4627e38a2b3228674c2fb19f059a", + "input_layernorm.weight": "442962ef4923e31f331597e007c41301c88b9cf34900e9e6c9570fba7b887f6d", + "post_attention_layernorm.weight": "16325c0e3226964c4e7ec0b20cd2a522cbd0380ec694f34d9aede17cc217b462" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "1483e52e20992c5b6111f4478ebc1b2701dbd0b645ccc86c234d6b4c54629bd7", + "self_attn.k_proj.weight": "4167b5b9d247abe59a84bbfc92234908c05f6680322139947a977d62b7a8de8c", + "self_attn.v_proj.weight": "18087bf6d3c06bf1d8233b679c2e146cc82b47e1dbfa85181da20197557b4f27", + "self_attn.o_proj.weight": "2bb782a492fa69fc1555d9d4d878be31196c4627e38a2b3228674c2fb19f059a", + "input_layernorm.weight": "442962ef4923e31f331597e007c41301c88b9cf34900e9e6c9570fba7b887f6d", + "post_attention_layernorm.weight": "16325c0e3226964c4e7ec0b20cd2a522cbd0380ec694f34d9aede17cc217b462" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "1483e52e20992c5b6111f4478ebc1b2701dbd0b645ccc86c234d6b4c54629bd7", + "self_attn.k_proj.weight": "4167b5b9d247abe59a84bbfc92234908c05f6680322139947a977d62b7a8de8c", + "self_attn.v_proj.weight": "18087bf6d3c06bf1d8233b679c2e146cc82b47e1dbfa85181da20197557b4f27", + "self_attn.o_proj.weight": "2bb782a492fa69fc1555d9d4d878be31196c4627e38a2b3228674c2fb19f059a", + "input_layernorm.weight": "442962ef4923e31f331597e007c41301c88b9cf34900e9e6c9570fba7b887f6d", + "post_attention_layernorm.weight": "16325c0e3226964c4e7ec0b20cd2a522cbd0380ec694f34d9aede17cc217b462" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 25, + "teacher_boundary_original_layer": 28 + }, + "lambda_init": "mka", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "mka", + "prior_mean": 0.6214287991453509 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 0.6214287877082825, + "per_tensor_mean": { + "mlp.gate_proj.weight": 0.6214287877082825, + "mlp.up_proj.weight": 0.6214287877082825, + "mlp.down_proj.weight": 0.6214287877082825 + } + }, + "post_merge_nll_scale": null, + "merge_only_ppl": null, + "post_ppl": null, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "instruction_dataset": null, + "instruction_config": null, + "instruction_split": "train" + }, + "lora": { + "enabled": false, + "seq_len": 1024, + "batch_size": 8, + "epochs": 0.0, + "rank": 8, + "alpha": 16.0, + "dropout": 0.0, + "target_modules": [ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "down_proj", + "up_proj" + ], + "respect_exclude_pairs": false, + "kl_enabled": false, + "kl_weight": 0.1, + "kl_temp": 4.0, + "post_ppl": null, + "lr": 0.0001, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "log_steps": 100, + "eval_every": 0, + "eval_max_batches": null + }, + "norm_policy": "hybrid", + "source_feature_transport": null, + "same_anchor_contextual_fisher": { + "computed": false + }, + "full_model_saved": false, + "timing": { + "seconds": { + "selection": 8.9774208557792, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 2.8817914426326752e-05, + "fit": 164.83233894500881, + "materialize_save_layer": 0.49374578800052404, + "metadata_write": 0.0009944126941263676, + "teacher_snapshot": 0.3301391610875726, + "cycle_cleanup": 0.14855425339192152, + "cycle_total": 174.78373082913458 + }, + "tracked_component_total_seconds": 174.7832222338766, + "cycle_total_seconds": 174.78373082913458, + "ratios_of_tracked_components": { + "selection": 0.051363172855152864, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.6487803610672448e-07, + "fit": 0.9430672855112343, + "materialize_save_layer": 0.002824903796199873, + "metadata_write": 5.689405890433515e-06, + "teacher_snapshot": 0.0018888492663547245, + "cycle_cleanup": 0.0008499342871316435 + }, + "ratios_of_cycle_total": { + "selection": 0.051363023395783705, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.6487755633559867e-07, + "fit": 0.9430645413224754, + "materialize_save_layer": 0.0028248955761403273, + "metadata_write": 5.689389335089131e-06, + "teacher_snapshot": 0.0018888437700778377, + "cycle_cleanup": 0.0008499318139463763 + } + }, + "recipient_original_layer": 27, + "removed_original_layer": 28, + "recipient_side": "left", + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 20, + 21, + 23, + 25, + 26, + 27, + 29, + 30, + 31 + ], + "fisher_computed": false, + "merge_initializer": "mka", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 28 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_5/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_5/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..bf81553a4d5cd34454ca65d10875ac18b396cb25 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_5/cycle_metadata.json @@ -0,0 +1,452 @@ +{ + "cycle": 5, + "layer_merged": 21, + "num_layers_before": 28, + "num_layers_after": 27, + "fused_layer_state": "fused_layer.pt", + "profile_no_save": false, + "dwce_score": null, + "dwce_scores": null, + "dwce_meta": { + "method": "mka", + "fisher_computed": false + }, + "fisher_num_batches": 0, + "merge_method": "reparam", + "merged_params": 3, + "num_sequences": 64, + "teacher_source": "previous_cycle_memory", + "teacher_cycle": 4, + "eval": { + "datasets": [ + "wikitext2" + ], + "configs": [ + null + ], + "split": "test", + "num_samples": 0, + "seq_len": 1024, + "post_ppl": null, + "merge_only_ppl": null + }, + "comm": { + "enabled": false + }, + "distill": { + "enabled": true, + "method": "reparam", + "calib_samples": 256, + "inst_samples": 0, + "seq_len": 1024, + "batch_size": 8, + "epochs": 1.0, + "lr": 0.0001, + "kl_weight": 0.02, + "kl_temp": 4.0, + "kl_chunk_size": 16384, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "reparam_eta": 0.0, + "reparam_gamma": 0.0, + "reparam_attn_reg_scale": 1.0, + "reparam_mlp_reg_scale": 1.0, + "reparam_param_subset": "mlp", + "reparam_train_subset": "mlp", + "reparam_skip_train": false, + "reparam_stats": { + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6221969723701477, + "std": 0.0, + "min": 0.6221969723701477, + "max": 0.6221969723701477, + "mean_abs_from_0_5": 0.1221969723701477, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6221969723701477, + "std": 0.0, + "min": 0.6221969723701477, + "max": 0.6221969723701477, + "mean_abs_from_0_5": 0.1221969723701477 + }, + "mlp.up_proj.weight": { + "mean": 0.6221969723701477, + "std": 0.0, + "min": 0.6221969723701477, + "max": 0.6221969723701477, + "mean_abs_from_0_5": 0.1221969723701477 + }, + "mlp.down_proj.weight": { + "mean": 0.6221969723701477, + "std": 0.0, + "min": 0.6221969723701477, + "max": 0.6221969723701477, + "mean_abs_from_0_5": 0.1221969723701477 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6221970319747925, + "std": 0.00010575140668483164, + "min": 0.6221970319747925, + "max": 0.6221970319747925, + "mean_abs_from_0_5": 0.12219703197479248, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6221970319747925, + "std": 0.00010575140668483164, + "min": 0.6221970319747925, + "max": 0.6221970319747925, + "mean_abs_from_0_5": 0.12219703197479248 + }, + "mlp.up_proj.weight": { + "mean": 0.6221970319747925, + "std": 0.00010575140668483164, + "min": 0.6221970319747925, + "max": 0.6221970319747925, + "mean_abs_from_0_5": 0.12219703197479248 + }, + "mlp.down_proj.weight": { + "mean": 0.6221970319747925, + "std": 0.00010575140668483164, + "min": 0.6221970319747925, + "max": 0.6221970319747925, + "mean_abs_from_0_5": 0.12219703197479248 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.017244738186102816, + "mean_abs": 5.998026067356391e-07, + "max_abs": 0.0014104843139648438 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": -5.122936548624628e-07, + "std": 0.0008861497273292803, + "rms": 0.0008861498754107833, + "mean_abs": 0.0007082510163031873, + "min": -0.00636459281668067, + "max": 0.006377923768013716, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": -1.5799352175755693e-06, + "std": 0.0008790690587729167, + "rms": 0.000879070478566533, + "mean_abs": 0.0007048696944756168, + "min": -0.00636459281668067, + "max": 0.00579824997112155 + }, + "mlp.up_proj.weight": { + "mean": 2.075030839218276e-08, + "std": 0.000904259461657283, + "rms": 0.0009042594618953648, + "mean_abs": 0.0007221191855413574, + "min": -0.006330917589366436, + "max": 0.005814752075821161 + }, + "mlp.down_proj.weight": { + "mean": 2.2303944595997953e-08, + "std": 0.0008748341121948127, + "rms": 0.0008748341124791328, + "mean_abs": 0.000697764168892588, + "min": -0.006065336987376213, + "max": 0.006377923768013716 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 158.20467386068776, + "dataset_tokens": 524288, + "tokens_per_second": 3313.9855302990527, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 56341469696, + "peak_reserved_bytes": 78932606976, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6221970199569331, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "43c71ff851719b981a17d39c96e58134600d702b67809ffe7e1367354f171f3a", + "self_attn.k_proj.weight": "029697bf31182f605dbe4470fd363c0f4da9b3e774c865e3b502102379acf6fa", + "self_attn.v_proj.weight": "bee45b937525908cad83825ef000c48c65c36c9b42a86342481c8d09f7c8b031", + "self_attn.o_proj.weight": "a7c625ad20b47e2ae39637b93e46fd03ac09ca50d199deb5baf6ae1b60479926", + "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7", + "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "43c71ff851719b981a17d39c96e58134600d702b67809ffe7e1367354f171f3a", + "self_attn.k_proj.weight": "029697bf31182f605dbe4470fd363c0f4da9b3e774c865e3b502102379acf6fa", + "self_attn.v_proj.weight": "bee45b937525908cad83825ef000c48c65c36c9b42a86342481c8d09f7c8b031", + "self_attn.o_proj.weight": "a7c625ad20b47e2ae39637b93e46fd03ac09ca50d199deb5baf6ae1b60479926", + "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7", + "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "43c71ff851719b981a17d39c96e58134600d702b67809ffe7e1367354f171f3a", + "self_attn.k_proj.weight": "029697bf31182f605dbe4470fd363c0f4da9b3e774c865e3b502102379acf6fa", + "self_attn.v_proj.weight": "bee45b937525908cad83825ef000c48c65c36c9b42a86342481c8d09f7c8b031", + "self_attn.o_proj.weight": "a7c625ad20b47e2ae39637b93e46fd03ac09ca50d199deb5baf6ae1b60479926", + "input_layernorm.weight": "ed0c6653c0e119743e0b773af0f779a71321e64c99fb70e94e4776ece1374ee7", + "post_attention_layernorm.weight": "5399a72fd083f13fbe3b8750a95263b2065fb475eef1701f08c99d3a8b2b5715" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 22, + "teacher_boundary_original_layer": 25 + }, + "lambda_init": "mka", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "mka", + "prior_mean": 0.6221970199569331 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 0.6221970319747925, + "per_tensor_mean": { + "mlp.gate_proj.weight": 0.6221970319747925, + "mlp.up_proj.weight": 0.6221970319747925, + "mlp.down_proj.weight": 0.6221970319747925 + } + }, + "post_merge_nll_scale": null, + "merge_only_ppl": null, + "post_ppl": null, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "instruction_dataset": null, + "instruction_config": null, + "instruction_split": "train" + }, + "lora": { + "enabled": false, + "seq_len": 1024, + "batch_size": 8, + "epochs": 0.0, + "rank": 8, + "alpha": 16.0, + "dropout": 0.0, + "target_modules": [ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "down_proj", + "up_proj" + ], + "respect_exclude_pairs": false, + "kl_enabled": false, + "kl_weight": 0.1, + "kl_temp": 4.0, + "post_ppl": null, + "lr": 0.0001, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "log_steps": 100, + "eval_every": 0, + "eval_max_batches": null + }, + "norm_policy": "hybrid", + "source_feature_transport": null, + "same_anchor_contextual_fisher": { + "computed": false + }, + "full_model_saved": false, + "timing": { + "seconds": { + "selection": 8.6126485071145, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 3.609200939536095e-05, + "fit": 158.33603044925258, + "materialize_save_layer": 0.49633969040587544, + "metadata_write": 0.0009788312017917633, + "teacher_snapshot": 0.35813615983352065, + "cycle_cleanup": 0.14467958128079772, + "cycle_total": 167.94952452601865 + }, + "tracked_component_total_seconds": 167.94884931109846, + "cycle_total_seconds": 167.94952452601865, + "ratios_of_tracked_components": { + "selection": 0.05128137848185516, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 2.1489881915479072e-07, + "fit": 0.9427634133768927, + "materialize_save_layer": 0.002955302715331412, + "metadata_write": 5.828150688776883e-06, + "teacher_snapshot": 0.0021324121082254665, + "cycle_cleanup": 0.0008614502681873209 + }, + "ratios_of_cycle_total": { + "selection": 0.05128117231305548, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 2.1489795518753965e-07, + "fit": 0.9427596231433406, + "materialize_save_layer": 0.00295529083399687, + "metadata_write": 5.828127257604253e-06, + "teacher_snapshot": 0.0021324035351945186, + "cycle_cleanup": 0.0008614468048606117 + } + }, + "recipient_original_layer": 23, + "removed_original_layer": 25, + "recipient_side": "left", + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 20, + 21, + 23, + 26, + 27, + 29, + 30, + 31 + ], + "fisher_computed": false, + "merge_initializer": "mka", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 25 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_6/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_6/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..670a863668450041cc663770123373cd5ed9d204 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_6/cycle_metadata.json @@ -0,0 +1,451 @@ +{ + "cycle": 6, + "layer_merged": 10, + "num_layers_before": 27, + "num_layers_after": 26, + "fused_layer_state": "fused_layer.pt", + "profile_no_save": false, + "dwce_score": null, + "dwce_scores": null, + "dwce_meta": { + "method": "mka", + "fisher_computed": false + }, + "fisher_num_batches": 0, + "merge_method": "reparam", + "merged_params": 3, + "num_sequences": 64, + "teacher_source": "previous_cycle_memory", + "teacher_cycle": 5, + "eval": { + "datasets": [ + "wikitext2" + ], + "configs": [ + null + ], + "split": "test", + "num_samples": 0, + "seq_len": 1024, + "post_ppl": null, + "merge_only_ppl": null + }, + "comm": { + "enabled": false + }, + "distill": { + "enabled": true, + "method": "reparam", + "calib_samples": 256, + "inst_samples": 0, + "seq_len": 1024, + "batch_size": 8, + "epochs": 1.0, + "lr": 0.0001, + "kl_weight": 0.02, + "kl_temp": 4.0, + "kl_chunk_size": 16384, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "reparam_eta": 0.0, + "reparam_gamma": 0.0, + "reparam_attn_reg_scale": 1.0, + "reparam_mlp_reg_scale": 1.0, + "reparam_param_subset": "mlp", + "reparam_train_subset": "mlp", + "reparam_skip_train": false, + "reparam_stats": { + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668 + }, + "mlp.up_proj.weight": { + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668 + }, + "mlp.down_proj.weight": { + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668 + }, + "mlp.up_proj.weight": { + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668 + }, + "mlp.down_proj.weight": { + "mean": 0.6211211681365967, + "std": 6.954265765167942e-05, + "min": 0.6211211681365967, + "max": 0.6211211681365967, + "mean_abs_from_0_5": 0.12112116813659668 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.015325511073016893, + "mean_abs": 5.175094256195561e-07, + "max_abs": 0.00034111738204956055 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": -9.499538943405891e-07, + "std": 0.0007645287922128008, + "rms": 0.0007645293823881233, + "mean_abs": 0.0006120525123108001, + "min": -0.004902039188891649, + "max": 0.004761568270623684, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": -2.76329176683378e-06, + "std": 0.0008060499610024697, + "rms": 0.0008060546975320421, + "mean_abs": 0.0006482953737889018, + "min": -0.004902039188891649, + "max": 0.004761568270623684 + }, + "mlp.up_proj.weight": { + "mean": -7.554790824672506e-08, + "std": 0.0007344616429140787, + "rms": 0.0007344616467995685, + "mean_abs": 0.0005870084943515914, + "min": -0.004594889469444752, + "max": 0.004446103703230619 + }, + "mlp.down_proj.weight": { + "mean": -1.1022007941262148e-08, + "std": 0.0007512372750668098, + "rms": 0.0007512372751476662, + "mean_abs": 0.0006008536687919072, + "min": -0.004617602098733187, + "max": 0.004696824587881565 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 147.67390455212444, + "dataset_tokens": 524288, + "tokens_per_second": 3550.3090514881196, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 66888679936, + "peak_reserved_bytes": 79958114304, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6211211480841742, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "53e37683daf2b4f755fef4ee6d24b20c07885de290d559e9bd8d0e13a1ad8f81", + "self_attn.k_proj.weight": "7f367d9f19a459039e3a17afefb6c6874147e8a3b60ecd58789c65e8e0cbafb8", + "self_attn.v_proj.weight": "3d69c8dff42f94ffec329af9af7d844de8350c2bbb7da8558e34dc6c186f5f7d", + "self_attn.o_proj.weight": "2015d40b1bcb9a7c46f362a2901ba4b6636f34b496426df97ee99d910e912eed", + "input_layernorm.weight": "215a4054b42dffd42acdc2d290049db92fba6920b1d5cc1e6bdb9d5a2cb4ed6c", + "post_attention_layernorm.weight": "880bfd813c0b0ae9ab6deed30a3dd1aef4ebf2b1fb8604921beb732a83deaf0b" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "53e37683daf2b4f755fef4ee6d24b20c07885de290d559e9bd8d0e13a1ad8f81", + "self_attn.k_proj.weight": "7f367d9f19a459039e3a17afefb6c6874147e8a3b60ecd58789c65e8e0cbafb8", + "self_attn.v_proj.weight": "3d69c8dff42f94ffec329af9af7d844de8350c2bbb7da8558e34dc6c186f5f7d", + "self_attn.o_proj.weight": "2015d40b1bcb9a7c46f362a2901ba4b6636f34b496426df97ee99d910e912eed", + "input_layernorm.weight": "215a4054b42dffd42acdc2d290049db92fba6920b1d5cc1e6bdb9d5a2cb4ed6c", + "post_attention_layernorm.weight": "880bfd813c0b0ae9ab6deed30a3dd1aef4ebf2b1fb8604921beb732a83deaf0b" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "53e37683daf2b4f755fef4ee6d24b20c07885de290d559e9bd8d0e13a1ad8f81", + "self_attn.k_proj.weight": "7f367d9f19a459039e3a17afefb6c6874147e8a3b60ecd58789c65e8e0cbafb8", + "self_attn.v_proj.weight": "3d69c8dff42f94ffec329af9af7d844de8350c2bbb7da8558e34dc6c186f5f7d", + "self_attn.o_proj.weight": "2015d40b1bcb9a7c46f362a2901ba4b6636f34b496426df97ee99d910e912eed", + "input_layernorm.weight": "215a4054b42dffd42acdc2d290049db92fba6920b1d5cc1e6bdb9d5a2cb4ed6c", + "post_attention_layernorm.weight": "880bfd813c0b0ae9ab6deed30a3dd1aef4ebf2b1fb8604921beb732a83deaf0b" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 11, + "teacher_boundary_original_layer": 11 + }, + "lambda_init": "mka", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "mka", + "prior_mean": 0.6211211480841742 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 0.6211211681365967, + "per_tensor_mean": { + "mlp.gate_proj.weight": 0.6211211681365967, + "mlp.up_proj.weight": 0.6211211681365967, + "mlp.down_proj.weight": 0.6211211681365967 + } + }, + "post_merge_nll_scale": null, + "merge_only_ppl": null, + "post_ppl": null, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "instruction_dataset": null, + "instruction_config": null, + "instruction_split": "train" + }, + "lora": { + "enabled": false, + "seq_len": 1024, + "batch_size": 8, + "epochs": 0.0, + "rank": 8, + "alpha": 16.0, + "dropout": 0.0, + "target_modules": [ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "down_proj", + "up_proj" + ], + "respect_exclude_pairs": false, + "kl_enabled": false, + "kl_weight": 0.1, + "kl_temp": 4.0, + "post_ppl": null, + "lr": 0.0001, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "log_steps": 100, + "eval_every": 0, + "eval_max_batches": null + }, + "norm_policy": "hybrid", + "source_feature_transport": null, + "same_anchor_contextual_fisher": { + "computed": false + }, + "full_model_saved": false, + "timing": { + "seconds": { + "selection": 8.204300501849502, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 3.612181171774864e-05, + "fit": 147.82563345786184, + "materialize_save_layer": 0.5231940727680922, + "metadata_write": 0.001027056947350502, + "teacher_snapshot": 0.37570329615846276, + "cycle_cleanup": 0.13669422315433621, + "cycle_total": 157.0674374839291 + }, + "tracked_component_total_seconds": 157.0665887305513, + "cycle_total_seconds": 157.0674374839291, + "ratios_of_tracked_components": { + "selection": 0.05223453675386069, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 2.2997769296254234e-07, + "fit": 0.941165365929336, + "materialize_save_layer": 0.0033310335253134886, + "metadata_write": 6.53899060042887e-06, + "teacher_snapshot": 0.0023920001013263492, + "cycle_cleanup": 0.0008702947218700725 + }, + "ratios_of_cycle_total": { + "selection": 0.05223425449141204, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 2.2997645022027286e-07, + "fit": 0.9411602801057166, + "materialize_save_layer": 0.0033310155252365696, + "metadata_write": 6.5389552653495665e-06, + "teacher_snapshot": 0.002391987175552566, + "cycle_cleanup": 0.0008702900190137919 + } + }, + "recipient_original_layer": 10, + "removed_original_layer": 11, + "recipient_side": "left", + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 20, + 21, + 23, + 26, + 27, + 29, + 30, + 31 + ], + "fisher_computed": false, + "merge_initializer": "mka", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 11 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_7/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_7/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..3d7856b57a746d35bd6464fa634c238e93ed2078 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_7/cycle_metadata.json @@ -0,0 +1,450 @@ +{ + "cycle": 7, + "layer_merged": 16, + "num_layers_before": 26, + "num_layers_after": 25, + "fused_layer_state": "fused_layer.pt", + "profile_no_save": false, + "dwce_score": null, + "dwce_scores": null, + "dwce_meta": { + "method": "mka", + "fisher_computed": false + }, + "fisher_num_batches": 0, + "merge_method": "reparam", + "merged_params": 3, + "num_sequences": 64, + "teacher_source": "previous_cycle_memory", + "teacher_cycle": 6, + "eval": { + "datasets": [ + "wikitext2" + ], + "configs": [ + null + ], + "split": "test", + "num_samples": 0, + "seq_len": 1024, + "post_ppl": null, + "merge_only_ppl": null + }, + "comm": { + "enabled": false + }, + "distill": { + "enabled": true, + "method": "reparam", + "calib_samples": 256, + "inst_samples": 0, + "seq_len": 1024, + "batch_size": 8, + "epochs": 1.0, + "lr": 0.0001, + "kl_weight": 0.02, + "kl_temp": 4.0, + "kl_chunk_size": 16384, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "reparam_eta": 0.0, + "reparam_gamma": 0.0, + "reparam_attn_reg_scale": 1.0, + "reparam_mlp_reg_scale": 1.0, + "reparam_param_subset": "mlp", + "reparam_train_subset": "mlp", + "reparam_skip_train": false, + "reparam_stats": { + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218 + }, + "mlp.up_proj.weight": { + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218 + }, + "mlp.down_proj.weight": { + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218 + }, + "mlp.up_proj.weight": { + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218 + }, + "mlp.down_proj.weight": { + "mean": 0.6229175925254822, + "std": 0.0, + "min": 0.6229175925254822, + "max": 0.6229175925254822, + "mean_abs_from_0_5": 0.12291759252548218 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.009353721000454441, + "mean_abs": 2.8153123193554903e-07, + "max_abs": 0.001277327537536621 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": 1.5348852977175348e-06, + "std": 0.0008906192953409906, + "rms": 0.0008906206179437796, + "mean_abs": 0.0007133157036843754, + "min": -0.006191921886056662, + "max": 0.0069657727144658566, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 4.687837125467402e-06, + "std": 0.0009487456182395482, + "rms": 0.0009487571996805385, + "mean_abs": 0.0007639551934387003, + "min": -0.005632347427308559, + "max": 0.0049436092376708984 + }, + "mlp.up_proj.weight": { + "mean": -2.580860609668889e-07, + "std": 0.000862742007209576, + "rms": 0.0008627420458123176, + "mean_abs": 0.0006906303710171155, + "min": -0.004639971535652876, + "max": 0.0049757156521081924 + }, + "mlp.down_proj.weight": { + "mean": 1.7490482865209094e-07, + "std": 0.000857409565592722, + "rms": 0.0008574095834323287, + "mean_abs": 0.0006853615465973105, + "min": -0.006191921886056662, + "max": 0.0069657727144658566 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 148.01820804690942, + "dataset_tokens": 524288, + "tokens_per_second": 3542.050717394474, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 58022471168, + "peak_reserved_bytes": 79513518080, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6229176202047336, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "f1a38d57cf5ef9ca4d1eb5a1f85ff7f3b0e48ca3108da13f083a7eb33304963d", + "self_attn.k_proj.weight": "64e044d1d4c42bdd8ca349d5aa091363741c62366b4097b9bf93f636de401d35", + "self_attn.v_proj.weight": "8ed75a50876602d6bf3c9a28561afab66ee8afa9e161a43048ae5c09211ad6db", + "self_attn.o_proj.weight": "349a7fb4bf47cacf9a61d82e86c1977787bc15eae2c6a148bee210df37b5f0e6", + "input_layernorm.weight": "3136ce06cd326def67ac994dc995f04f4d8677a7c624d2992d3f489e52036507", + "post_attention_layernorm.weight": "cfd7949654b781ca46277155f18c3f381fbfe9ed6d3863ac6953f30f3ea697aa" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "f1a38d57cf5ef9ca4d1eb5a1f85ff7f3b0e48ca3108da13f083a7eb33304963d", + "self_attn.k_proj.weight": "64e044d1d4c42bdd8ca349d5aa091363741c62366b4097b9bf93f636de401d35", + "self_attn.v_proj.weight": "8ed75a50876602d6bf3c9a28561afab66ee8afa9e161a43048ae5c09211ad6db", + "self_attn.o_proj.weight": "349a7fb4bf47cacf9a61d82e86c1977787bc15eae2c6a148bee210df37b5f0e6", + "input_layernorm.weight": "3136ce06cd326def67ac994dc995f04f4d8677a7c624d2992d3f489e52036507", + "post_attention_layernorm.weight": "cfd7949654b781ca46277155f18c3f381fbfe9ed6d3863ac6953f30f3ea697aa" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "f1a38d57cf5ef9ca4d1eb5a1f85ff7f3b0e48ca3108da13f083a7eb33304963d", + "self_attn.k_proj.weight": "64e044d1d4c42bdd8ca349d5aa091363741c62366b4097b9bf93f636de401d35", + "self_attn.v_proj.weight": "8ed75a50876602d6bf3c9a28561afab66ee8afa9e161a43048ae5c09211ad6db", + "self_attn.o_proj.weight": "349a7fb4bf47cacf9a61d82e86c1977787bc15eae2c6a148bee210df37b5f0e6", + "input_layernorm.weight": "3136ce06cd326def67ac994dc995f04f4d8677a7c624d2992d3f489e52036507", + "post_attention_layernorm.weight": "cfd7949654b781ca46277155f18c3f381fbfe9ed6d3863ac6953f30f3ea697aa" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 17, + "teacher_boundary_original_layer": 18 + }, + "lambda_init": "mka", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "mka", + "prior_mean": 0.6229176202047336 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 0.6229175925254822, + "per_tensor_mean": { + "mlp.gate_proj.weight": 0.6229175925254822, + "mlp.up_proj.weight": 0.6229175925254822, + "mlp.down_proj.weight": 0.6229175925254822 + } + }, + "post_merge_nll_scale": null, + "merge_only_ppl": null, + "post_ppl": null, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "instruction_dataset": null, + "instruction_config": null, + "instruction_split": "train" + }, + "lora": { + "enabled": false, + "seq_len": 1024, + "batch_size": 8, + "epochs": 0.0, + "rank": 8, + "alpha": 16.0, + "dropout": 0.0, + "target_modules": [ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "down_proj", + "up_proj" + ], + "respect_exclude_pairs": false, + "kl_enabled": false, + "kl_weight": 0.1, + "kl_temp": 4.0, + "post_ppl": null, + "lr": 0.0001, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "log_steps": 100, + "eval_every": 0, + "eval_max_batches": null + }, + "norm_policy": "hybrid", + "source_feature_transport": null, + "same_anchor_contextual_fisher": { + "computed": false + }, + "full_model_saved": false, + "timing": { + "seconds": { + "selection": 7.9346559080295265, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 7.710373029112816e-05, + "fit": 148.18194967275485, + "materialize_save_layer": 0.5536296330392361, + "metadata_write": 0.0009848130866885185, + "teacher_snapshot": 0.3938145418651402, + "cycle_cleanup": 0.21588695887476206, + "cycle_total": 157.28293945407495 + }, + "tracked_component_total_seconds": 157.2809986313805, + "cycle_total_seconds": 157.28293945407495, + "ratios_of_tracked_components": { + "selection": 0.050448916125119356, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 4.902291501329806e-07, + "fit": 0.9421478179957956, + "materialize_save_layer": 0.0035200032925577864, + "metadata_write": 6.2614880071853125e-06, + "teacher_snapshot": 0.0025038914127708677, + "cycle_cleanup": 0.001372619456599054 + }, + "ratios_of_cycle_total": { + "selection": 0.05044829360114017, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 4.902231008573036e-07, + "fit": 0.9421361921839114, + "materialize_save_layer": 0.0035199598568088205, + "metadata_write": 6.261410742365189e-06, + "teacher_snapshot": 0.00250386051552737, + "cycle_cleanup": 0.0013726025189006524 + } + }, + "recipient_original_layer": 17, + "removed_original_layer": 18, + "recipient_side": "left", + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 12, + 13, + 14, + 15, + 16, + 17, + 20, + 21, + 23, + 26, + 27, + 29, + 30, + 31 + ], + "fisher_computed": false, + "merge_initializer": "mka", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 18 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_8/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_8/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..59a3d2af6253f6869dfcb9b1b800ca6dc05c61d7 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/stage_metadata/cycle_8/cycle_metadata.json @@ -0,0 +1,449 @@ +{ + "cycle": 8, + "layer_merged": 16, + "num_layers_before": 25, + "num_layers_after": 24, + "fused_layer_state": "fused_layer.pt", + "profile_no_save": false, + "dwce_score": null, + "dwce_scores": null, + "dwce_meta": { + "method": "mka", + "fisher_computed": false + }, + "fisher_num_batches": 0, + "merge_method": "reparam", + "merged_params": 3, + "num_sequences": 64, + "teacher_source": "previous_cycle_memory", + "teacher_cycle": 7, + "eval": { + "datasets": [ + "wikitext2" + ], + "configs": [ + null + ], + "split": "test", + "num_samples": 0, + "seq_len": 1024, + "post_ppl": null, + "merge_only_ppl": null + }, + "comm": { + "enabled": false + }, + "distill": { + "enabled": true, + "method": "reparam", + "calib_samples": 256, + "inst_samples": 0, + "seq_len": 1024, + "batch_size": 8, + "epochs": 1.0, + "lr": 0.0001, + "kl_weight": 0.02, + "kl_temp": 4.0, + "kl_chunk_size": 16384, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "reparam_eta": 0.0, + "reparam_gamma": 0.0, + "reparam_attn_reg_scale": 1.0, + "reparam_mlp_reg_scale": 1.0, + "reparam_param_subset": "mlp", + "reparam_train_subset": "mlp", + "reparam_skip_train": false, + "reparam_stats": { + "enabled": true, + "epochs": 1.0, + "requested_epochs": 1.0, + "skip_train": false, + "trained": true, + "lr": 0.0001, + "hidden_mse_weight": 1.0, + "attn_mse_weight": 0.0, + "mlp_mse_weight": 1.0, + "eta": 0.0, + "gamma": 0.0, + "attn_reg_scale": 1.0, + "mlp_reg_scale": 1.0, + "param_subset": "mlp", + "train_subset": "mlp", + "num_gates": 3, + "num_attn_gates": 0, + "num_mlp_gates": 3, + "num_other_gates": 0, + "num_trainable_attn_gates": 0, + "num_trainable_mlp_gates": 3, + "num_trainable_other_gates": 0, + "lambda_init_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862 + }, + "mlp.up_proj.weight": { + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862 + }, + "mlp.down_proj.weight": { + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862 + }, + "mlp.up_proj.weight": { + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862 + }, + "mlp.down_proj.weight": { + "mean": 0.6223904490470886, + "std": 8.630744330786893e-06, + "min": 0.6223904490470886, + "max": 0.6223904490470886, + "mean_abs_from_0_5": 0.12239044904708862 + } + } + }, + "lambda_delta_from_init": { + "num_tensors": 3, + "num_elements": 3, + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.up_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + }, + "mlp.down_proj.weight": { + "mean_abs": 0.0, + "rms": 0.0, + "max_abs": 0.0 + } + } + }, + "first_grad_summary": { + "joint": { + "step": 1, + "phase": "joint", + "gate": { + "num_tensors": 3, + "num_tensors_without_grad": 3, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + }, + "u": { + "num_tensors": 3, + "num_tensors_without_grad": 0, + "num_elements": 176160768, + "l2": 0.009576967976147916, + "mean_abs": 2.923745363486454e-07, + "max_abs": 0.0009045600891113281 + }, + "rho": { + "num_tensors": 0, + "num_tensors_without_grad": 0, + "num_elements": 0, + "l2": 0.0, + "mean_abs": null, + "max_abs": 0.0 + } + } + }, + "u_delta_summary": { + "num_tensors": 3, + "num_elements": 176160768, + "mean": 1.0223904117386458e-06, + "std": 0.0009100702131976495, + "rms": 0.0009100707874840118, + "mean_abs": 0.0007217294270438808, + "min": -0.005950410384684801, + "max": 0.006033126264810562, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 3.1802483135834336e-06, + "std": 0.0009605824510155752, + "rms": 0.0009605877155046415, + "mean_abs": 0.000767326115497521, + "min": -0.005950410384684801, + "max": 0.006033126264810562 + }, + "mlp.up_proj.weight": { + "mean": -2.316466764438831e-07, + "std": 0.0009094989642336212, + "rms": 0.00090949899373348, + "mean_abs": 0.000719951931387186, + "min": -0.005685383919626474, + "max": 0.005684840492904186 + }, + "mlp.down_proj.weight": { + "mean": 1.1856959807638695e-07, + "std": 0.0008571868651909685, + "rms": 0.0008571868733914847, + "mean_abs": 0.0006779102342469352, + "min": -0.005608192179352045, + "max": 0.005835949908941984 + } + } + }, + "rho_objective": "none", + "rho_schedule": "joint", + "additive_u": true, + "rho_epochs": 0.0, + "rho_lr": null, + "rho_bounds": null, + "rho_after_phase": null, + "rho_final": {}, + "u_fisher_orthogonality": {}, + "runtime": { + "seconds": 144.06955006718636, + "dataset_tokens": 524288, + "tokens_per_second": 3639.1312373468236, + "batch_size": 8, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 56008057344, + "peak_reserved_bytes": 77118570496, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:8x1024": 64, + "student:8x1024": 64 + } + }, + "ablation": { + "lambda": 0.6223904334015297, + "endpoint_clamping": false, + "initial_u_nonzero": 0, + "merged_parameters": [ + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight" + ], + "parameterization": "W_initial + U_add", + "fisher_computed": false, + "fit_scope": "mlp", + "attention_initialization": "MKA_merge", + "norm_initialization": "anchor_Wa", + "norms_trainable": false, + "frozen_MKA_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "c2d269beae16d485167c22a3e390eb1009f2f29db5a15ccf6608b3e152183b0e", + "self_attn.k_proj.weight": "2eddd8dce925c09c5aae054e0abd9de0f49d179db37a2eba7d63d205fe9f2736", + "self_attn.v_proj.weight": "48a7a8be43dddd6b910a909a30dd1b2949c3b9c63ac97a37e894f5bfd1fd6787", + "self_attn.o_proj.weight": "7fd00db7930f63d6d9ea5ae7887847bbdbbd2012a69e4510211048d000d29005", + "input_layernorm.weight": "3136ce06cd326def67ac994dc995f04f4d8677a7c624d2992d3f489e52036507", + "post_attention_layernorm.weight": "cfd7949654b781ca46277155f18c3f381fbfe9ed6d3863ac6953f30f3ea697aa" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "c2d269beae16d485167c22a3e390eb1009f2f29db5a15ccf6608b3e152183b0e", + "self_attn.k_proj.weight": "2eddd8dce925c09c5aae054e0abd9de0f49d179db37a2eba7d63d205fe9f2736", + "self_attn.v_proj.weight": "48a7a8be43dddd6b910a909a30dd1b2949c3b9c63ac97a37e894f5bfd1fd6787", + "self_attn.o_proj.weight": "7fd00db7930f63d6d9ea5ae7887847bbdbbd2012a69e4510211048d000d29005", + "input_layernorm.weight": "3136ce06cd326def67ac994dc995f04f4d8677a7c624d2992d3f489e52036507", + "post_attention_layernorm.weight": "cfd7949654b781ca46277155f18c3f381fbfe9ed6d3863ac6953f30f3ea697aa" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "c2d269beae16d485167c22a3e390eb1009f2f29db5a15ccf6608b3e152183b0e", + "self_attn.k_proj.weight": "2eddd8dce925c09c5aae054e0abd9de0f49d179db37a2eba7d63d205fe9f2736", + "self_attn.v_proj.weight": "48a7a8be43dddd6b910a909a30dd1b2949c3b9c63ac97a37e894f5bfd1fd6787", + "self_attn.o_proj.weight": "7fd00db7930f63d6d9ea5ae7887847bbdbbd2012a69e4510211048d000d29005", + "input_layernorm.weight": "3136ce06cd326def67ac994dc995f04f4d8677a7c624d2992d3f489e52036507", + "post_attention_layernorm.weight": "cfd7949654b781ca46277155f18c3f381fbfe9ed6d3863ac6953f30f3ea697aa" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "mka", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 17, + "teacher_boundary_original_layer": 20 + }, + "lambda_init": "mka", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "mka", + "prior_mean": 0.6223904334015297 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 0.6223904490470886, + "per_tensor_mean": { + "mlp.gate_proj.weight": 0.6223904490470886, + "mlp.up_proj.weight": 0.6223904490470886, + "mlp.down_proj.weight": 0.6223904490470886 + } + }, + "post_merge_nll_scale": null, + "merge_only_ppl": null, + "post_ppl": null, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "instruction_dataset": null, + "instruction_config": null, + "instruction_split": "train" + }, + "lora": { + "enabled": false, + "seq_len": 1024, + "batch_size": 8, + "epochs": 0.0, + "rank": 8, + "alpha": 16.0, + "dropout": 0.0, + "target_modules": [ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "down_proj", + "up_proj" + ], + "respect_exclude_pairs": false, + "kl_enabled": false, + "kl_weight": 0.1, + "kl_temp": 4.0, + "post_ppl": null, + "lr": 0.0001, + "weight_decay": 0.0, + "max_grad_norm": 1.0, + "grad_accum_steps": 1, + "log_steps": 100, + "eval_every": 0, + "eval_max_batches": null + }, + "norm_policy": "hybrid", + "source_feature_transport": null, + "same_anchor_contextual_fisher": { + "computed": false + }, + "full_model_saved": false, + "timing": { + "seconds": { + "selection": 7.680482163093984, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 3.161095082759857e-05, + "fit": 144.22112287394702, + "materialize_save_layer": 0.5603097528219223, + "metadata_write": 0.0010012388229370117, + "teacher_snapshot": 0.38460053503513336, + "cycle_cleanup": 0.20894353231415153, + "cycle_total": 153.05723206326365 + }, + "tracked_component_total_seconds": 153.05649170698598, + "cycle_total_seconds": 153.05723206326365, + "ratios_of_tracked_components": { + "selection": 0.05018070176205027, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 2.06531264862095e-07, + "fit": 0.9422738053479395, + "materialize_save_layer": 0.0036608035802531596, + "metadata_write": 6.54162924924348e-06, + "teacher_snapshot": 0.002512801193505855, + "cycle_cleanup": 0.0013651399557371058 + }, + "ratios_of_cycle_total": { + "selection": 0.05018045903194816, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 2.065302658454761e-07, + "fit": 0.9422692474559818, + "materialize_save_layer": 0.0036607858725050484, + "metadata_write": 6.5415976065944166e-06, + "teacher_snapshot": 0.0025127890387836435, + "cycle_cleanup": 0.0013651333523906155 + } + }, + "recipient_original_layer": 17, + "removed_original_layer": 20, + "recipient_side": "left", + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 12, + 13, + 14, + 15, + 16, + 17, + 21, + 23, + 26, + 27, + 29, + 30, + 31 + ], + "fisher_computed": false, + "merge_initializer": "mka", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 20 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/training_elapsed.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/training_elapsed.json new file mode 100644 index 0000000000000000000000000000000000000000..3693153f077a8620ca6f7784d5a5097c7df7126c --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-llama31-mka-mlp-batch/batch_large/training_elapsed.json @@ -0,0 +1,4 @@ +{ + "wall_seconds": 1382.1486237049103, + "completed_utc": "2026-11-26T08:44:35Z" +}