diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_01_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_01_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..d7d380c913851a677727ba4f9901039f92e82fb7 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_01_fit.json @@ -0,0 +1,308 @@ +{ + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 9.49544724743403, + "mean_abs": 0.00018087541037756536, + "max_abs": 1.5859873294830322 + }, + "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": 150994944, + "mean": 1.6938262964079815e-06, + "std": 0.0028841262342925596, + "rms": 0.00288412673167843, + "mean_abs": 0.0022766475255290666, + "min": -0.028415188193321228, + "max": 0.030315399169921875, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 5.346755642676726e-06, + "std": 0.002756188385278948, + "rms": 0.0027561935713847235, + "mean_abs": 0.0021897933135430017, + "min": -0.024268098175525665, + "max": 0.023231012746691704 + }, + "mlp.up_proj.weight": { + "mean": -2.945407118204457e-07, + "std": 0.0026402173161349488, + "rms": 0.002640217332564322, + "mean_abs": 0.0020853507642944655, + "min": -0.02331394888460636, + "max": 0.022465486079454422 + }, + "mlp.down_proj.weight": { + "mean": 2.92639583676646e-08, + "std": 0.0032229195531651707, + "rms": 0.0032229195532980284, + "mean_abs": 0.002554798498749733, + "min": -0.028415188193321228, + "max": 0.030315399169921875 + } + } + }, + "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": 284.4065435389057, + "dataset_tokens": 524288, + "tokens_per_second": 1843.4456305970311, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 38770888192, + "peak_reserved_bytes": 40705720320, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 31 + ], + [ + 32 + ] + ], + "retention_ratios": [ + 0.49274789168296595, + 0.5072521083170339 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 6054, + 6234 + ], + "pair_score": 0.11533127194072337, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "d32ab579b634854ee33973f309191b5099d830b8f9189443b26791e043f35b74", + "self_attn.k_proj.weight": "1a63ee1e67c33062741b1acbdcb80b0ec9e16b0f30e984b21a1a41e899504765", + "self_attn.v_proj.weight": "9ec2df6bba949c6870ca18d7dfde4a4055b72c809b44958868777e77f5abf1c8", + "self_attn.o_proj.weight": "8e9f8603686d189fecd3a4ba41ac32046c14ce9bf75662a70042a453b8984f72", + "self_attn.q_norm.weight": "1ae662bfcbfd5edee375b6a3bafa86cd26fe6dd611568b98b45950949b91a97b", + "self_attn.k_norm.weight": "3588b84b908a2d2d498d1f96db9990fa492b15088fe42fe7d8ace619738a1119", + "input_layernorm.weight": "7ab4e8ed36ba6396ebde3cf6685dc9ac0df299665cdd8bb682af51cc443b989e", + "post_attention_layernorm.weight": "0940f7475c1f814c377a0e5c3e55bc6b058aba1290a64ee2ca3c1c8f270751d8" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "d32ab579b634854ee33973f309191b5099d830b8f9189443b26791e043f35b74", + "self_attn.k_proj.weight": "1a63ee1e67c33062741b1acbdcb80b0ec9e16b0f30e984b21a1a41e899504765", + "self_attn.v_proj.weight": "9ec2df6bba949c6870ca18d7dfde4a4055b72c809b44958868777e77f5abf1c8", + "self_attn.o_proj.weight": "8e9f8603686d189fecd3a4ba41ac32046c14ce9bf75662a70042a453b8984f72", + "self_attn.q_norm.weight": "1ae662bfcbfd5edee375b6a3bafa86cd26fe6dd611568b98b45950949b91a97b", + "self_attn.k_norm.weight": "3588b84b908a2d2d498d1f96db9990fa492b15088fe42fe7d8ace619738a1119", + "input_layernorm.weight": "7ab4e8ed36ba6396ebde3cf6685dc9ac0df299665cdd8bb682af51cc443b989e", + "post_attention_layernorm.weight": "0940f7475c1f814c377a0e5c3e55bc6b058aba1290a64ee2ca3c1c8f270751d8" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "d32ab579b634854ee33973f309191b5099d830b8f9189443b26791e043f35b74", + "self_attn.k_proj.weight": "1a63ee1e67c33062741b1acbdcb80b0ec9e16b0f30e984b21a1a41e899504765", + "self_attn.v_proj.weight": "9ec2df6bba949c6870ca18d7dfde4a4055b72c809b44958868777e77f5abf1c8", + "self_attn.o_proj.weight": "8e9f8603686d189fecd3a4ba41ac32046c14ce9bf75662a70042a453b8984f72", + "self_attn.q_norm.weight": "1ae662bfcbfd5edee375b6a3bafa86cd26fe6dd611568b98b45950949b91a97b", + "self_attn.k_norm.weight": "3588b84b908a2d2d498d1f96db9990fa492b15088fe42fe7d8ace619738a1119", + "input_layernorm.weight": "7ab4e8ed36ba6396ebde3cf6685dc9ac0df299665cdd8bb682af51cc443b989e", + "post_attention_layernorm.weight": "0940f7475c1f814c377a0e5c3e55bc6b058aba1290a64ee2ca3c1c8f270751d8" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 32, + "teacher_boundary_original_layer": 32 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_02_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_02_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..0002c1ee4e84b7aad7a55db5cb15d6eb16afde8b --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_02_fit.json @@ -0,0 +1,308 @@ +{ + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 0.28547625475643207, + "mean_abs": 4.936821420010852e-06, + "max_abs": 0.03876304626464844 + }, + "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": 150994944, + "mean": -2.2277035264374313e-06, + "std": 0.003590529790157256, + "rms": 0.003590530481233896, + "mean_abs": 0.0027030425456662974, + "min": -0.04027918726205826, + "max": 0.037824470549821854, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": -6.615836658359815e-06, + "std": 0.0036853567166835904, + "rms": 0.0036853626549499226, + "mean_abs": 0.002706917623678843, + "min": -0.03582677245140076, + "max": 0.03232936933636665 + }, + "mlp.up_proj.weight": { + "mean": 9.250769987071787e-08, + "std": 0.003794212333341261, + "rms": 0.0037942123344689885, + "mean_abs": 0.0028184043864409127, + "min": -0.033416759222745895, + "max": 0.03145444020628929 + }, + "mlp.down_proj.weight": { + "mean": -1.5978162082319614e-07, + "std": 0.0032707464357456407, + "rms": 0.003270746439648445, + "mean_abs": 0.0025838056268791356, + "min": -0.04027918726205826, + "max": 0.037824470549821854 + } + } + }, + "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": 287.0148811088875, + "dataset_tokens": 524288, + "tokens_per_second": 1826.6927414160662, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 40117289984, + "peak_reserved_bytes": 51361349632, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 16 + ], + [ + 17 + ] + ], + "retention_ratios": [ + 0.49296001567209896, + 0.507039984327901 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 6057, + 6231 + ], + "pair_score": 0.11846736168607752, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "d2ed544f73cf62e3ab17f0be58f92f865cd3605e6d229fe8b2bd23de52252508", + "self_attn.k_proj.weight": "787f7f67063f02e7d3fd3f715d589274faeccf7d41d87f074f9e5010c8fcab43", + "self_attn.v_proj.weight": "cbeea55153838935a713e0e697686d9e0494ecaa9faed73c9c9f3d742db218d2", + "self_attn.o_proj.weight": "6fbabb27e0f0a37a8c41a199de67ed0cdfbfc7f7d1187a7d4dd9519c6194c5f2", + "self_attn.q_norm.weight": "349a1ca5fc11e844626318e972364bf926df4415d34cde698fcdc1fed7bb86c3", + "self_attn.k_norm.weight": "68f81d391604fc4461e9297f19ca7a56b30cf90c5f8e0520137b7eb84d37ab91", + "input_layernorm.weight": "086e8d855b92cf3fb06fd4a34cdcedd527143c24144a737b1a49446c980dbd41", + "post_attention_layernorm.weight": "0b0aa8913baf6ec21771d1d6834adf8ce81c80a3a7719fa50a6a56f71d52e2a3" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "d2ed544f73cf62e3ab17f0be58f92f865cd3605e6d229fe8b2bd23de52252508", + "self_attn.k_proj.weight": "787f7f67063f02e7d3fd3f715d589274faeccf7d41d87f074f9e5010c8fcab43", + "self_attn.v_proj.weight": "cbeea55153838935a713e0e697686d9e0494ecaa9faed73c9c9f3d742db218d2", + "self_attn.o_proj.weight": "6fbabb27e0f0a37a8c41a199de67ed0cdfbfc7f7d1187a7d4dd9519c6194c5f2", + "self_attn.q_norm.weight": "349a1ca5fc11e844626318e972364bf926df4415d34cde698fcdc1fed7bb86c3", + "self_attn.k_norm.weight": "68f81d391604fc4461e9297f19ca7a56b30cf90c5f8e0520137b7eb84d37ab91", + "input_layernorm.weight": "086e8d855b92cf3fb06fd4a34cdcedd527143c24144a737b1a49446c980dbd41", + "post_attention_layernorm.weight": "0b0aa8913baf6ec21771d1d6834adf8ce81c80a3a7719fa50a6a56f71d52e2a3" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "d2ed544f73cf62e3ab17f0be58f92f865cd3605e6d229fe8b2bd23de52252508", + "self_attn.k_proj.weight": "787f7f67063f02e7d3fd3f715d589274faeccf7d41d87f074f9e5010c8fcab43", + "self_attn.v_proj.weight": "cbeea55153838935a713e0e697686d9e0494ecaa9faed73c9c9f3d742db218d2", + "self_attn.o_proj.weight": "6fbabb27e0f0a37a8c41a199de67ed0cdfbfc7f7d1187a7d4dd9519c6194c5f2", + "self_attn.q_norm.weight": "349a1ca5fc11e844626318e972364bf926df4415d34cde698fcdc1fed7bb86c3", + "self_attn.k_norm.weight": "68f81d391604fc4461e9297f19ca7a56b30cf90c5f8e0520137b7eb84d37ab91", + "input_layernorm.weight": "086e8d855b92cf3fb06fd4a34cdcedd527143c24144a737b1a49446c980dbd41", + "post_attention_layernorm.weight": "0b0aa8913baf6ec21771d1d6834adf8ce81c80a3a7719fa50a6a56f71d52e2a3" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 17, + "teacher_boundary_original_layer": 17 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_03_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_03_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..222f19a5c1839dae74f2c66e5d7a8b7890b97213 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_03_fit.json @@ -0,0 +1,308 @@ +{ + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 1.9195377668022477, + "mean_abs": 4.386278063369294e-05, + "max_abs": 0.15239524841308594 + }, + "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": 150994944, + "mean": 4.834807075187402e-06, + "std": 0.002954291666716121, + "rms": 0.0029542956228833586, + "mean_abs": 0.0023312543829282126, + "min": -0.025260327383875847, + "max": 0.025104448199272156, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.5033686698491996e-05, + "std": 0.0027293740459918606, + "rms": 0.0027294154492619347, + "mean_abs": 0.0021729754904905954, + "min": -0.02162746898829937, + "max": 0.0205176193267107 + }, + "mlp.up_proj.weight": { + "mean": 1.5114774972365316e-07, + "std": 0.0027591918042724883, + "rms": 0.002759191808412404, + "mean_abs": 0.0021809920047720275, + "min": -0.024778185412287712, + "max": 0.025104448199272156 + }, + "mlp.down_proj.weight": { + "mean": -6.804132226534421e-07, + "std": 0.003334777247271745, + "rms": 0.003334777316685999, + "mean_abs": 0.0026397956535220146, + "min": -0.025260327383875847, + "max": 0.022698627784848213 + } + } + }, + "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": 275.03382919635624, + "dataset_tokens": 524288, + "tokens_per_second": 1906.2673182130352, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 37833298944, + "peak_reserved_bytes": 51449430016, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 26 + ], + [ + 27 + ] + ], + "retention_ratios": [ + 0.500755807036962, + 0.4992441929630379 + ], + "retained_attention_groups": [ + 5, + 3 + ], + "retained_mlp_neurons": [ + 6154, + 6134 + ], + "pair_score": 0.11813264054820892, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "e374ecba7e5771f2299e56089ddd77b8b27f79f973e8be4e6cee80b9eac2612d", + "self_attn.k_proj.weight": "cf81f8d90cec377c6663e4b11e3dc0b61a0381e37444c00eef678183b4297b44", + "self_attn.v_proj.weight": "08d06843a169474bcd7a1f077dab1521fd59dd7dc4f0cbb81b4c399d0a153f98", + "self_attn.o_proj.weight": "efccaf7cf05bb7a6242e5ceb3afe68109d2e1c0e094f812a140e810d1b447b9c", + "self_attn.q_norm.weight": "4f1a08be52e5dedcad350ef489a3f349c839f22f0c2ee184e5edc2a1d4a0ddd9", + "self_attn.k_norm.weight": "f9ee6e6f0ac01557912733c0a1e3e3fbc977bd73cc9b89f203f13d1798e07ba6", + "input_layernorm.weight": "18d7e105f8c8b1594f50e198525ed0ec0b52e763ad77399b17b78ead143a289e", + "post_attention_layernorm.weight": "aeb4c2bf8614b342c7e265383dc930e75db4283123cb51d99196d1bbf113fd8b" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "e374ecba7e5771f2299e56089ddd77b8b27f79f973e8be4e6cee80b9eac2612d", + "self_attn.k_proj.weight": "cf81f8d90cec377c6663e4b11e3dc0b61a0381e37444c00eef678183b4297b44", + "self_attn.v_proj.weight": "08d06843a169474bcd7a1f077dab1521fd59dd7dc4f0cbb81b4c399d0a153f98", + "self_attn.o_proj.weight": "efccaf7cf05bb7a6242e5ceb3afe68109d2e1c0e094f812a140e810d1b447b9c", + "self_attn.q_norm.weight": "4f1a08be52e5dedcad350ef489a3f349c839f22f0c2ee184e5edc2a1d4a0ddd9", + "self_attn.k_norm.weight": "f9ee6e6f0ac01557912733c0a1e3e3fbc977bd73cc9b89f203f13d1798e07ba6", + "input_layernorm.weight": "18d7e105f8c8b1594f50e198525ed0ec0b52e763ad77399b17b78ead143a289e", + "post_attention_layernorm.weight": "aeb4c2bf8614b342c7e265383dc930e75db4283123cb51d99196d1bbf113fd8b" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "e374ecba7e5771f2299e56089ddd77b8b27f79f973e8be4e6cee80b9eac2612d", + "self_attn.k_proj.weight": "cf81f8d90cec377c6663e4b11e3dc0b61a0381e37444c00eef678183b4297b44", + "self_attn.v_proj.weight": "08d06843a169474bcd7a1f077dab1521fd59dd7dc4f0cbb81b4c399d0a153f98", + "self_attn.o_proj.weight": "efccaf7cf05bb7a6242e5ceb3afe68109d2e1c0e094f812a140e810d1b447b9c", + "self_attn.q_norm.weight": "4f1a08be52e5dedcad350ef489a3f349c839f22f0c2ee184e5edc2a1d4a0ddd9", + "self_attn.k_norm.weight": "f9ee6e6f0ac01557912733c0a1e3e3fbc977bd73cc9b89f203f13d1798e07ba6", + "input_layernorm.weight": "18d7e105f8c8b1594f50e198525ed0ec0b52e763ad77399b17b78ead143a289e", + "post_attention_layernorm.weight": "aeb4c2bf8614b342c7e265383dc930e75db4283123cb51d99196d1bbf113fd8b" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 26, + "teacher_boundary_original_layer": 27 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_04_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_04_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..b9aa5c5834fff151009f57dd123888a32bc39238 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_04_fit.json @@ -0,0 +1,309 @@ +{ + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 0.5103952856501015, + "mean_abs": 4.802161230246485e-06, + "max_abs": 0.18325042724609375 + }, + "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": 150994944, + "mean": 2.1773275370328014e-07, + "std": 0.004527799256407125, + "rms": 0.00452779926164229, + "mean_abs": 0.003343291063275602, + "min": -0.04195663332939148, + "max": 0.042360153049230576, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.2623284722697765e-06, + "std": 0.004667664245278318, + "rms": 0.0046676644159710946, + "mean_abs": 0.0033581051975488663, + "min": -0.04188692569732666, + "max": 0.04206804931163788 + }, + "mlp.up_proj.weight": { + "mean": -2.837029266326378e-07, + "std": 0.005126653429482778, + "rms": 0.005126653437332669, + "mean_abs": 0.003825555555522442, + "min": -0.0383785143494606, + "max": 0.037312258034944534 + }, + "mlp.down_proj.weight": { + "mean": -3.2542728452729836e-07, + "std": 0.0036651373492196473, + "rms": 0.00366513736366698, + "mean_abs": 0.0028462124367554984, + "min": -0.04195663332939148, + "max": 0.042360153049230576 + } + } + }, + "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": 272.50738346390426, + "dataset_tokens": 524288, + "tokens_per_second": 1923.940530842336, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 38422417408, + "peak_reserved_bytes": 50077892608, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 15 + ], + [ + 16, + 17 + ] + ], + "retention_ratios": [ + 0.48481783779572774, + 0.5151821622042723 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 5957, + 6331 + ], + "pair_score": 0.12428857100770828, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "e144fc375feeba841fb893f66d6c6fa9ef04120dbfa4ddfc1a159bf86586ba61", + "self_attn.k_proj.weight": "355b2a930766fc9c33f032fc19c3d1c618a5cc70d08acf1492aea8d9dc474150", + "self_attn.v_proj.weight": "34f582d607f0468a641dc8622fa95cc0bdbfdc2f38b98a32e11e6ad55d7b2e37", + "self_attn.o_proj.weight": "2f832c98994cce37666e06e9fec044ca2ecf17cb00b5adb1f10358c4367d3070", + "self_attn.q_norm.weight": "92b6ba51de0e72d7322500ceb344593844994aa05de41a1566908d0036b72158", + "self_attn.k_norm.weight": "fe2847d3261818e9ce010ef6c3e5aaded6c3045337c7b2989470d6d405bde5d9", + "input_layernorm.weight": "a36bf9c9668635c84481fa731271a83870120a57b6610c2ff64274e6a96d9f3c", + "post_attention_layernorm.weight": "02c0294d3d2fc22669c98157d5514cddf1a41a4ff47925bc0c560e86a60aa425" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "e144fc375feeba841fb893f66d6c6fa9ef04120dbfa4ddfc1a159bf86586ba61", + "self_attn.k_proj.weight": "355b2a930766fc9c33f032fc19c3d1c618a5cc70d08acf1492aea8d9dc474150", + "self_attn.v_proj.weight": "34f582d607f0468a641dc8622fa95cc0bdbfdc2f38b98a32e11e6ad55d7b2e37", + "self_attn.o_proj.weight": "2f832c98994cce37666e06e9fec044ca2ecf17cb00b5adb1f10358c4367d3070", + "self_attn.q_norm.weight": "92b6ba51de0e72d7322500ceb344593844994aa05de41a1566908d0036b72158", + "self_attn.k_norm.weight": "fe2847d3261818e9ce010ef6c3e5aaded6c3045337c7b2989470d6d405bde5d9", + "input_layernorm.weight": "a36bf9c9668635c84481fa731271a83870120a57b6610c2ff64274e6a96d9f3c", + "post_attention_layernorm.weight": "02c0294d3d2fc22669c98157d5514cddf1a41a4ff47925bc0c560e86a60aa425" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "e144fc375feeba841fb893f66d6c6fa9ef04120dbfa4ddfc1a159bf86586ba61", + "self_attn.k_proj.weight": "355b2a930766fc9c33f032fc19c3d1c618a5cc70d08acf1492aea8d9dc474150", + "self_attn.v_proj.weight": "34f582d607f0468a641dc8622fa95cc0bdbfdc2f38b98a32e11e6ad55d7b2e37", + "self_attn.o_proj.weight": "2f832c98994cce37666e06e9fec044ca2ecf17cb00b5adb1f10358c4367d3070", + "self_attn.q_norm.weight": "92b6ba51de0e72d7322500ceb344593844994aa05de41a1566908d0036b72158", + "self_attn.k_norm.weight": "fe2847d3261818e9ce010ef6c3e5aaded6c3045337c7b2989470d6d405bde5d9", + "input_layernorm.weight": "a36bf9c9668635c84481fa731271a83870120a57b6610c2ff64274e6a96d9f3c", + "post_attention_layernorm.weight": "02c0294d3d2fc22669c98157d5514cddf1a41a4ff47925bc0c560e86a60aa425" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 16, + "teacher_boundary_original_layer": 16 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_05_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_05_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..1d7170f82f1d838ff8abf2c8a8db7fe05b00fb41 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_05_fit.json @@ -0,0 +1,308 @@ +{ + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 10.416070559929201, + "mean_abs": 0.00014571001843756271, + "max_abs": 1.5470943450927734 + }, + "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": 150994944, + "mean": 3.504058844959622e-06, + "std": 0.0028318628407741995, + "rms": 0.002831865008679988, + "mean_abs": 0.0022335324643386733, + "min": -0.026923593133687973, + "max": 0.029769256711006165, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0593326199644556e-05, + "std": 0.0026527072310847228, + "rms": 0.0026527283827050877, + "mean_abs": 0.00211204681545496, + "min": -0.023384634405374527, + "max": 0.021433265879750252 + }, + "mlp.up_proj.weight": { + "mean": -1.3555364830608596e-07, + "std": 0.002661194413471638, + "rms": 0.002661194416923996, + "mean_abs": 0.0020990585908293724, + "min": -0.01704355515539646, + "max": 0.017607910558581352 + }, + "mlp.down_proj.weight": { + "mean": 5.440398354039644e-08, + "std": 0.0031526900707367247, + "rms": 0.0031526900712061322, + "mean_abs": 0.002489491986731688, + "min": -0.026923593133687973, + "max": 0.029769256711006165 + } + } + }, + "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": 263.1926762089133, + "dataset_tokens": 524288, + "tokens_per_second": 1992.0311140566776, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 35835041792, + "peak_reserved_bytes": 48907681792, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 29 + ], + [ + 30 + ] + ], + "retention_ratios": [ + 0.5168892574349215, + 0.4831107425650785 + ], + "retained_attention_groups": [ + 5, + 3 + ], + "retained_mlp_neurons": [ + 6352, + 5936 + ], + "pair_score": 0.12363086149413535, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "52fbd62bd62d7e2eaac0d2200d13f871e3deb60c0fd528297ee4536e9d8dc086", + "self_attn.k_proj.weight": "8111ddc37251c97bb655b31cd12861532c4bfbebd575bf99d2b1fbe10c48e056", + "self_attn.v_proj.weight": "90ab892c075978b6c4da576a84726e0dd1b2c03a2693ae085e9fb4854f8f5cda", + "self_attn.o_proj.weight": "0bd5ffb8b1db91700ecef537352b4938c61ab309f0c133e406f70406ea3d5479", + "self_attn.q_norm.weight": "da82f14c18c6dd24be49f9ea70b0dba47f259589a8c36f25319404914cc93e30", + "self_attn.k_norm.weight": "e997dc8cf097fb2e1771403fe8dfd46c8e38290d07e3fc105cf003611032c7f4", + "input_layernorm.weight": "64e67fc0c3a1540d2fc0134655058358a78cc81e047873cf05afac1c6a2fc0d0", + "post_attention_layernorm.weight": "0a89cbbfd56094d174142e7b4ad773e644f7bb78c6b3539ebb3eab6c048680cd" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "52fbd62bd62d7e2eaac0d2200d13f871e3deb60c0fd528297ee4536e9d8dc086", + "self_attn.k_proj.weight": "8111ddc37251c97bb655b31cd12861532c4bfbebd575bf99d2b1fbe10c48e056", + "self_attn.v_proj.weight": "90ab892c075978b6c4da576a84726e0dd1b2c03a2693ae085e9fb4854f8f5cda", + "self_attn.o_proj.weight": "0bd5ffb8b1db91700ecef537352b4938c61ab309f0c133e406f70406ea3d5479", + "self_attn.q_norm.weight": "da82f14c18c6dd24be49f9ea70b0dba47f259589a8c36f25319404914cc93e30", + "self_attn.k_norm.weight": "e997dc8cf097fb2e1771403fe8dfd46c8e38290d07e3fc105cf003611032c7f4", + "input_layernorm.weight": "64e67fc0c3a1540d2fc0134655058358a78cc81e047873cf05afac1c6a2fc0d0", + "post_attention_layernorm.weight": "0a89cbbfd56094d174142e7b4ad773e644f7bb78c6b3539ebb3eab6c048680cd" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "52fbd62bd62d7e2eaac0d2200d13f871e3deb60c0fd528297ee4536e9d8dc086", + "self_attn.k_proj.weight": "8111ddc37251c97bb655b31cd12861532c4bfbebd575bf99d2b1fbe10c48e056", + "self_attn.v_proj.weight": "90ab892c075978b6c4da576a84726e0dd1b2c03a2693ae085e9fb4854f8f5cda", + "self_attn.o_proj.weight": "0bd5ffb8b1db91700ecef537352b4938c61ab309f0c133e406f70406ea3d5479", + "self_attn.q_norm.weight": "da82f14c18c6dd24be49f9ea70b0dba47f259589a8c36f25319404914cc93e30", + "self_attn.k_norm.weight": "e997dc8cf097fb2e1771403fe8dfd46c8e38290d07e3fc105cf003611032c7f4", + "input_layernorm.weight": "64e67fc0c3a1540d2fc0134655058358a78cc81e047873cf05afac1c6a2fc0d0", + "post_attention_layernorm.weight": "0a89cbbfd56094d174142e7b4ad773e644f7bb78c6b3539ebb3eab6c048680cd" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 27, + "teacher_boundary_original_layer": 30 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_06_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_06_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..a7ba379779825a0a690577aa414a3175b881e34e --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_06_fit.json @@ -0,0 +1,309 @@ +{ + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 1.6286034611369704, + "mean_abs": 4.974205835929347e-05, + "max_abs": 0.09180885553359985 + }, + "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": 150994944, + "mean": 3.004043845875357e-06, + "std": 0.002940920321421633, + "rms": 0.0029409218556823553, + "mean_abs": 0.002319265363944901, + "min": -0.02507743053138256, + "max": 0.02854803204536438, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 8.660291011134783e-06, + "std": 0.002758917691235299, + "rms": 0.0027589312836044885, + "mean_abs": 0.0022007301449775696, + "min": -0.021901600062847137, + "max": 0.024919675663113594 + }, + "mlp.up_proj.weight": { + "mean": 3.8269778694181394e-07, + "std": 0.0027593195629921686, + "rms": 0.0027593195895308843, + "mean_abs": 0.0021812085372706256, + "min": -0.019312186166644096, + "max": 0.017826871946454048 + }, + "mlp.down_proj.weight": { + "mean": -3.085726045052676e-08, + "std": 0.003274372864827382, + "rms": 0.0032743728649727794, + "mean_abs": 0.002575857409586509, + "min": -0.02507743053138256, + "max": 0.02854803204536438 + } + } + }, + "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": 295.43956048227847, + "dataset_tokens": 524288, + "tokens_per_second": 1774.603235748615, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 35365853184, + "peak_reserved_bytes": 47737470976, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 25 + ], + [ + 26, + 27 + ] + ], + "retention_ratios": [ + 0.5023699918186109, + 0.49763000818138914 + ], + "retained_attention_groups": [ + 5, + 3 + ], + "retained_mlp_neurons": [ + 6174, + 6114 + ], + "pair_score": 0.12410008491195262, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "39f86798d44a14cf29c0724dc84fe0261eb909a05cd405ac91ac7d141f235a4e", + "self_attn.k_proj.weight": "e23576863e9742419b554ec91e06851542fa31624588dd0b0865c98ca756ef07", + "self_attn.v_proj.weight": "32df6f78cdcbd2eb1155384475ea6ded1079aee19486bca7713627278410d373", + "self_attn.o_proj.weight": "607f1bd80abb8a599c6b66c669658355b73eb737edc5366d0e1afc494609943f", + "self_attn.q_norm.weight": "a24069bc529bcd467f912646b8707018d31f4a0446da073b1b205c4db50ee145", + "self_attn.k_norm.weight": "9dab9cd5fae1f8d67c448cfcf98e579cbcfc38d8c416771282eb1fe691b20022", + "input_layernorm.weight": "1ac54bb5ca0b83123b8cffdb4badce519a1ce5ddd669f6243d10f00b493d445d", + "post_attention_layernorm.weight": "394b5889e1bf81ccb8c96b48f7f760df70a5d0b24835ffa47bdf1e053daeecea" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "39f86798d44a14cf29c0724dc84fe0261eb909a05cd405ac91ac7d141f235a4e", + "self_attn.k_proj.weight": "e23576863e9742419b554ec91e06851542fa31624588dd0b0865c98ca756ef07", + "self_attn.v_proj.weight": "32df6f78cdcbd2eb1155384475ea6ded1079aee19486bca7713627278410d373", + "self_attn.o_proj.weight": "607f1bd80abb8a599c6b66c669658355b73eb737edc5366d0e1afc494609943f", + "self_attn.q_norm.weight": "a24069bc529bcd467f912646b8707018d31f4a0446da073b1b205c4db50ee145", + "self_attn.k_norm.weight": "9dab9cd5fae1f8d67c448cfcf98e579cbcfc38d8c416771282eb1fe691b20022", + "input_layernorm.weight": "1ac54bb5ca0b83123b8cffdb4badce519a1ce5ddd669f6243d10f00b493d445d", + "post_attention_layernorm.weight": "394b5889e1bf81ccb8c96b48f7f760df70a5d0b24835ffa47bdf1e053daeecea" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "39f86798d44a14cf29c0724dc84fe0261eb909a05cd405ac91ac7d141f235a4e", + "self_attn.k_proj.weight": "e23576863e9742419b554ec91e06851542fa31624588dd0b0865c98ca756ef07", + "self_attn.v_proj.weight": "32df6f78cdcbd2eb1155384475ea6ded1079aee19486bca7713627278410d373", + "self_attn.o_proj.weight": "607f1bd80abb8a599c6b66c669658355b73eb737edc5366d0e1afc494609943f", + "self_attn.q_norm.weight": "a24069bc529bcd467f912646b8707018d31f4a0446da073b1b205c4db50ee145", + "self_attn.k_norm.weight": "9dab9cd5fae1f8d67c448cfcf98e579cbcfc38d8c416771282eb1fe691b20022", + "input_layernorm.weight": "1ac54bb5ca0b83123b8cffdb4badce519a1ce5ddd669f6243d10f00b493d445d", + "post_attention_layernorm.weight": "394b5889e1bf81ccb8c96b48f7f760df70a5d0b24835ffa47bdf1e053daeecea" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 24, + "teacher_boundary_original_layer": 26 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_07_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_07_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..429fba7271e932e1cff0dcd77d89ec4379de203b --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_07_fit.json @@ -0,0 +1,308 @@ +{ + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 0.23740315356757863, + "mean_abs": 5.882513101419641e-06, + "max_abs": 0.027914047241210938 + }, + "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": 150994944, + "mean": 1.3507076851561174e-06, + "std": 0.003134056113070226, + "rms": 0.0031340564041325266, + "mean_abs": 0.002464224429180225, + "min": -0.029158497229218483, + "max": 0.030568668618798256, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 4.040793404177141e-06, + "std": 0.0028221248657079863, + "rms": 0.0028221277585642104, + "mean_abs": 0.002228420072545608, + "min": -0.029158497229218483, + "max": 0.030568668618798256 + }, + "mlp.up_proj.weight": { + "mean": -6.914443323087956e-07, + "std": 0.003002453443705404, + "rms": 0.003002453523322835, + "mean_abs": 0.002365610251824061, + "min": -0.025998085737228394, + "max": 0.022817036136984825 + }, + "mlp.down_proj.weight": { + "mean": 7.027739836000061e-07, + "std": 0.003533807563180072, + "rms": 0.003533807633060967, + "mean_abs": 0.0027986429631710052, + "min": -0.02480441704392433, + "max": 0.022958504036068916 + } + } + }, + "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": 277.19303956301883, + "dataset_tokens": 524288, + "tokens_per_second": 1891.418344510072, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 35199262720, + "peak_reserved_bytes": 46567260160, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 20 + ], + [ + 21 + ] + ], + "retention_ratios": [ + 0.47186972247563475, + 0.5281302775243653 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 5798, + 6490 + ], + "pair_score": 0.1278106997859605, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "100c474fa668596c16128a59e841aa485f057f3767c68833a4766a06e067a114", + "self_attn.k_proj.weight": "df3000d47df027011761b871c1d47491a2f13c4dd3363175be9e93970d1f9be5", + "self_attn.v_proj.weight": "bb7a683a3151ecc3ca6739b59f54dfcbdc6d328334af50213c274a5c4226ba18", + "self_attn.o_proj.weight": "663b0ca3ae6bbbb3c613ee1f9af319eec3b35f0dbc01efc7b6d774625a8db0e8", + "self_attn.q_norm.weight": "5aee4fb2de6a7f64cd3162db26cc0a06e004f6e91f8d1bfb0bb33a18e3c72eec", + "self_attn.k_norm.weight": "c27266ee8a88066155b72fae60bf106ecbce5880cc8a3d37dfce5e7a6b671567", + "input_layernorm.weight": "34a032c26054d427bf876a4574e76d16fe6275d6f951c1ff686f89def2c68581", + "post_attention_layernorm.weight": "2331ab53730e845fdf782fc2d6aab39a66b8e7bb31afed5212594790002946a0" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "100c474fa668596c16128a59e841aa485f057f3767c68833a4766a06e067a114", + "self_attn.k_proj.weight": "df3000d47df027011761b871c1d47491a2f13c4dd3363175be9e93970d1f9be5", + "self_attn.v_proj.weight": "bb7a683a3151ecc3ca6739b59f54dfcbdc6d328334af50213c274a5c4226ba18", + "self_attn.o_proj.weight": "663b0ca3ae6bbbb3c613ee1f9af319eec3b35f0dbc01efc7b6d774625a8db0e8", + "self_attn.q_norm.weight": "5aee4fb2de6a7f64cd3162db26cc0a06e004f6e91f8d1bfb0bb33a18e3c72eec", + "self_attn.k_norm.weight": "c27266ee8a88066155b72fae60bf106ecbce5880cc8a3d37dfce5e7a6b671567", + "input_layernorm.weight": "34a032c26054d427bf876a4574e76d16fe6275d6f951c1ff686f89def2c68581", + "post_attention_layernorm.weight": "2331ab53730e845fdf782fc2d6aab39a66b8e7bb31afed5212594790002946a0" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "100c474fa668596c16128a59e841aa485f057f3767c68833a4766a06e067a114", + "self_attn.k_proj.weight": "df3000d47df027011761b871c1d47491a2f13c4dd3363175be9e93970d1f9be5", + "self_attn.v_proj.weight": "bb7a683a3151ecc3ca6739b59f54dfcbdc6d328334af50213c274a5c4226ba18", + "self_attn.o_proj.weight": "663b0ca3ae6bbbb3c613ee1f9af319eec3b35f0dbc01efc7b6d774625a8db0e8", + "self_attn.q_norm.weight": "5aee4fb2de6a7f64cd3162db26cc0a06e004f6e91f8d1bfb0bb33a18e3c72eec", + "self_attn.k_norm.weight": "c27266ee8a88066155b72fae60bf106ecbce5880cc8a3d37dfce5e7a6b671567", + "input_layernorm.weight": "34a032c26054d427bf876a4574e76d16fe6275d6f951c1ff686f89def2c68581", + "post_attention_layernorm.weight": "2331ab53730e845fdf782fc2d6aab39a66b8e7bb31afed5212594790002946a0" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 19, + "teacher_boundary_original_layer": 21 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_08_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_08_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..0f0a99e70db460f85af5e684b91c47f0c0ff94ac --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_08_fit.json @@ -0,0 +1,309 @@ +{ + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 6.49169853930633, + "mean_abs": 9.474362013861537e-05, + "max_abs": 1.5315284729003906 + }, + "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": 150994944, + "mean": 4.591499305206526e-06, + "std": 0.0027378081098337064, + "rms": 0.002737811959966769, + "mean_abs": 0.0021497576704455745, + "min": -0.032534871250391006, + "max": 0.03337450698018074, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.311179221374914e-05, + "std": 0.0026171782407182786, + "rms": 0.0026172110848734155, + "mean_abs": 0.002076787098000447, + "min": -0.022585367783904076, + "max": 0.024974439293146133 + }, + "mlp.up_proj.weight": { + "mean": 6.339674503882028e-07, + "std": 0.002621912470452202, + "rms": 0.0026219125470975375, + "mean_abs": 0.0020654979161918163, + "min": -0.01963549107313156, + "max": 0.021688615903258324 + }, + "mlp.down_proj.weight": { + "mean": 2.873825148223356e-08, + "std": 0.002960172919978422, + "rms": 0.002960172920117922, + "mean_abs": 0.0023069879971444607, + "min": -0.032534871250391006, + "max": 0.03337450698018074 + } + } + }, + "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": 267.72440619114786, + "dataset_tokens": 524288, + "tokens_per_second": 1958.3123087615434, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 33519681536, + "peak_reserved_bytes": 45397049344, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 28 + ], + [ + 29, + 30 + ] + ], + "retention_ratios": [ + 0.46346630280250284, + 0.5365336971974971 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 5695, + 6593 + ], + "pair_score": 0.13028502202731498, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "36252b41be52e81d520f07dfc5c92c7933266cc8b572ca413af64b3d6d715629", + "self_attn.k_proj.weight": "da2a0f50a824c4ed95a852d28a0729890e6df83eeea7dcaed1383ee0a17c41c7", + "self_attn.v_proj.weight": "a097c0995b19020bc7d3bf86b42791bb50e8b0a0965f1c9d575fca0804816eec", + "self_attn.o_proj.weight": "2fd02a6653ed46d24683bacdf5074072c9e4564bc9e10224082af2787419a7e5", + "self_attn.q_norm.weight": "984494fcfbe0781014b23dc6f76c39fcc7a024d5474c3e993da11f808c4c6e5b", + "self_attn.k_norm.weight": "6a7a2aa47fc5932c85a04ec3f8126eec8459cbe3dda0f027ea100b437d4e5af7", + "input_layernorm.weight": "bef856a0d4f111bad8496c0bed2bfb65efbef1580f074bc4d9929d8185e8e9b7", + "post_attention_layernorm.weight": "4e0f51ab4f79e73bd1ca169a404e5308778535c28228aedb026fef9993e650c3" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "36252b41be52e81d520f07dfc5c92c7933266cc8b572ca413af64b3d6d715629", + "self_attn.k_proj.weight": "da2a0f50a824c4ed95a852d28a0729890e6df83eeea7dcaed1383ee0a17c41c7", + "self_attn.v_proj.weight": "a097c0995b19020bc7d3bf86b42791bb50e8b0a0965f1c9d575fca0804816eec", + "self_attn.o_proj.weight": "2fd02a6653ed46d24683bacdf5074072c9e4564bc9e10224082af2787419a7e5", + "self_attn.q_norm.weight": "984494fcfbe0781014b23dc6f76c39fcc7a024d5474c3e993da11f808c4c6e5b", + "self_attn.k_norm.weight": "6a7a2aa47fc5932c85a04ec3f8126eec8459cbe3dda0f027ea100b437d4e5af7", + "input_layernorm.weight": "bef856a0d4f111bad8496c0bed2bfb65efbef1580f074bc4d9929d8185e8e9b7", + "post_attention_layernorm.weight": "4e0f51ab4f79e73bd1ca169a404e5308778535c28228aedb026fef9993e650c3" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "36252b41be52e81d520f07dfc5c92c7933266cc8b572ca413af64b3d6d715629", + "self_attn.k_proj.weight": "da2a0f50a824c4ed95a852d28a0729890e6df83eeea7dcaed1383ee0a17c41c7", + "self_attn.v_proj.weight": "a097c0995b19020bc7d3bf86b42791bb50e8b0a0965f1c9d575fca0804816eec", + "self_attn.o_proj.weight": "2fd02a6653ed46d24683bacdf5074072c9e4564bc9e10224082af2787419a7e5", + "self_attn.q_norm.weight": "984494fcfbe0781014b23dc6f76c39fcc7a024d5474c3e993da11f808c4c6e5b", + "self_attn.k_norm.weight": "6a7a2aa47fc5932c85a04ec3f8126eec8459cbe3dda0f027ea100b437d4e5af7", + "input_layernorm.weight": "bef856a0d4f111bad8496c0bed2bfb65efbef1580f074bc4d9929d8185e8e9b7", + "post_attention_layernorm.weight": "4e0f51ab4f79e73bd1ca169a404e5308778535c28228aedb026fef9993e650c3" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 24, + "teacher_boundary_original_layer": 29 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_09_fit.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_09_fit.json new file mode 100644 index 0000000000000000000000000000000000000000..6cf796325c7a39649864028377e2bf47415f797a --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/cycle_09_fit.json @@ -0,0 +1,308 @@ +{ + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 0.5486992756018507, + "mean_abs": 7.279721204314329e-06, + "max_abs": 0.08547437191009521 + }, + "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": 150994944, + "mean": -2.401146111373641e-06, + "std": 0.0028625390829901984, + "rms": 0.00286254009005097, + "mean_abs": 0.002229874281005727, + "min": -0.031118491664528847, + "max": 0.03590920567512512, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": -7.017540459249479e-06, + "std": 0.0026435958450601446, + "rms": 0.0026436051592273304, + "mean_abs": 0.0020676087588071823, + "min": -0.026987718418240547, + "max": 0.029445279389619827 + }, + "mlp.up_proj.weight": { + "mean": -3.4636233673760824e-07, + "std": 0.0026137689593844203, + "rms": 0.0026137689823334392, + "mean_abs": 0.0020307997862497964, + "min": -0.03019127808511257, + "max": 0.026006054133176804 + }, + "mlp.down_proj.weight": { + "mean": 1.6046446186616473e-07, + "std": 0.0032805442756951874, + "rms": 0.0032805442796196645, + "mean_abs": 0.0025912142979602018, + "min": -0.031118491664528847, + "max": 0.03590920567512512 + } + } + }, + "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": 251.94926179386675, + "dataset_tokens": 524288, + "tokens_per_second": 2080.92691467756, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 33655689216, + "peak_reserved_bytes": 44226838528, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 18 + ], + [ + 19 + ] + ], + "retention_ratios": [ + 0.43171495242956137, + 0.5682850475704386 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 5304, + 6984 + ], + "pair_score": 0.13059031313404124, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "f2a853932fea15a5a825782f208d6ca3f77ccf896addd4d9e56f0e8e9082fe6b", + "self_attn.k_proj.weight": "5575d2b5c9f9213078cee249df0db1a0d912c10900df8a7636095e4835a61217", + "self_attn.v_proj.weight": "9f294925ca5d2ae3ada26843af7fde6baa73c1a158e80d0baf14a4871dffb000", + "self_attn.o_proj.weight": "cb2a380e6bebe924e97bca438e8be51a7557b79f87c3a9eff7f3d94816a19401", + "self_attn.q_norm.weight": "92f79f4e9257476501577f2a7519154db20b0859e33b071a9498bb47136dce8f", + "self_attn.k_norm.weight": "6714e2b2f504289ad5c98deb930db2b2ba947ad86b1bc6fe814f461ae93ef273", + "input_layernorm.weight": "0b6edcbe6fc1e1bf40352a8291be48de9315be9a8b60b0e5f6f79e926527c90c", + "post_attention_layernorm.weight": "dba76b7f863c3425bdc928b6d785d9d8b414258c7d2cac5c591cadce3d89bba5" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "f2a853932fea15a5a825782f208d6ca3f77ccf896addd4d9e56f0e8e9082fe6b", + "self_attn.k_proj.weight": "5575d2b5c9f9213078cee249df0db1a0d912c10900df8a7636095e4835a61217", + "self_attn.v_proj.weight": "9f294925ca5d2ae3ada26843af7fde6baa73c1a158e80d0baf14a4871dffb000", + "self_attn.o_proj.weight": "cb2a380e6bebe924e97bca438e8be51a7557b79f87c3a9eff7f3d94816a19401", + "self_attn.q_norm.weight": "92f79f4e9257476501577f2a7519154db20b0859e33b071a9498bb47136dce8f", + "self_attn.k_norm.weight": "6714e2b2f504289ad5c98deb930db2b2ba947ad86b1bc6fe814f461ae93ef273", + "input_layernorm.weight": "0b6edcbe6fc1e1bf40352a8291be48de9315be9a8b60b0e5f6f79e926527c90c", + "post_attention_layernorm.weight": "dba76b7f863c3425bdc928b6d785d9d8b414258c7d2cac5c591cadce3d89bba5" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "f2a853932fea15a5a825782f208d6ca3f77ccf896addd4d9e56f0e8e9082fe6b", + "self_attn.k_proj.weight": "5575d2b5c9f9213078cee249df0db1a0d912c10900df8a7636095e4835a61217", + "self_attn.v_proj.weight": "9f294925ca5d2ae3ada26843af7fde6baa73c1a158e80d0baf14a4871dffb000", + "self_attn.o_proj.weight": "cb2a380e6bebe924e97bca438e8be51a7557b79f87c3a9eff7f3d94816a19401", + "self_attn.q_norm.weight": "92f79f4e9257476501577f2a7519154db20b0859e33b071a9498bb47136dce8f", + "self_attn.k_norm.weight": "6714e2b2f504289ad5c98deb930db2b2ba947ad86b1bc6fe814f461ae93ef273", + "input_layernorm.weight": "0b6edcbe6fc1e1bf40352a8291be48de9315be9a8b60b0e5f6f79e926527c90c", + "post_attention_layernorm.weight": "dba76b7f863c3425bdc928b6d785d9d8b414258c7d2cac5c591cadce3d89bba5" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 17, + "teacher_boundary_original_layer": 19 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/data_fingerprints.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/data_fingerprints.json new file mode 100644 index 0000000000000000000000000000000000000000..d33fb86c58efcaca8b4733e314402b8360ba403b --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/data_fingerprints.json @@ -0,0 +1,14 @@ +{ + "calib_loader": { + "sequences": 64, + "sha256": "85a84b9a68cf0856fd363186d3a273860886b1c17f876cae145fd092454aff55", + "attention_mask_sha256": "b1476de1907209012e63fa502715fd97db26e595352faa808d8c10433a1472a4", + "valid_tokens": 65536 + }, + "distill_loader": { + "sequences": 512, + "sha256": "5d9d4cc2f81d8712b932806c0c2b2992dce9bd3e6c7a143f1f670649b8bfe693", + "attention_mask_sha256": "c8e7f8e30cd532b82e6af4b98d596bc7106f29f9fb2b398b44355e624898a30d", + "valid_tokens": 524288 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/selection.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/selection.json new file mode 100644 index 0000000000000000000000000000000000000000..b641caf70f5f28ae507826bd3ae23907d64e9c7f --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/selection.json @@ -0,0 +1,662 @@ +[ + { + "cycle": 1, + "pair_index": 31, + "initializer": "come", + "lambda_left": null, + "recipient_original_layer": 31, + "recipient_side": "left", + "removed_original_layer": 32, + "source_lineage": [ + [ + 31 + ], + [ + 32 + ] + ], + "retention_ratios": [ + 0.49274789168296595, + 0.5072521083170339 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 6054, + 6234 + ], + "pair_score": 0.11533127194072337, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false, + "removed_original_layers": [ + 32 + ], + "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, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 33, + 34, + 35 + ] + }, + { + "cycle": 2, + "pair_index": 16, + "initializer": "come", + "lambda_left": null, + "recipient_original_layer": 16, + "recipient_side": "left", + "removed_original_layer": 17, + "source_lineage": [ + [ + 16 + ], + [ + 17 + ] + ], + "retention_ratios": [ + 0.49296001567209896, + 0.507039984327901 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 6057, + 6231 + ], + "pair_score": 0.11846736168607752, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false, + "removed_original_layers": [ + 17 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 33, + 34, + 35 + ] + }, + { + "cycle": 3, + "pair_index": 25, + "initializer": "come", + "lambda_left": null, + "recipient_original_layer": 26, + "recipient_side": "left", + "removed_original_layer": 27, + "source_lineage": [ + [ + 26 + ], + [ + 27 + ] + ], + "retention_ratios": [ + 0.500755807036962, + 0.4992441929630379 + ], + "retained_attention_groups": [ + 5, + 3 + ], + "retained_mlp_neurons": [ + 6154, + 6134 + ], + "pair_score": 0.11813264054820892, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false, + "removed_original_layers": [ + 27 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 28, + 29, + 30, + 31, + 33, + 34, + 35 + ] + }, + { + "cycle": 4, + "pair_index": 15, + "initializer": "come", + "lambda_left": null, + "recipient_original_layer": 15, + "recipient_side": "left", + "removed_original_layer": 16, + "source_lineage": [ + [ + 15 + ], + [ + 16, + 17 + ] + ], + "retention_ratios": [ + 0.48481783779572774, + 0.5151821622042723 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 5957, + 6331 + ], + "pair_score": 0.12428857100770828, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false, + "removed_original_layers": [ + 16 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 28, + 29, + 30, + 31, + 33, + 34, + 35 + ] + }, + { + "cycle": 5, + "pair_index": 26, + "initializer": "come", + "lambda_left": null, + "recipient_original_layer": 29, + "recipient_side": "left", + "removed_original_layer": 30, + "source_lineage": [ + [ + 29 + ], + [ + 30 + ] + ], + "retention_ratios": [ + 0.5168892574349215, + 0.4831107425650785 + ], + "retained_attention_groups": [ + 5, + 3 + ], + "retained_mlp_neurons": [ + 6352, + 5936 + ], + "pair_score": 0.12363086149413535, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false, + "removed_original_layers": [ + 30 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 28, + 29, + 31, + 33, + 34, + 35 + ] + }, + { + "cycle": 6, + "pair_index": 23, + "initializer": "come", + "lambda_left": null, + "recipient_original_layer": 25, + "recipient_side": "left", + "removed_original_layer": 26, + "source_lineage": [ + [ + 25 + ], + [ + 26, + 27 + ] + ], + "retention_ratios": [ + 0.5023699918186109, + 0.49763000818138914 + ], + "retained_attention_groups": [ + 5, + 3 + ], + "retained_mlp_neurons": [ + 6174, + 6114 + ], + "pair_score": 0.12410008491195262, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false, + "removed_original_layers": [ + 26 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 28, + 29, + 31, + 33, + 34, + 35 + ] + }, + { + "cycle": 7, + "pair_index": 18, + "initializer": "come", + "lambda_left": null, + "recipient_original_layer": 20, + "recipient_side": "left", + "removed_original_layer": 21, + "source_lineage": [ + [ + 20 + ], + [ + 21 + ] + ], + "retention_ratios": [ + 0.47186972247563475, + 0.5281302775243653 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 5798, + 6490 + ], + "pair_score": 0.1278106997859605, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false, + "removed_original_layers": [ + 21 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 18, + 19, + 20, + 22, + 23, + 24, + 25, + 28, + 29, + 31, + 33, + 34, + 35 + ] + }, + { + "cycle": 8, + "pair_index": 23, + "initializer": "come", + "lambda_left": null, + "recipient_original_layer": 28, + "recipient_side": "left", + "removed_original_layer": 29, + "source_lineage": [ + [ + 28 + ], + [ + 29, + 30 + ] + ], + "retention_ratios": [ + 0.46346630280250284, + 0.5365336971974971 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 5695, + 6593 + ], + "pair_score": 0.13028502202731498, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false, + "removed_original_layers": [ + 29 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 18, + 19, + 20, + 22, + 23, + 24, + 25, + 28, + 31, + 33, + 34, + 35 + ] + }, + { + "cycle": 9, + "pair_index": 16, + "initializer": "come", + "lambda_left": null, + "recipient_original_layer": 18, + "recipient_side": "left", + "removed_original_layer": 19, + "source_lineage": [ + [ + 18 + ], + [ + 19 + ] + ], + "retention_ratios": [ + 0.43171495242956137, + 0.5682850475704386 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 5304, + 6984 + ], + "pair_score": 0.13059031313404124, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false, + "removed_original_layers": [ + 19 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 18, + 20, + 22, + 23, + 24, + 25, + 28, + 31, + 33, + 34, + 35 + ] + } +] diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/selection_inputs.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/selection_inputs.json new file mode 100644 index 0000000000000000000000000000000000000000..1513f7f0e3263ceb5ca39bd58acd6b5c29f05a48 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/audit/selection_inputs.json @@ -0,0 +1,6 @@ +{ + "input_ids_sha256": "0e958e9f08255ee1a4bb4f029d8e7af94c8a26c6b31366a9223fb7629ebf53e3", + "sequences": 94, + "source": "/workspace/qwen3-mlp-fit-20261126/calibration/come.pt", + "independent_of_fit_loader": true +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/abprune_compact.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/abprune_compact.py new file mode 100644 index 0000000000000000000000000000000000000000..ffabddabd8ced8b87666f63fb9f99fae8b36cb38 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/bootstrap_llama31_come_fit2.sh b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/collect_qwen_mlp_fit_comparison.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/collect_qwen_mlp_fit_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..06e49d5908cea3c6be03aa2ef0a5405245976705 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/collect_qwen_mlp_fit_comparison.py @@ -0,0 +1,68 @@ +"""Collect the Qwen3-8B-Base native MKA/CoMe batch-one MLP FiT results.""" +import argparse +import json +import math +from pathlib import Path + + +FIT_IDS = "5d9d4cc2f81d8712b932806c0c2b2992dce9bd3e6c7a143f1f670649b8bfe693" +FIT_MASK = "c8e7f8e30cd532b82e6af4b98d596bc7106f29f9fb2b398b44355e624898a30d" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("root", type=Path) + parser.add_argument("--output", type=Path) + a = parser.parse_args() + rows = [] + for method in ("mka", "come"): + run = a.root / "full" / method + 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(value) and 0 <= value <= 1 for value in scores.values()) + fits = [json.loads((run / "audit" / f"cycle_{cycle:02d}_fit.json").read_text()) + for cycle in range(1, 10)] + 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["runtime"]["batch_size"] == 1 + assert fit["ablation"]["frozen_attention_norm_unchanged"] + assert len(fit["ablation"]["frozen_attention_norm_expected_sha256"]) == 8 + fingerprints = json.loads((run / "audit/data_fingerprints.json").read_text()) + distill = fingerprints["distill_loader"] + assert distill["sequences"] == 512 and distill["sha256"] == FIT_IDS + assert distill["attention_mask_sha256"] == FIT_MASK + ppl = json.loads((run / "eval/final_ppl.json").read_text()) + metrics = ppl.get("metrics", ppl) + value = next((metrics[key] for key in ("ppl", "perplexity") if key in metrics), None) + assert value is not None and math.isfinite(value) and value > 0 + native = json.loads((run / "audit/selection_inputs.json").read_text()) + rows.append({"arm": method, "method": method, "batch_size": 1, "fit_scope": "mlp", + "bench12": sum(scores[key] for key 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(fit["runtime"]["seconds"] for fit in fits), + "peak_allocated_bytes": max(fit["runtime"]["peak_allocated_bytes"] for fit in fits), + "peak_reserved_bytes": max(fit["runtime"]["peak_reserved_bytes"] for fit in fits), + "optimizer_updates_per_stage": 512, "fit_input_sha256": FIT_IDS, + "fit_mask_sha256": FIT_MASK, "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"{method}_backup.json").read_text())}) + result = {"model": "Qwen/Qwen3-8B-Base", "model_revision": "49e3418fbbbca6ecbdf9608b4d22e5a407081db4", + "model_variant": "Base", "original_layers": 36, "removed_blocks": 9, + "fit_scope": "mlp", "batch_size": 1, "accuracy_scale": "fraction", "rows": rows, + "smoke": json.loads((a.root / "smoke_summary.json").read_text()), + "selection_provenance": json.loads((a.root / "selection_provenance.json").read_text()), + "qualification": "Both methods retain their own historical native selection data; identical pinned SlimPajama512x1024 FiT examples/masks/LR/loss/epochs and512updates perstage; attention and allnorms frozen duringFiT"} + output = a.output or a.root / "summary.json" + output.parent.mkdir(parents=True, exist_ok=True) + output.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-qwen3-base-mka-come-mlp-fit/come/code/come.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/come.py new file mode 100644 index 0000000000000000000000000000000000000000..22d1937fdbf534bb2c3e37af3357627040ef4372 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/eval_llama31_8b_12bench.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/eval_llama31_fit_ablation_one.sh b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/evaluate_abprune_compact_ppl.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/evaluate_hchc_wikitext2_ppl.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/fit_ablation_come.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/fit_ablation_mka.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/fuse_layers.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/fuse_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..5cca981f0f2f951ce21d88119fd12d26c6d8a089 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/fuse_layers_distill.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/inspect_qwen_mlp_fit_run.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/inspect_qwen_mlp_fit_run.py new file mode 100644 index 0000000000000000000000000000000000000000..edd7ae1ff8392b5a33dbc7ac4d8fb6457f205837 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/inspect_qwen_mlp_fit_run.py @@ -0,0 +1,50 @@ +"""Read-only compact snapshot of Qwen Base MKA/CoMe nine-stage FiT runs.""" +import argparse +import json +from pathlib import Path +import subprocess +import time + + +def log_tail(path): + with path.open("rb") as stream: + stream.seek(max(0, path.stat().st_size - 65536)) + text = stream.read().decode("utf-8", errors="replace") + lines = text.replace("\r", "\n").splitlines() + return next((line for line in reversed(lines) if line.strip()), "")[-500:] + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("root", type=Path) + a = p.parse_args() + root = a.root + snapshot = {"utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "status": json.loads((root / "status.json").read_text()), "arms": {}} + for name in ("mka", "come"): + run = root / "full" / name + audits = sorted((run / "audit").glob("cycle_*_fit.json")) + row = {"trained_cycles": len(audits), "total_cycles": 9, + "training_complete": (run / "TRAIN_COMPLETE").exists(), + "evaluation_complete": (run / "EVAL_COMPLETE").exists(), + "backup_complete": (run / "BACKUP_COMPLETE").exists()} + for key, relative in (("training", "logs/train.log"), ("evaluation", "logs/eval14.log")): + path = run / relative + if path.exists(): + row[key + "_last_line"] = log_tail(path) + row[key + "_log_age_seconds"] = time.time() - path.stat().st_mtime + if audits: + try: + row["last_fit_runtime"] = json.loads(audits[-1].read_text()).get("runtime") + except json.JSONDecodeError: + # A writer may be publishing this newest audit during the read. + row["last_fit_audit_pending"] = True + snapshot["arms"][name] = row + snapshot["gpu"] = subprocess.check_output( + ["nvidia-smi", "--query-gpu=index,utilization.gpu,memory.used", "--format=csv,noheader"], + text=True).splitlines() + print(json.dumps(snapshot, ensure_ascii=True)) + + +if __name__ == "__main__": + main() diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/launch_llama31_come_fit2.sh b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/launch_qwen_mlp_fit_comparison.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/launch_qwen_mlp_fit_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..afbbf3a858ce603034adefe537418b1c8086d4da --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/launch_qwen_mlp_fit_comparison.py @@ -0,0 +1,281 @@ +"""Compare native MKA and CoMe Qwen3-8B-Base MLP-only FiT, batch one.""" +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 + + +MODEL_ID = "Qwen/Qwen3-8B-Base" +REVISION = "49e3418fbbbca6ecbdf9608b4d22e5a407081db4" +FIT_IDS = "5d9d4cc2f81d8712b932806c0c2b2992dce9bd3e6c7a143f1f670649b8bfe693" +FIT_MASK = "c8e7f8e30cd532b82e6af4b98d596bc7106f29f9fb2b398b44355e624898a30d" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("project", "external", "root"): + parser.add_argument("--" + name, type=Path, required=True) + parser.add_argument("--model", required=True) + parser.add_argument("--session", required=True) + parser.add_argument("--eval-root", type=Path, required=True) + for method in ("mka", "come"): + parser.add_argument(f"--{method}-selection", type=Path, required=True) + parser.add_argument(f"--{method}-selection-metadata", type=Path) + parser.add_argument(f"--{method}-selection-hash", required=True) + parser.add_argument("--come-minimum-retention", type=float, default=0, + help="Historical native Qwen Base CoMe uses zero, unlike the Llama control") + parser.add_argument("--expected-fit-hash", default=FIT_IDS) + parser.add_argument("--expected-fit-mask-hash", default=FIT_MASK) + parser.add_argument("--smoke-only", action="store_true", + help="Stop after the two validated one-stage 64-sequence probes") + parser.add_argument("--experiment-id", default="20261126-qwen3-base-mka-come-mlp-fit") + parser.add_argument("--protocol", default="exp_md/2026-11-26_qwen3-base-mka-come-mlp-fit.md") + a = parser.parse_args() + root = a.root.resolve() + root.mkdir(parents=True, exist_ok=True) + assert a.expected_fit_hash == FIT_IDS and a.expected_fit_mask_hash == FIT_MASK + assert a.come_minimum_retention == 0, "Preserve the historical Qwen Base CoMe minimum retention" + 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") + lock = threading.RLock() + state = {"experiment": a.experiment_id, "session": a.session, "model": MODEL_ID, + "model_revision": REVISION, "removed_blocks": 9, "original_layers": 36, + "fit_scope": "mlp", "fit_batch_size": 1, "scope": ["mka", "come"], + "phase": "validation", "arms": {}, "auto_return": False, + "instance_return_policy": "explicit_user_instruction_only"} + + 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 = dict(env) + if gpu is not None: + child["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], cwd=a.project, env=child, + stdout=stream, stderr=subprocess.STDOUT) + if check and result.returncode: + raise RuntimeError(f"Command failed ({result.returncode}); see {log}") + return result.returncode + + def training_command(method, output, gpu, cycles=9, tokens=524288): + return ["bash", a.project / "scripts/run_qwen_mlp_fit_arm.sh", a.project, a.external, + output, a.model, method, root / "calibration" / f"{method}.pt", + getattr(a, f"{method}_selection_hash"), gpu, cycles, tokens, + a.expected_fit_hash, a.expected_fit_mask_hash, a.come_minimum_retention] + + def validate_fit(method, fit, tokens): + assert fit["trained"] and fit["num_trainable_mlp_gates"] == 3 + assert fit["num_trainable_attn_gates"] == fit["num_trainable_other_gates"] == 0 + audit = fit["ablation"] + assert audit["fit_scope"] == "mlp" and not audit["norms_trainable"] + assert audit["attention_initialization"] == ("MKA_merge" if method == "mka" else "CoMe_channel_merge") + assert not audit["source_feature_transport"] and audit["frozen_attention_norm_unchanged"] + frozen = audit["frozen_attention_norm_expected_sha256"] + assert len(frozen) == 8, "Qwen frozen tensors: attention4, QK norms2, residual norms2" + assert audit["frozen_attention_norm_before_sha256"] == frozen + assert audit["frozen_attention_norm_after_sha256"] == frozen + assert fit["runtime"]["batch_size"] == 1 and fit["runtime"]["dataset_tokens"] == tokens + shapes = fit["runtime"]["actual_forward_shapes"] + assert shapes and all(name.endswith(":1x1024") for name in shapes), shapes + assert fit["first_grad_summary"]["joint"]["u"]["num_tensors_without_grad"] == 0 + updates = fit["u_delta_summary"]["per_tensor"] + assert len(updates) == 3 and all(record["rms"] > 0 for record in updates.values()) + + def validate_inputs(method, output, full=False): + native = json.loads((output / "audit/selection_inputs.json").read_text()) + assert native["input_ids_sha256"] == getattr(a, f"{method}_selection_hash") + fingerprints = json.loads((output / "audit/data_fingerprints.json").read_text()) + distill = fingerprints["distill_loader"] + assert distill["sequences"] == (512 if full else 64) + if full: + assert distill["sha256"] == a.expected_fit_hash + assert distill["attention_mask_sha256"] == a.expected_fit_mask_hash + return distill + + def smoke(method, gpu): + out = root / "probes" / method + path = out / "audit/cycle_01_fit.json" + if not ((out / "TRAIN_COMPLETE").exists() and path.is_file()): + run(training_command(method, out, gpu, cycles=1, tokens=65536), root / f"{method}_smoke.log") + fit = json.loads(path.read_text()) + validate_fit(method, fit, 65536) + data = validate_inputs(method, out) + return {"method": method, "gpu": gpu, "completed": True, "batch_size": 1, + "fit_runtime": fit["runtime"], "distill_loader": data, + "frozen_tensor_count": len(fit["ablation"]["frozen_attention_norm_expected_sha256"]), + "selection": json.loads((out / "audit/selection.json").read_text())} + + def complete_arm(method, gpu): + out = root / "full" / method + with lock: + state["arms"][method] = {"phase": "training", "gpu": gpu, "batch_size": 1, + "started_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())} + save() + if not (out / "TRAIN_COMPLETE").exists(): + started = time.time() + run(training_command(method, out, gpu), root / f"{method}_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, 10): + validate_fit(method, json.loads((out / "audit" / f"cycle_{cycle:02d}_fit.json").read_text()), 524288) + validate_inputs(method, out, full=True) + with lock: + state["arms"][method]["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_09", + "--anchor", 12, "--cycles", 9, "--original-layers", 36, + "--seq-len", 2048, "--batch-size", 8, "--output", out / "eval/final_ppl.json"], + root / f"{method}_ppl.log", gpu) + evaluation_env = dict(env, LMEVAL_LOCAL_CACHE=str(a.eval_root / "lmeval_cache"), MODEL_REVISION=REVISION) + with (root / f"{method}_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, "12", "9", str(gpu)], env=evaluation_env, + stdout=stream, stderr=subprocess.STDOUT, check=True) + (out / "EVAL_COMPLETE").touch() + with lock: + state["arms"][method]["phase"] = "backup" + save() + backup = root / "backup" / method + if not backup.exists(): + run([sys.executable, a.project / "scripts/package_final_fit_backup.py", out, backup, + a.project, a.external, "--protocol", a.protocol, "--cycles", 9, "--original-layers", 36], + root / f"{method}_backup.log") + for filename in ("launch_qwen_mlp_fit_comparison.py", "run_qwen_mlp_fit_arm.sh", + "collect_qwen_mlp_fit_comparison.py", "prepare_qwen_mlp_fit_calibrations.py", + "inspect_qwen_mlp_fit_run.py", "monitor_qwen_mlp_fit_local.ps1"): + 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") + for filename in ("selection_provenance.json", "smoke_summary.json", "first_native_validation.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"{method}_backup.log") + upload_env = dict(env, HF_HUB_OFFLINE="0", HF_DATASETS_OFFLINE="0", TRANSFORMERS_OFFLINE="0") + with (root / f"{method}_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}/{method}", "--commit-message", + f"Native {method} Qwen3 Base MLP-only FiT batch1"], env=upload_env, + stdout=stream, check=True) + (out / "BACKUP_COMPLETE").touch() + with lock: + state["arms"][method]["phase"] = "complete" + save() + + save() + try: + import torch + provenance = {} + (root / "calibration").mkdir(exist_ok=True) + for method in ("mka", "come"): + source = getattr(a, f"{method}_selection") + batches = torch.load(source, weights_only=True, map_location="cpu") + checksum, mask_sum = hashlib.sha256(), hashlib.sha256() + sequences = 0 + lengths = set() + for batch in batches: + ids, mask = batch["input_ids"], batch["attention_mask"] + assert ids.ndim == 2 and ids.shape == mask.shape and bool(mask.any()) + if method == "come": + assert bool(mask.all()), "Native CoMe windows must be unpadded" + checksum.update(ids.numpy().astype("$null + if ($LASTEXITCODE -ne 0) { throw 'Read-only SSH progress check failed.' } + $state = ($snapshot -join "`n") | ConvertFrom-Json + $snapshot | Add-Content -LiteralPath $log -Encoding utf8 + '{0} 상태={1} 학습단계: mka={2}/9 come={3}/9' -f $state.utc,$state.status.phase,$state.arms.mka.trained_cycles,$state.arms.come.trained_cycles + if ($Once -or $state.status.phase -in @('complete','failed')) { break } + Start-Sleep -Seconds $IntervalSeconds +} while ($true) diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/offline_eval_policy.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/package_final_fit_backup.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/prepare_lmeval9_local_cache.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/prepare_offline_ppl_cache.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/prepare_offline_ppl_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..d4ae21e89d126fc4a7e031ced9d510abe37790e9 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/prepare_offline_ppl_cache.py @@ -0,0 +1,30 @@ +"""Export the warmed WikiText dataset once; never contact the Hub here.""" +import os +for key in ('HF_HUB_OFFLINE', 'HF_DATASETS_OFFLINE', 'TRANSFORMERS_OFFLINE'): + os.environ[key] = '1' + +import json +from pathlib import Path +import sys +from datasets import load_dataset, load_from_disk + +root = Path(sys.argv[1]) +source = load_dataset('Salesforce/wikitext', 'wikitext-2-raw-v1') +cache = root / 'wikitext2_cache' +if not cache.exists(): + temporary = root / f'wikitext2_cache_partial_{os.getpid()}' + source.save_to_disk(str(temporary)) + temporary.rename(cache) +restored = load_from_disk(str(cache)) +assert set(source) == set(restored) +assert all(source[k].data.table.equals(restored[k].data.table) for k in source) +policy = {'wikitext_cache': str(cache), 'dataset': 'Salesforce/wikitext', + 'config': 'wikitext-2-raw-v1', 'splits': {k: len(v) for k,v in restored.items()}, + 'fingerprints': {k: v._fingerprint for k,v in source.items()}} +for family in ('base', 'instruct'): + target = root / 'full' / family / 'offline_eval.json' + target.parent.mkdir(parents=True, exist_ok=True) + temporary = target.with_suffix('.json.partial') + temporary.write_text(json.dumps(policy, indent=2) + '\n') + temporary.replace(target) +print('OFFLINE_PPL_CACHE_EXACT_ROWS_VERIFIED', policy['splits'], flush=True) diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/prepare_qwen_mlp_fit_calibrations.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/prepare_qwen_mlp_fit_calibrations.py new file mode 100644 index 0000000000000000000000000000000000000000..6799ca5d2914398c563610650ede0f4748fdf01f --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/prepare_qwen_mlp_fit_calibrations.py @@ -0,0 +1,98 @@ +"""Restore native Qwen MKA tokens and freeze the legacy native CoMe loader.""" +import argparse +import hashlib +import json +from pathlib import Path + +import torch +from datasets import load_dataset +from transformers import AutoTokenizer + +REVISION = "49e3418fbbbca6ecbdf9608b4d22e5a407081db4" +MKA_FILE_HASH = "aa8b546874da296d54ef69d73faffc83802deb089c0209cc55593e32ab50489b" +MKA_IDS_HASH = "4f47034e02892bf464998e540be8bd7bc0718f83f6bc9d354c887cc2874cada9" +VOCAB_HASH = "c605f1c0a80a9501fca9782b942a7f01474e3f37b1c59e3efea82da0e2f20376" + + +def save_batches(batches, metadata, output): + output.mkdir(parents=True, exist_ok=True) + path = output / "selection.pt" + ids, masks = hashlib.sha256(), hashlib.sha256() + for b in batches: + ids.update(b["input_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-qwen3-base-mka-come-mlp-fit/come/code/run_llama31_base_fit_ablation.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/run_llama31_base_fit_ablation.py new file mode 100644 index 0000000000000000000000000000000000000000..8e27459de55bf48de7946104e26c340b2df461d5 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/run_llama31_base_fit_ablation.py @@ -0,0 +1,926 @@ +#!/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 residual/QK norms 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": + actual_names = {n for n, _ in layer_a.named_parameters()} + assert set(state["come_initial"]) == actual_names, "Native CoMe initialization must cover every block parameter" + 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, + "attention_norm_initialization": "CoMe_retention_weighted_QK" if any( + n.startswith("self_attn.") and "norm" in n for n in actual_names) else None, + "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_mlp: + hashes = {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} + 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, "CoMe frozen initialization does not match native merge" + state["initialization_audit"].update({ + "frozen_attention_norm_expected_sha256": hashes, + "frozen_attention_norm_before_sha256": measured, + }) + 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 + } + frozen_norms = state["initialization_audit"]["frozen_norm_expected_sha256"] + assert len(frozen_norms) >= 2 and all("norm" in n for n in frozen_norms) + 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, qk_norms=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)) + if qk_norms: + self.self_attn.q_norm = torch.nn.RMSNorm(2) + self.self_attn.k_norm = torch.nn.RMSNorm(2) + 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) + if qk_norms: + a.self_attn.q_norm.weight.fill_(2) + b.self_attn.q_norm.weight.fill_(6) + a.self_attn.k_norm.weight.fill_(4) + b.self_attn.k_norm.weight.fill_(8) + untouched = {n: p.detach().clone() for n, p in a.named_parameters()} + untouched_b = {n: p.detach().clone() for n, p in b.named_parameters()} + pair = [copy.deepcopy(a), copy.deepcopy(b)] + ratios = [.25, .75] if qk_norms else [.5, .5] + come.merge_attention(pair, ratios, [torch.tensor([0., 1.]), torch.tensor([1., 0.])]) + come.merge_mlp(pair, ratios, [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 len(expected))) + 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 all(torch.equal(p, untouched_b[n]) for n, p in b.named_parameters()) + assert bool((merged["input_layernorm.weight"] == 3).all()) + if qk_norms: + assert len(expected) == 11 + assert bool((merged["self_attn.q_norm.weight"] == 5).all()) + assert bool((merged["self_attn.k_norm.weight"] == 7).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"]) == len(expected) - len(layer._name_map) + if mlp_only: + audit = state["initialization_audit"] + assert len(audit["frozen_attention_norm_expected_sha256"]) == len(expected) - 3 + assert audit["frozen_attention_norm_before_sha256"] == audit["frozen_attention_norm_expected_sha256"] + 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(("QWEN_QK_NORMS_NATIVE_INIT_FROZEN_OK " if qk_norms else "") + ( + "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 + f"COME_NATIVE_MERGE_{len(expected)}_U_GRADIENTS_NORMS_TEACHER_UNCHANGED_OK")), flush=True) + + +def mka_algebra_test(torch, distill, mlp_only=False, qk_norms=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)) + if qk_norms: + self.self_attn.q_norm = torch.nn.RMSNorm(2) + self.self_attn.k_norm = torch.nn.RMSNorm(2) + 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) + if qk_norms: + a.self_attn.q_norm.weight.fill_(2) + b.self_attn.q_norm.weight.fill_(6) + a.self_attn.k_norm.weight.fill_(4) + b.self_attn.k_norm.weight.fill_(8) + 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"]) == len(expected) - 3 + 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(("QWEN_QK_NORMS_ANCHOR_FROZEN_OK " if qk_norms else "") + ( + "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("--expected-fit-input-hash", + help="Require this distillation input SHA256 before any training") + parser.add_argument("--expected-fit-mask-hash", + help="Require this distillation attention-mask SHA256 before any training") + 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 all native block weights including residual/QK norms") + parser.add_argument("--fit-come-mlp", action="store_true", + help="CoMe initializes every block weight; fit3 MLP weights, freeze merged attention/norms") + parser.add_argument("--fit-come-attention", action="store_true", + help="CoMe initializes every block weight; fit7 projections, freeze merged residual/QK 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() + assert bool(opt.expected_fit_input_hash) == bool(opt.expected_fit_mask_hash), "Specify both expected FiT hashes together" + 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: + qk_norms = opt.model_id in ("Qwen/Qwen3-8B-Base", "Qwen/Qwen3-8B") + if opt.initializer == "come": + come_algebra_test(torch, distill, mlp_only=opt.fit_come_mlp, + attention_and_mlp=opt.fit_come_attention, qk_norms=qk_norms) + elif opt.initializer == "mka": + mka_algebra_test(torch, distill, mlp_only=opt.fit_mka_mlp, qk_norms=qk_norms) + 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 or opt.fit_come_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 merged attention/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-qwen3-base-mka-come-mlp-fit/come/code/run_llama31_come_fit_arm.sh b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/code/run_qwen_mlp_fit_arm.sh b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/run_qwen_mlp_fit_arm.sh new file mode 100644 index 0000000000000000000000000000000000000000..cbdad4788c88a1b2f85237a923804f4bf120e1d7 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/code/run_qwen_mlp_fit_arm.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +set -euo pipefail +project="$1"; external="$2"; root="$3"; model="$4"; method="$5"; selection="$6"; selection_hash="$7"; gpu="$8" +cycles="${9:-9}"; tokens="${10:-524288}"; fit_hash="${11:-}"; fit_mask_hash="${12:-}"; come_minimum="${13:-0}" +case "$method" in + mka) scope_args=(--fit-mka-mlp --mka-data "$selection" --mka-samples 100) ;; + come) scope_args=(--fit-come-mlp --selection-data "$selection" --come-minimum-retention "$come_minimum" --come-power 1) ;; + *) echo 'Method must be mka or come'; exit 2 ;; +esac +[[ -s "$selection" ]] || { echo 'Frozen native selection input is required; no resampling'; exit 1; } +if [[ "$tokens" == 524288 ]]; then + [[ -n "$fit_hash" && -n "$fit_mask_hash" ]] || { echo 'Full FiT requires pinned token/mask hashes'; exit 1; } + scope_args+=(--expected-fit-input-hash "$fit_hash" --expected-fit-mask-hash "$fit_mask_hash") +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 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 +mkdir -p "$root/logs" "$root/audit" "$root/run" +python "$project/scripts/run_llama31_base_fit_ablation.py" \ + --external-root "$external" --initializer "$method" "${scope_args[@]}" --audit-root "$root/audit" \ + --selection-hash "$selection_hash" --record-fit-runtime --original-layers 36 --fixed-anchor 12 \ + --model-id Qwen/Qwen3-8B-Base --base-revision 49e3418fbbbca6ecbdf9608b4d22e5a407081db4 \ + --model "$model" --output_dir "$root/run" --layer 12 --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 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 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-qwen3-base-mka-come-mlp-fit/come/code/source_feature_transport.py b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/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-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0015.pt b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0015.pt new file mode 100644 index 0000000000000000000000000000000000000000..cf01560087b710ea1f837bd75dbdff21b47c4147 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0015.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:80dc7228f4a34261a00664948eaf3619cdee5fef0dc9dae6e72d330d624c72d1 +size 385897862 diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0018.pt b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0018.pt new file mode 100644 index 0000000000000000000000000000000000000000..902f96336f7c48ef753b5fa0e5d48a4e0dfffff4 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0018.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85faba5efb76fdae0c2b8a6357db84d42f0e19b8a7592d9f9d2d5862b3f6b9b4 +size 385897862 diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0020.pt b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0020.pt new file mode 100644 index 0000000000000000000000000000000000000000..f949c6160e5f4227fe082d0639341393cc78dd04 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0020.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06b6663e17e2d5749b618bb43a1df5541bc76139b82e57c5cfa05a4e0e61ac93 +size 385897862 diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0025.pt b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0025.pt new file mode 100644 index 0000000000000000000000000000000000000000..9a2ed857b5dcd7884e50b759b1b5b8c31ddd45cc --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0025.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d0ded25ce72f3b53059a9f5f885fb0178b0509db3a4a6e593dc862c897aee78 +size 385897862 diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0028.pt b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0028.pt new file mode 100644 index 0000000000000000000000000000000000000000..c2cf1cb61a926431e3978c096b9022ff72d3e452 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0028.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50abe4d738ed5839b7060ce33964007e4679091dfcded790b56075937fb8bd60 +size 385897862 diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0031.pt b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0031.pt new file mode 100644 index 0000000000000000000000000000000000000000..75df24082941940fdc6de44f07b5859bda9be184 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/layer_original_0031.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c5ec97998485de8ddd46981befd5a33566982ddfaa57ce2b97f9884e341eb49 +size 385897862 diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..511191542aebc3b1a2b6740318084fabf3f8792a --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/compact/stage_09/metadata.json @@ -0,0 +1,110 @@ +{ + "format": "abprune_compact_stage_v2", + "model": "Qwen/Qwen3-8B-Base", + "base_model_revision": "49e3418fbbbca6ecbdf9608b4d22e5a407081db4", + "run_id": "qwen3_8b_base_fit_come_9block", + "target_prune_count": 9, + "stage": 9, + "removed_count": 9, + "original_layer_count": 36, + "layer_order": [ + 31, + 16, + 25, + 15, + 26, + 23, + 18, + 23, + 16 + ], + "latest_pair_index": 16, + "latest_recipient_side": "left", + "latest_recipient_original_layer": 18, + "latest_removed_original_layer": 19, + "removed_original_layers": [ + 16, + 17, + 19, + 21, + 26, + 27, + 29, + 30, + 32 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 18, + 20, + 22, + 23, + 24, + 25, + 28, + 31, + 33, + 34, + 35 + ], + "retained_layer_states": [ + { + "original_layer": 15, + "state_file": "layer_original_0015.pt", + "sha256": "80dc7228f4a34261a00664948eaf3619cdee5fef0dc9dae6e72d330d624c72d1", + "source_cycle": 4, + "recipient_side": "left" + }, + { + "original_layer": 18, + "state_file": "layer_original_0018.pt", + "sha256": "85faba5efb76fdae0c2b8a6357db84d42f0e19b8a7592d9f9d2d5862b3f6b9b4", + "source_cycle": 9, + "recipient_side": "left" + }, + { + "original_layer": 20, + "state_file": "layer_original_0020.pt", + "sha256": "06b6663e17e2d5749b618bb43a1df5541bc76139b82e57c5cfa05a4e0e61ac93", + "source_cycle": 7, + "recipient_side": "left" + }, + { + "original_layer": 25, + "state_file": "layer_original_0025.pt", + "sha256": "4d0ded25ce72f3b53059a9f5f885fb0178b0509db3a4a6e593dc862c897aee78", + "source_cycle": 6, + "recipient_side": "left" + }, + { + "original_layer": 28, + "state_file": "layer_original_0028.pt", + "sha256": "50abe4d738ed5839b7060ce33964007e4679091dfcded790b56075937fb8bd60", + "source_cycle": 8, + "recipient_side": "left" + }, + { + "original_layer": 31, + "state_file": "layer_original_0031.pt", + "sha256": "5c5ec97998485de8ddd46981befd5a33566982ddfaa57ce2b97f9884e341eb49", + "source_cycle": 1, + "recipient_side": "left" + } + ], + "source_cycle": "cycle_9" +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/eval/final_14bench.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/eval/final_14bench.json new file mode 100644 index 0000000000000000000000000000000000000000..aec7a93fbb75e971b2698037bf754aa1f4d3f7c6 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/eval/final_14bench.json @@ -0,0 +1,37 @@ +{ + "task_scores": { + "race_high": 0.3259005145797599, + "race_middle": 0.29735376044568246, + "c3": 0.5243835616438356, + "cmnli": 0.3360836532962993, + "chid": 0.698019801980198, + "piqa": 0.6855277475516867, + "winogrande": 0.5540647198105761, + "hellaswag": 0.5182234614618602, + "arc_challenge": 0.310580204778157, + "arc_easy": 0.5050505050505051, + "openbookqa": 0.312, + "sciq": 0.782, + "mmlu": 0.3698191140863125, + "cmmlu": 0.36142289759972374 + }, + "macro_mean_14": 0.4700307101631855, + "tasks": [ + "race_high", + "race_middle", + "c3", + "cmnli", + "chid", + "piqa", + "winogrande", + "hellaswag", + "arc_challenge", + "arc_easy", + "openbookqa", + "sciq", + "mmlu", + "cmmlu" + ], + "opencompass_protocol": "OpenCompass 0.5.4 canonical PPL prompts; full-prompt mean CE; lowest PPL", + "lm_eval_num_fewshot": 0 +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/eval/final_lmeval9.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/eval/final_lmeval9.json new file mode 100644 index 0000000000000000000000000000000000000000..51fa4a3a28b932934f779d1c061ab344d8b1e8bc --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/eval/final_lmeval9.json @@ -0,0 +1,1401 @@ +{ + "model": "/workspace/models/qwen3-base-49e3418", + "revision": "49e3418fbbbca6ecbdf9608b4d22e5a407081db4", + "compact_stage": "/workspace/qwen3-mlp-fit-20261126/full/come/compact/stage_09", + "cycle": 9, + "anchor": 12, + "tasks": [ + "piqa", + "winogrande", + "hellaswag", + "arc_challenge", + "arc_easy", + "openbookqa", + "sciq", + "mmlu", + "cmmlu" + ], + "num_fewshot": 0, + "batch_size": "auto:4", + "limit": null, + "dataset_cache": "/workspace/come-attn-fit-20261126/lmeval_cache", + "preferred_metrics": { + "piqa": "acc_norm,none", + "winogrande": "acc,none", + "hellaswag": "acc_norm,none", + "arc_challenge": "acc_norm,none", + "arc_easy": "acc_norm,none", + "openbookqa": "acc_norm,none", + "sciq": "acc_norm,none", + "mmlu": "acc,none", + "cmmlu": "acc,none" + }, + "task_scores": { + "piqa": 0.6855277475516867, + "winogrande": 0.5540647198105761, + "hellaswag": 0.5182234614618602, + "arc_challenge": 0.310580204778157, + "arc_easy": 0.5050505050505051, + "openbookqa": 0.312, + "sciq": 0.782, + "mmlu": 0.3698191140863125, + "cmmlu": 0.36142289759972374 + }, + "macro_mean_all_rows": 0.4887431833709801, + "lm_eval_results": { + "piqa": { + "name": "piqa", + "alias": "piqa", + "sample_len": 1838, + "acc,none": 0.6751904243743199, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.6855277475516867, + "acc_norm_stderr,none": "N/A" + }, + "winogrande": { + "name": "winogrande", + "alias": "winogrande", + "sample_len": 1267, + "acc,none": 0.5540647198105761, + "acc_stderr,none": "N/A" + }, + "hellaswag": { + "name": "hellaswag", + "alias": "hellaswag", + "sample_len": 10042, + "acc,none": 0.37870942043417644, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.5182234614618602, + "acc_norm_stderr,none": "N/A" + }, + "arc_challenge": { + "name": "arc_challenge", + "alias": "arc_challenge", + "sample_len": 1172, + "acc,none": 0.27986348122866894, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.310580204778157, + "acc_norm_stderr,none": "N/A" + }, + "arc_easy": { + "name": "arc_easy", + "alias": "arc_easy", + "sample_len": 2376, + "acc,none": 0.5576599326599326, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.5050505050505051, + "acc_norm_stderr,none": "N/A" + }, + "openbookqa": { + "name": "openbookqa", + "alias": "openbookqa", + "sample_len": 500, + "acc,none": 0.202, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.312, + "acc_norm_stderr,none": "N/A" + }, + "sciq": { + "name": "sciq", + "alias": "sciq", + "sample_len": 1000, + "acc,none": 0.82, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.782, + "acc_norm_stderr,none": "N/A" + }, + "mmlu_abstract_algebra": { + "name": "mmlu_abstract_algebra", + "alias": "abstract_algebra", + "sample_len": 100, + "acc,none": 0.28, + "acc_stderr,none": "N/A" + }, + "mmlu_anatomy": { + "name": "mmlu_anatomy", + "alias": "anatomy", + "sample_len": 135, + "acc,none": 0.3851851851851852, + "acc_stderr,none": "N/A" + }, + "mmlu_astronomy": { + "name": "mmlu_astronomy", + "alias": "astronomy", + "sample_len": 152, + "acc,none": 0.4473684210526316, + "acc_stderr,none": "N/A" + }, + "mmlu_college_biology": { + "name": "mmlu_college_biology", + "alias": "college_biology", + "sample_len": 144, + "acc,none": 0.4791666666666667, + "acc_stderr,none": "N/A" + }, + "mmlu_college_chemistry": { + "name": "mmlu_college_chemistry", + "alias": "college_chemistry", + "sample_len": 100, + "acc,none": 0.36, + "acc_stderr,none": "N/A" + }, + "mmlu_college_computer_science": { + "name": "mmlu_college_computer_science", + "alias": "college_computer_science", + "sample_len": 100, + "acc,none": 0.35, + "acc_stderr,none": "N/A" + }, + "mmlu_college_mathematics": { + "name": "mmlu_college_mathematics", + "alias": "college_mathematics", + "sample_len": 100, + "acc,none": 0.27, + "acc_stderr,none": "N/A" + }, + "mmlu_college_physics": { + "name": "mmlu_college_physics", + "alias": "college_physics", + "sample_len": 102, + "acc,none": 0.30392156862745096, + "acc_stderr,none": "N/A" + }, + "mmlu_computer_security": { + "name": "mmlu_computer_security", + "alias": "computer_security", + "sample_len": 100, + "acc,none": 0.51, + "acc_stderr,none": "N/A" + }, + "mmlu_conceptual_physics": { + "name": "mmlu_conceptual_physics", + "alias": "conceptual_physics", + "sample_len": 235, + "acc,none": 0.425531914893617, + "acc_stderr,none": "N/A" + }, + "mmlu_electrical_engineering": { + "name": "mmlu_electrical_engineering", + "alias": "electrical_engineering", + "sample_len": 145, + "acc,none": 0.4206896551724138, + "acc_stderr,none": "N/A" + }, + "mmlu_elementary_mathematics": { + "name": "mmlu_elementary_mathematics", + "alias": "elementary_mathematics", + "sample_len": 378, + "acc,none": 0.29365079365079366, + "acc_stderr,none": "N/A" + }, + "mmlu_high_school_biology": { + "name": "mmlu_high_school_biology", + "alias": "high_school_biology", + "sample_len": 310, + "acc,none": 0.42258064516129035, + "acc_stderr,none": "N/A" + }, + "mmlu_high_school_chemistry": { + "name": "mmlu_high_school_chemistry", + "alias": "high_school_chemistry", + "sample_len": 203, + "acc,none": 0.28078817733990147, + "acc_stderr,none": "N/A" + }, + "mmlu_high_school_computer_science": { + "name": "mmlu_high_school_computer_science", + "alias": "high_school_computer_science", + "sample_len": 100, + "acc,none": 0.34, + "acc_stderr,none": "N/A" + }, + "mmlu_high_school_mathematics": { + "name": "mmlu_high_school_mathematics", + "alias": "high_school_mathematics", + "sample_len": 270, + "acc,none": 0.22962962962962963, + "acc_stderr,none": "N/A" + }, + "mmlu_high_school_physics": { + "name": "mmlu_high_school_physics", + "alias": "high_school_physics", + "sample_len": 151, + "acc,none": 0.2251655629139073, + "acc_stderr,none": "N/A" + }, + "mmlu_high_school_statistics": { + "name": "mmlu_high_school_statistics", + "alias": "high_school_statistics", + "sample_len": 216, + "acc,none": 0.28703703703703703, + "acc_stderr,none": "N/A" + }, + "mmlu_machine_learning": { + "name": "mmlu_machine_learning", + "alias": "machine_learning", + "sample_len": 112, + "acc,none": 0.3482142857142857, + "acc_stderr,none": "N/A" + }, + "mmlu_business_ethics": { + "name": "mmlu_business_ethics", + "alias": "business_ethics", + "sample_len": 100, + "acc,none": 0.45, + "acc_stderr,none": "N/A" + }, + "mmlu_clinical_knowledge": { + "name": "mmlu_clinical_knowledge", + "alias": "clinical_knowledge", + "sample_len": 265, + "acc,none": 0.38113207547169814, + "acc_stderr,none": "N/A" + }, + "mmlu_college_medicine": { + "name": "mmlu_college_medicine", + "alias": "college_medicine", + "sample_len": 173, + "acc,none": 0.3236994219653179, + "acc_stderr,none": "N/A" + }, + "mmlu_global_facts": { + "name": "mmlu_global_facts", + "alias": "global_facts", + "sample_len": 100, + "acc,none": 0.23, + "acc_stderr,none": "N/A" + }, + "mmlu_human_aging": { + "name": "mmlu_human_aging", + "alias": "human_aging", + "sample_len": 223, + "acc,none": 0.4798206278026906, + "acc_stderr,none": "N/A" + }, + "mmlu_management": { + "name": "mmlu_management", + "alias": "management", + "sample_len": 103, + "acc,none": 0.30097087378640774, + "acc_stderr,none": "N/A" + }, + "mmlu_marketing": { + "name": "mmlu_marketing", + "alias": "marketing", + "sample_len": 234, + "acc,none": 0.47863247863247865, + "acc_stderr,none": "N/A" + }, + "mmlu_medical_genetics": { + "name": "mmlu_medical_genetics", + "alias": "medical_genetics", + "sample_len": 100, + "acc,none": 0.43, + "acc_stderr,none": "N/A" + }, + "mmlu_miscellaneous": { + "name": "mmlu_miscellaneous", + "alias": "miscellaneous", + "sample_len": 783, + "acc,none": 0.4444444444444444, + "acc_stderr,none": "N/A" + }, + "mmlu_nutrition": { + "name": "mmlu_nutrition", + "alias": "nutrition", + "sample_len": 306, + "acc,none": 0.40522875816993464, + "acc_stderr,none": "N/A" + }, + "mmlu_professional_accounting": { + "name": "mmlu_professional_accounting", + "alias": "professional_accounting", + "sample_len": 282, + "acc,none": 0.3049645390070922, + "acc_stderr,none": "N/A" + }, + "mmlu_professional_medicine": { + "name": "mmlu_professional_medicine", + "alias": "professional_medicine", + "sample_len": 272, + "acc,none": 0.36764705882352944, + "acc_stderr,none": "N/A" + }, + "mmlu_virology": { + "name": "mmlu_virology", + "alias": "virology", + "sample_len": 166, + "acc,none": 0.3855421686746988, + "acc_stderr,none": "N/A" + }, + "mmlu_econometrics": { + "name": "mmlu_econometrics", + "alias": "econometrics", + "sample_len": 114, + "acc,none": 0.32456140350877194, + "acc_stderr,none": "N/A" + }, + "mmlu_high_school_geography": { + "name": "mmlu_high_school_geography", + "alias": "high_school_geography", + "sample_len": 198, + "acc,none": 0.398989898989899, + "acc_stderr,none": "N/A" + }, + "mmlu_high_school_government_and_politics": { + "name": "mmlu_high_school_government_and_politics", + "alias": "high_school_government_and_politics", + "sample_len": 193, + "acc,none": 0.46632124352331605, + "acc_stderr,none": "N/A" + }, + "mmlu_high_school_macroeconomics": { + "name": "mmlu_high_school_macroeconomics", + "alias": "high_school_macroeconomics", + "sample_len": 390, + "acc,none": 0.32564102564102565, + "acc_stderr,none": "N/A" + }, + "mmlu_high_school_microeconomics": { + "name": "mmlu_high_school_microeconomics", + "alias": "high_school_microeconomics", + "sample_len": 238, + "acc,none": 0.3697478991596639, + "acc_stderr,none": "N/A" + }, + "mmlu_high_school_psychology": { + "name": "mmlu_high_school_psychology", + "alias": "high_school_psychology", + "sample_len": 545, + "acc,none": 0.47339449541284406, + "acc_stderr,none": "N/A" + }, + "mmlu_human_sexuality": { + "name": "mmlu_human_sexuality", + "alias": "human_sexuality", + "sample_len": 131, + "acc,none": 0.40458015267175573, + "acc_stderr,none": "N/A" + }, + "mmlu_professional_psychology": { + "name": "mmlu_professional_psychology", + "alias": "professional_psychology", + "sample_len": 612, + "acc,none": 0.3937908496732026, + "acc_stderr,none": "N/A" + }, + "mmlu_public_relations": { + "name": "mmlu_public_relations", + "alias": "public_relations", + "sample_len": 110, + "acc,none": 0.32727272727272727, + "acc_stderr,none": "N/A" + }, + "mmlu_security_studies": { + "name": "mmlu_security_studies", + "alias": "security_studies", + "sample_len": 245, + "acc,none": 0.23673469387755103, + "acc_stderr,none": "N/A" + }, + "mmlu_sociology": { + "name": "mmlu_sociology", + "alias": "sociology", + "sample_len": 201, + "acc,none": 0.5522388059701493, + "acc_stderr,none": "N/A" + }, + "mmlu_us_foreign_policy": { + "name": "mmlu_us_foreign_policy", + "alias": "us_foreign_policy", + "sample_len": 100, + "acc,none": 0.56, + "acc_stderr,none": "N/A" + }, + "mmlu_formal_logic": { + "name": "mmlu_formal_logic", + "alias": "formal_logic", + "sample_len": 126, + "acc,none": 0.2857142857142857, + "acc_stderr,none": "N/A" + }, + "mmlu_high_school_european_history": { + "name": "mmlu_high_school_european_history", + "alias": "high_school_european_history", + "sample_len": 165, + "acc,none": 0.46060606060606063, + "acc_stderr,none": "N/A" + }, + "mmlu_high_school_us_history": { + "name": "mmlu_high_school_us_history", + "alias": "high_school_us_history", + "sample_len": 204, + "acc,none": 0.5686274509803921, + "acc_stderr,none": "N/A" + }, + "mmlu_high_school_world_history": { + "name": "mmlu_high_school_world_history", + "alias": "high_school_world_history", + "sample_len": 237, + "acc,none": 0.5822784810126582, + "acc_stderr,none": "N/A" + }, + "mmlu_international_law": { + "name": "mmlu_international_law", + "alias": "international_law", + "sample_len": 121, + "acc,none": 0.36363636363636365, + "acc_stderr,none": "N/A" + }, + "mmlu_jurisprudence": { + "name": "mmlu_jurisprudence", + "alias": "jurisprudence", + "sample_len": 108, + "acc,none": 0.3888888888888889, + "acc_stderr,none": "N/A" + }, + "mmlu_logical_fallacies": { + "name": "mmlu_logical_fallacies", + "alias": "logical_fallacies", + "sample_len": 163, + "acc,none": 0.4049079754601227, + "acc_stderr,none": "N/A" + }, + "mmlu_moral_disputes": { + "name": "mmlu_moral_disputes", + "alias": "moral_disputes", + "sample_len": 346, + "acc,none": 0.37572254335260113, + "acc_stderr,none": "N/A" + }, + "mmlu_moral_scenarios": { + "name": "mmlu_moral_scenarios", + "alias": "moral_scenarios", + "sample_len": 895, + "acc,none": 0.23798882681564246, + "acc_stderr,none": "N/A" + }, + "mmlu_philosophy": { + "name": "mmlu_philosophy", + "alias": "philosophy", + "sample_len": 311, + "acc,none": 0.3215434083601286, + "acc_stderr,none": "N/A" + }, + "mmlu_prehistory": { + "name": "mmlu_prehistory", + "alias": "prehistory", + "sample_len": 324, + "acc,none": 0.4382716049382716, + "acc_stderr,none": "N/A" + }, + "mmlu_professional_law": { + "name": "mmlu_professional_law", + "alias": "professional_law", + "sample_len": 1534, + "acc,none": 0.2900912646675359, + "acc_stderr,none": "N/A" + }, + "mmlu_world_religions": { + "name": "mmlu_world_religions", + "alias": "world_religions", + "sample_len": 171, + "acc,none": 0.4853801169590643, + "acc_stderr,none": "N/A" + }, + "cmmlu_agronomy": { + "name": "cmmlu_agronomy", + "alias": "cmmlu_agronomy", + "sample_len": 169, + "acc,none": 0.378698224852071, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.378698224852071, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_anatomy": { + "name": "cmmlu_anatomy", + "alias": "cmmlu_anatomy", + "sample_len": 148, + "acc,none": 0.3310810810810811, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.3310810810810811, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_ancient_chinese": { + "name": "cmmlu_ancient_chinese", + "alias": "cmmlu_ancient_chinese", + "sample_len": 164, + "acc,none": 0.25, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.25, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_arts": { + "name": "cmmlu_arts", + "alias": "cmmlu_arts", + "sample_len": 160, + "acc,none": 0.5, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.5, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_astronomy": { + "name": "cmmlu_astronomy", + "alias": "cmmlu_astronomy", + "sample_len": 165, + "acc,none": 0.28484848484848485, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.28484848484848485, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_business_ethics": { + "name": "cmmlu_business_ethics", + "alias": "cmmlu_business_ethics", + "sample_len": 209, + "acc,none": 0.35406698564593303, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.35406698564593303, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_chinese_civil_service_exam": { + "name": "cmmlu_chinese_civil_service_exam", + "alias": "cmmlu_chinese_civil_service_exam", + "sample_len": 160, + "acc,none": 0.34375, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.34375, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_chinese_driving_rule": { + "name": "cmmlu_chinese_driving_rule", + "alias": "cmmlu_chinese_driving_rule", + "sample_len": 131, + "acc,none": 0.40458015267175573, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.40458015267175573, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_chinese_food_culture": { + "name": "cmmlu_chinese_food_culture", + "alias": "cmmlu_chinese_food_culture", + "sample_len": 136, + "acc,none": 0.3088235294117647, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.3088235294117647, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_chinese_foreign_policy": { + "name": "cmmlu_chinese_foreign_policy", + "alias": "cmmlu_chinese_foreign_policy", + "sample_len": 107, + "acc,none": 0.42990654205607476, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.42990654205607476, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_chinese_history": { + "name": "cmmlu_chinese_history", + "alias": "cmmlu_chinese_history", + "sample_len": 323, + "acc,none": 0.47058823529411764, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.47058823529411764, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_chinese_literature": { + "name": "cmmlu_chinese_literature", + "alias": "cmmlu_chinese_literature", + "sample_len": 204, + "acc,none": 0.31862745098039214, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.31862745098039214, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_chinese_teacher_qualification": { + "name": "cmmlu_chinese_teacher_qualification", + "alias": "cmmlu_chinese_teacher_qualification", + "sample_len": 179, + "acc,none": 0.4581005586592179, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.4581005586592179, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_clinical_knowledge": { + "name": "cmmlu_clinical_knowledge", + "alias": "cmmlu_clinical_knowledge", + "sample_len": 237, + "acc,none": 0.3459915611814346, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.3459915611814346, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_college_actuarial_science": { + "name": "cmmlu_college_actuarial_science", + "alias": "cmmlu_college_actuarial_science", + "sample_len": 106, + "acc,none": 0.2358490566037736, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.2358490566037736, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_college_education": { + "name": "cmmlu_college_education", + "alias": "cmmlu_college_education", + "sample_len": 107, + "acc,none": 0.4953271028037383, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.4953271028037383, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_college_engineering_hydrology": { + "name": "cmmlu_college_engineering_hydrology", + "alias": "cmmlu_college_engineering_hydrology", + "sample_len": 106, + "acc,none": 0.3867924528301887, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.3867924528301887, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_college_law": { + "name": "cmmlu_college_law", + "alias": "cmmlu_college_law", + "sample_len": 108, + "acc,none": 0.2962962962962963, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.2962962962962963, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_college_mathematics": { + "name": "cmmlu_college_mathematics", + "alias": "cmmlu_college_mathematics", + "sample_len": 105, + "acc,none": 0.21904761904761905, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.21904761904761905, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_college_medical_statistics": { + "name": "cmmlu_college_medical_statistics", + "alias": "cmmlu_college_medical_statistics", + "sample_len": 106, + "acc,none": 0.36792452830188677, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.36792452830188677, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_college_medicine": { + "name": "cmmlu_college_medicine", + "alias": "cmmlu_college_medicine", + "sample_len": 273, + "acc,none": 0.32234432234432236, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.32234432234432236, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_computer_science": { + "name": "cmmlu_computer_science", + "alias": "cmmlu_computer_science", + "sample_len": 204, + "acc,none": 0.4019607843137255, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.4019607843137255, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_computer_security": { + "name": "cmmlu_computer_security", + "alias": "cmmlu_computer_security", + "sample_len": 171, + "acc,none": 0.3391812865497076, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.3391812865497076, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_conceptual_physics": { + "name": "cmmlu_conceptual_physics", + "alias": "cmmlu_conceptual_physics", + "sample_len": 147, + "acc,none": 0.36054421768707484, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.36054421768707484, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_construction_project_management": { + "name": "cmmlu_construction_project_management", + "alias": "cmmlu_construction_project_management", + "sample_len": 139, + "acc,none": 0.33093525179856115, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.33093525179856115, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_economics": { + "name": "cmmlu_economics", + "alias": "cmmlu_economics", + "sample_len": 159, + "acc,none": 0.389937106918239, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.389937106918239, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_education": { + "name": "cmmlu_education", + "alias": "cmmlu_education", + "sample_len": 163, + "acc,none": 0.36809815950920244, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.36809815950920244, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_electrical_engineering": { + "name": "cmmlu_electrical_engineering", + "alias": "cmmlu_electrical_engineering", + "sample_len": 172, + "acc,none": 0.436046511627907, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.436046511627907, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_elementary_chinese": { + "name": "cmmlu_elementary_chinese", + "alias": "cmmlu_elementary_chinese", + "sample_len": 252, + "acc,none": 0.38492063492063494, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.38492063492063494, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_elementary_commonsense": { + "name": "cmmlu_elementary_commonsense", + "alias": "cmmlu_elementary_commonsense", + "sample_len": 198, + "acc,none": 0.36363636363636365, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.36363636363636365, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_elementary_information_and_technology": { + "name": "cmmlu_elementary_information_and_technology", + "alias": "cmmlu_elementary_information_and_technology", + "sample_len": 238, + "acc,none": 0.5042016806722689, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.5042016806722689, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_elementary_mathematics": { + "name": "cmmlu_elementary_mathematics", + "alias": "cmmlu_elementary_mathematics", + "sample_len": 230, + "acc,none": 0.2826086956521739, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.2826086956521739, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_ethnology": { + "name": "cmmlu_ethnology", + "alias": "cmmlu_ethnology", + "sample_len": 135, + "acc,none": 0.3925925925925926, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.3925925925925926, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_food_science": { + "name": "cmmlu_food_science", + "alias": "cmmlu_food_science", + "sample_len": 143, + "acc,none": 0.3006993006993007, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.3006993006993007, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_genetics": { + "name": "cmmlu_genetics", + "alias": "cmmlu_genetics", + "sample_len": 176, + "acc,none": 0.30113636363636365, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.30113636363636365, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_global_facts": { + "name": "cmmlu_global_facts", + "alias": "cmmlu_global_facts", + "sample_len": 149, + "acc,none": 0.40939597315436244, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.40939597315436244, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_high_school_biology": { + "name": "cmmlu_high_school_biology", + "alias": "cmmlu_high_school_biology", + "sample_len": 169, + "acc,none": 0.26627218934911245, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.26627218934911245, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_high_school_chemistry": { + "name": "cmmlu_high_school_chemistry", + "alias": "cmmlu_high_school_chemistry", + "sample_len": 132, + "acc,none": 0.29545454545454547, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.29545454545454547, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_high_school_geography": { + "name": "cmmlu_high_school_geography", + "alias": "cmmlu_high_school_geography", + "sample_len": 118, + "acc,none": 0.3474576271186441, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.3474576271186441, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_high_school_mathematics": { + "name": "cmmlu_high_school_mathematics", + "alias": "cmmlu_high_school_mathematics", + "sample_len": 164, + "acc,none": 0.25, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.25, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_high_school_physics": { + "name": "cmmlu_high_school_physics", + "alias": "cmmlu_high_school_physics", + "sample_len": 110, + "acc,none": 0.34545454545454546, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.34545454545454546, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_high_school_politics": { + "name": "cmmlu_high_school_politics", + "alias": "cmmlu_high_school_politics", + "sample_len": 143, + "acc,none": 0.38461538461538464, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.38461538461538464, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_human_sexuality": { + "name": "cmmlu_human_sexuality", + "alias": "cmmlu_human_sexuality", + "sample_len": 126, + "acc,none": 0.3333333333333333, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.3333333333333333, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_international_law": { + "name": "cmmlu_international_law", + "alias": "cmmlu_international_law", + "sample_len": 185, + "acc,none": 0.31891891891891894, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.31891891891891894, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_journalism": { + "name": "cmmlu_journalism", + "alias": "cmmlu_journalism", + "sample_len": 172, + "acc,none": 0.3430232558139535, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.3430232558139535, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_jurisprudence": { + "name": "cmmlu_jurisprudence", + "alias": "cmmlu_jurisprudence", + "sample_len": 411, + "acc,none": 0.36009732360097324, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.36009732360097324, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_legal_and_moral_basis": { + "name": "cmmlu_legal_and_moral_basis", + "alias": "cmmlu_legal_and_moral_basis", + "sample_len": 214, + "acc,none": 0.5327102803738317, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.5327102803738317, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_logical": { + "name": "cmmlu_logical", + "alias": "cmmlu_logical", + "sample_len": 123, + "acc,none": 0.2845528455284553, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.2845528455284553, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_machine_learning": { + "name": "cmmlu_machine_learning", + "alias": "cmmlu_machine_learning", + "sample_len": 122, + "acc,none": 0.2786885245901639, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.2786885245901639, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_management": { + "name": "cmmlu_management", + "alias": "cmmlu_management", + "sample_len": 210, + "acc,none": 0.4095238095238095, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.4095238095238095, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_marketing": { + "name": "cmmlu_marketing", + "alias": "cmmlu_marketing", + "sample_len": 180, + "acc,none": 0.37777777777777777, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.37777777777777777, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_marxist_theory": { + "name": "cmmlu_marxist_theory", + "alias": "cmmlu_marxist_theory", + "sample_len": 189, + "acc,none": 0.5185185185185185, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.5185185185185185, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_modern_chinese": { + "name": "cmmlu_modern_chinese", + "alias": "cmmlu_modern_chinese", + "sample_len": 116, + "acc,none": 0.29310344827586204, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.29310344827586204, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_nutrition": { + "name": "cmmlu_nutrition", + "alias": "cmmlu_nutrition", + "sample_len": 145, + "acc,none": 0.33793103448275863, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.33793103448275863, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_philosophy": { + "name": "cmmlu_philosophy", + "alias": "cmmlu_philosophy", + "sample_len": 105, + "acc,none": 0.34285714285714286, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.34285714285714286, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_professional_accounting": { + "name": "cmmlu_professional_accounting", + "alias": "cmmlu_professional_accounting", + "sample_len": 175, + "acc,none": 0.36, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.36, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_professional_law": { + "name": "cmmlu_professional_law", + "alias": "cmmlu_professional_law", + "sample_len": 211, + "acc,none": 0.2796208530805687, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.2796208530805687, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_professional_medicine": { + "name": "cmmlu_professional_medicine", + "alias": "cmmlu_professional_medicine", + "sample_len": 376, + "acc,none": 0.3191489361702128, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.3191489361702128, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_professional_psychology": { + "name": "cmmlu_professional_psychology", + "alias": "cmmlu_professional_psychology", + "sample_len": 232, + "acc,none": 0.3793103448275862, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.3793103448275862, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_public_relations": { + "name": "cmmlu_public_relations", + "alias": "cmmlu_public_relations", + "sample_len": 174, + "acc,none": 0.3620689655172414, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.3620689655172414, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_security_study": { + "name": "cmmlu_security_study", + "alias": "cmmlu_security_study", + "sample_len": 135, + "acc,none": 0.37037037037037035, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.37037037037037035, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_sociology": { + "name": "cmmlu_sociology", + "alias": "cmmlu_sociology", + "sample_len": 226, + "acc,none": 0.33185840707964603, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.33185840707964603, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_sports_science": { + "name": "cmmlu_sports_science", + "alias": "cmmlu_sports_science", + "sample_len": 165, + "acc,none": 0.3333333333333333, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.3333333333333333, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_traditional_chinese_medicine": { + "name": "cmmlu_traditional_chinese_medicine", + "alias": "cmmlu_traditional_chinese_medicine", + "sample_len": 185, + "acc,none": 0.35135135135135137, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.35135135135135137, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_virology": { + "name": "cmmlu_virology", + "alias": "cmmlu_virology", + "sample_len": 169, + "acc,none": 0.35502958579881655, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.35502958579881655, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_world_history": { + "name": "cmmlu_world_history", + "alias": "cmmlu_world_history", + "sample_len": 161, + "acc,none": 0.422360248447205, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.422360248447205, + "acc_norm_stderr,none": "N/A" + }, + "cmmlu_world_religions": { + "name": "cmmlu_world_religions", + "alias": "cmmlu_world_religions", + "sample_len": 160, + "acc,none": 0.4125, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.4125, + "acc_norm_stderr,none": "N/A" + }, + "mmlu_stem": { + "alias": "stem", + "name": "mmlu_stem", + "sample_len": 3153, + "acc,none": 0.34506818902632413, + "acc_stderr,none": "N/A", + "sample_count": { + "acc,none": 3153 + } + }, + "mmlu_other": { + "alias": "other", + "name": "mmlu_other", + "sample_len": 3107, + "acc,none": 0.39909880914065016, + "acc_stderr,none": "N/A", + "sample_count": { + "acc,none": 3107 + } + }, + "mmlu_social_sciences": { + "alias": "social sciences", + "name": "mmlu_social_sciences", + "sample_len": 3077, + "acc,none": 0.40103997400065, + "acc_stderr,none": "N/A", + "sample_count": { + "acc,none": 3077 + } + }, + "mmlu_humanities": { + "alias": "humanities", + "name": "mmlu_humanities", + "sample_len": 4705, + "acc,none": 0.3466524973432519, + "acc_stderr,none": "N/A", + "sample_count": { + "acc,none": 4705 + } + }, + "mmlu": { + "alias": "mmlu", + "name": "mmlu", + "sample_len": 14042, + "acc,none": 0.3698191140863125, + "acc_stderr,none": "N/A", + "sample_count": { + "acc,none": 14042 + } + }, + "cmmlu": { + "alias": "cmmlu", + "name": "cmmlu", + "sample_len": 11582, + "acc,none": 0.36142289759972374, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.36142289759972374, + "acc_norm_stderr,none": "N/A", + "sample_count": { + "acc,none": 11582, + "acc_norm,none": 11582 + } + } + }, + "lm_eval_groups": { + "mmlu_stem": { + "alias": "stem", + "name": "mmlu_stem", + "sample_len": 3153, + "acc,none": 0.34506818902632413, + "acc_stderr,none": "N/A", + "sample_count": { + "acc,none": 3153 + } + }, + "mmlu_other": { + "alias": "other", + "name": "mmlu_other", + "sample_len": 3107, + "acc,none": 0.39909880914065016, + "acc_stderr,none": "N/A", + "sample_count": { + "acc,none": 3107 + } + }, + "mmlu_social_sciences": { + "alias": "social sciences", + "name": "mmlu_social_sciences", + "sample_len": 3077, + "acc,none": 0.40103997400065, + "acc_stderr,none": "N/A", + "sample_count": { + "acc,none": 3077 + } + }, + "mmlu_humanities": { + "alias": "humanities", + "name": "mmlu_humanities", + "sample_len": 4705, + "acc,none": 0.3466524973432519, + "acc_stderr,none": "N/A", + "sample_count": { + "acc,none": 4705 + } + }, + "mmlu": { + "alias": "mmlu", + "name": "mmlu", + "sample_len": 14042, + "acc,none": 0.3698191140863125, + "acc_stderr,none": "N/A", + "sample_count": { + "acc,none": 14042 + } + }, + "cmmlu": { + "alias": "cmmlu", + "name": "cmmlu", + "sample_len": 11582, + "acc,none": 0.36142289759972374, + "acc_stderr,none": "N/A", + "acc_norm,none": 0.36142289759972374, + "acc_norm_stderr,none": "N/A", + "sample_count": { + "acc,none": 11582, + "acc_norm,none": 11582 + } + } + }, + "lm_eval_versions": { + "arc_challenge": 1.0, + "arc_easy": 1.0, + "cmmlu": "1.0", + "cmmlu_agronomy": 1.0, + "cmmlu_anatomy": 1.0, + "cmmlu_ancient_chinese": 1.0, + "cmmlu_arts": 1.0, + "cmmlu_astronomy": 1.0, + "cmmlu_business_ethics": 1.0, + "cmmlu_chinese_civil_service_exam": 1.0, + "cmmlu_chinese_driving_rule": 1.0, + "cmmlu_chinese_food_culture": 1.0, + "cmmlu_chinese_foreign_policy": 1.0, + "cmmlu_chinese_history": 1.0, + "cmmlu_chinese_literature": 1.0, + "cmmlu_chinese_teacher_qualification": 1.0, + "cmmlu_clinical_knowledge": 1.0, + "cmmlu_college_actuarial_science": 1.0, + "cmmlu_college_education": 1.0, + "cmmlu_college_engineering_hydrology": 1.0, + "cmmlu_college_law": 1.0, + "cmmlu_college_mathematics": 1.0, + "cmmlu_college_medical_statistics": 1.0, + "cmmlu_college_medicine": 1.0, + "cmmlu_computer_science": 1.0, + "cmmlu_computer_security": 1.0, + "cmmlu_conceptual_physics": 1.0, + "cmmlu_construction_project_management": 1.0, + "cmmlu_economics": 1.0, + "cmmlu_education": 1.0, + "cmmlu_electrical_engineering": 1.0, + "cmmlu_elementary_chinese": 1.0, + "cmmlu_elementary_commonsense": 1.0, + "cmmlu_elementary_information_and_technology": 1.0, + "cmmlu_elementary_mathematics": 1.0, + "cmmlu_ethnology": 1.0, + "cmmlu_food_science": 1.0, + "cmmlu_genetics": 1.0, + "cmmlu_global_facts": 1.0, + "cmmlu_high_school_biology": 1.0, + "cmmlu_high_school_chemistry": 1.0, + "cmmlu_high_school_geography": 1.0, + "cmmlu_high_school_mathematics": 1.0, + "cmmlu_high_school_physics": 1.0, + "cmmlu_high_school_politics": 1.0, + "cmmlu_human_sexuality": 1.0, + "cmmlu_international_law": 1.0, + "cmmlu_journalism": 1.0, + "cmmlu_jurisprudence": 1.0, + "cmmlu_legal_and_moral_basis": 1.0, + "cmmlu_logical": 1.0, + "cmmlu_machine_learning": 1.0, + "cmmlu_management": 1.0, + "cmmlu_marketing": 1.0, + "cmmlu_marxist_theory": 1.0, + "cmmlu_modern_chinese": 1.0, + "cmmlu_nutrition": 1.0, + "cmmlu_philosophy": 1.0, + "cmmlu_professional_accounting": 1.0, + "cmmlu_professional_law": 1.0, + "cmmlu_professional_medicine": 1.0, + "cmmlu_professional_psychology": 1.0, + "cmmlu_public_relations": 1.0, + "cmmlu_security_study": 1.0, + "cmmlu_sociology": 1.0, + "cmmlu_sports_science": 1.0, + "cmmlu_traditional_chinese_medicine": 1.0, + "cmmlu_virology": 1.0, + "cmmlu_world_history": 1.0, + "cmmlu_world_religions": 1.0, + "hellaswag": 1.0, + "mmlu": "2", + "mmlu_abstract_algebra": 1.0, + "mmlu_anatomy": 1.0, + "mmlu_astronomy": 1.0, + "mmlu_business_ethics": 1.0, + "mmlu_clinical_knowledge": 1.0, + "mmlu_college_biology": 1.0, + "mmlu_college_chemistry": 1.0, + "mmlu_college_computer_science": 1.0, + "mmlu_college_mathematics": 1.0, + "mmlu_college_medicine": 1.0, + "mmlu_college_physics": 1.0, + "mmlu_computer_security": 1.0, + "mmlu_conceptual_physics": 1.0, + "mmlu_econometrics": 1.0, + "mmlu_electrical_engineering": 1.0, + "mmlu_elementary_mathematics": 1.0, + "mmlu_formal_logic": 1.0, + "mmlu_global_facts": 1.0, + "mmlu_high_school_biology": 1.0, + "mmlu_high_school_chemistry": 1.0, + "mmlu_high_school_computer_science": 1.0, + "mmlu_high_school_european_history": 1.0, + "mmlu_high_school_geography": 1.0, + "mmlu_high_school_government_and_politics": 1.0, + "mmlu_high_school_macroeconomics": 1.0, + "mmlu_high_school_mathematics": 1.0, + "mmlu_high_school_microeconomics": 1.0, + "mmlu_high_school_physics": 1.0, + "mmlu_high_school_psychology": 1.0, + "mmlu_high_school_statistics": 1.0, + "mmlu_high_school_us_history": 1.0, + "mmlu_high_school_world_history": 1.0, + "mmlu_human_aging": 1.0, + "mmlu_human_sexuality": 1.0, + "mmlu_humanities": "2", + "mmlu_international_law": 1.0, + "mmlu_jurisprudence": 1.0, + "mmlu_logical_fallacies": 1.0, + "mmlu_machine_learning": 1.0, + "mmlu_management": 1.0, + "mmlu_marketing": 1.0, + "mmlu_medical_genetics": 1.0, + "mmlu_miscellaneous": 1.0, + "mmlu_moral_disputes": 1.0, + "mmlu_moral_scenarios": 1.0, + "mmlu_nutrition": 1.0, + "mmlu_other": "2", + "mmlu_philosophy": 1.0, + "mmlu_prehistory": 1.0, + "mmlu_professional_accounting": 1.0, + "mmlu_professional_law": 1.0, + "mmlu_professional_medicine": 1.0, + "mmlu_professional_psychology": 1.0, + "mmlu_public_relations": 1.0, + "mmlu_security_studies": 1.0, + "mmlu_social_sciences": "2", + "mmlu_sociology": 1.0, + "mmlu_stem": "2", + "mmlu_us_foreign_policy": 1.0, + "mmlu_virology": 1.0, + "mmlu_world_religions": 1.0, + "openbookqa": 1.0, + "piqa": 1.0, + "sciq": 1.0, + "winogrande": 1.0 + }, + "lm_eval_config": { + "model": "/workspace/models/qwen3-base-49e3418", + "model_args": null, + "model_num_parameters": 6454217472, + "model_dtype": "torch.bfloat16", + "model_revision": "main", + "model_sha": "", + "batch_size": "auto:4", + "batch_sizes": [ + 64, + 64, + 64, + 64 + ], + "device": null, + "use_cache": null, + "limit": null, + "bootstrap_iters": 0, + "gen_kwargs": null, + "random_seed": 0, + "numpy_seed": 1234, + "torch_seed": 1234, + "fewshot_seed": 1234 + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/eval/final_opencompass5.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/eval/final_opencompass5.json new file mode 100644 index 0000000000000000000000000000000000000000..186241c34df6b9fb1fc26f3fbabd19efe4136daf --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/eval/final_opencompass5.json @@ -0,0 +1,44 @@ +{ + "model": "/workspace/models/qwen3-base-49e3418", + "revision": "49e3418fbbbca6ecbdf9608b4d22e5a407081db4", + "compact_stage": "/workspace/qwen3-mlp-fit-20261126/full/come/compact/stage_09", + "cycle": 9, + "anchor": 12, + "tokenizer": "/workspace/models/qwen3-base-49e3418", + "protocol": "OpenCompass 0.5.4 canonical PPL prompts; full-prompt mean CE; lowest PPL", + "max_batch": 32, + "token_budget": 8192, + "limit": null, + "results": { + "race-middle": { + "accuracy": 0.29735376044568246, + "correct": 427, + "samples": 1436, + "choices": 5744 + }, + "race-high": { + "accuracy": 0.3259005145797599, + "correct": 1140, + "samples": 3498, + "choices": 13992 + }, + "C3": { + "accuracy": 0.5243835616438356, + "correct": 957, + "samples": 1825, + "choices": 7300 + }, + "cmnli": { + "accuracy": 0.3360836532962993, + "correct": 4114, + "samples": 12241, + "choices": 36723 + }, + "chid-dev": { + "accuracy": 0.698019801980198, + "correct": 141, + "samples": 202, + "choices": 1414 + } + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/eval/final_ppl.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/eval/final_ppl.json new file mode 100644 index 0000000000000000000000000000000000000000..808b13202b64a1a12b65e99b9fe612db6fae4b72 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/eval/final_ppl.json @@ -0,0 +1,40 @@ +{ + "model": "/workspace/models/qwen3-base-49e3418", + "revision": "49e3418fbbbca6ecbdf9608b4d22e5a407081db4", + "compact_stage": "/workspace/qwen3-mlp-fit-20261126/full/come/compact/stage_09", + "dataset": "Salesforce/wikitext:wikitext-2-raw-v1:test", + "offline_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" + } + }, + "protocol": "HCHC experiment.py: filter empty rows, join with double newline, then tokenize the complete stream once", + "sequence_length": 2048, + "batch_size": 8, + "dtype": "bfloat16", + "metrics": { + "nll": 2.9620428200425772, + "perplexity": 19.337434332734354, + "tokens": 296815, + "sequences": 145, + "source_tokens": 298938 + }, + "anchor": 12, + "cycles": 9, + "original_layers": 36, + "decoder_layers": 27, + "post_merge_residual_scale": null, + "post_merge_residual_scales": [], + "parameterization": "unscaled compact ABPrune", + "linear_patch": null +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/first_native_validation.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/first_native_validation.json new file mode 100644 index 0000000000000000000000000000000000000000..dc9e4431a0470fe23a1e531ed545321880f3065e --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/first_native_validation.json @@ -0,0 +1,22 @@ +{ + "passed": true, + "mka": { + "original_input_cache_verified": true, + "first_pair_matches": true, + "pair_index": 13, + "observed_lambda": 0.6225208206034097, + "historical_lambda": 0.6225201943477188, + "observed_pair_npib": 2.0866975139397255, + "historical_pair_npib": 2.104302442487761, + "exact_historical_numeric_reproduction_claimed": false + }, + "come": { + "historical_token_cache_available": false, + "legacy_reconstructed_windows": 94, + "first_pair_matches": true, + "first_score_ratios_retained_channels_exactly_match": true, + "pair_index": 31, + "pair_score": 0.11533127194072337 + }, + "validation_scope": "Native parameter algebra, immutable MKA input / legacy CoMe input recipe and first-stage selection; no nine-stage historical replay claimed" +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/logs/eval14.log b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/logs/eval14.log new file mode 100644 index 0000000000000000000000000000000000000000..b82e35c827b485afbc07ff7fb71c6e530aee4978 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/logs/eval14.log @@ -0,0 +1,497 @@ +[transformers] `torch_dtype` is deprecated! Use `dtype` instead! + Loading weights: 0%| | 0/399 [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.float() @ position_ids_expanded.float()).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) + CoMe calibration (36 layers): 1%| | 1/94 [00:00<01:10, 1.32it/s] CoMe calibration (36 layers): 2%|▏ | 2/94 [00:01<00:43, 2.12it/s] CoMe calibration (36 layers): 3%|▎ | 3/94 [00:01<00:34, 2.64it/s] CoMe calibration (36 layers): 4%|▍ | 4/94 [00:01<00:30, 2.99it/s] CoMe calibration (36 layers): 5%|▌ | 5/94 [00:01<00:27, 3.22it/s] CoMe calibration (36 layers): 6%|▋ | 6/94 [00:02<00:26, 3.37it/s] CoMe calibration (36 layers): 7%|▋ | 7/94 [00:02<00:24, 3.48it/s] CoMe calibration (36 layers): 9%|▊ | 8/94 [00:02<00:24, 3.54it/s] CoMe calibration (36 layers): 10%|▉ | 9/94 [00:02<00:23, 3.59it/s] CoMe calibration (36 layers): 11%|█ | 10/94 [00:03<00:23, 3.63it/s] CoMe calibration (36 layers): 12%|█▏ | 11/94 [00:03<00:22, 3.66it/s] CoMe calibration (36 layers): 13%|█▎ | 12/94 [00:03<00:22, 3.68it/s] CoMe calibration (36 layers): 14%|█▍ | 13/94 [00:03<00:21, 3.69it/s] CoMe calibration (36 layers): 15%|█▍ | 14/94 [00:04<00:21, 3.68it/s] CoMe calibration (36 layers): 16%|█▌ | 15/94 [00:04<00:21, 3.69it/s] CoMe calibration (36 layers): 17%|█▋ | 16/94 [00:04<00:21, 3.70it/s] CoMe calibration (36 layers): 18%|█▊ | 17/94 [00:05<00:20, 3.71it/s] CoMe calibration (36 layers): 19%|█▉ | 18/94 [00:05<00:20, 3.71it/s] CoMe calibration (36 layers): 20%|██ | 19/94 [00:05<00:20, 3.72it/s] CoMe calibration (36 layers): 21%|██▏ | 20/94 [00:05<00:19, 3.72it/s] CoMe calibration (36 layers): 22%|██▏ | 21/94 [00:06<00:19, 3.72it/s] CoMe calibration (36 layers): 23%|██▎ | 22/94 [00:06<00:19, 3.72it/s] CoMe calibration (36 layers): 24%|██▍ | 23/94 [00:06<00:19, 3.72it/s] CoMe calibration (36 layers): 26%|██▌ | 24/94 [00:06<00:18, 3.72it/s] CoMe calibration (36 layers): 27%|██▋ | 25/94 [00:07<00:18, 3.71it/s] CoMe calibration (36 layers): 28%|██▊ | 26/94 [00:07<00:18, 3.71it/s] CoMe calibration (36 layers): 29%|██▊ | 27/94 [00:07<00:18, 3.72it/s] CoMe calibration (36 layers): 30%|██▉ | 28/94 [00:08<00:17, 3.72it/s] CoMe calibration (36 layers): 31%|███ | 29/94 [00:08<00:17, 3.72it/s] CoMe calibration (36 layers): 32%|███▏ | 30/94 [00:08<00:17, 3.72it/s] CoMe calibration (36 layers): 33%|███▎ | 31/94 [00:08<00:16, 3.72it/s] CoMe calibration (36 layers): 34%|███▍ | 32/94 [00:09<00:16, 3.72it/s] CoMe calibration (36 layers): 35%|███▌ | 33/94 [00:09<00:16, 3.72it/s] CoMe calibration (36 layers): 36%|███▌ | 34/94 [00:09<00:16, 3.72it/s] CoMe calibration (36 layers): 37%|███▋ | 35/94 [00:09<00:15, 3.72it/s] CoMe calibration (36 layers): 38%|███▊ | 36/94 [00:10<00:15, 3.72it/s] CoMe calibration (36 layers): 39%|███▉ | 37/94 [00:10<00:15, 3.72it/s] CoMe calibration (36 layers): 40%|████ | 38/94 [00:10<00:15, 3.72it/s] CoMe calibration (36 layers): 41%|████▏ | 39/94 [00:10<00:14, 3.72it/s] CoMe calibration (36 layers): 43%|████▎ | 40/94 [00:11<00:14, 3.72it/s] CoMe calibration (36 layers): 44%|████▎ | 41/94 [00:11<00:14, 3.72it/s] CoMe calibration (36 layers): 45%|████▍ | 42/94 [00:11<00:13, 3.72it/s] CoMe calibration (36 layers): 46%|████▌ | 43/94 [00:12<00:13, 3.72it/s] CoMe calibration (36 layers): 47%|████▋ | 44/94 [00:12<00:13, 3.72it/s] CoMe calibration (36 layers): 48%|████▊ | 45/94 [00:12<00:13, 3.72it/s] CoMe calibration (36 layers): 49%|████▉ | 46/94 [00:12<00:12, 3.72it/s] CoMe calibration (36 layers): 50%|█████ | 47/94 [00:13<00:12, 3.72it/s] CoMe calibration (36 layers): 51%|█████ | 48/94 [00:13<00:12, 3.72it/s] CoMe calibration (36 layers): 52%|█████▏ | 49/94 [00:13<00:12, 3.72it/s] CoMe calibration (36 layers): 53%|█████▎ | 50/94 [00:13<00:11, 3.73it/s] CoMe calibration (36 layers): 54%|█████▍ | 51/94 [00:14<00:11, 3.73it/s] CoMe calibration (36 layers): 55%|█████▌ | 52/94 [00:14<00:11, 3.73it/s] CoMe calibration (36 layers): 56%|█████▋ | 53/94 [00:14<00:10, 3.73it/s] CoMe calibration (36 layers): 57%|█████▋ | 54/94 [00:15<00:10, 3.73it/s] CoMe calibration (36 layers): 59%|█████▊ | 55/94 [00:15<00:10, 3.73it/s] CoMe calibration (36 layers): 60%|█████▉ | 56/94 [00:15<00:10, 3.73it/s] CoMe calibration (36 layers): 61%|██████ | 57/94 [00:15<00:09, 3.73it/s] CoMe calibration (36 layers): 62%|██████▏ | 58/94 [00:16<00:09, 3.72it/s] CoMe calibration (36 layers): 63%|██████▎ | 59/94 [00:16<00:09, 3.72it/s] CoMe calibration (36 layers): 64%|██████▍ | 60/94 [00:16<00:09, 3.72it/s] CoMe calibration (36 layers): 65%|██████▍ | 61/94 [00:16<00:08, 3.72it/s] CoMe calibration (36 layers): 66%|██████▌ | 62/94 [00:17<00:08, 3.72it/s] CoMe calibration (36 layers): 67%|██████▋ | 63/94 [00:17<00:08, 3.72it/s] CoMe calibration (36 layers): 68%|██████▊ | 64/94 [00:17<00:08, 3.72it/s] CoMe calibration (36 layers): 69%|██████▉ | 65/94 [00:17<00:07, 3.72it/s] CoMe calibration (36 layers): 70%|███████ | 66/94 [00:18<00:07, 3.72it/s] CoMe calibration (36 layers): 71%|███████▏ | 67/94 [00:18<00:07, 3.72it/s] CoMe calibration (36 layers): 72%|███████▏ | 68/94 [00:18<00:06, 3.72it/s] CoMe calibration (36 layers): 73%|███████▎ | 69/94 [00:19<00:06, 3.72it/s] CoMe calibration (36 layers): 74%|███████▍ | 70/94 [00:19<00:06, 3.72it/s] CoMe calibration (36 layers): 76%|███████▌ | 71/94 [00:19<00:06, 3.72it/s] CoMe calibration (36 layers): 77%|███████▋ | 72/94 [00:19<00:05, 3.72it/s] CoMe calibration (36 layers): 78%|███████▊ | 73/94 [00:20<00:05, 3.72it/s] CoMe calibration (36 layers): 79%|███████▊ | 74/94 [00:20<00:05, 3.72it/s] CoMe calibration (36 layers): 80%|███████▉ | 75/94 [00:20<00:05, 3.72it/s] CoMe calibration (36 layers): 81%|████████ | 76/94 [00:20<00:04, 3.72it/s] CoMe calibration (36 layers): 82%|████████▏ | 77/94 [00:21<00:04, 3.72it/s] CoMe calibration (36 layers): 83%|████████▎ | 78/94 [00:21<00:04, 3.72it/s] CoMe calibration (36 layers): 84%|████████▍ | 79/94 [00:21<00:04, 3.72it/s] CoMe calibration (36 layers): 85%|████████▌ | 80/94 [00:21<00:03, 3.72it/s] CoMe calibration (36 layers): 86%|████████▌ | 81/94 [00:22<00:03, 3.72it/s] CoMe calibration (36 layers): 87%|████████▋ | 82/94 [00:22<00:03, 3.72it/s] CoMe calibration (36 layers): 88%|████████▊ | 83/94 [00:22<00:02, 3.72it/s] CoMe calibration (36 layers): 89%|████████▉ | 84/94 [00:23<00:02, 3.72it/s] CoMe calibration (36 layers): 90%|█████████ | 85/94 [00:23<00:02, 3.73it/s] CoMe calibration (36 layers): 91%|█████████▏| 86/94 [00:23<00:02, 3.73it/s] CoMe calibration (36 layers): 93%|█████████▎| 87/94 [00:23<00:01, 3.73it/s] CoMe calibration (36 layers): 94%|█████████▎| 88/94 [00:24<00:01, 3.73it/s] CoMe calibration (36 layers): 95%|█████████▍| 89/94 [00:24<00:01, 3.72it/s] CoMe calibration (36 layers): 96%|█████████▌| 90/94 [00:24<00:01, 3.72it/s] CoMe calibration (36 layers): 97%|█████████▋| 91/94 [00:24<00:00, 3.72it/s] CoMe calibration (36 layers): 98%|█████████▊| 92/94 [00:25<00:00, 3.72it/s] CoMe calibration (36 layers): 99%|█████████▉| 93/94 [00:25<00:00, 3.72it/s] CoMe calibration (36 layers): 100%|██████████| 94/94 [00:25<00:00, 3.72it/s] CoMe calibration (36 layers): 100%|██████████| 94/94 [00:25<00:00, 3.65it/s] +[fit-ablation] selection {"cycle": 1, "pair_index": 31, "initializer": "come", "lambda_left": null, "recipient_original_layer": 31, "recipient_side": "left", "removed_original_layer": 32, "source_lineage": [[31], [32]], "retention_ratios": [0.49274789168296595, 0.5072521083170339], "retained_attention_groups": [3, 5], "retained_mlp_neurons": [6054, 6234], "pair_score": 0.11533127194072337, "minimum_retention": 0.0, "adjusted_minimum": 0.0, "power": 1.0, "allow_repeat": true, "sbi_metric": "angular_last", "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", "teacher_mutated_during_initialization": false, "removed_original_layers": [32], "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, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35]} +[fuse] Head permutation disabled; merging with original head order. +[fit-ablation] Fisher bypassed: non-Fisher initializer + Loading weights: 0%| | 0/399 [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.) + 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=9.495447e+00 u_mean_abs=0.00018087541037756536 u_max_abs=1.585987e+00 rho_l2=0.000000e+00 +[reparam] epoch=1 step=1 phase=joint loss=1.993739e+01 mse=8.713206e+00 mlp_mse=1.122095e+01 kl=1.007872e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 0%| | 1/512 [00:00<06:29, 1.31batch/s] Reparam (cycle 1/9, epoch 1): 0%| | 2/512 [00:01<05:22, 1.58batch/s] Reparam (cycle 1/9, epoch 1): 1%| | 3/512 [00:01<05:00, 1.70batch/s] Reparam (cycle 1/9, epoch 1): 1%| | 4/512 [00:02<04:48, 1.76batch/s] Reparam (cycle 1/9, epoch 1): 1%| | 5/512 [00:02<04:41, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 1%| | 6/512 [00:03<04:44, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 1%|▏ | 7/512 [00:04<04:40, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 2%|▏ | 8/512 [00:04<04:37, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 2%|▏ | 9/512 [00:05<04:36, 1.82batch/s][reparam] epoch=1 step=10 phase=joint loss=1.842634e+01 mse=1.012162e+01 mlp_mse=8.300457e+00 kl=1.332995e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 2%|▏ | 10/512 [00:05<04:43, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 2%|▏ | 11/512 [00:06<04:39, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 2%|▏ | 12/512 [00:06<04:37, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 3%|▎ | 13/512 [00:07<04:36, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 3%|▎ | 14/512 [00:07<04:35, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 3%|▎ | 15/512 [00:08<04:33, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 3%|▎ | 16/512 [00:08<04:32, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 3%|▎ | 17/512 [00:09<04:35, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 4%|▎ | 18/512 [00:10<04:34, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 4%|▎ | 19/512 [00:10<04:32, 1.81batch/s][reparam] epoch=1 step=20 phase=joint loss=2.523621e+01 mse=1.128024e+01 mlp_mse=1.395164e+01 kl=1.352824e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 4%|▍ | 20/512 [00:11<04:38, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 4%|▍ | 21/512 [00:11<04:35, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 4%|▍ | 22/512 [00:12<04:33, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 4%|▍ | 23/512 [00:12<04:31, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 5%|▍ | 24/512 [00:13<04:30, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 5%|▍ | 25/512 [00:14<04:28, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 5%|▌ | 26/512 [00:14<04:27, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 5%|▌ | 27/512 [00:15<04:27, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 5%|▌ | 28/512 [00:15<04:26, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 6%|▌ | 29/512 [00:16<04:25, 1.82batch/s][reparam] epoch=1 step=30 phase=joint loss=1.665132e+01 mse=9.763360e+00 mlp_mse=6.884627e+00 kl=1.041849e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 6%|▌ | 30/512 [00:16<04:31, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 6%|▌ | 31/512 [00:17<04:28, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 6%|▋ | 32/512 [00:17<04:26, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 6%|▋ | 33/512 [00:18<04:24, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 7%|▋ | 34/512 [00:19<04:23, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 7%|▋ | 35/512 [00:19<04:28, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 7%|▋ | 36/512 [00:20<04:25, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 7%|▋ | 37/512 [00:20<04:23, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 7%|▋ | 38/512 [00:21<04:21, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 8%|▊ | 39/512 [00:21<04:20, 1.81batch/s][reparam] epoch=1 step=40 phase=joint loss=1.385808e+01 mse=7.123575e+00 mlp_mse=6.731851e+00 kl=8.303708e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 8%|▊ | 40/512 [00:22<04:25, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 8%|▊ | 41/512 [00:22<04:22, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 8%|▊ | 42/512 [00:23<04:21, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 8%|▊ | 43/512 [00:24<04:19, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 9%|▊ | 44/512 [00:24<04:18, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 9%|▉ | 45/512 [00:25<04:17, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 9%|▉ | 46/512 [00:25<04:16, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 9%|▉ | 47/512 [00:26<04:15, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 9%|▉ | 48/512 [00:26<04:15, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 10%|▉ | 49/512 [00:27<04:15, 1.81batch/s][reparam] epoch=1 step=50 phase=joint loss=2.159654e+01 mse=1.203315e+01 mlp_mse=9.559290e+00 kl=1.281822e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 10%|▉ | 50/512 [00:27<04:20, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 10%|▉ | 51/512 [00:28<04:17, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 10%|█ | 52/512 [00:29<04:15, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 10%|█ | 53/512 [00:29<04:14, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 11%|█ | 54/512 [00:30<04:13, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 11%|█ | 55/512 [00:30<04:12, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 11%|█ | 56/512 [00:31<04:11, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 11%|█ | 57/512 [00:31<04:10, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 11%|█▏ | 58/512 [00:32<04:09, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 12%|█▏ | 59/512 [00:32<04:08, 1.82batch/s][reparam] epoch=1 step=60 phase=joint loss=2.976302e+01 mse=1.778382e+01 mlp_mse=1.197095e+01 kl=2.577611e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 12%|█▏ | 60/512 [00:33<04:15, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 12%|█▏ | 61/512 [00:33<04:12, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 12%|█▏ | 62/512 [00:34<04:10, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 12%|█▏ | 63/512 [00:35<04:08, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 12%|█▎ | 64/512 [00:35<04:07, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 13%|█▎ | 65/512 [00:36<04:06, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 13%|█▎ | 66/512 [00:36<04:05, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 13%|█▎ | 67/512 [00:37<04:05, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 13%|█▎ | 68/512 [00:37<04:04, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 13%|█▎ | 69/512 [00:38<04:03, 1.82batch/s][reparam] epoch=1 step=70 phase=joint loss=1.457231e+01 mse=8.249085e+00 mlp_mse=6.319852e+00 kl=1.054310e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 14%|█▎ | 70/512 [00:38<04:09, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 14%|█▍ | 71/512 [00:39<04:07, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 14%|█▍ | 72/512 [00:40<04:05, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 14%|█▍ | 73/512 [00:40<04:03, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 14%|█▍ | 74/512 [00:41<04:02, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 15%|█▍ | 75/512 [00:41<04:01, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 15%|█▍ | 76/512 [00:42<03:59, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 15%|█▌ | 77/512 [00:42<03:58, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 15%|█▌ | 78/512 [00:43<03:57, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 15%|█▌ | 79/512 [00:43<03:56, 1.83batch/s][reparam] epoch=1 step=80 phase=joint loss=1.339967e+01 mse=7.827529e+00 mlp_mse=5.570068e+00 kl=6.481708e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 16%|█▌ | 80/512 [00:44<04:02, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 16%|█▌ | 81/512 [00:45<04:00, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 16%|█▌ | 82/512 [00:45<04:00, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 16%|█▌ | 83/512 [00:46<03:58, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 16%|█▋ | 84/512 [00:46<03:56, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 17%|█▋ | 85/512 [00:47<03:56, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 17%|█▋ | 86/512 [00:47<03:55, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 17%|█▋ | 87/512 [00:48<03:53, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 17%|█▋ | 88/512 [00:48<03:51, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 17%|█▋ | 89/512 [00:49<03:50, 1.84batch/s][reparam] epoch=1 step=90 phase=joint loss=1.685338e+01 mse=9.473111e+00 mlp_mse=7.377256e+00 kl=9.401032e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 18%|█▊ | 90/512 [00:50<03:56, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 18%|█▊ | 91/512 [00:50<03:53, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 18%|█▊ | 92/512 [00:51<03:50, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 18%|█▊ | 93/512 [00:51<03:49, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 18%|█▊ | 94/512 [00:52<03:48, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 19%|█▊ | 95/512 [00:52<03:47, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 19%|█▉ | 96/512 [00:53<03:47, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 19%|█▉ | 97/512 [00:53<03:46, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 19%|█▉ | 98/512 [00:54<03:46, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 19%|█▉ | 99/512 [00:54<03:46, 1.82batch/s][reparam] epoch=1 step=100 phase=joint loss=1.869901e+01 mse=1.146862e+01 mlp_mse=7.226452e+00 kl=1.230350e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 20%|█▉ | 100/512 [00:55<03:51, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 20%|█▉ | 101/512 [00:56<03:49, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 20%|█▉ | 102/512 [00:56<03:47, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 20%|██ | 103/512 [00:57<03:47, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 20%|██ | 104/512 [00:57<03:45, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 21%|██ | 105/512 [00:58<03:44, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 21%|██ | 106/512 [00:58<03:43, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 21%|██ | 107/512 [00:59<03:42, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 21%|██ | 108/512 [00:59<03:41, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 21%|██▏ | 109/512 [01:00<03:41, 1.82batch/s][reparam] epoch=1 step=110 phase=joint loss=1.707070e+01 mse=1.013579e+01 mlp_mse=6.931905e+00 kl=9.401769e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 21%|██▏ | 110/512 [01:01<03:46, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 22%|██▏ | 111/512 [01:01<03:43, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 22%|██▏ | 112/512 [01:02<03:42, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 22%|██▏ | 113/512 [01:02<03:40, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 22%|██▏ | 114/512 [01:03<03:39, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 22%|██▏ | 115/512 [01:03<03:38, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 23%|██▎ | 116/512 [01:04<03:37, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 23%|██▎ | 117/512 [01:04<03:36, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 23%|██▎ | 118/512 [01:05<03:36, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 23%|██▎ | 119/512 [01:06<03:36, 1.82batch/s][reparam] epoch=1 step=120 phase=joint loss=1.183206e+01 mse=6.411361e+00 mlp_mse=5.418117e+00 kl=8.066068e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 23%|██▎ | 120/512 [01:06<03:41, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 24%|██▎ | 121/512 [01:07<03:39, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 24%|██▍ | 122/512 [01:07<03:37, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 24%|██▍ | 123/512 [01:08<03:36, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 24%|██▍ | 124/512 [01:08<03:35, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 24%|██▍ | 125/512 [01:09<03:34, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 25%|██▍ | 126/512 [01:09<03:33, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 25%|██▍ | 127/512 [01:10<03:32, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 25%|██▌ | 128/512 [01:11<03:31, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 25%|██▌ | 129/512 [01:11<03:30, 1.82batch/s][reparam] epoch=1 step=130 phase=joint loss=1.989583e+01 mse=1.176176e+01 mlp_mse=8.129807e+00 kl=1.330787e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 25%|██▌ | 130/512 [01:12<03:34, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 26%|██▌ | 131/512 [01:12<03:33, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 26%|██▌ | 132/512 [01:13<03:31, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 26%|██▌ | 133/512 [01:13<03:30, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 26%|██▌ | 134/512 [01:14<03:29, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 26%|██▋ | 135/512 [01:14<03:28, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 27%|██▋ | 136/512 [01:15<03:27, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 27%|██▋ | 137/512 [01:16<03:26, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 27%|██▋ | 138/512 [01:16<03:25, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 27%|██▋ | 139/512 [01:17<03:24, 1.82batch/s][reparam] epoch=1 step=140 phase=joint loss=2.473298e+01 mse=1.409919e+01 mlp_mse=1.062912e+01 kl=1.458902e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 27%|██▋ | 140/512 [01:17<03:29, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 28%|██▊ | 141/512 [01:18<03:27, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 28%|██▊ | 142/512 [01:18<03:25, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 28%|██▊ | 143/512 [01:19<03:24, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 28%|██▊ | 144/512 [01:19<03:23, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 28%|██▊ | 145/512 [01:20<03:21, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 29%|██▊ | 146/512 [01:20<03:20, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 29%|██▊ | 147/512 [01:21<03:20, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 29%|██▉ | 148/512 [01:22<03:19, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 29%|██▉ | 149/512 [01:22<03:18, 1.82batch/s][reparam] epoch=1 step=150 phase=joint loss=1.805863e+01 mse=1.029811e+01 mlp_mse=7.756531e+00 kl=1.246822e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 29%|██▉ | 150/512 [01:23<03:23, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 29%|██▉ | 151/512 [01:23<03:20, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 30%|██▉ | 152/512 [01:24<03:19, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 30%|██▉ | 153/512 [01:24<03:17, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 30%|███ | 154/512 [01:25<03:16, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 30%|███ | 155/512 [01:25<03:15, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 30%|███ | 156/512 [01:26<03:15, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 31%|███ | 157/512 [01:27<03:14, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 31%|███ | 158/512 [01:27<03:14, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 31%|███ | 159/512 [01:28<03:12, 1.83batch/s][reparam] epoch=1 step=160 phase=joint loss=1.644199e+01 mse=9.631566e+00 mlp_mse=6.807730e+00 kl=8.405818e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 31%|███▏ | 160/512 [01:28<03:17, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 31%|███▏ | 161/512 [01:29<03:15, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 32%|███▏ | 162/512 [01:29<03:13, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 32%|███▏ | 163/512 [01:30<03:11, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 32%|███▏ | 164/512 [01:30<03:10, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 32%|███▏ | 165/512 [01:31<03:09, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 32%|███▏ | 166/512 [01:31<03:08, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 33%|███▎ | 167/512 [01:32<03:07, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 33%|███▎ | 168/512 [01:33<03:07, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 33%|███▎ | 169/512 [01:33<03:07, 1.83batch/s][reparam] epoch=1 step=170 phase=joint loss=1.774180e+01 mse=1.009788e+01 mlp_mse=7.640302e+00 kl=1.130928e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 33%|███▎ | 170/512 [01:34<03:11, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 33%|███▎ | 171/512 [01:34<03:09, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 34%|███▎ | 172/512 [01:35<03:08, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 34%|███▍ | 173/512 [01:35<03:07, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 34%|███▍ | 174/512 [01:36<03:06, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 34%|███▍ | 175/512 [01:36<03:05, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 34%|███▍ | 176/512 [01:37<03:05, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 35%|███▍ | 177/512 [01:38<03:05, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 35%|███▍ | 178/512 [01:38<03:04, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 35%|███▍ | 179/512 [01:39<03:03, 1.81batch/s][reparam] epoch=1 step=180 phase=joint loss=1.737082e+01 mse=1.072108e+01 mlp_mse=6.646894e+00 kl=8.923613e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 35%|███▌ | 180/512 [01:39<03:07, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 35%|███▌ | 181/512 [01:40<03:05, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 36%|███▌ | 182/512 [01:40<03:03, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 36%|███▌ | 183/512 [01:41<03:02, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 36%|███▌ | 184/512 [01:41<03:02, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 36%|███▌ | 185/512 [01:42<03:00, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 36%|███▋ | 186/512 [01:43<02:59, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 37%|███▋ | 187/512 [01:43<02:58, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 37%|███▋ | 188/512 [01:44<02:58, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 37%|███▋ | 189/512 [01:44<02:57, 1.82batch/s][reparam] epoch=1 step=190 phase=joint loss=1.812694e+01 mse=1.091961e+01 mlp_mse=7.204376e+00 kl=9.223578e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 37%|███▋ | 190/512 [01:45<03:01, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 37%|███▋ | 191/512 [01:45<02:59, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 38%|███▊ | 192/512 [01:46<02:57, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 38%|███▊ | 193/512 [01:46<02:56, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 38%|███▊ | 194/512 [01:47<02:55, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 38%|███▊ | 195/512 [01:48<02:54, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 38%|███▊ | 196/512 [01:48<02:53, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 38%|███▊ | 197/512 [01:49<02:53, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 39%|███▊ | 198/512 [01:49<02:52, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 39%|███▉ | 199/512 [01:50<02:51, 1.82batch/s][reparam] epoch=1 step=200 phase=joint loss=1.328311e+01 mse=7.936556e+00 mlp_mse=5.343438e+00 kl=9.732845e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 39%|███▉ | 200/512 [01:50<02:55, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 39%|███▉ | 201/512 [01:51<02:53, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 39%|███▉ | 202/512 [01:51<02:52, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 40%|███▉ | 203/512 [01:52<02:50, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 40%|███▉ | 204/512 [01:53<02:49, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 40%|████ | 205/512 [01:53<02:48, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 40%|████ | 206/512 [01:54<02:48, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 40%|████ | 207/512 [01:54<02:47, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 41%|████ | 208/512 [01:55<02:47, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 41%|████ | 209/512 [01:55<02:46, 1.82batch/s][reparam] epoch=1 step=210 phase=joint loss=1.492975e+01 mse=9.093560e+00 mlp_mse=5.833399e+00 kl=8.713976e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 41%|████ | 210/512 [01:56<02:49, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 41%|████ | 211/512 [01:56<02:48, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 41%|████▏ | 212/512 [01:57<02:47, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 42%|████▏ | 213/512 [01:58<02:45, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 42%|████▏ | 214/512 [01:58<02:44, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 42%|████▏ | 215/512 [01:59<02:44, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 42%|████▏ | 216/512 [01:59<02:43, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 42%|████▏ | 217/512 [02:00<02:42, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 43%|████▎ | 218/512 [02:00<02:42, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 43%|████▎ | 219/512 [02:01<02:41, 1.81batch/s][reparam] epoch=1 step=220 phase=joint loss=1.744568e+01 mse=1.033351e+01 mlp_mse=7.108315e+00 kl=1.205339e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 43%|████▎ | 220/512 [02:01<02:45, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 43%|████▎ | 221/512 [02:02<02:43, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 43%|████▎ | 222/512 [02:03<02:41, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 44%|████▎ | 223/512 [02:03<02:40, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 44%|████▍ | 224/512 [02:04<02:39, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 44%|████▍ | 225/512 [02:04<02:38, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 44%|████▍ | 226/512 [02:05<02:37, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 44%|████▍ | 227/512 [02:05<02:36, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 45%|████▍ | 228/512 [02:06<02:36, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 45%|████▍ | 229/512 [02:06<02:36, 1.81batch/s][reparam] epoch=1 step=230 phase=joint loss=2.064344e+01 mse=1.203646e+01 mlp_mse=8.602280e+00 kl=1.468392e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 45%|████▍ | 230/512 [02:07<02:39, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 45%|████▌ | 231/512 [02:08<02:37, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 45%|████▌ | 232/512 [02:08<02:35, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 46%|████▌ | 233/512 [02:09<02:34, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 46%|████▌ | 234/512 [02:09<02:33, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 46%|████▌ | 235/512 [02:10<02:32, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 46%|████▌ | 236/512 [02:10<02:32, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 46%|████▋ | 237/512 [02:11<02:31, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 46%|████▋ | 238/512 [02:11<02:31, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 47%|████▋ | 239/512 [02:12<02:30, 1.82batch/s][reparam] epoch=1 step=240 phase=joint loss=1.553425e+01 mse=9.486114e+00 mlp_mse=6.044197e+00 kl=1.230900e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 47%|████▋ | 240/512 [02:13<02:33, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 47%|████▋ | 241/512 [02:13<02:31, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 47%|████▋ | 242/512 [02:14<02:29, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 47%|████▋ | 243/512 [02:14<02:28, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 48%|████▊ | 244/512 [02:15<02:27, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 48%|████▊ | 245/512 [02:15<02:26, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 48%|████▊ | 246/512 [02:16<02:28, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 48%|████▊ | 247/512 [02:16<02:26, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 48%|████▊ | 248/512 [02:17<02:25, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 49%|████▊ | 249/512 [02:17<02:24, 1.81batch/s][reparam] epoch=1 step=250 phase=joint loss=1.973632e+01 mse=1.213655e+01 mlp_mse=7.596562e+00 kl=1.001919e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 49%|████▉ | 250/512 [02:18<02:27, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 49%|████▉ | 251/512 [02:19<02:25, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 49%|████▉ | 252/512 [02:19<02:24, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 49%|████▉ | 253/512 [02:20<02:23, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 50%|████▉ | 254/512 [02:20<02:22, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 50%|████▉ | 255/512 [02:21<02:21, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 50%|█████ | 256/512 [02:21<02:20, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 50%|█████ | 257/512 [02:22<02:20, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 50%|█████ | 258/512 [02:22<02:19, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 51%|█████ | 259/512 [02:23<02:18, 1.83batch/s][reparam] epoch=1 step=260 phase=joint loss=1.337037e+01 mse=8.339733e+00 mlp_mse=5.027091e+00 kl=1.108101e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 51%|█████ | 260/512 [02:24<02:21, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 51%|█████ | 261/512 [02:24<02:30, 1.67batch/s] Reparam (cycle 1/9, epoch 1): 51%|█████ | 262/512 [02:25<02:25, 1.72batch/s] Reparam (cycle 1/9, epoch 1): 51%|█████▏ | 263/512 [02:25<02:21, 1.76batch/s] Reparam (cycle 1/9, epoch 1): 52%|█████▏ | 264/512 [02:26<02:18, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 52%|█████▏ | 265/512 [02:26<02:17, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 52%|█████▏ | 266/512 [02:27<02:16, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 52%|█████▏ | 267/512 [02:28<02:18, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 52%|█████▏ | 268/512 [02:28<02:16, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 53%|█████▎ | 269/512 [02:29<02:15, 1.79batch/s][reparam] epoch=1 step=270 phase=joint loss=1.340551e+01 mse=8.562282e+00 mlp_mse=4.840580e+00 kl=8.279055e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 53%|█████▎ | 270/512 [02:29<02:17, 1.76batch/s] Reparam (cycle 1/9, epoch 1): 53%|█████▎ | 271/512 [02:30<02:15, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 53%|█████▎ | 272/512 [02:30<02:13, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 53%|█████▎ | 273/512 [02:31<02:12, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 54%|█████▎ | 274/512 [02:31<02:11, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 54%|█████▎ | 275/512 [02:32<02:10, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 54%|█████▍ | 276/512 [02:33<02:09, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 54%|█████▍ | 277/512 [02:33<02:11, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 54%|█████▍ | 278/512 [02:34<02:10, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 54%|█████▍ | 279/512 [02:34<02:09, 1.80batch/s][reparam] epoch=1 step=280 phase=joint loss=2.706939e+01 mse=1.660356e+01 mlp_mse=1.044367e+01 kl=6.925943e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 55%|█████▍ | 280/512 [02:35<02:11, 1.76batch/s] Reparam (cycle 1/9, epoch 1): 55%|█████▍ | 281/512 [02:35<02:09, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 55%|█████▌ | 282/512 [02:36<02:08, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 55%|█████▌ | 283/512 [02:36<02:07, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 55%|█████▌ | 284/512 [02:37<02:06, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 56%|█████▌ | 285/512 [02:38<02:05, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 56%|█████▌ | 286/512 [02:38<02:05, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 56%|█████▌ | 287/512 [02:39<02:03, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 56%|█████▋ | 288/512 [02:39<02:02, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 56%|█████▋ | 289/512 [02:40<02:25, 1.53batch/s][reparam] epoch=1 step=290 phase=joint loss=3.800401e+01 mse=2.273061e+01 mlp_mse=1.526369e+01 kl=3.035819e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 57%|█████▋ | 290/512 [02:41<02:21, 1.57batch/s] Reparam (cycle 1/9, epoch 1): 57%|█████▋ | 291/512 [02:41<02:14, 1.64batch/s] Reparam (cycle 1/9, epoch 1): 57%|█████▋ | 292/512 [02:42<02:09, 1.69batch/s] Reparam (cycle 1/9, epoch 1): 57%|█████▋ | 293/512 [02:42<02:06, 1.73batch/s] Reparam (cycle 1/9, epoch 1): 57%|█████▋ | 294/512 [02:43<02:04, 1.76batch/s] Reparam (cycle 1/9, epoch 1): 58%|█████▊ | 295/512 [02:43<02:02, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 58%|█████▊ | 296/512 [02:44<02:00, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 58%|█████▊ | 297/512 [02:45<01:59, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 58%|█████▊ | 298/512 [02:45<01:58, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 58%|█████▊ | 299/512 [02:46<01:57, 1.81batch/s][reparam] epoch=1 step=300 phase=joint loss=1.477566e+01 mse=9.266447e+00 mlp_mse=5.506171e+00 kl=9.495223e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 59%|█████▊ | 300/512 [02:46<01:59, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 59%|█████▉ | 301/512 [02:47<01:58, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 59%|█████▉ | 302/512 [02:47<01:57, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 59%|█████▉ | 303/512 [02:48<01:56, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 59%|█████▉ | 304/512 [02:48<01:55, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 60%|█████▉ | 305/512 [02:49<01:54, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 60%|█████▉ | 306/512 [02:50<01:53, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 60%|█████▉ | 307/512 [02:50<01:53, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 60%|██████ | 308/512 [02:51<01:52, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 60%|██████ | 309/512 [02:51<01:51, 1.82batch/s][reparam] epoch=1 step=310 phase=joint loss=1.424337e+01 mse=8.876520e+00 mlp_mse=5.362486e+00 kl=1.365300e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 61%|██████ | 310/512 [02:52<01:53, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 61%|██████ | 311/512 [02:52<01:52, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 61%|██████ | 312/512 [02:53<01:51, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 61%|██████ | 313/512 [02:53<01:50, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 61%|██████▏ | 314/512 [02:54<01:49, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 62%|██████▏ | 315/512 [02:55<01:48, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 62%|██████▏ | 316/512 [02:55<01:47, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 62%|██████▏ | 317/512 [02:56<01:47, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 62%|██████▏ | 318/512 [02:56<01:46, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 62%|██████▏ | 319/512 [02:57<01:49, 1.76batch/s][reparam] epoch=1 step=320 phase=joint loss=1.702548e+01 mse=1.134166e+01 mlp_mse=5.680345e+00 kl=1.085404e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 62%|██████▎ | 320/512 [02:57<01:50, 1.73batch/s] Reparam (cycle 1/9, epoch 1): 63%|██████▎ | 321/512 [02:58<01:47, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 63%|██████▎ | 322/512 [02:58<01:45, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 63%|██████▎ | 323/512 [02:59<01:44, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 63%|██████▎ | 324/512 [03:00<01:42, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 63%|██████▎ | 325/512 [03:00<01:41, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 64%|██████▎ | 326/512 [03:01<01:41, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 64%|██████▍ | 327/512 [03:01<01:40, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 64%|██████▍ | 328/512 [03:02<01:39, 1.85batch/s] Reparam (cycle 1/9, epoch 1): 64%|██████▍ | 329/512 [03:02<01:38, 1.85batch/s][reparam] epoch=1 step=330 phase=joint loss=2.727214e+01 mse=1.613594e+01 mlp_mse=1.112971e+01 kl=2.026357e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 64%|██████▍ | 330/512 [03:03<01:41, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 65%|██████▍ | 331/512 [03:03<01:39, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 65%|██████▍ | 332/512 [03:04<01:38, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 65%|██████▌ | 333/512 [03:04<01:38, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 65%|██████▌ | 334/512 [03:05<01:37, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 65%|██████▌ | 335/512 [03:06<01:37, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 66%|██████▌ | 336/512 [03:06<01:36, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 66%|██████▌ | 337/512 [03:07<01:36, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 66%|██████▌ | 338/512 [03:07<01:35, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 66%|██████▌ | 339/512 [03:08<01:35, 1.82batch/s][reparam] epoch=1 step=340 phase=joint loss=1.742981e+01 mse=1.017932e+01 mlp_mse=7.247119e+00 kl=1.052968e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 66%|██████▋ | 340/512 [03:08<01:36, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 67%|██████▋ | 341/512 [03:09<01:35, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 67%|██████▋ | 342/512 [03:09<01:34, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 67%|██████▋ | 343/512 [03:10<01:33, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 67%|██████▋ | 344/512 [03:11<01:33, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 67%|██████▋ | 345/512 [03:11<01:32, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 68%|██████▊ | 346/512 [03:12<01:32, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 68%|██████▊ | 347/512 [03:12<01:31, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 68%|██████▊ | 348/512 [03:13<01:30, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 68%|██████▊ | 349/512 [03:13<01:30, 1.81batch/s][reparam] epoch=1 step=350 phase=joint loss=1.615130e+01 mse=1.035571e+01 mlp_mse=5.792356e+00 kl=1.008799e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 68%|██████▊ | 350/512 [03:14<01:31, 1.76batch/s] Reparam (cycle 1/9, epoch 1): 69%|██████▊ | 351/512 [03:14<01:30, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 69%|██████▉ | 352/512 [03:15<01:29, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 69%|██████▉ | 353/512 [03:16<01:28, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 69%|██████▉ | 354/512 [03:16<01:27, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 69%|██████▉ | 355/512 [03:17<01:26, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 70%|██████▉ | 356/512 [03:17<01:25, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 70%|██████▉ | 357/512 [03:18<01:25, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 70%|██████▉ | 358/512 [03:18<01:24, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 70%|███████ | 359/512 [03:19<01:24, 1.82batch/s][reparam] epoch=1 step=360 phase=joint loss=1.580187e+01 mse=1.039565e+01 mlp_mse=5.402530e+00 kl=1.151167e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 70%|███████ | 360/512 [03:19<01:25, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 71%|███████ | 361/512 [03:20<01:24, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 71%|███████ | 362/512 [03:21<01:23, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 71%|███████ | 363/512 [03:21<01:22, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 71%|███████ | 364/512 [03:22<01:21, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 71%|███████▏ | 365/512 [03:22<01:21, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 71%|███████▏ | 366/512 [03:23<01:20, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 72%|███████▏ | 367/512 [03:23<01:20, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 72%|███████▏ | 368/512 [03:24<01:19, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 72%|███████▏ | 369/512 [03:24<01:18, 1.82batch/s][reparam] epoch=1 step=370 phase=joint loss=1.652007e+01 mse=9.894043e+00 mlp_mse=6.622660e+00 kl=1.052392e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 72%|███████▏ | 370/512 [03:25<01:20, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 72%|███████▏ | 371/512 [03:26<01:18, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 73%|███████▎ | 372/512 [03:26<01:17, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 73%|███████▎ | 373/512 [03:27<01:16, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 73%|███████▎ | 374/512 [03:27<01:16, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 73%|███████▎ | 375/512 [03:28<01:15, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 73%|███████▎ | 376/512 [03:28<01:14, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 74%|███████▎ | 377/512 [03:29<01:14, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 74%|███████▍ | 378/512 [03:29<01:13, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 74%|███████▍ | 379/512 [03:30<01:13, 1.82batch/s][reparam] epoch=1 step=380 phase=joint loss=1.048226e+01 mse=6.617739e+00 mlp_mse=3.862432e+00 kl=6.538314e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 74%|███████▍ | 380/512 [03:31<01:14, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 74%|███████▍ | 381/512 [03:31<01:13, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 75%|███████▍ | 382/512 [03:32<01:12, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 75%|███████▍ | 383/512 [03:32<01:11, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 75%|███████▌ | 384/512 [03:33<01:10, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 75%|███████▌ | 385/512 [03:33<01:10, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 75%|███████▌ | 386/512 [03:34<01:09, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 76%|███████▌ | 387/512 [03:34<01:09, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 76%|███████▌ | 388/512 [03:35<01:08, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 76%|███████▌ | 389/512 [03:36<01:08, 1.81batch/s][reparam] epoch=1 step=390 phase=joint loss=1.109388e+01 mse=7.004797e+00 mlp_mse=4.086828e+00 kl=7.051707e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 76%|███████▌ | 390/512 [03:36<01:09, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 76%|███████▋ | 391/512 [03:37<01:07, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 77%|███████▋ | 392/512 [03:37<01:07, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 77%|███████▋ | 393/512 [03:38<01:06, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 77%|███████▋ | 394/512 [03:38<01:05, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 77%|███████▋ | 395/512 [03:39<01:04, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 77%|███████▋ | 396/512 [03:39<01:04, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 78%|███████▊ | 397/512 [03:40<01:03, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 78%|███████▊ | 398/512 [03:41<01:02, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 78%|███████▊ | 399/512 [03:41<01:02, 1.82batch/s][reparam] epoch=1 step=400 phase=joint loss=1.645780e+01 mse=1.032099e+01 mlp_mse=6.133494e+00 kl=1.039166e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 78%|███████▊ | 400/512 [03:42<01:03, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 78%|███████▊ | 401/512 [03:42<01:02, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 79%|███████▊ | 402/512 [03:43<01:01, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 79%|███████▊ | 403/512 [03:43<01:00, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 79%|███████▉ | 404/512 [03:44<00:59, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 79%|███████▉ | 405/512 [03:44<00:59, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 79%|███████▉ | 406/512 [03:45<00:58, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 79%|███████▉ | 407/512 [03:46<00:57, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 80%|███████▉ | 408/512 [03:46<00:57, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 80%|███████▉ | 409/512 [03:47<00:56, 1.82batch/s][reparam] epoch=1 step=410 phase=joint loss=1.389991e+01 mse=8.504156e+00 mlp_mse=5.393105e+00 kl=8.281047e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 80%|████████ | 410/512 [03:47<00:57, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 80%|████████ | 411/512 [03:48<00:56, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 80%|████████ | 412/512 [03:48<00:55, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 81%|████████ | 413/512 [03:49<00:55, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 81%|████████ | 414/512 [03:49<00:54, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 81%|████████ | 415/512 [03:50<00:53, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 81%|████████▏ | 416/512 [03:51<00:53, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 81%|████████▏ | 417/512 [03:51<00:52, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 82%|████████▏ | 418/512 [03:52<00:51, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 82%|████████▏ | 419/512 [03:52<00:51, 1.81batch/s][reparam] epoch=1 step=420 phase=joint loss=1.030276e+01 mse=6.277914e+00 mlp_mse=4.022878e+00 kl=6.165919e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 82%|████████▏ | 420/512 [03:53<00:51, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 82%|████████▏ | 421/512 [03:53<00:51, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 82%|████████▏ | 422/512 [03:54<00:50, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 83%|████████▎ | 423/512 [03:54<00:49, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 83%|████████▎ | 424/512 [03:55<00:48, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 83%|████████▎ | 425/512 [03:56<00:48, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 83%|████████▎ | 426/512 [03:56<00:47, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 83%|████████▎ | 427/512 [03:57<00:46, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 84%|████████▎ | 428/512 [03:57<00:46, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 84%|████████▍ | 429/512 [03:58<00:45, 1.82batch/s][reparam] epoch=1 step=430 phase=joint loss=1.853214e+01 mse=1.098472e+01 mlp_mse=7.542384e+00 kl=1.573884e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 84%|████████▍ | 430/512 [03:58<00:46, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 84%|████████▍ | 431/512 [03:59<00:45, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 84%|████████▍ | 432/512 [03:59<00:44, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 85%|████████▍ | 433/512 [04:00<00:43, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 85%|████████▍ | 434/512 [04:01<00:43, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 85%|████████▍ | 435/512 [04:01<00:42, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 85%|████████▌ | 436/512 [04:02<00:42, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 85%|████████▌ | 437/512 [04:02<00:41, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 86%|████████▌ | 438/512 [04:03<00:40, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 86%|████████▌ | 439/512 [04:03<00:40, 1.81batch/s][reparam] epoch=1 step=440 phase=joint loss=1.347232e+01 mse=8.152021e+00 mlp_mse=5.317660e+00 kl=8.244053e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 86%|████████▌ | 440/512 [04:04<00:40, 1.77batch/s] Reparam (cycle 1/9, epoch 1): 86%|████████▌ | 441/512 [04:04<00:39, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 86%|████████▋ | 442/512 [04:05<00:38, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 87%|████████▋ | 443/512 [04:05<00:38, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 87%|████████▋ | 444/512 [04:06<00:37, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 87%|████████▋ | 445/512 [04:07<00:36, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 87%|████████▋ | 446/512 [04:07<00:35, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 87%|████████▋ | 447/512 [04:08<00:35, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 88%|████████▊ | 448/512 [04:08<00:34, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 88%|████████▊ | 449/512 [04:09<00:34, 1.84batch/s][reparam] epoch=1 step=450 phase=joint loss=1.565186e+01 mse=9.379218e+00 mlp_mse=6.268640e+00 kl=1.249998e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 88%|████████▊ | 450/512 [04:09<00:34, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 88%|████████▊ | 451/512 [04:10<00:33, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 88%|████████▊ | 452/512 [04:10<00:33, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 88%|████████▊ | 453/512 [04:11<00:32, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 89%|████████▊ | 454/512 [04:12<00:31, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 89%|████████▉ | 455/512 [04:12<00:31, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 89%|████████▉ | 456/512 [04:13<00:30, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 89%|████████▉ | 457/512 [04:13<00:29, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 89%|████████▉ | 458/512 [04:14<00:29, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 90%|████████▉ | 459/512 [04:14<00:28, 1.84batch/s][reparam] epoch=1 step=460 phase=joint loss=1.607323e+01 mse=1.081147e+01 mlp_mse=5.257923e+00 kl=1.200672e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 90%|████████▉ | 460/512 [04:15<00:29, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 90%|█████████ | 461/512 [04:15<00:28, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 90%|█████████ | 462/512 [04:16<00:27, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 90%|█████████ | 463/512 [04:16<00:26, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 91%|█████████ | 464/512 [04:17<00:26, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 91%|█████████ | 465/512 [04:18<00:25, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 91%|█████████ | 466/512 [04:18<00:25, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 91%|█████████ | 467/512 [04:19<00:24, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 91%|█████████▏| 468/512 [04:19<00:23, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 92%|█████████▏| 469/512 [04:20<00:23, 1.84batch/s][reparam] epoch=1 step=470 phase=joint loss=2.451468e+01 mse=1.429939e+01 mlp_mse=1.021035e+01 kl=1.542461e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 92%|█████████▏| 470/512 [04:20<00:23, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 92%|█████████▏| 471/512 [04:21<00:22, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 92%|█████████▏| 472/512 [04:21<00:22, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 92%|█████████▏| 473/512 [04:22<00:21, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 93%|█████████▎| 474/512 [04:22<00:20, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 93%|█████████▎| 475/512 [04:23<00:20, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 93%|█████████▎| 476/512 [04:24<00:19, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 93%|█████████▎| 477/512 [04:24<00:19, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 93%|█████████▎| 478/512 [04:25<00:18, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 94%|█████████▎| 479/512 [04:25<00:17, 1.84batch/s][reparam] epoch=1 step=480 phase=joint loss=1.375456e+01 mse=8.364067e+00 mlp_mse=5.388103e+00 kl=7.470160e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 94%|█████████▍| 480/512 [04:26<00:17, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 94%|█████████▍| 481/512 [04:26<00:17, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 94%|█████████▍| 482/512 [04:27<00:16, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 94%|█████████▍| 483/512 [04:27<00:15, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 95%|█████████▍| 484/512 [04:28<00:15, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 95%|█████████▍| 485/512 [04:29<00:14, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 95%|█████████▍| 486/512 [04:29<00:14, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 95%|█████████▌| 487/512 [04:30<00:13, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 95%|█████████▌| 488/512 [04:30<00:13, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 96%|█████████▌| 489/512 [04:31<00:12, 1.83batch/s][reparam] epoch=1 step=490 phase=joint loss=1.644021e+01 mse=9.567679e+00 mlp_mse=6.868656e+00 kl=1.211434e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 96%|█████████▌| 490/512 [04:31<00:12, 1.78batch/s] Reparam (cycle 1/9, epoch 1): 96%|█████████▌| 491/512 [04:32<00:11, 1.80batch/s] Reparam (cycle 1/9, epoch 1): 96%|█████████▌| 492/512 [04:32<00:11, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 96%|█████████▋| 493/512 [04:33<00:10, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 96%|█████████▋| 494/512 [04:33<00:09, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 97%|█████████▋| 495/512 [04:34<00:09, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 97%|█████████▋| 496/512 [04:35<00:08, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 97%|█████████▋| 497/512 [04:35<00:08, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 97%|█████████▋| 498/512 [04:36<00:07, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 97%|█████████▋| 499/512 [04:36<00:07, 1.84batch/s][reparam] epoch=1 step=500 phase=joint loss=1.812911e+01 mse=1.073903e+01 mlp_mse=7.386460e+00 kl=1.132199e-02 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 98%|█████████▊| 500/512 [04:37<00:06, 1.76batch/s] Reparam (cycle 1/9, epoch 1): 98%|█████████▊| 501/512 [04:37<00:06, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 98%|█████████▊| 502/512 [04:38<00:05, 1.81batch/s] Reparam (cycle 1/9, epoch 1): 98%|█████████▊| 503/512 [04:38<00:04, 1.82batch/s] Reparam (cycle 1/9, epoch 1): 98%|█████████▊| 504/512 [04:39<00:04, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 99%|█████████▊| 505/512 [04:39<00:03, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 99%|█████████▉| 506/512 [04:40<00:03, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 99%|█████████▉| 507/512 [04:41<00:02, 1.83batch/s] Reparam (cycle 1/9, epoch 1): 99%|█████████▉| 508/512 [04:41<00:02, 1.84batch/s] Reparam (cycle 1/9, epoch 1): 99%|█████████▉| 509/512 [04:42<00:01, 1.84batch/s][reparam] epoch=1 step=510 phase=joint loss=1.363130e+01 mse=8.306231e+00 mlp_mse=5.322867e+00 kl=6.888318e-03 lambda_mean=0.9998999834060669 lambda_std=0.0 lambda_abs0.5=0.4998999834060669 + Reparam (cycle 1/9, epoch 1): 100%|█████████▉| 510/512 [04:42<00:01, 1.79batch/s] Reparam (cycle 1/9, epoch 1): 100%|█████████▉| 511/512 [04:43<00:00, 1.67batch/s] Reparam (cycle 1/9, epoch 1): 100%|██████████| 512/512 [04:43<00:00, 1.72batch/s] Reparam (cycle 1/9, epoch 1): 100%|██████████| 512/512 [04:43<00:00, 1.80batch/s] +[timing] Cycle 1 component wall-clock: +[timing] selection: 26.873s (8.52% of cycle) +[timing] rebase: 0.000s (0.00% of cycle) +[timing] fisher: 0.000s (0.00% of cycle) +[timing] fit: 287.817s (91.26% of cycle) +[timing] materialize_save_layer: 0.438s (0.14% of cycle) +[timing] metadata_write: 0.001s (0.00% of cycle) +[timing] teacher_snapshot: 0.115s (0.04% of cycle) +[timing] cycle_cleanup: 0.146s (0.05% of cycle) +[timing] cycle_total: 315.391s +[timing] tracked_components_total: 315.391s +[progressive] Cycle 2/9 + CoMe calibration (35 layers): 0%| | 0/94 [00:0027layers, nine removals. GPU0 MKA / GPU1 CoMe on the existing retained +two-A100-SXM4-80GB instance62646539. No new rental or host restart. +**Do not return, destroy or stop the instance without a new explicit user +instruction**, even when experiments and backups finish. + +Session/SSH: 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 artifact root: /workspace/qwen3-mlp-fit-20261126. +Controlling local branch: codex/qwen3-mka-come-mlp-fit-20261126. +Existing external FiT engine: /workspace/external/come-attn-fit. +Model: Qwen/Qwen3-8B-Base@49e3418fbbbca6ecbdf9608b4d22e5a407081db4, +local /workspace/models/qwen3-base-49e3418. Exact snapshot prefetched; +both GPUs idle before this new preparation. Existing Llama MKA evaluation +is complete; its batch1 weight upload continues independently on CPU/network. + +Both methods use native dynamic pair selection and initialization, reselect +after each stage's FiT, with no imposed ABPrune span, Fisher, Transport, +rho, LoRA, head permutation, or extra donor model. Fit only selected merged +block's three MLP projections: gate/up/down. Qwen's block has11weights, +including Q/K norms. Freeze the four initialized attention projections and +all four initialized norms (eight frozen parameter tensors). + +- Corrected local MKA variant: native frozen100x512 SlimPajama windows, + seed0, mean-pooled block outputs before final norm; sigma8/alpha.5/dim2/ + MIneighbors5/entropyneighbors50/beta1. Maximum adjacent NPIB, deeper + exact ties, recompute after each merge/FiT. Initialize seven projections + by FP32 lerp then model-dtype conversion; retain all four left-anchor norms. + This is the project's corrected local variant, not an exact paper reproduction. +- Native CoMe: SlimPajama256 source rows ->94packed2048windows, + seed10/buffer10000, scoringbatch1, angular_last, power1, minimumretention0, + repeat allowed. **Do not substitute Llama's minimumretention.97.** + Q/K norms follow native retention-weighted merge, two residual RMSNorms + follow native unweighted pair mean; freeze all four after initialization. + +MKA original token cache: HF LJYAI/paper_revision at +15b4ad6fcdf6a42344a86296b4dafa662d08f282, +runs/vast-paper_revision-mka-all-small-5090x8-ca-54482709/ +20261006-mka-small-13checkpoints/qwen3_base_remove9/model/calibration_ids.pt. +File448967bytes/SHA256aa8b546874da296d54ef69d73faffc83802deb089c0209cc55593e32ab50489b; +input SHA2564f47034e02892bf464998e540be8bd7bc0718f83f6bc9d354c887cc2874cada9; +vocabulary SHA256c605f1c0a80a9501fca9782b942a7f01474e3f37b1c59e3efea82da0e2f20376. +CoMe historical token cache was not saved. Reconstruct with pinned legacy +datasets3.1.0 / Transformers4.52.1, preserve exact new tokens/doc hashes, +compare native behavior where practical, and qualify any historical numerical +differences instead of claiming an immutable original token-cache match. + +FiT recipe matches existing Qwen Base ABPrune controls: pinned SlimPajama +b5f90f419b7489cdba26fdbc8c022fcb5562f968; seed42;512x1024,524288tokens/stage; +batch1,accumulation1,one epoch/stage,512updates/stage,LR1e-4,WD0,clip1; +hiddenMSE1/MLPMSE1/attentionMSE0/KL.02/temp4,previous-cycle teacher, +BF16 model plus zero-initialized additive FP32 U. Expected FiT input SHA256 +5d9d4cc2f81d8712b932806c0c2b2992dce9bd3e6c7a143f1f670649b8bfe693; +mask SHA256c8e7f8e30cd532b82e6af4b98d596bc7106f29f9fb2b398b44355e624898a30d. +Check both hashes before full training. Native selection data remains separate. + +Before full9cycles, validate Qwen native11weight initialization, frozen8, +three nonzero MLP U gradients/updates, unchanged teacher, and a real +64sequence/batch1 one-cycle smoke per method. Preserve Llama regression tests. +Reuse strict offline131benchmark assets under /workspace/come-attn-fit-20261126. +Final metrics: WikiText2 packed2048 PPL, full Bench12, MMLU and CMMLU separately. +Back up only final reconstructible stage09 compact states, code, audits and +raw results. No raw token caches or private pooled features are published. + +HF output: LJYAI/paper_revision/runs/ +vast-paper_revision-come-attn-fit-20261126-62646539/ +20261126-qwen3-base-mka-come-mlp-fit/. +Only the local controller pushes GitHub; code/notes move by SSH Git bundles. +Read-only five-minute monitoring must never change the instance state. + +Status: model downloaded and native input/calibration preparation in progress; +no new Qwen accuracy result exists yet. Verified historical no-FiT references +and fitting hashes are recorded in +results/qwen3_base_mka_come_mlp_fit_20261126/native_references.json. + + +## Validated launch, 2026-11-26 18:55:45 KST + +Source74185322c, production controllerPID13362, GPU0MKA/GPU1CoMe, +eachbatch1/9cycles. Actual full512x1024 FiT input/mask hashes in BOTHarms +match existing Qwen Base controls exactly before fitting began. All131offline +benchmark caches validated. Two real64sequence probes passed MLP3/attention0/ +other0, three nonzero U gradients and updates, and all8frozen attention/norm +expected-before-after hashes. Actualteacher/student forward shape1x1024. +Smoke FiT secondsMKA36.1529198/CoMe36.1404278; peak reserved43.16GB/40.71GB. +QwenQKnorm/teacher/native initializer algebra and LlamaMLP3/attention7/full9 +regressions passed; no host restart or rental. + +MKA immutable input100x512 hash4f470... restored exactly. CoMe legacy +preparation initially ran offline and fell back to a different cached dataset +reader, yielding106windows; the94window guard rejected it before saving or +training. Repeated only preparation with the same pinned legacy loader online; +existingMKA tensors were revalidated without overwrite. Correct94window CoMe +input SHA2560e958e9f08255ee1a4bb4f029d8e7af94c8a26c6b31366a9223fb7629ebf53e3, +maskSHA25639024bd69b2936f651f76827b6e0b1118b908ff87f1aa3df24f097246fd42dfa. +No wrong106window checkpoint exists or was used. + +Native first-stage checks: CoMe pair31/32, score0.11533127194072337, +ratios[0.49274789168296595,0.5072521083170339], retained attention3/5 and +MLP6054/6234, all exactly equal the historical first stage. Historical CoMe +token cache was not saved: this verifies reconstructed recipe/first behavior, +not an immutable historical token hash or full9stage replay. MKA pair13/14 +matches historical; observedlambda0.6225208206034097 versus0.6225201943477188, +NPIB2.0866975139397255 versus2.104302442487761. Preserve numerical differences; +do not force historical coefficients or claim byte-identical full replay. + +Exact command: +```bash +python scripts/launch_qwen_mlp_fit_comparison.py --project /workspace/paper_revision/sessions/vast-paper_revision-come-attn-fit-20261126-62646539 --external /workspace/external/come-attn-fit --root /workspace/qwen3-mlp-fit-20261126 --model /workspace/models/qwen3-base-49e3418 --session vast-paper_revision-come-attn-fit-20261126-62646539 --mka-selection /workspace/qwen3-mlp-fit-20261126/calibration/mka/selection.pt --mka-selection-metadata /workspace/qwen3-mlp-fit-20261126/calibration/mka/selection.json --mka-selection-hash 4f47034e02892bf464998e540be8bd7bc0718f83f6bc9d354c887cc2874cada9 --come-selection /workspace/qwen3-mlp-fit-20261126/calibration/come/selection.pt --come-selection-metadata /workspace/qwen3-mlp-fit-20261126/calibration/come/selection.json --come-selection-hash 0e958e9f08255ee1a4bb4f029d8e7af94c8a26c6b31366a9223fb7629ebf53e3 --eval-root /workspace/come-attn-fit-20261126 +``` +Five-minute read-only monitor is active. Both arms automatically advance to +PPL/full14task evaluation/final verified model backup. Bench12 excludesMMLU/ +CMMLU, which remain separate. **Retain instance62646539 after completion.** + +## Training checkpoint 2026-11-26T10:20:10Z + +Completed stages MKA4/9, CoMe4/9. Every completed audit confirms MLP3/attention0/other0, nonzero MLP updates and exact expected/before/after hashes for eight frozen attention/norm tensors. Both fullFiT512token/mask hashes remain matched. No failure, resampling or training/host restart. No final accuracy available. Instance retained running. + +## Both9stage pruning/FiT runs completed + +- mka: completed2026-11-26T10:38:54Z, pruning+FiT wall2588.620101213455s, WikiText2 PPL15.782106613626244/NLL2.7588768054699075, 145sequences/296815predictedtokens; final compact retains5fitted block states. +- come: completed2026-11-26T10:41:13Z, pruning+FiT wall2727.9755203723907s, WikiText2 PPL19.337434332734354/NLL2.9620428200425772, 145sequences/296815predictedtokens; final compact retains6fitted block states. + +Both final models contain27layers after9removals from36. All18audits passed MLP3/attention0/other0, nonzeroUupdates and8exact frozen attention/norm hashes. Both actual512FiTinput/mask hashes match historicalQwenABcontrols. No training or host restart. Full14task evaluations are active ontheirassignedGPUs; no final accuracy claim yet. Instance explicitly retained. diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/selection_provenance.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/selection_provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..c293f440652d52f348ab01045ef194c1d1a601e0 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/selection_provenance.json @@ -0,0 +1,926 @@ +{ + "mka": { + "input_ids_sha256": "4f47034e02892bf464998e540be8bd7bc0718f83f6bc9d354c887cc2874cada9", + "attention_mask_sha256": "ffe472b00e055e867ecb0129008048236f4d8f7a3730ec6fecda87fc1666dd88", + "sequences": 100, + "sequence_lengths": [ + 512 + ], + "source": "/workspace/qwen3-mlp-fit-20261126/calibration/mka/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": "4f47034e02892bf464998e540be8bd7bc0718f83f6bc9d354c887cc2874cada9", + "records": [ + { + "stream_row": 7, + "document_sha256": "ac8f5a3f6a1b650d5f5c904320601f606c1c72b1f223d3e1769098dd14676f53", + "document_tokens": 872, + "window_start": 197 + }, + { + "stream_row": 9, + "document_sha256": "e7ebf1f41fda85fc9fe3abc20ab9b3230e7778740d71ebe744343a36118314aa", + "document_tokens": 1150, + "window_start": 430 + }, + { + "stream_row": 10, + "document_sha256": "f3a470d344261f8c757c32d506c3b5067df8fc3a91bdd92fd755526e0c1c0549", + "document_tokens": 802, + "window_start": 20 + }, + { + "stream_row": 14, + "document_sha256": "a874cf9d27742fa7a7eb51e37ac45a3246595e9984edfbadc144c8542f37cd98", + "document_tokens": 818, + "window_start": 132 + }, + { + "stream_row": 15, + "document_sha256": "39bf4b2abf97638a52ea61d8ca420e1219d0db31e682a52f5ecfb82670c8e300", + "document_tokens": 907, + "window_start": 261 + }, + { + "stream_row": 16, + "document_sha256": "9b453670291bfd6f9cced57fc1094c77caa5ca6cc370540bb242db5847c54e0d", + "document_tokens": 1529, + "window_start": 497 + }, + { + "stream_row": 18, + "document_sha256": "e085745d2b085e958c6fb0a061167c07b4a105acf2984df9000074e61a8fe431", + "document_tokens": 4747, + "window_start": 3317 + }, + { + "stream_row": 19, + "document_sha256": "61846a47c7366bc70861e4de60ef663305ecaed30363491fb755da985169bf6b", + "document_tokens": 781, + "window_start": 155 + }, + { + "stream_row": 27, + "document_sha256": "5f5f5dbea899373c49f9f7f99bec079aedb0884c7a872ec869b23d321d0b6998", + "document_tokens": 575, + "window_start": 61 + }, + { + "stream_row": 28, + "document_sha256": "ba37621eb085caf6a3d3acc584a3637ad5515ec9a9c2f186eb354fe408928600", + "document_tokens": 1883, + "window_start": 733 + }, + { + "stream_row": 29, + "document_sha256": "28e404de6977048dff9e6fdbd26104891c16e71fb0bb99cba2e22a322ef1fe1f", + "document_tokens": 1073, + "window_start": 223 + }, + { + "stream_row": 31, + "document_sha256": "9c87a61d98482a65d867adeffa221f43f82d0ccf370f36ffe545d9e7a5426e08", + "document_tokens": 932, + "window_start": 258 + }, + { + "stream_row": 32, + "document_sha256": "38caae31be8b4ae1c73a20badeead6019f84ab99e0604775ab555d1bc04bc548", + "document_tokens": 918, + "window_start": 71 + }, + { + "stream_row": 35, + "document_sha256": "17dc044eac594c2ea35e3bbb11f53b9895af962909ba2c9c29dab2a3cc90b50d", + "document_tokens": 1412, + "window_start": 288 + }, + { + "stream_row": 36, + "document_sha256": "31dd14a43e53f072ebc19f903b8a3ce00240c11a2f18cd3d37ecb3e1c2fb6f4d", + "document_tokens": 602, + "window_start": 17 + }, + { + "stream_row": 37, + "document_sha256": "7687dcdfd2228b3a40ee05588e34fe8ae32847c9f4352ba145df66ca1651f727", + "document_tokens": 8963, + "window_start": 1553 + }, + { + "stream_row": 38, + "document_sha256": "bafd2c425da5306cdcd1f6f0f98c72c056bf9f85d1ccc4041250e4d34a6c0f34", + "document_tokens": 2494, + "window_start": 1266 + }, + { + "stream_row": 39, + "document_sha256": "a3b57c263d0241a65fd9801fabfa397a638b08ba5cb2404f7a012694c2941600", + "document_tokens": 530, + "window_start": 8 + }, + { + "stream_row": 41, + "document_sha256": "f3b1c751a067c70411a4505410a624ba5dea1656388f71b515ae7d3e106f41ba", + "document_tokens": 679, + "window_start": 136 + }, + { + "stream_row": 42, + "document_sha256": "7f228cc247a0e4b8419f878cd733f42f02b64c2fa579d2ed9875086168966093", + "document_tokens": 821, + "window_start": 308 + }, + { + "stream_row": 46, + "document_sha256": "de284cb2c03376538e0d8f5ef5fad5067290a3adb5c367d5ace76eda4ea1b1a0", + "document_tokens": 6342, + "window_start": 1203 + }, + { + "stream_row": 48, + "document_sha256": "d24468963a0957a4593f82d06244cc20984efd278dc1a955c9a004e1c0babe28", + "document_tokens": 675, + "window_start": 79 + }, + { + "stream_row": 51, + "document_sha256": "3f216a2a101412af8ddf477aee2e3817c8066dd800443a5f165c00fcd33c45d6", + "document_tokens": 1429, + "window_start": 101 + }, + { + "stream_row": 54, + "document_sha256": "4bea3ec348c6d9f45244f54914e9213e205e6af866955981d97ad96115ad786e", + "document_tokens": 794, + "window_start": 37 + }, + { + "stream_row": 57, + "document_sha256": "45f2e7f10bd217f4d05d713fc1a35b615dc2bc3fc8dc3c5cddb13444aa65c42e", + "document_tokens": 686, + "window_start": 84 + }, + { + "stream_row": 59, + "document_sha256": "99f31522002ab42befbe9f27c8f0fd800c737ee6a8fc5cdb92f605e64e21786e", + "document_tokens": 933, + "window_start": 241 + }, + { + "stream_row": 65, + "document_sha256": "dba1f1e2cf2f539e439afcb1887d85c1471066b6369c2e4f498a69a0e22e5f33", + "document_tokens": 639, + "window_start": 25 + }, + { + "stream_row": 68, + "document_sha256": "db7f48a6a54726f9d26c63feeabcb408811fdab46f783c71c3a119a189ce4eaa", + "document_tokens": 530, + "window_start": 11 + }, + { + "stream_row": 69, + "document_sha256": "964a9cdee6ae7edae357b5dd6e78bee0c7191015b9d2c264b0848997991bbbda", + "document_tokens": 2962, + "window_start": 1778 + }, + { + "stream_row": 72, + "document_sha256": "3363525f1892fa4c5861396ac3ff1f50cb0467ac9f62535661175f782126f2af", + "document_tokens": 1162, + "window_start": 323 + }, + { + "stream_row": 73, + "document_sha256": "6cee5651cfd4f572d4947575edf5b1c46d9eede1109803facc4d071ad5f69dd6", + "document_tokens": 789, + "window_start": 104 + }, + { + "stream_row": 75, + "document_sha256": "0742ae31108e5d9b935d774d7f279ccf8868598d730b6bbaba5d45bb645e22ed", + "document_tokens": 802, + "window_start": 282 + }, + { + "stream_row": 78, + "document_sha256": "61e6a936c26215c9299723c8bf7c153839a83ddada61eb920efc4f80158f7649", + "document_tokens": 1278, + "window_start": 488 + }, + { + "stream_row": 79, + "document_sha256": "d8782bc5106f420942824a2f496be7a8c572b4724a4b50c3136426cb27729739", + "document_tokens": 639, + "window_start": 113 + }, + { + "stream_row": 80, + "document_sha256": "a834ec2f3e3d86c0a1273ffc1e36ba4f52170c41f55e626b4523fe34fda2dded", + "document_tokens": 544, + "window_start": 16 + }, + { + "stream_row": 81, + "document_sha256": "787a6c5f80a4241a55126c45bd7eca61273e0b218d02f81af8d853e85f2ac29e", + "document_tokens": 1052, + "window_start": 63 + }, + { + "stream_row": 82, + "document_sha256": "3967691ef9bd4974968f5918fbc65346db671d66bdcc4a18c1bfbba3d7eb37d5", + "document_tokens": 1020, + "window_start": 412 + }, + { + "stream_row": 83, + "document_sha256": "38b10f5054055c4c0c57fee6b480738a3492b1350622fd732d0790dcc6808e12", + "document_tokens": 543, + "window_start": 0 + }, + { + "stream_row": 84, + "document_sha256": "45a76e3f846e93b7835fbfe6221e6a9e21c28aaa1c94d0ca78117ac522deeafc", + "document_tokens": 2918, + "window_start": 382 + }, + { + "stream_row": 86, + "document_sha256": "2ed365b0740b4c5f9baad5437d467ebe69eb824d0c6a8edc56e2a9e970317e1d", + "document_tokens": 1808, + "window_start": 816 + }, + { + "stream_row": 87, + "document_sha256": "4bdf800f977234dea28671a9d23768fa30f66532f1600761e64ee90c86fd53a9", + "document_tokens": 1544, + "window_start": 2 + }, + { + "stream_row": 92, + "document_sha256": "eb93106c54737f50d673c29edf656f5178af3dbf413eb79dfa3f61c6f710a069", + "document_tokens": 1186, + "window_start": 626 + }, + { + "stream_row": 93, + "document_sha256": "3120d36379b208a8e4eaa02e3fd5015e9d958b7ed2ae6dba0221d3e88c2c7d7f", + "document_tokens": 518, + "window_start": 3 + }, + { + "stream_row": 95, + "document_sha256": "3e5db6ad1c2841d479024cd9b2a8b38ea93d3830915ab63a8436ffee00f139e0", + "document_tokens": 978, + "window_start": 423 + }, + { + "stream_row": 96, + "document_sha256": "221cccbf757dfeb0e3d0cc40110f75bbbc780ec0b9d206d3c1e1ca3813153bad", + "document_tokens": 732, + "window_start": 85 + }, + { + "stream_row": 99, + "document_sha256": "0c1ca5bf83aad68526b3d13a9e434a47bc4bf27e6b87a3bd5d082c3aee5a6c62", + "document_tokens": 910, + "window_start": 124 + }, + { + "stream_row": 100, + "document_sha256": "1bbc555069faa98706d13743ae017f19af8fc33043d8f4e62f1d855cf7bc79b7", + "document_tokens": 3308, + "window_start": 1332 + }, + { + "stream_row": 101, + "document_sha256": "83c257e5bc7f875f867c7fecb5e009bb02ef07755dce732253204347b6d34279", + "document_tokens": 1135, + "window_start": 64 + }, + { + "stream_row": 104, + "document_sha256": "18bae193a83cd9726ac9acf57ba8bdac90ea88d7d9bb6c3828cd9a806eb454cc", + "document_tokens": 1680, + "window_start": 391 + }, + { + "stream_row": 107, + "document_sha256": "8f76fb28b427752f0c9332c80680a860dee9d173d44cede21dfced6b4779e62d", + "document_tokens": 516, + "window_start": 4 + }, + { + "stream_row": 109, + "document_sha256": "c18430c70e629666b90bb2ef5bdd4ace00e2ed3b7ea0d8435e449ba56a25a373", + "document_tokens": 743, + "window_start": 56 + }, + { + "stream_row": 111, + "document_sha256": "200ec00054fefaae120ef97dbfbe549a22f4fbaa61ffdc968629acc3e3be8f24", + "document_tokens": 551, + "window_start": 15 + }, + { + "stream_row": 112, + "document_sha256": "761ec6fa54a210354cf704d0b57856957bfce1fb4a773121bc86c1c4b96d8b5b", + "document_tokens": 1578, + "window_start": 291 + }, + { + "stream_row": 114, + "document_sha256": "a7bec15db4d041cb3f705633b46a3563ccd59dd8f483ca3da19d52f2b812912e", + "document_tokens": 2788, + "window_start": 2224 + }, + { + "stream_row": 116, + "document_sha256": "dd0b8b22dada2f6d54f8cec7c4f7cec0626601e4102d4ab228c230fada5c1a8b", + "document_tokens": 1553, + "window_start": 917 + }, + { + "stream_row": 117, + "document_sha256": "b3f79c4a4087cc2a02ed5932cf7065e0d5e05430ff423ad20226695f20f463e7", + "document_tokens": 1167, + "window_start": 93 + }, + { + "stream_row": 122, + "document_sha256": "e254a6211037dd8ddc5b0cf1e0af8c1714f59f3faf6d55a5a4e670e4d53af90d", + "document_tokens": 1109, + "window_start": 82 + }, + { + "stream_row": 123, + "document_sha256": "cc1f8ed0ef69b4ec8fcd16d3bd51627f650b2350fb22a9bb49e6c4ff76589e44", + "document_tokens": 1014, + "window_start": 163 + }, + { + "stream_row": 133, + "document_sha256": "c2d6e5e101653b8924ec02b7c8cd08df0fb7364ce23aac8279a537d0df9c30c3", + "document_tokens": 986, + "window_start": 448 + }, + { + "stream_row": 134, + "document_sha256": "fe588286dc9e9f94c84e85bed56b884593ab4e95006f1df1b80156e7896119b4", + "document_tokens": 4828, + "window_start": 4161 + }, + { + "stream_row": 136, + "document_sha256": "ef5743d7bf8b263b2b779577ee4868a1eba7029b3d8cb8e88c9dbc8309f1102f", + "document_tokens": 633, + "window_start": 119 + }, + { + "stream_row": 138, + "document_sha256": "8c204bb1fad0ecbc9af02f979558112a36919e9c445067473a2a80b905dd826b", + "document_tokens": 580, + "window_start": 62 + }, + { + "stream_row": 142, + "document_sha256": "d2300adfc617626fd5c6002c103a9e66fe1b97a06a6eac3bc77e52586a1ffc7c", + "document_tokens": 1001, + "window_start": 55 + }, + { + "stream_row": 143, + "document_sha256": "50fb87425312b4c122ff4fba823fe633affb9d71079df249d972be02aa224595", + "document_tokens": 1046, + "window_start": 308 + }, + { + "stream_row": 145, + "document_sha256": "09ff974ba31eb969eec8386b34b141b57dbe1734534440ac0ba2abb863a4653c", + "document_tokens": 1026, + "window_start": 298 + }, + { + "stream_row": 147, + "document_sha256": "810c56f4f2963a75381eb74236c11b72c5af6a450f0c822df24c5b28e712d0ed", + "document_tokens": 1501, + "window_start": 723 + }, + { + "stream_row": 148, + "document_sha256": "fe6318e204bf58d9b05ee4b791790aad966a51589a33d45859f63c1da11d5289", + "document_tokens": 574, + "window_start": 7 + }, + { + "stream_row": 149, + "document_sha256": "6b6881ed8c9cff458b1713575025d93557c7a848eeaaaaefd214c897c0b832ab", + "document_tokens": 1025, + "window_start": 340 + }, + { + "stream_row": 152, + "document_sha256": "47a668a81190f31ddf4d032bd43ae313351da66c7f8f702704a2baa9c46e4ad4", + "document_tokens": 531, + "window_start": 17 + }, + { + "stream_row": 154, + "document_sha256": "710b8937ad9077d5adba175c809252ac4baa7ca3bd1cc4226974577a4eacc5db", + "document_tokens": 849, + "window_start": 104 + }, + { + "stream_row": 155, + "document_sha256": "d9b32336230adab9d6152902ce065f56a32258c16984905acea5d8f870152efd", + "document_tokens": 554, + "window_start": 38 + }, + { + "stream_row": 156, + "document_sha256": "f53168b17d15cd4bb8919f334b5d9506207fb6d8a8a7580517e67399208c78be", + "document_tokens": 2139, + "window_start": 1120 + }, + { + "stream_row": 161, + "document_sha256": "b9cbc598151fe111acfd40ed8f2f2ec1be56ed64d74676b46b75d2c6d758269b", + "document_tokens": 859, + "window_start": 300 + }, + { + "stream_row": 162, + "document_sha256": "4b1d0ea5f0c919705d9738680a8ac4b4e4838f5cc6d456180fd091e66d152ec6", + "document_tokens": 863, + "window_start": 147 + }, + { + "stream_row": 164, + "document_sha256": "92825ee82231a7f7fa657e099045a3358d50318a0f3be57a80c406479c7ed718", + "document_tokens": 541, + "window_start": 14 + }, + { + "stream_row": 166, + "document_sha256": "763f108003221c14e9453aa571fa06e781de5ed014966d885a34070591a3f95e", + "document_tokens": 562, + "window_start": 5 + }, + { + "stream_row": 167, + "document_sha256": "41a85298c65411bd707b1334c5640ce1baa45351bf61dadc8e48c367196602ff", + "document_tokens": 515, + "window_start": 3 + }, + { + "stream_row": 169, + "document_sha256": "f005fdb48a62cd9721e7bf75e3d2063e6b1b94fa91b2eb98d066f4314c3584dc", + "document_tokens": 1051, + "window_start": 324 + }, + { + "stream_row": 170, + "document_sha256": "25fbbd49d00fc724ce7aa37c66dc7049b3623232e2aca591cfa1d6738fc5eb7a", + "document_tokens": 3318, + "window_start": 2357 + }, + { + "stream_row": 174, + "document_sha256": "350d16bb5744818cf0b571daad84f28952520db6ba912332facfd386e4b55797", + "document_tokens": 605, + "window_start": 30 + }, + { + "stream_row": 175, + "document_sha256": "1643b3346064d62f69e623ec6756854c42af79f001f6361986e8b6a680288934", + "document_tokens": 526, + "window_start": 4 + }, + { + "stream_row": 180, + "document_sha256": "76a7817b5df2ba303bd9f267b17f13d536cd70486cc2749a2d2ea3c047ef23d7", + "document_tokens": 1476, + "window_start": 188 + }, + { + "stream_row": 183, + "document_sha256": "5eea333eff35ef9159959130f6324bc4fc48c79653eef0ea2e7ae327c4953e2d", + "document_tokens": 669, + "window_start": 48 + }, + { + "stream_row": 184, + "document_sha256": "f70e79851a29ebaa170c88a406a1ae66b54f9fdd908240e66422a98236acfee0", + "document_tokens": 685, + "window_start": 47 + }, + { + "stream_row": 185, + "document_sha256": "894ee1d6c5c54fc87fd055f03db0e70b0e3ea992739a224559bca00352990522", + "document_tokens": 549, + "window_start": 2 + }, + { + "stream_row": 186, + "document_sha256": "ef035a5d5ac9731a04a871afe15ca61c46494558183c325148ed61de861eecca", + "document_tokens": 1518, + "window_start": 627 + }, + { + "stream_row": 194, + "document_sha256": "df983f275b9d6849f99e17382a1155ce8cdeb1373cf1ada1812153abc4f37513", + "document_tokens": 3087, + "window_start": 1065 + }, + { + "stream_row": 195, + "document_sha256": "482a63cc59d885c8e12220a545622adb1e220fe22aad3fbff061f35332183802", + "document_tokens": 869, + "window_start": 243 + }, + { + "stream_row": 197, + "document_sha256": "828d8df579d793b76867d769eec0786a277f0f0ba7b89d23c3d908b64a72fd6c", + "document_tokens": 6622, + "window_start": 565 + }, + { + "stream_row": 198, + "document_sha256": "201105829879f989134e803f9ab7f1c7ef420ff6162005c95425a8e948dfec1a", + "document_tokens": 893, + "window_start": 45 + }, + { + "stream_row": 199, + "document_sha256": "123a4795b17fbaed2dde8918120bac5670f328b944863436f2ff29baf9114e44", + "document_tokens": 732, + "window_start": 173 + }, + { + "stream_row": 201, + "document_sha256": "a60c9991d65750a9de7fafca0720902a94359d160d48a35fc6f0e647d35ffce7", + "document_tokens": 748, + "window_start": 193 + }, + { + "stream_row": 203, + "document_sha256": "eebaa4e728a24c68cc584b4c82dd5cd8b8781e7dc6c2410ba8b0dd6c6a7e6ca8", + "document_tokens": 1081, + "window_start": 133 + }, + { + "stream_row": 211, + "document_sha256": "ee8a9c62150dd3921f428e93cb8fae6c244116b170c5acdb0c0e518305af61d3", + "document_tokens": 800, + "window_start": 76 + }, + { + "stream_row": 212, + "document_sha256": "2eda120c7738f2619b9101f61d7f72b3ec913075c0d96a854a9bf6b8b19bd820", + "document_tokens": 548, + "window_start": 2 + }, + { + "stream_row": 216, + "document_sha256": "995e06891a0dafef53cd75bdc365612ed91e9274cd6129576bb184f83b8a6c62", + "document_tokens": 886, + "window_start": 41 + }, + { + "stream_row": 217, + "document_sha256": "c5d55d18293389ea70f9528071a82fbdaf4890e1fea8a5901a98d7d4ab109ce2", + "document_tokens": 638, + "window_start": 114 + }, + { + "stream_row": 221, + "document_sha256": "5e7b9074e4d8ed846a796c32dcb97b509de1493492bef5bd626510460ce986d1", + "document_tokens": 791, + "window_start": 276 + }, + { + "stream_row": 228, + "document_sha256": "83718c91cb73096a48a712c05b0cf2e9e263e9969ebffb76cfcc92fafc812575", + "document_tokens": 995, + "window_start": 349 + }, + { + "stream_row": 230, + "document_sha256": "fbf88a5484bddd53b1096cda09692af34716716daad60a37071985230751123b", + "document_tokens": 522, + "window_start": 6 + } + ], + "tokenizer": "Qwen/Qwen3-8B-Base", + "tokenizer_revision": "49e3418fbbbca6ecbdf9608b4d22e5a407081db4", + "tokenizer_vocab_sha256": "c605f1c0a80a9501fca9782b942a7f01474e3f37b1c59e3efea82da0e2f20376", + "method": "MKA", + "resampled": false, + "source_file_sha256": "aa8b546874da296d54ef69d73faffc83802deb089c0209cc55593e32ab50489b", + "source_revision": "15b4ad6fcdf6a42344a86296b4dafa662d08f282", + "source_path": "runs/vast-paper_revision-mka-all-small-5090x8-ca-54482709/20261006-mka-small-13checkpoints/qwen3_base_remove9/model/calibration_ids.pt", + "attention_mask_sha256": "ffe472b00e055e867ecb0129008048236f4d8f7a3730ec6fecda87fc1666dd88", + "selection_file_sha256": "f3a8c20e9f030320e2d81ce4dd4f6b6a37007420fc876d93621196841eaba714" + }, + "independent_of_fit_loader": true + }, + "come": { + "input_ids_sha256": "0e958e9f08255ee1a4bb4f029d8e7af94c8a26c6b31366a9223fb7629ebf53e3", + "attention_mask_sha256": "39024bd69b2936f651f76827b6e0b1118b908ff87f1aa3df24f097246fd42dfa", + "sequences": 94, + "sequence_lengths": [ + 2048 + ], + "source": "/workspace/qwen3-mlp-fit-20261126/calibration/come/selection.pt", + "native_metadata": { + "method": "CoMe", + "dataset": "DKYoon/SlimPajama-6B", + "revision": "b5f90f419b7489cdba26fdbc8c022fcb5562f968", + "source_rows": 256, + "packed_windows": 94, + "sequence_length": 2048, + "seed": 10, + "shuffle_buffer": 10000, + "minimum_retention": 0, + "power": 1, + "allow_repeat": true, + "tokenizer_revision": "49e3418fbbbca6ecbdf9608b4d22e5a407081db4", + "tokenizer_vocab_sha256": "c605f1c0a80a9501fca9782b942a7f01474e3f37b1c59e3efea82da0e2f20376", + "document_sha256": [ + "66a91920b0bae173f1358bed835f82ab2eb1c7ef88770f7e491f5dec5f909ece", + "4c9c11fe028c42302635e14b84fe7b7cacc5e3e117403e4cb82835fbe59f52c9", + "cf15a05f1cf742435bd5c9ed6912f15186e24af0320482a81ef3b4d54bbbf1a6", + "35eb16b2a6850fa9d5d36c68504e1ec5ab273bcc3c2ac3e3b8d8030c8fe58f90", + "ed774be40798d103a70a475bf2b1eebd92a8a7d268e25e666d55c838a517dcaa", + "63494fb3f8686df3c411d75cbd9088e389656573a12ab921aec96f39bc4b6b1c", + "cac4ff4bb05eaf6176dd1ad0de2f19e7599ec061b713b3bbf26d7baf376a17c9", + "429acbb01053919556788130e4e66e5078d6804757615e0fe5b6e1a6a8e93b12", + "ea5ef96735fcb6b0c1ddc2bd732199d7fe9ccb49105b308bd603860df886589c", + "aa70a871ed16bc60e5daa14f451b84187016104c90a54e9d2c9b4b03b3ec903f", + "2115deb147f8bd11bd4b9bba2ac1270805ec0231479a6a13b6c97cc779120eb4", + "369867e6f9bf92cf40877e14916c37c066874a5c105de6793a10027582e8967c", + "8e6ac295580e91402a7ad229cd829d7abc4c073d3978de10bb6228e4b169d112", + "29f613aac3d264e572db3d9236114b2cf62132dad11960499b524b48ded58390", + "0a6d75079971ad81caf667df89ec626069d8efd3fe1807eb7a28f33f8eef351f", + "cb8bd0a5e2215486758a23515cf403ce0522e9c22d002d5e9b4e32e65c2cad66", + "5b9270fbfbe06ddb476d638000647b87f932bfaaa4f35770e3990e3171b03ad2", + "805e3fe263674a8cf6661a34240d63495eb594f1b0d9111f281aa547a9cf3e6d", + "0c03d6531e0bc4741e9a98f6e51c3863b3b42b1cbe2d403ddf783e3d7724ac60", + "8a16d3ee0b1288280c8a75a148be3b71d32f79fec9035005e68225de2bfad699", + "c3beb61844d22bab8b0a73d6ee10cb66acbc1525b088e33f893bf00f82ae2917", + "745230ca762fbedb9b35581dbee45a3af689c4f287fe5def329da2a971463c70", + "82f4ea628c86ffe8413a95bd6b88867fa3a9a672251666b8c4fad1904e6c03f4", + "193898127932eb91758f6eba683d46a9761da7af2a1b8f5f290aa191c034948b", + "84692c686286c22a54cfc4489c73b4c0d7c3154a2f68edaea2571fffcaa3527a", + "fd9770c7ae0238064b2d0c8cc4a3fa374cb9a1647fc01f09f9901a9023ff3a0c", + "941c550d574525a320b38708f7d4e5d1b59da735f68035537734cd7c3816178c", + "430f01667a3307ab921170ae798c031f822000a89535f528e7391ecd6e75baa4", + "b2e23f37d9e467c6ff33b08f50adf8bb4d0b5d050854e62ef80fc76fc3f6ccc0", + "435aa6636a1627d9fb61c8eb2cf4dbdb8b9360f64d8e6783f42a20a34810d882", + "0806d9f44fb259daf66c553fd49f532e4f887389dc5457decf7a46c934bc1179", + "43793c6d1a50dafc1cc12426b603d039a2f7922c5eeae85de7ed968177daa03f", + "02563c0890fcdb00f1b9650cd2a4298c8b1a2df974b7a8f50707af20efdaa5f3", + "1f7db3122ffff8d25f096baee2e840a07257ca1366cbda8dfe4d9721eddf5ccf", + "a26cd59526989d8a50d84b36e32d4ffc8757c6f85fcdc035b0e3d28b6a5982ee", + "abba750ced6a10ffb3402fb4532d4d49d1fc40ebb651a4d1eb7d4aab649e054c", + "64f0f72630ed850de36cd72e0f0857cda386e4ad2f0596adad0e996552d2cafc", + "1244eadd69d352d9d7ee804183d96b9c7f5a0b6dd1499423e4084251fe101883", + "5859634d8d29c36cffaa8bcfa8f3f3681b09ebec1502004b46f258a5c0c8a377", + "4b4ae5d04befe92238cb418f2a2d01a9e41360c9c24f27c97519b8fb37637d6a", + "2f543caeed3881b8cb9f726b872449dbb605d0486ee0f2a2a5b4826a7be50e32", + "e11e21f053f885d88bc79a5687df36c05dcc4afe63afe3606376d3a99713823e", + "0779233542bd095965973358b33dd310dae3562549186f35c2112187517cde7e", + "ff1521a7cf6f1f12c6d27a149abd57105b4349ab16ee22cc12cc757a323fe12d", + "0da7c629d4c1ce0bc542a3548640f2f4327b8e878f792573479871a35497b9ee", + "4a3c6d8fe16d4397fc40fb45ac8b06633646de8aa058748e63d0f08c6f002f25", + "ee05caf3047a516a252a810c1e80552146a1ddf774e7f9c0b746a51b5bd114dc", + "3d8eaebf3fed26ca6133c3444f16b3b4136cf4675444521f7e3680284a379fc2", + "70c16e5620b029f04e1fadb7e4fc0089ad8ff1f311b4992808dff65a57447a04", + "6d0ca2fa8a309ddd4437244facfc2c47a0b329027192dbaf9c1c3ab3d83efb77", + "f3cf06736f94c125f0b089445dc1f409b0075ece5410ce617bedccaccbf9a37e", + "51b5aa6c0644873c668cf428e81e842b7a2435db3a73e7fce95c03f2535e90ea", + "96e6eb3fa0610ab20cfc9da6a28187550887746df0fca4dc66ec259bc35951ca", + "90e323e250b7bb09132d516ec3c83010d41f557f0c6ba2f5331c527d8d051969", + "68be832448768b16715c1b5b8ae9d4876c582de5444d4eb5ff78e97915e2ae06", + "da99fa04f2db61ed7f79035e949ad8f099281ecee5856cebd573948c446dfdbd", + "a6b912d91fdeb08f7e04b119b46bedfaff7eedaa246ce5e349375c9c1a5958a1", + "6a549596c1d618b6aab32ddeffa4ad4fc926d4a75734c68b97964226209a7c04", + "d267dc9304c61c151eb882df2d6197bb547dc7bdf8495c4ba72191c9df1ac5be", + "d0801e91edffa884ee243d624aabab5fe79293b1c6f3a1dbdf59267dae082ef3", + "4a92547059f9a23c2cce60f59a8014a34b18642a9a3a927ad7e0b128fa3e3d22", + "49abfe1f5b881185512836a2df3dc432948cd2b1e4942fbd6ab739a4ad998a31", + "ece8521f8504b92b58e6af4c7ce217ce2c5cb7a934674ae5ae088bdccb8b03f4", + "24d55b39b0ff2e198a1a76548e5d626bcbca7600bd3576e1a17ed912977fe18e", + "807ca4ede99622d8b3f93f42cc1a0fd9ad25af31e56709c4c92c26153cc6a28b", + "a0b8d9865b66ec7f96423b4d6496217ddd0d1ace83ac7324f81953876720df5f", + "4cf42715f72da1b4b39071f51abd4a75a365592ad29819ec04d98be263e88035", + "9fa1bb1cf021cececad7cf6bebecf3b717c73994d6a0604ae254aebf0418f67d", + "bd91fabd6617ba1c445cd781cbf6f9f444b43d2faf4717118365ad4ca2f9804a", + "3ff407a3e7cea8dd22efab0da886003954414bd462f03f97f621e616441c8967", + "c1449d9df51439e50eb6677d1911cedd718bbe68afb574d2a02ab0c9a576035f", + "14369aa7e3647026998f9abcae88aba267801fb6cdd601a2e13ce8b12b7c3788", + "be3c20828214add07c0495a728031a5d27d203242ffb09a52cb529d376b621a4", + "35099d0c3e379ebbf03fafa79c3010dd193cfe10e28b80150fb6cd95e87b11bb", + "4dfcfcb214f6fa56a0114f8d43f6b9b12244b787a1fd89750ded80e6c682421c", + "5af9c93ad231e304b5fe0ddbe7f3ff920fb4e81739268ba755b6c931cdaa6181", + "0c804eaa60c52d1f5d9b9ffa84ec2f953d77d01f5c1e4f374921ba20a3c80852", + "2ac74aa4a8d4b63e798422c9cdabd2ce9d2c2140e66ca77c35491f1e334b1914", + "e316d7fa935aea9eac600d354f653a0289e31b6502012b0ac8434978245b91f4", + "d819729e0f02792195f5acc48c341172bce59745e9abd344c8640f52fe0ee7e7", + "f60a7d6bb7ccd41639e9ae096f18b58afc55797db5bff80349218a85bb762781", + "1f63ca6a9c3f5538fc512d87612fbe8b95bbdf202c9b80f160005c1d4330ef8f", + "a6a9dd386d1208ab2dcd02c8bba7f56f6d939f0b68e2676dcf0f5bf1d8cc3b6c", + "4c69bbe29f4692ccdfae8d6802e91f24602ea5f7936f64b8c17a753b814067a8", + "10b5953e646398fb78c1f89aa337fc28f69dc37555d6a139010a069e8546ceb7", + "a5d816421b3e52258d78690334b2882c31615b357855f1d9aa6f89f14b7fa91a", + "a08a068a1c09ea4db7ad2afecfdf5b04539e499a76e373f6dd47fc9066606b83", + "07f60fd64b2de962ec6c25289e5f85803fc91a06cdd5c89a82389006b898919a", + "dd8ebdec3d29dffc90c556ab3726288577d1333c088abe1d652b36a9aa22e709", + "faa47b41b0e4b6dbe18471e9d41ce663567b5c66286a120fef59e12b0bb9f224", + "fb1ec17b78c0da4526804fa2616955e1775392154999417e356f46a8e5970834", + "586abd1adf4d20711e215e304829bd822b7b4bf301bccec6fb7fcc5e075725b2", + "65b3a5c9b827466e2a74339ad4c7af540c0c697c4db18f01b7884768753712da", + "e455d12c18bb33fcd3ec899367d0e44d9a2aaab226cf6c72cc479edff8d19342", + "7e547a15bd58ada10583b9e23a84592adc696e5a9889c5d326173a2a42d9912b", + "9df705b2288fd2c68196b6ce8969198f3b3fb4d87c2eb9a72aaae25517f2be63", + "ebcc89b0a26584cac258484a49f904caa1beda0b6393d1bbd522d78d63f60517", + "cb89fa3170d57fda3417e7fe9e8fac4b698041a693b0967452d8d04f85398054", + "509b8ffe130a8ecd960246b6f8f203cbc0093e2a2cc7d6f0a51bdcfce56e8d67", + "940b3565b35fe83a22f279f4fe651b7dab0ab0edd26d59184c3448d68d751dc1", + "bb4ecc9ac6e0cc795a1ac55f35e7f92ab0608f3bea3319e1da144d12e4ffd3c4", + "ed2e4a6389d0e34614ef1470904778130d5d9fe20088a91e34fb8ad36fce660a", + "2a31716f5b0d7419d3b0c8160e75b1ab50ac130dfe83f45c3316096c6a8b4a06", + "93cb973d4dd5f8ffdbaded93d36613023cf64e6937d1911711fbc2855171fff3", + "f3297e311d9e4f33487cb7cce9aab8efc41d09141eaf0683d8fa54a6c0cf1bb8", + "fa0649cb410deae374b31ca7ea4db1167ecf032b15ae65d2ccc82070d8e08855", + "085b78e95e96ab60df8159ff230bab7a0ff2db6a044d1fc7a4a3901fcce96bee", + "ea25f2759e061db2165faf5a9d4605efc5fe980220c234257bac1e1dc9f754fd", + "4284b99b3bac785acc6cfb4413abe7d34598121c252bcbd5dfb287c897bdc8aa", + "3f70854091b67df47f489a9426c61028675fba33c94b4dc8e0bf5afed5c5a2b8", + "4688fd74c5731cfba52278c257c1899113f728cf2d361644969e46eaaa0af16c", + "61e89708d1e4fb4de8725a40eaf10ead9836eaa95435c65c15fceb3f91ec206c", + "30c8dd505c1d4b929adfab32099b577ba9383c27f99c9830fdde8e80aa51d7b8", + "70b7d51569bfb9a76b919a38ae4cda335fffbf64bf9e3abef9f6639b7a1c535d", + "61a7b400bc1a856ff212d69f0adaef0eadc9497b25e7535cb61a202b87245ee3", + "22fec0d329f114939a06f604dc20a685c4a4a5856a16dd6470f4618eb869189c", + "6cf3913056607eb2424e9e1a4b8bdbdae02e40b651e172f5fab23e572e88770d", + "416814fe94960a520801b5ab8184e8d4c2e3844523f63405ef3cc11646419627", + "66bb46651cb36c32e19c32177fd5267a481279e65ec699402e1cdcff51a4a0c5", + "fa352ae86d29c9977709971cbfb70b9cf75544ceac4c1f5e963a0117f7153419", + "ea5b5ffbc5df76c0c31aee27a746b6d6c671680b2c821eb07e8229fda77216ed", + "d38d08d69b684028791fbda3843c4edaa1a2aa85f39b05b5686c814bec4be3d6", + "9fa107a7f46ead894a279a9ef8322b5d54d933d4824c83ba0f24cf9a6c8de0dd", + "1251d25a6ca6a862fa5552914b95327fd7179c5a63cf32f2821b35ad389fbbba", + "0cdc803ad1e2c35ac42abfcdfd9dfef8cf485aed13eb2d82003e9ed404d87af5", + "c474bbf1fda50e09a86f61ea2eb8371e1720e7491ae29f56b1abb4c01b2b1cf8", + "3cb8346c0f1935873f573c798467f2ddc68f0471cdf2b32c93c3a3aa01f5c218", + "56c8d1fd004f6c4cfe096ad3332a55e72e0e2f5a11fffb19ff11f742689c9cc2", + "02881633069e1972f3aa093cb554ddc3c5f75164e33f13f7c3e224c21ca831a6", + "6c47d17994d4c311386faf3456f85ec06d92ae6005011348815a93a15970ce3c", + "603a5607bf708a4ac47ee02bf19ba28255613b6f4248f5fa3fa4222babb67021", + "407280d3f62785a3a2dcbc295bf43dc7345d7c9f81114171aa3b01fe04863cbf", + "cf2c297fa17eb5916ccc3cc3e2231bf591f8474ee1686b5bab5482c12d9fa53b", + "4adb2cf6f6f7fb87f7fcbce96e125cfc3886b7524456c176e1f6e75368c5b32d", + "ac641bce538a8e97f735c57abb12942f60f9acacfa6f843fc66c4310c22b8c42", + "d8ca38f0adc98b99478d86db0d32d6e5f2473fcca18883edbb5f086fe15208ce", + "8378bcd4d425a6db520da702429a08a7357129bab2b2e3ca65da470e54411164", + "932ec6c95ffcb26d725f88896bae4a5a49766f8d729ba755362237085c90006f", + "9ce8e66983365fbfc046abb1f051a0a32795b45401b6267dd6f602b541dc7682", + "df77917c03e56bf4a4e46bca24c65fdc473b68dadd6ebca8364a118a1d31fcaf", + "69a276decf28ad05d1e0cc165bf70c9c0b6916c4dde45e1ec18f6a81fd61dae7", + "ceac9a0257e9a957c6a9acc4e7d370f07530ba75e21c433d07345a5363a8085e", + "878c683f2b6c6fa441f4f4a314f3276b2987459d37a96faa242876910bad23f8", + "f5aaa159a79d2ecef525ac22a4de90665e3c280bac3b322e0f331ad74ff84ab2", + "5b6ebb960516902dc18747bcc30fb2a6bd0df8e899f3c7bcf49917fd79d8d694", + "55c94e7ededaa187bea7ad5a42eec593383acfdb16dbd7e6f45946e2b64b9911", + "ca259c06db9ca1e908628a562b30033e4bbfa41d580236d903f9dfa03b9d7ef0", + "74962565a38c44d5bd632c2b441384c4b7eea986effa2c20da5e3149b969af27", + "1cec2a299253b91bc41a053f7df9abe402fda9580728f74e52c3601d431a7ebf", + "e29a1701b968a3820c91c138496e804438c3a88b40372a0649443b3088b8f6ee", + "3a1e90d4a5017eb8c1afe13d85a6e6dc40fe396b6ae57ba1c6ae4632713a71d7", + "aab32315869971146c5d43fafc898cb11968e7f3f4cee650a675f25c26525c64", + "a97768072ce3d498397e2cc34878587aaad509f8ef3e50bea1e0b6061b7e4ec1", + "553bdc67b399405d0f0fdca8cd902807af62b6f624be9a9729bc411d2e0c5055", + "371be56e24386e6a9b789b220a2662e1a8feb332bb3d6b630ecce82f797fd26c", + "6e549d5713541dfe3486e52134b5001d6413a9a79cfaaaf59021b079cc2cc513", + "0c1fb806b7773c0907cbc9bb46c9dbace41ea8ed9f3656e060ff5553aea4a58f", + "e31eb6c39580e67d503ea66dc44d5b31ad0bb347cd21b0a5bb711064be5f4751", + "c5622d646f66cf80bc71459138a8af9e94eda03b20f7956512bffb76c3cdeda9", + "b9e9086f05d7b6e804e88d67c9a9fc21ef3f510388c1b38f99502364b8850b4e", + "f9b0565b8ee0dd86b76fe5904b52be3d1e70827d7ffeda9d8fc436ed80e76e8b", + "885d686f77fe2f9b21386ef69ba7973c9256bd44409cefd5731af689e00bc27a", + "c88a9906a8ac533c4b9df24d8a29650b360effb58f2ddd0569e8ca2291ad48d6", + "f01b1828f3edbdcbad863ffb1d32db86641b30dee589bed46be0bfa29d402d7c", + "1c8568020fd353b9a291b3d039ce4b9fca71b42aad87f35f31f035e1dfba8590", + "899e3061ad0f08bd8c8666fc64d31cbbb55b449d0f4e990351ab218be073530c", + "0a2ae9eaee123136c78606aff373d7a224b0a8aeb6ed8c2b25cda24a26a08d32", + "627130a07f0c8965287b2bd3940938aea612041e30e86a21769fb52379838711", + "fd30b523998eb9b56e4e6d050c02a6c892bfdcde240b5f9faafb63f29e585a60", + "5877833a41220841e5485bda718aae780b73b79e3c476d21fdb15782a0c06f7a", + "88b3e5cb858a2d2f6c02a9ad690b7a12ed5936defe819a7d1279c4c38a02c23a", + "b69b05d71ab9f67456bc143d34d2f545ab02ffb2e0dc85528710d48fbeb2ca76", + "0f422c44489dd49e420ac536168a27cebf6b17bec5f709c622b76eeb656c6b66", + "919f2441fad94c62bc9275ade6d4eae45055485319a1f320415bca277c40997a", + "da698f08d773da4cfb6e8ac5f9eb41ee2a700cfd12023212e125f87b8d2d5d96", + "e62a6f3345fc5d927368dac32b6f192aa0728db95b9d0329b53b5474860804d6", + "d9ec8ebe00319467206c4d323d8fd241c5293c0aac4a3b97d9b77422aa498783", + "25d33548e8f7e7de2866f533e73f70b12e0046362d57c146244000cb5b3a868c", + "6e836a4e0bfc9890eb36711e1139c12b7e76f5a59fa3b48face945fc04a8b0ac", + "b7388da7b7fbec0b73ca15eb236d1fd5de29301bcfad26922a74310d58fa2414", + "a9833dbef8631dd9b6412abb72f8b93c8333dddc5fab087aa6873aa858e00355", + "6b26336e74471326af52d445094f98099c1cad78a4aec235d6feb051e6015e93", + "d31266d9976427552a4bb51929736c95f0234744105e80d25b3b5aaf9d447768", + "8dee05933d5970feb29e5bad97e1ffdfc356e1b9983e8b3df5ca02d47dd53abd", + "5dfa3242c2adf36d19b141dfcd5bfb10dcb73da4941cf485dd562e30b8231339", + "cda868eb45d0e52178f34ce8f620ef5cbad1000cb016cb9570f7c52b9b37bd82", + "ef114151d83adef562e6f719afe3140018e333f6079768b6f7fad13a6535339b", + "adb74f98c63dcccb7014da2fe583010b117e75d0caf6ee2491efab43b6c97f9c", + "9f493482a1884b9205fdb2ebc9739bd22de0d41934e9cdb141bb5523baeb7ef0", + "2eb20c5a1f855ec299cc13e9c38ef6bcb5a0d5bcfb362bf5a9ff299a1d228679", + "f524790d712616f726140df1ac4037dde415a9172008f595f35a436da5819a23", + "c1dcb662c74ebec5c41507c1941969ce456d4e9c8e4ac39f72c9c6d66f70dc07", + "2d663ce42f4f534345d77492e027f6b4ed3f5af29c7ae4d46760a14f006810f3", + "1d7c46eb71dc7ee584e650e623dcdfeee034e700860c1a2391d767261b399529", + "6b21a2043790a95ba9f5b6e94a49e200f16bfa0da5103279f4d85009655fda23", + "9750efd6f8fc01594ebc6945ec317fb05f33fbf66ac825978d02f95be458b4f6", + "33b3abdbe4e15dbddedc2f3148a5149e4538eddd3a2ec95ed352174a5038d5cc", + "fcf2b9613d0daf403a6fab1dd7472ee9e1191b54431b7d4067923d55ee7172d2", + "3f1f139eb99644a3762a666d6194ad0fb0ec4be765c10b2dde0dc26399c08724", + "3ea6a81fc198435cdc118d95714ad6df617897aceb3fd28aaf5194b6bb2fdb16", + "72719dcb0a8ed816ed1e35acc118d0d26b9ab9513178488974474d31d884c2c4", + "b7ef0727a48371a432e2529c2de68e6c09d2172b245141ee8aea642c9e16ebc7", + "53e438f93c2cac1e8ab600639fa1387a4fb38207fa5f5e6506a21999de7c3b1c", + "222013b8387fb25d7ebcd5660c1685c99e49e22fbdbe6655da9335cefe9b51a9", + "94ddfacfa5ab0bb4c96e90c97057424903b82deb27dbdbb6e7f1cd0f2010ca10", + "b69b3f7601d6c11dd5633b6fba76313e03585b14163f952c37b1bc62ec53f155", + "03346230dc04b3ec4ec443345a8778bd8341cd4288e9c9a13f7647fcc30576ab", + "37f0b2f2f02fad8a573c5f313fca1bf3e07bf398de12fc2f328eab7cbd7be689", + "867680063b9ab553fc530d91b0a2756d0861d592849a121776169c94e217db9e", + "f077a1162a91bd0d5857e27b4af9c9ee2f4e320f4128540668f2a46ea024a7ee", + "487e8cdef6be06b910a276a77e9c330e871e4bf4f7aa5745eb2abc0e0e596b27", + "5475822e235bdf9c42d8ce69d4eba78c467fe5554b35083ff09fe39243f4d9bb", + "2c55c5d9edb372d5d401faa511d91abf6e3e5079734f506a9b858a2ee4b1d579", + "c34f9eeaed9318ab8aa7ee1e5510ceb53283786d913289664dc5195776405660", + "85999553f92abbc71a6cf2de56b32340e1805610dda15392bfeb782511386948", + "28f8df6e084aa487ee1be16cfcfb94493dd8be70d1ff34597bc680377dd2b313", + "f912e124d8b91080c9412d10f159d7d58212fd3e5e34cb4fa5125e9e5eb459b6", + "4a33d33bd077c3e3bde29806f5eeb66e0d7e0c02262a794edee6a0179cd84497", + "06e5091c5c9327812aafc0854756a67f930e79a09b9d905aeb9dc69dee35b67c", + "faee03b91afa3145242e8f9e8d66d6d20cea27710e35ad73bf01ae582f29d76c", + "933ca2f648c61e068d46ea9f2994a86c884cad0fa3f2ee43e064c9eadd6cdc10", + "2b8a1837cadc840f2a1bc17312b1eb5e0aba9c81cb602d85d89e012539aec537", + "f91fd01f352b10b886d7c9bcb610175ee2732b5cba1809ea4dd914883cfb70dd", + "a58f0ae473e9c4572ea52c394bd74227e7739f667c00c92d07ebc194a7529f6e", + "d310a001aacc6a8f3ca3549c434f5373d3965bb33e4b10a118817fde74622bf5", + "9c8899856e7b3bec2b6725d004e8b954efdcdfe36c262ebcf2696956799b133b", + "d4917f0f4550087cbb590d4cfc332c21726e6535fc1204bbc879020bb803043a", + "88796c1569dc54e01f45badc2be538815ed87dfa01c378beffb162d3af79dd2e", + "2d0688a287d9a3282686bdf0cd38054f50f159259871c31b5184234eaf9ea2c3", + "ac6fb4a4dd3915f7a9fc4ce0593e3355594841b934ae75f63785cb66fc466ee2", + "8970545eaeffecd0f11f49856035ef34f42c9a1e6487ee21e4cd45dfdbc466df", + "4c5fd8ebbf0b78ed3cd28e13dd453a39275661997d3f168fb027e6618e1c7817", + "b34b6fe3fdf158c6f537107c21cfb7110d4a2697e4fa0f61caf9f8c071c39fab", + "107eef28e9ec5a697276ff6e6098eeb1325262f27b9164618b895cc4be928e88", + "52298a3df410049afdea2a2e24eaa3070b9d74116023ed1bb0a8cc5fe9a0d7ce", + "19791e2b4528054d9ea564361be20301fbc53a85c870d4889ad0a3f7c48d12da", + "fd2ceb30fda2b6db56eb733dfd859ae80f45c782f6f8d6e22abec9f0a588c72e", + "7b930e7b4060202ef0d5a2f3b8c833c8b79ffcc512dfabb26fd16cde603a5260", + "232d155d43eedb14089c11a69442ffe72a6ef06d87b4b5eb5d5fafbd3c668e93", + "9f3801d3c979b9e9378256cb633b18e7a2df9a191923aed0317d9d48fd625cb4", + "2fc28f0cab841d68c66191f8aeda40b4c727087183e44d6da67d3b1ee6257eea", + "3a26c72e9f48452c1fc7b8b6b1734d403a9c8b01eddca80a59066ed22f59728d", + "b1cd45299ed893cc1671f3b74478702d26b042d25277c781c3ed909833cfd8de", + "f05e9fcc4e180037894659e936f33b9c78ad2a893d0fdddfa0d64df256d87ee9", + "a1b11e064ad826f744e853ae925b6078487fa5f5f1237c89e2f0d279bc14d24b", + "dc97280b277d3a95ae16d574904837e469c54fcdc554ac1c11cd442cc57d3c14", + "480af4e625057cd6e719a07e104d0f9a74f5a78dbb5cd7dd3382ef21d0e040bc", + "e2a4511b5facf3678749ce19e2e812ce0876b5643ec316a13829e419660c0971", + "e35812b5bd7dde5f55be4c3679b01931493ccf1c68a43cb6ae194c2ad43ac70d", + "e956b400e5432f2e0376e432f335e4918454f924d951cb9f47aa7648edbfbfba", + "f419bc427564ae1144fe9fe8d9ef5193450cc1cb82f988518a54d61c53b02816", + "161dcec881cf321ea18e8fd3dcde094671e242f9c5d40a662ae9667d1f2cdd0f", + "5ca73ed50a1a7bb63b53bd3005db873c3636945355ce073a60fe58a0e5dd2288", + "74badddeea26e609f5b9b12ebc375d05a38a8eed333cc78e1b0e11c070a137f6", + "0297898e7508e689770c409b749d98b212bc909c2bb9c9e58e5aaae8b342fb7a", + "c60adc9f0939f3d212ceedd83fdcdb7f10d1d7c33822aea0620fd70ecb2d819f" + ], + "datasets_version": "3.1.0", + "transformers_version": "4.52.1", + "historical_token_hash_available": false, + "validation": "Pinned legacy loader and historical source arguments/window count; not an immutable historical token-cache claim", + "input_ids_sha256": "0e958e9f08255ee1a4bb4f029d8e7af94c8a26c6b31366a9223fb7629ebf53e3", + "attention_mask_sha256": "39024bd69b2936f651f76827b6e0b1118b908ff87f1aa3df24f097246fd42dfa", + "selection_file_sha256": "538f3330f2db732fe22f3a18de220082f5cea09025c6fad490e8ef05b513ad12" + }, + "independent_of_fit_loader": true + } +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/smoke_summary.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/smoke_summary.json new file mode 100644 index 0000000000000000000000000000000000000000..20874798f40695c30cc5538022ba4b4aa4483011 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/smoke_summary.json @@ -0,0 +1,1617 @@ +{ + "model": "Qwen/Qwen3-8B-Base", + "batch_size": 1, + "samples_per_probe": 64, + "probes": [ + { + "method": "mka", + "gpu": 0, + "completed": true, + "batch_size": 1, + "fit_runtime": { + "seconds": 36.1529198018834, + "dataset_tokens": 65536, + "tokens_per_second": 1812.7443193837385, + "batch_size": 1, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 41410369024, + "peak_reserved_bytes": 43159388160, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 64, + "student:1x1024": 64 + } + }, + "distill_loader": { + "sequences": 64, + "sha256": "660c914673cdc92b5818f82c9a8eaedbe5b81f501b9b08a5d03a9180abfcc8b5", + "attention_mask_sha256": "b1476de1907209012e63fa502715fd97db26e595352faa808d8c10433a1472a4", + "valid_tokens": 65536 + }, + "frozen_tensor_count": 8, + "selection": [ + { + "cycle": 1, + "pair_index": 13, + "initializer": "mka", + "lambda_left": 0.6225208206034097, + "recipient_original_layer": 13, + "recipient_side": "left", + "removed_original_layer": 14, + "npib_matrix": [ + [ + 2.305650187293982, + 1.6552668795066114, + 1.4346626550632378, + 1.0719049997932595, + 0.7364311678484329, + 0.6349153081177873, + 0.4879861230703414, + 0.6435725449714257, + 0.6730559876823013, + 0.5609387395565991, + 0.5434408771872553, + 0.4868431075228783, + 0.5683401587444541, + 0.5423009042422741, + 0.5446230551854597, + 0.815907364579963, + 0.29639349190493974, + 0.35913145879472497, + 0.3869380556585767, + 0.36496289639878615, + 0.5567115516831481, + 0.5865939302188461, + 0.5323923237634158, + 0.5313209902809335, + 0.4370254856258094, + 0.38271800090754104, + 0.3185984303150101, + 0.2768717599683702, + 0.2212556826799991, + 0.2145700682917155, + 0.37336284621872834, + 0.3216052140629787, + 0.38518197537047966, + 0.40935300158392696, + 0.3652341454849093, + 0.7374747821372646 + ], + [ + 1.6552668795066114, + 2.2979443101576607, + 1.7190146228502712, + 1.1398947911943877, + 0.7486903852789452, + 0.659850180328128, + 0.48375331517247283, + 0.6198209317313721, + 0.6140644433183479, + 0.5525940117423009, + 0.5149186721330308, + 0.45334446358290986, + 0.5378654738393881, + 0.5451197481728552, + 0.5322776253528904, + 0.8061675131642572, + 0.368127831412138, + 0.4301748385969982, + 0.37903233421662097, + 0.36946973779517917, + 0.5048278029472789, + 0.5230316313366685, + 0.518941399976448, + 0.4962674957937342, + 0.40987730966772823, + 0.36034007500499105, + 0.2913178657733092, + 0.22021185548587877, + 0.1746953789213012, + 0.20288799926475004, + 0.38234045463065425, + 0.2912795609314152, + 0.3751773883715947, + 0.38551435569092873, + 0.3935357622772774, + 0.7857756907284158 + ], + [ + 1.4346626550632378, + 1.7190146228502712, + 2.4001717562494442, + 1.2170461776551214, + 0.782238385183101, + 0.694950220188372, + 0.5097294835029202, + 0.6121399131185826, + 0.6251158496854786, + 0.6181810602199665, + 0.5808843524716246, + 0.5127404433633352, + 0.578843214471934, + 0.5903055187808183, + 0.5927486126229855, + 0.8204739404098746, + 0.362852742338131, + 0.380419479706645, + 0.35895896371432656, + 0.4316751311186592, + 0.5446020774778243, + 0.604175420869232, + 0.577858761207751, + 0.5729151116384797, + 0.4362621399991447, + 0.39232177348389374, + 0.329610157664566, + 0.2534492885353103, + 0.19793704636592005, + 0.1713332677199978, + 0.3769358070561172, + 0.31109460373826886, + 0.3687222185730669, + 0.3865308260476435, + 0.4069758632536385, + 0.7545606031187027 + ], + [ + 1.0719049997932595, + 1.1398947911943877, + 1.2170461776551214, + 2.4145928212758827, + 1.1579796910418625, + 0.9892784549377822, + 0.5630919956120025, + 0.7062582392987986, + 0.8069767659764245, + 0.7109553181227747, + 0.6573819412464661, + 0.6724558180414543, + 0.8215048114713313, + 0.8546689537254759, + 0.8488163780022493, + 0.924324415972487, + 0.4728895759092582, + 0.49348893763975615, + 0.3744698887476712, + 0.5548457536211793, + 0.6947102129572347, + 0.7408272349527266, + 0.685148785716988, + 0.5496104519106, + 0.4464278812146982, + 0.44137842434263336, + 0.3098377739302371, + 0.22620271293456898, + 0.18952071385240238, + 0.14775354769490578, + 0.3952272777526577, + 0.2939288288485044, + 0.31659617483521796, + 0.36216300715708005, + 0.39423341416604796, + 0.6713107705170177 + ], + [ + 0.7364311678484329, + 0.7486903852789452, + 0.782238385183101, + 1.1579796910418625, + 2.6737433631618197, + 1.825810249644986, + 0.6838193516976033, + 0.874620175699387, + 0.9244046309405789, + 0.7394669958296858, + 0.7759342858945596, + 0.7588367742875349, + 1.0835367672918625, + 1.1008161070541351, + 1.0961030980309772, + 1.0162684687140187, + 0.5183733204199158, + 0.4578301996091929, + 0.36452995067196486, + 0.6077639197240532, + 0.7413065988228765, + 0.7188752305391151, + 0.6913977751607956, + 0.5214130148461293, + 0.49603924703320357, + 0.4350631334826289, + 0.33111315385749224, + 0.30453435721935773, + 0.2386483071883892, + 0.1514405425341951, + 0.3881934751828999, + 0.3255988577489347, + 0.3623816668894299, + 0.3696144001186907, + 0.38513702653134535, + 0.5000560663248542 + ], + [ + 0.6349153081177873, + 0.659850180328128, + 0.694950220188372, + 0.9892784549377822, + 1.825810249644986, + 2.622874081222646, + 0.6967135661907065, + 0.8698213398020422, + 0.8609797263301064, + 0.6983594641304631, + 0.7686510672009131, + 0.7427912577166207, + 1.0937828329508412, + 1.1401150617386264, + 1.1489820531148844, + 1.024039047292708, + 0.5474814917074503, + 0.5033031415793491, + 0.33102555117244964, + 0.6197742753595777, + 0.7097641164907397, + 0.6727068864362054, + 0.6617537516426755, + 0.5312957627366661, + 0.46962677202335473, + 0.455688077409496, + 0.32574632460822933, + 0.3274547866535751, + 0.23372522695218384, + 0.17878679647671947, + 0.3846721381393894, + 0.30471780458433767, + 0.33331825851725627, + 0.33848861921500856, + 0.3436827798836983, + 0.49558113685100236 + ], + [ + 0.4879861230703414, + 0.48375331517247283, + 0.5097294835029202, + 0.5630919956120025, + 0.6838193516976033, + 0.6967135661907065, + 2.53232736054775, + 1.4379287874503774, + 1.0731347620278802, + 0.6708032195240902, + 0.6001630290694683, + 0.6735531980632752, + 0.7098247682152311, + 0.7658361528232361, + 0.7603086637962913, + 0.6723963355772139, + 0.5125852640654355, + 0.45290130923408206, + 0.43983461270645996, + 0.5024012338150626, + 0.4959648481031189, + 0.4539293831167823, + 0.5078934870838312, + 0.3393590758134077, + 0.4117164299734432, + 0.35365415255202537, + 0.3507392634838096, + 0.23610215711052718, + 0.2179223814599531, + 0.1426983647909565, + 0.35263688468780535, + 0.25219402395043394, + 0.26035144994104625, + 0.2809704797220342, + 0.27558140766329364, + 0.4102622509422214 + ], + [ + 0.6435725449714257, + 0.6198209317313721, + 0.6121399131185826, + 0.7062582392987986, + 0.874620175699387, + 0.8698213398020422, + 1.4379287874503774, + 2.453036460666547, + 1.4826199649874394, + 0.8203679202130315, + 0.6896317502271339, + 0.7616110951219671, + 0.9566630338157303, + 1.0005181801980905, + 0.9674995209474123, + 0.792716103841807, + 0.49367979574521764, + 0.46077564475908767, + 0.4424316573555446, + 0.5679862226830141, + 0.659218686702423, + 0.6214192226532664, + 0.6274270025647364, + 0.41344291149127704, + 0.4112634540894503, + 0.3557290701594083, + 0.3499300171512096, + 0.1788615192687154, + 0.23526876721362708, + 0.1633055840740454, + 0.3682913609723196, + 0.27649922533106763, + 0.3366713018964663, + 0.37354909320615515, + 0.3471102413908271, + 0.4663701238095269 + ], + [ + 0.6730559876823013, + 0.6140644433183479, + 0.6251158496854786, + 0.8069767659764245, + 0.9244046309405789, + 0.8609797263301064, + 1.0731347620278802, + 1.4826199649874394, + 2.401680718627779, + 0.9783335292579045, + 0.7727053389169971, + 0.9152745066329905, + 1.0988925198765678, + 1.1150972261352559, + 1.0829979749365521, + 0.8688666444588854, + 0.5095083437407347, + 0.4833289060932434, + 0.4058743717618952, + 0.643213823314105, + 0.7099131448830591, + 0.657682627100569, + 0.6704932795767751, + 0.5545591628502947, + 0.4428770410436966, + 0.386769926093613, + 0.31542110994513844, + 0.19169517139670575, + 0.21498387175366665, + 0.1735653700221343, + 0.41240245471200565, + 0.3621567881805424, + 0.38413873273692406, + 0.4054042789782842, + 0.40009385863665475, + 0.5404228458357689 + ], + [ + 0.5609387395565991, + 0.5525940117423009, + 0.6181810602199665, + 0.7109553181227747, + 0.7394669958296858, + 0.6983594641304631, + 0.6708032195240902, + 0.8203679202130315, + 0.9783335292579045, + 2.1452613419713673, + 1.1338689649842157, + 1.3471906312857087, + 0.8624981821496415, + 0.8501018197763551, + 0.8513781335534238, + 0.840836573400373, + 0.5107779042877395, + 0.4635167418310859, + 0.3624478455421156, + 0.6818158500479942, + 0.783614114192468, + 0.7682202082467748, + 0.7757460901373722, + 0.6713612126507303, + 0.5238234664434501, + 0.4652372887749629, + 0.3906400726404951, + 0.2531290548063733, + 0.21965102522286228, + 0.12182820263699651, + 0.41189089481798324, + 0.3915240248208806, + 0.42916261589875027, + 0.4226315531038823, + 0.359097271969746, + 0.4452504407891437 + ], + [ + 0.5434408771872553, + 0.5149186721330308, + 0.5808843524716246, + 0.6573819412464661, + 0.7759342858945596, + 0.7686510672009131, + 0.6001630290694683, + 0.6896317502271339, + 0.7727053389169971, + 1.1338689649842157, + 2.046473602908692, + 1.1804298472175094, + 0.8319491590018276, + 0.8317981321437611, + 0.8309595200998839, + 0.8953175325530609, + 0.4807691233074817, + 0.4545867085713419, + 0.42916437933028934, + 0.7292235079783117, + 0.862301414970022, + 0.829352083982088, + 0.8230799761702206, + 0.6792460422840784, + 0.661377699935948, + 0.6028344539273038, + 0.4678872601294528, + 0.3609952178065911, + 0.2691647405321276, + 0.16821180047694648, + 0.49564781398055585, + 0.4301426854019401, + 0.43766378748915297, + 0.492094805542044, + 0.3930940666989968, + 0.5323974653880782 + ], + [ + 0.4868431075228783, + 0.45334446358290986, + 0.5127404433633352, + 0.6724558180414543, + 0.7588367742875349, + 0.7427912577166207, + 0.6735531980632752, + 0.7616110951219671, + 0.9152745066329905, + 1.3471906312857087, + 1.1804298472175094, + 2.2186609076590034, + 0.9903297135038043, + 1.0136352594163558, + 0.9669521179840245, + 0.8906875240413356, + 0.5664142128627849, + 0.49634628250889934, + 0.4047366284475955, + 0.7935949717355554, + 0.8920365218736125, + 0.850004624836189, + 0.8717520618334886, + 0.7366988035904066, + 0.559554194143612, + 0.5048113411251253, + 0.4013034098215975, + 0.29069428555867477, + 0.2415185727755765, + 0.16070202284398202, + 0.4727905501642757, + 0.4091675526732869, + 0.40668941187015356, + 0.40686105828827884, + 0.36139350037150564, + 0.4576022356884752 + ], + [ + 0.5683401587444541, + 0.5378654738393881, + 0.578843214471934, + 0.8215048114713313, + 1.0835367672918625, + 1.0937828329508412, + 0.7098247682152311, + 0.9566630338157303, + 1.0988925198765678, + 0.8624981821496415, + 0.8319491590018276, + 0.9903297135038043, + 2.400282292579902, + 1.9538423363875246, + 1.927179104881176, + 1.3706246792332777, + 0.6502247769516513, + 0.5792520409812817, + 0.38269275832015465, + 0.8034376448117027, + 0.8605772477723336, + 0.6892895347285863, + 0.7349258459944704, + 0.6628950307775187, + 0.508402900081458, + 0.42612915165979715, + 0.319573540123407, + 0.23825332233169605, + 0.23084373919343024, + 0.19434138441423168, + 0.4116090306808467, + 0.2746030005846192, + 0.30512506864684064, + 0.34363151996709124, + 0.32247361553629217, + 0.40252115473075883 + ], + [ + 0.5423009042422741, + 0.5451197481728552, + 0.5903055187808183, + 0.8546689537254759, + 1.1008161070541351, + 1.1401150617386264, + 0.7658361528232361, + 1.0005181801980905, + 1.1150972261352559, + 0.8501018197763551, + 0.8317981321437611, + 1.0136352594163558, + 1.9538423363875246, + 2.452228282516318, + 2.0866975139397255, + 1.3261530330777536, + 0.6664234186473529, + 0.5841889282489692, + 0.3751110742920831, + 0.8315537554246573, + 0.913785617817912, + 0.7454038951285489, + 0.7832555635730966, + 0.6716396662320755, + 0.4768680537663344, + 0.4069397832176846, + 0.2997441845096902, + 0.23652156653352727, + 0.22723940631366607, + 0.16493349269051302, + 0.371563590567422, + 0.26699484555280817, + 0.31036901997010624, + 0.33507110139342355, + 0.33419204304208505, + 0.43080648322536214 + ], + [ + 0.5446230551854597, + 0.5322776253528904, + 0.5927486126229855, + 0.8488163780022493, + 1.0961030980309772, + 1.1489820531148844, + 0.7603086637962913, + 0.9674995209474123, + 1.0829979749365521, + 0.8513781335534238, + 0.8309595200998839, + 0.9669521179840245, + 1.927179104881176, + 2.0866975139397255, + 2.400681174328214, + 1.394413385179029, + 0.7109766855013561, + 0.6248536114125106, + 0.3964012319350023, + 0.8476940146407219, + 0.8998893871628223, + 0.7377148822748366, + 0.7863826379569855, + 0.6581321950835723, + 0.47678594890279147, + 0.4212089736246031, + 0.29980046759991885, + 0.24341065109270305, + 0.21545711156204164, + 0.17089674306818697, + 0.3718246479123746, + 0.25692768135344385, + 0.31361896833742425, + 0.3326503266511644, + 0.3400517614884095, + 0.43566964041477757 + ], + [ + 0.815907364579963, + 0.8061675131642572, + 0.8204739404098746, + 0.924324415972487, + 1.0162684687140187, + 1.024039047292708, + 0.6723963355772139, + 0.792716103841807, + 0.8688666444588854, + 0.840836573400373, + 0.8953175325530609, + 0.8906875240413356, + 1.3706246792332777, + 1.3261530330777536, + 1.394413385179029, + 2.6049408204716205, + 0.8717303316262373, + 0.7777902650390054, + 0.47363726638476805, + 0.9035449718942922, + 0.9572324393089343, + 0.7798631167442767, + 0.8548042452785399, + 0.6758418696719484, + 0.665416132665469, + 0.4681971518684334, + 0.47477314507992247, + 0.3541544909773488, + 0.30359971107210365, + 0.2654911195993618, + 0.45343460883668246, + 0.3880951583226638, + 0.42475793634082326, + 0.43403064224715504, + 0.4565143913242386, + 0.5992313598915628 + ], + [ + 0.29639349190493974, + 0.368127831412138, + 0.362852742338131, + 0.4728895759092582, + 0.5183733204199158, + 0.5474814917074503, + 0.5125852640654355, + 0.49367979574521764, + 0.5095083437407347, + 0.5107779042877395, + 0.4807691233074817, + 0.5664142128627849, + 0.6502247769516513, + 0.6664234186473529, + 0.7109766855013561, + 0.8717303316262373, + 2.504428758997986, + 1.7318004828926319, + 0.9567352917607901, + 0.7356154814326675, + 0.6180275693496031, + 0.5752701177866741, + 0.5566469613230948, + 0.44936649872905005, + 0.4030275280490919, + 0.3309256800225664, + 0.2640740954630783, + 0.23057391895321716, + 0.16573630334416597, + 0.13134643615480718, + 0.29676604880087964, + 0.2820442735801314, + 0.26793713938529384, + 0.29738778162089974, + 0.3426610278631678, + 0.410454128370749 + ], + [ + 0.35913145879472497, + 0.4301748385969982, + 0.380419479706645, + 0.49348893763975615, + 0.4578301996091929, + 0.5033031415793491, + 0.45290130923408206, + 0.46077564475908767, + 0.4833289060932434, + 0.4635167418310859, + 0.4545867085713419, + 0.49634628250889934, + 0.5792520409812817, + 0.5841889282489692, + 0.6248536114125106, + 0.7777902650390054, + 1.7318004828926319, + 2.527483427607099, + 1.0628451192074664, + 0.6635287504561621, + 0.5902363745211439, + 0.5957440012840971, + 0.48912867902634666, + 0.3353733354895105, + 0.36149065611054987, + 0.3516398543050553, + 0.23198808296058068, + 0.21640595702003665, + 0.1810688991480484, + 0.1351907595216186, + 0.2945173833296438, + 0.2680641752690711, + 0.29544609936867255, + 0.2796533847865352, + 0.36190084889278507, + 0.4240093655620234 + ], + [ + 0.3869380556585767, + 0.37903233421662097, + 0.35895896371432656, + 0.3744698887476712, + 0.36452995067196486, + 0.33102555117244964, + 0.43983461270645996, + 0.4424316573555446, + 0.4058743717618952, + 0.3624478455421156, + 0.42916437933028934, + 0.4047366284475955, + 0.38269275832015465, + 0.3751110742920831, + 0.3964012319350023, + 0.47363726638476805, + 0.9567352917607901, + 1.0628451192074664, + 2.466322704356928, + 0.4737134758553192, + 0.5102893420743602, + 0.5864589586159981, + 0.4181960884556129, + 0.3087378028168884, + 0.33230859662845724, + 0.33371688494006513, + 0.24181616649389642, + 0.2769751067498019, + 0.20164274731386753, + 0.22385756003928603, + 0.32336726984596187, + 0.33866954536112, + 0.30985601806979046, + 0.35569967351885295, + 0.3804596524701908, + 0.45995980352673327 + ], + [ + 0.36496289639878615, + 0.36946973779517917, + 0.4316751311186592, + 0.5548457536211793, + 0.6077639197240532, + 0.6197742753595777, + 0.5024012338150626, + 0.5679862226830141, + 0.643213823314105, + 0.6818158500479942, + 0.7292235079783117, + 0.7935949717355554, + 0.8034376448117027, + 0.8315537554246573, + 0.8476940146407219, + 0.9035449718942922, + 0.7356154814326675, + 0.6635287504561621, + 0.4737134758553192, + 2.139165791052378, + 1.2476009623550912, + 1.013614653744425, + 1.230879571422206, + 0.7981300104907002, + 0.7214384354928701, + 0.6033285022872041, + 0.4701968756017591, + 0.36447589191780433, + 0.2840394755836451, + 0.2224069523627671, + 0.5176572159325629, + 0.40046699591888424, + 0.40234273047663066, + 0.44392256140307534, + 0.38286422689778726, + 0.4947963745772036 + ], + [ + 0.5567115516831481, + 0.5048278029472789, + 0.5446020774778243, + 0.6947102129572347, + 0.7413065988228765, + 0.7097641164907397, + 0.4959648481031189, + 0.659218686702423, + 0.7099131448830591, + 0.783614114192468, + 0.862301414970022, + 0.8920365218736125, + 0.8605772477723336, + 0.913785617817912, + 0.8998893871628223, + 0.9572324393089343, + 0.6180275693496031, + 0.5902363745211439, + 0.5102893420743602, + 1.2476009623550912, + 2.152034434912148, + 1.6159125953730789, + 1.491331774961376, + 0.842515319741636, + 0.7050654530069503, + 0.6068775586043075, + 0.505292318904508, + 0.3600837304295023, + 0.29413063790082145, + 0.2727348635658477, + 0.6979037035785116, + 0.5544248774587957, + 0.5674278677581182, + 0.5698891365432074, + 0.5069825943663989, + 0.5675391535001235 + ], + [ + 0.5865939302188461, + 0.5230316313366685, + 0.604175420869232, + 0.7408272349527266, + 0.7188752305391151, + 0.6727068864362054, + 0.4539293831167823, + 0.6214192226532664, + 0.657682627100569, + 0.7682202082467748, + 0.829352083982088, + 0.850004624836189, + 0.6892895347285863, + 0.7454038951285489, + 0.7377148822748366, + 0.7798631167442767, + 0.5752701177866741, + 0.5957440012840971, + 0.5864589586159981, + 1.013614653744425, + 1.6159125953730789, + 2.219314067348883, + 1.3897446238454214, + 0.7958853498480747, + 0.5954907613179435, + 0.5354595310548329, + 0.45552335667443816, + 0.30170858794685357, + 0.26373346506735845, + 0.21153882005517605, + 0.7123058490478006, + 0.5785525036861556, + 0.5717102406581342, + 0.6048259976991424, + 0.5307623425407216, + 0.6404634216535294 + ], + [ + 0.5323923237634158, + 0.518941399976448, + 0.577858761207751, + 0.685148785716988, + 0.6913977751607956, + 0.6617537516426755, + 0.5078934870838312, + 0.6274270025647364, + 0.6704932795767751, + 0.7757460901373722, + 0.8230799761702206, + 0.8717520618334886, + 0.7349258459944704, + 0.7832555635730966, + 0.7863826379569855, + 0.8548042452785399, + 0.5566469613230948, + 0.48912867902634666, + 0.4181960884556129, + 1.230879571422206, + 1.491331774961376, + 1.3897446238454214, + 2.1676929835567553, + 1.0204227898351914, + 0.7949711643717421, + 0.6360916621077033, + 0.48951277150203903, + 0.3586417806817347, + 0.32799795657351044, + 0.24470035102759513, + 0.6751487063135334, + 0.5132946297620539, + 0.5193369684060585, + 0.5625820596163011, + 0.4811517763005098, + 0.5781440516601454 + ], + [ + 0.5313209902809335, + 0.4962674957937342, + 0.5729151116384797, + 0.5496104519106, + 0.5214130148461293, + 0.5312957627366661, + 0.3393590758134077, + 0.41344291149127704, + 0.5545591628502947, + 0.6713612126507303, + 0.6792460422840784, + 0.7366988035904066, + 0.6628950307775187, + 0.6716396662320755, + 0.6581321950835723, + 0.6758418696719484, + 0.44936649872905005, + 0.3353733354895105, + 0.3087378028168884, + 0.7981300104907002, + 0.842515319741636, + 0.7958853498480747, + 1.0204227898351914, + 2.347108509318992, + 0.7280439733261743, + 0.6246914993941999, + 0.5388454751120707, + 0.4612670031955219, + 0.4761167121657454, + 0.40108031041023395, + 0.626846442577947, + 0.5133218236470763, + 0.442231218931831, + 0.4661607501017166, + 0.3396968217858663, + 0.5440037984796178 + ], + [ + 0.4370254856258094, + 0.40987730966772823, + 0.4362621399991447, + 0.4464278812146982, + 0.49603924703320357, + 0.46962677202335473, + 0.4117164299734432, + 0.4112634540894503, + 0.4428770410436966, + 0.5238234664434501, + 0.661377699935948, + 0.559554194143612, + 0.508402900081458, + 0.4768680537663344, + 0.47678594890279147, + 0.665416132665469, + 0.4030275280490919, + 0.36149065611054987, + 0.33230859662845724, + 0.7214384354928701, + 0.7050654530069503, + 0.5954907613179435, + 0.7949711643717421, + 0.7280439733261743, + 2.230039256685809, + 1.4298952070650681, + 1.066606098785605, + 0.8538879407643882, + 0.6673429918896702, + 0.5256710665275203, + 0.6096019367557568, + 0.5887539299598556, + 0.45723595938357325, + 0.4916108734426842, + 0.4171167011070133, + 0.5582247941121101 + ], + [ + 0.38271800090754104, + 0.36034007500499105, + 0.39232177348389374, + 0.44137842434263336, + 0.4350631334826289, + 0.455688077409496, + 0.35365415255202537, + 0.3557290701594083, + 0.386769926093613, + 0.4652372887749629, + 0.6028344539273038, + 0.5048113411251253, + 0.42612915165979715, + 0.4069397832176846, + 0.4212089736246031, + 0.4681971518684334, + 0.3309256800225664, + 0.3516398543050553, + 0.33371688494006513, + 0.6033285022872041, + 0.6068775586043075, + 0.5354595310548329, + 0.6360916621077033, + 0.6246914993941999, + 1.4298952070650681, + 2.2246308026310113, + 1.0063150409455381, + 1.0393741080964938, + 0.7948812742181706, + 0.6217747413865006, + 0.6009023400524411, + 0.5280639662898673, + 0.44050214246761743, + 0.479889006330885, + 0.40389793503859445, + 0.5020610533419535 + ], + [ + 0.3185984303150101, + 0.2913178657733092, + 0.329610157664566, + 0.3098377739302371, + 0.33111315385749224, + 0.32574632460822933, + 0.3507392634838096, + 0.3499300171512096, + 0.31542110994513844, + 0.3906400726404951, + 0.4678872601294528, + 0.4013034098215975, + 0.319573540123407, + 0.2997441845096902, + 0.29980046759991885, + 0.47477314507992247, + 0.2640740954630783, + 0.23198808296058068, + 0.24181616649389642, + 0.4701968756017591, + 0.505292318904508, + 0.45552335667443816, + 0.48951277150203903, + 0.5388454751120707, + 1.066606098785605, + 1.0063150409455381, + 2.2159187533924363, + 1.0777906760908198, + 0.8289771301037943, + 0.646513655657286, + 0.6051079774167758, + 0.5051946984899275, + 0.40358305956032864, + 0.4623270231896509, + 0.404509520281524, + 0.4706515957263996 + ], + [ + 0.2768717599683702, + 0.22021185548587877, + 0.2534492885353103, + 0.22620271293456898, + 0.30453435721935773, + 0.3274547866535751, + 0.23610215711052718, + 0.1788615192687154, + 0.19169517139670575, + 0.2531290548063733, + 0.3609952178065911, + 0.29069428555867477, + 0.23825332233169605, + 0.23652156653352727, + 0.24341065109270305, + 0.3541544909773488, + 0.23057391895321716, + 0.21640595702003665, + 0.2769751067498019, + 0.36447589191780433, + 0.3600837304295023, + 0.30170858794685357, + 0.3586417806817347, + 0.4612670031955219, + 0.8538879407643882, + 1.0393741080964938, + 1.0777906760908198, + 2.145324953219808, + 1.1839666632398622, + 0.8735664957696214, + 0.6415751834517252, + 0.5222100716945796, + 0.4340163945933199, + 0.39416507200014456, + 0.4023051864074542, + 0.37275691439708547 + ], + [ + 0.2212556826799991, + 0.1746953789213012, + 0.19793704636592005, + 0.18952071385240238, + 0.2386483071883892, + 0.23372522695218384, + 0.2179223814599531, + 0.23526876721362708, + 0.21498387175366665, + 0.21965102522286228, + 0.2691647405321276, + 0.2415185727755765, + 0.23084373919343024, + 0.22723940631366607, + 0.21545711156204164, + 0.30359971107210365, + 0.16573630334416597, + 0.1810688991480484, + 0.20164274731386753, + 0.2840394755836451, + 0.29413063790082145, + 0.26373346506735845, + 0.32799795657351044, + 0.4761167121657454, + 0.6673429918896702, + 0.7948812742181706, + 0.8289771301037943, + 1.1839666632398622, + 2.1681401334123516, + 1.211515221902029, + 0.6984065335046676, + 0.5995311794140863, + 0.47463103236874715, + 0.46334263113658286, + 0.48068624631311263, + 0.42037876863223544 + ], + [ + 0.2145700682917155, + 0.20288799926475004, + 0.1713332677199978, + 0.14775354769490578, + 0.1514405425341951, + 0.17878679647671947, + 0.1426983647909565, + 0.1633055840740454, + 0.1735653700221343, + 0.12182820263699651, + 0.16821180047694648, + 0.16070202284398202, + 0.19434138441423168, + 0.16493349269051302, + 0.17089674306818697, + 0.2654911195993618, + 0.13134643615480718, + 0.1351907595216186, + 0.22385756003928603, + 0.2224069523627671, + 0.2727348635658477, + 0.21153882005517605, + 0.24470035102759513, + 0.40108031041023395, + 0.5256710665275203, + 0.6217747413865006, + 0.646513655657286, + 0.8735664957696214, + 1.211515221902029, + 2.2153418300093426, + 0.7633326854954349, + 0.6633904211204562, + 0.5497894526304581, + 0.5067251364694288, + 0.4916216094000571, + 0.38130847935896345 + ], + [ + 0.37336284621872834, + 0.38234045463065425, + 0.3769358070561172, + 0.3952272777526577, + 0.3881934751828999, + 0.3846721381393894, + 0.35263688468780535, + 0.3682913609723196, + 0.41240245471200565, + 0.41189089481798324, + 0.49564781398055585, + 0.4727905501642757, + 0.4116090306808467, + 0.371563590567422, + 0.3718246479123746, + 0.45343460883668246, + 0.29676604880087964, + 0.2945173833296438, + 0.32336726984596187, + 0.5176572159325629, + 0.6979037035785116, + 0.7123058490478006, + 0.6751487063135334, + 0.626846442577947, + 0.6096019367557568, + 0.6009023400524411, + 0.6051079774167758, + 0.6415751834517252, + 0.6984065335046676, + 0.7633326854954349, + 2.1656260567602774, + 1.3271538422296743, + 1.2190934948976753, + 1.1496664268085595, + 0.8820172136144802, + 0.611677474841992 + ], + [ + 0.3216052140629787, + 0.2912795609314152, + 0.31109460373826886, + 0.2939288288485044, + 0.3255988577489347, + 0.30471780458433767, + 0.25219402395043394, + 0.27649922533106763, + 0.3621567881805424, + 0.3915240248208806, + 0.4301426854019401, + 0.4091675526732869, + 0.2746030005846192, + 0.26699484555280817, + 0.25692768135344385, + 0.3880951583226638, + 0.2820442735801314, + 0.2680641752690711, + 0.33866954536112, + 0.40046699591888424, + 0.5544248774587957, + 0.5785525036861556, + 0.5132946297620539, + 0.5133218236470763, + 0.5887539299598556, + 0.5280639662898673, + 0.5051946984899275, + 0.5222100716945796, + 0.5995311794140863, + 0.6633904211204562, + 1.3271538422296743, + 2.061831431610429, + 1.3815342895617113, + 1.2330707876314593, + 0.8925471890057596, + 0.5892731711712359 + ], + [ + 0.38518197537047966, + 0.3751773883715947, + 0.3687222185730669, + 0.31659617483521796, + 0.3623816668894299, + 0.33331825851725627, + 0.26035144994104625, + 0.3366713018964663, + 0.38413873273692406, + 0.42916261589875027, + 0.43766378748915297, + 0.40668941187015356, + 0.30512506864684064, + 0.31036901997010624, + 0.31361896833742425, + 0.42475793634082326, + 0.26793713938529384, + 0.29544609936867255, + 0.30985601806979046, + 0.40234273047663066, + 0.5674278677581182, + 0.5717102406581342, + 0.5193369684060585, + 0.442231218931831, + 0.45723595938357325, + 0.44050214246761743, + 0.40358305956032864, + 0.4340163945933199, + 0.47463103236874715, + 0.5497894526304581, + 1.2190934948976753, + 1.3815342895617113, + 2.2326398881670437, + 1.5866199911650796, + 1.1127169525962552, + 0.6325465553502884 + ], + [ + 0.40935300158392696, + 0.38551435569092873, + 0.3865308260476435, + 0.36216300715708005, + 0.3696144001186907, + 0.33848861921500856, + 0.2809704797220342, + 0.37354909320615515, + 0.4054042789782842, + 0.4226315531038823, + 0.492094805542044, + 0.40686105828827884, + 0.34363151996709124, + 0.33507110139342355, + 0.3326503266511644, + 0.43403064224715504, + 0.29738778162089974, + 0.2796533847865352, + 0.35569967351885295, + 0.44392256140307534, + 0.5698891365432074, + 0.6048259976991424, + 0.5625820596163011, + 0.4661607501017166, + 0.4916108734426842, + 0.479889006330885, + 0.4623270231896509, + 0.39416507200014456, + 0.46334263113658286, + 0.5067251364694288, + 1.1496664268085595, + 1.2330707876314593, + 1.5866199911650796, + 2.203815278165966, + 1.3360616923464685, + 0.8174660405672398 + ], + [ + 0.3652341454849093, + 0.3935357622772774, + 0.4069758632536385, + 0.39423341416604796, + 0.38513702653134535, + 0.3436827798836983, + 0.27558140766329364, + 0.3471102413908271, + 0.40009385863665475, + 0.359097271969746, + 0.3930940666989968, + 0.36139350037150564, + 0.32247361553629217, + 0.33419204304208505, + 0.3400517614884095, + 0.4565143913242386, + 0.3426610278631678, + 0.36190084889278507, + 0.3804596524701908, + 0.38286422689778726, + 0.5069825943663989, + 0.5307623425407216, + 0.4811517763005098, + 0.3396968217858663, + 0.4171167011070133, + 0.40389793503859445, + 0.404509520281524, + 0.4023051864074542, + 0.48068624631311263, + 0.4916216094000571, + 0.8820172136144802, + 0.8925471890057596, + 1.1127169525962552, + 1.3360616923464685, + 2.2600761495136616, + 0.9388366526701876 + ], + [ + 0.7374747821372646, + 0.7857756907284158, + 0.7545606031187027, + 0.6713107705170177, + 0.5000560663248542, + 0.49558113685100236, + 0.4102622509422214, + 0.4663701238095269, + 0.5404228458357689, + 0.4452504407891437, + 0.5323974653880782, + 0.4576022356884752, + 0.40252115473075883, + 0.43080648322536214, + 0.43566964041477757, + 0.5992313598915628, + 0.410454128370749, + 0.4240093655620234, + 0.45995980352673327, + 0.4947963745772036, + 0.5675391535001235, + 0.6404634216535294, + 0.5781440516601454, + 0.5440037984796178, + 0.5582247941121101, + 0.5020610533419535, + 0.4706515957263996, + 0.37275691439708547, + 0.42037876863223544, + 0.38130847935896345, + 0.611677474841992, + 0.5892731711712359, + 0.6325465553502884, + 0.8174660405672398, + 0.9388366526701876, + 2.3599888394853727 + ] + ], + "entropies": [ + -0.6579794819126111, + -0.6875693822799921, + -0.6627783794893399, + -0.6168285238964241, + -0.5808114532600014, + -0.5684782741810955, + -0.5945551705522, + -0.5981622711733671, + -0.6265209298818185, + -0.7085453438135044, + -0.7789605104498797, + -0.6937787458982444, + -0.6351847772646338, + -0.614012894939202, + -0.6377650420208455, + -0.6253634992904115, + -0.6048328065912397, + -0.6054910671172148, + -0.6238762826490499, + -0.8367723291027195, + -0.9175775767071254, + -0.9377281868650514, + -0.8644173623871289, + -0.6598490620296592, + -0.6970255719579596, + -0.6583859342000297, + -0.6663928597037044, + -0.6687377355315302, + -0.6714259515133286, + -0.670648536855068, + -0.8295466453196146, + -0.8440531721565206, + -0.8515671911579495, + -0.888002284725176, + -0.7947375613118061, + -0.9643807895978999 + ], + "pair_npib": 2.0866975139397255, + "source_lineage": [ + [ + 13 + ], + [ + 14 + ] + ], + "geometry_samples": 100, + "geometry_sequence_length": 512, + "geometry_input_ids_sha256": "4f47034e02892bf464998e540be8bd7bc0718f83f6bc9d354c887cc2874cada9", + "selection_policy": "native_dynamic_adjacent_NPIB", + "score_data": "saved_native_MKA_geometry_not_CoMe_calibration", + "removed_original_layers": [ + 14 + ], + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35 + ] + } + ] + }, + { + "method": "come", + "gpu": 1, + "completed": true, + "batch_size": 1, + "fit_runtime": { + "seconds": 36.14042781619355, + "dataset_tokens": 65536, + "tokens_per_second": 1813.3708968059057, + "batch_size": 1, + "batches_per_epoch": 64, + "grad_accumulation": 1, + "peak_allocated_bytes": 38770888192, + "peak_reserved_bytes": 40705720320, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 64, + "student:1x1024": 64 + } + }, + "distill_loader": { + "sequences": 64, + "sha256": "660c914673cdc92b5818f82c9a8eaedbe5b81f501b9b08a5d03a9180abfcc8b5", + "attention_mask_sha256": "b1476de1907209012e63fa502715fd97db26e595352faa808d8c10433a1472a4", + "valid_tokens": 65536 + }, + "frozen_tensor_count": 8, + "selection": [ + { + "cycle": 1, + "pair_index": 31, + "initializer": "come", + "lambda_left": null, + "recipient_original_layer": 31, + "recipient_side": "left", + "removed_original_layer": 32, + "source_lineage": [ + [ + 31 + ], + [ + 32 + ] + ], + "retention_ratios": [ + 0.49274789168296595, + 0.5072521083170339 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 6054, + 6234 + ], + "pair_score": 0.11533127194072337, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false, + "removed_original_layers": [ + 32 + ], + "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, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 33, + 34, + 35 + ] + } + ] + } + ], + "full_fit_input_sha256": "5d9d4cc2f81d8712b932806c0c2b2992dce9bd3e6c7a143f1f670649b8bfe693", + "full_fit_mask_sha256": "c8e7f8e30cd532b82e6af4b98d596bc7106f29f9fb2b398b44355e624898a30d" +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_1/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_1/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..1f29984d549cd713f18ee5e7664df2888c92c95c --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_1/cycle_metadata.json @@ -0,0 +1,512 @@ +{ + "cycle": 1, + "layer_merged": 31, + "num_layers_before": 36, + "num_layers_after": 35, + "fused_layer_state": "fused_layer.pt", + "profile_no_save": false, + "dwce_score": null, + "dwce_scores": null, + "dwce_meta": { + "method": "come", + "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": 1, + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 9.49544724743403, + "mean_abs": 0.00018087541037756536, + "max_abs": 1.5859873294830322 + }, + "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": 150994944, + "mean": 1.6938262964079815e-06, + "std": 0.0028841262342925596, + "rms": 0.00288412673167843, + "mean_abs": 0.0022766475255290666, + "min": -0.028415188193321228, + "max": 0.030315399169921875, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 5.346755642676726e-06, + "std": 0.002756188385278948, + "rms": 0.0027561935713847235, + "mean_abs": 0.0021897933135430017, + "min": -0.024268098175525665, + "max": 0.023231012746691704 + }, + "mlp.up_proj.weight": { + "mean": -2.945407118204457e-07, + "std": 0.0026402173161349488, + "rms": 0.002640217332564322, + "mean_abs": 0.0020853507642944655, + "min": -0.02331394888460636, + "max": 0.022465486079454422 + }, + "mlp.down_proj.weight": { + "mean": 2.92639583676646e-08, + "std": 0.0032229195531651707, + "rms": 0.0032229195532980284, + "mean_abs": 0.002554798498749733, + "min": -0.028415188193321228, + "max": 0.030315399169921875 + } + } + }, + "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": 284.4065435389057, + "dataset_tokens": 524288, + "tokens_per_second": 1843.4456305970311, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 38770888192, + "peak_reserved_bytes": 40705720320, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 31 + ], + [ + 32 + ] + ], + "retention_ratios": [ + 0.49274789168296595, + 0.5072521083170339 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 6054, + 6234 + ], + "pair_score": 0.11533127194072337, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "d32ab579b634854ee33973f309191b5099d830b8f9189443b26791e043f35b74", + "self_attn.k_proj.weight": "1a63ee1e67c33062741b1acbdcb80b0ec9e16b0f30e984b21a1a41e899504765", + "self_attn.v_proj.weight": "9ec2df6bba949c6870ca18d7dfde4a4055b72c809b44958868777e77f5abf1c8", + "self_attn.o_proj.weight": "8e9f8603686d189fecd3a4ba41ac32046c14ce9bf75662a70042a453b8984f72", + "self_attn.q_norm.weight": "1ae662bfcbfd5edee375b6a3bafa86cd26fe6dd611568b98b45950949b91a97b", + "self_attn.k_norm.weight": "3588b84b908a2d2d498d1f96db9990fa492b15088fe42fe7d8ace619738a1119", + "input_layernorm.weight": "7ab4e8ed36ba6396ebde3cf6685dc9ac0df299665cdd8bb682af51cc443b989e", + "post_attention_layernorm.weight": "0940f7475c1f814c377a0e5c3e55bc6b058aba1290a64ee2ca3c1c8f270751d8" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "d32ab579b634854ee33973f309191b5099d830b8f9189443b26791e043f35b74", + "self_attn.k_proj.weight": "1a63ee1e67c33062741b1acbdcb80b0ec9e16b0f30e984b21a1a41e899504765", + "self_attn.v_proj.weight": "9ec2df6bba949c6870ca18d7dfde4a4055b72c809b44958868777e77f5abf1c8", + "self_attn.o_proj.weight": "8e9f8603686d189fecd3a4ba41ac32046c14ce9bf75662a70042a453b8984f72", + "self_attn.q_norm.weight": "1ae662bfcbfd5edee375b6a3bafa86cd26fe6dd611568b98b45950949b91a97b", + "self_attn.k_norm.weight": "3588b84b908a2d2d498d1f96db9990fa492b15088fe42fe7d8ace619738a1119", + "input_layernorm.weight": "7ab4e8ed36ba6396ebde3cf6685dc9ac0df299665cdd8bb682af51cc443b989e", + "post_attention_layernorm.weight": "0940f7475c1f814c377a0e5c3e55bc6b058aba1290a64ee2ca3c1c8f270751d8" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "d32ab579b634854ee33973f309191b5099d830b8f9189443b26791e043f35b74", + "self_attn.k_proj.weight": "1a63ee1e67c33062741b1acbdcb80b0ec9e16b0f30e984b21a1a41e899504765", + "self_attn.v_proj.weight": "9ec2df6bba949c6870ca18d7dfde4a4055b72c809b44958868777e77f5abf1c8", + "self_attn.o_proj.weight": "8e9f8603686d189fecd3a4ba41ac32046c14ce9bf75662a70042a453b8984f72", + "self_attn.q_norm.weight": "1ae662bfcbfd5edee375b6a3bafa86cd26fe6dd611568b98b45950949b91a97b", + "self_attn.k_norm.weight": "3588b84b908a2d2d498d1f96db9990fa492b15088fe42fe7d8ace619738a1119", + "input_layernorm.weight": "7ab4e8ed36ba6396ebde3cf6685dc9ac0df299665cdd8bb682af51cc443b989e", + "post_attention_layernorm.weight": "0940f7475c1f814c377a0e5c3e55bc6b058aba1290a64ee2ca3c1c8f270751d8" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 32, + "teacher_boundary_original_layer": 32 + }, + "lambda_init": "come", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "come", + "prior_mean": 1.0 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 1.0, + "per_tensor_mean": { + "mlp.gate_proj.weight": 1.0, + "mlp.up_proj.weight": 1.0, + "mlp.down_proj.weight": 1.0 + } + }, + "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": 1, + "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": 26.87309643207118, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 5.208328366279602e-05, + "fit": 287.81725655309856, + "materialize_save_layer": 0.43788330676034093, + "metadata_write": 0.000996471382677555, + "teacher_snapshot": 0.1149786920286715, + "cycle_cleanup": 0.1462872140109539, + "cycle_total": 315.3912298628129 + }, + "tracked_component_total_seconds": 315.39055075263605, + "cycle_total_seconds": 315.3912298628129, + "ratios_of_tracked_components": { + "selection": 0.08520577540431139, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.651390111038725e-07, + "fit": 0.9125741271140254, + "materialize_save_layer": 0.0013883843562065915, + "metadata_write": 3.1594839487093496e-06, + "teacher_snapshot": 0.0003645597236641704, + "cycle_cleanup": 0.0004638287788326557 + }, + "ratios_of_cycle_total": { + "selection": 0.08520559193659344, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.6513865552143258e-07, + "fit": 0.9125721621311147, + "materialize_save_layer": 0.00138838136669434, + "metadata_write": 3.159477145610531e-06, + "teacher_snapshot": 0.0003645589386828679, + "cycle_cleanup": 0.00046382778010214514 + } + }, + "recipient_original_layer": 31, + "removed_original_layer": 32, + "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, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 33, + 34, + 35 + ], + "fisher_computed": false, + "merge_initializer": "come", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 32 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_2/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_2/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..52eca15d011fb7b7eca95305112cd0f740b151f0 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_2/cycle_metadata.json @@ -0,0 +1,511 @@ +{ + "cycle": 2, + "layer_merged": 16, + "num_layers_before": 35, + "num_layers_after": 34, + "fused_layer_state": "fused_layer.pt", + "profile_no_save": false, + "dwce_score": null, + "dwce_scores": null, + "dwce_meta": { + "method": "come", + "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": 1, + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 0.28547625475643207, + "mean_abs": 4.936821420010852e-06, + "max_abs": 0.03876304626464844 + }, + "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": 150994944, + "mean": -2.2277035264374313e-06, + "std": 0.003590529790157256, + "rms": 0.003590530481233896, + "mean_abs": 0.0027030425456662974, + "min": -0.04027918726205826, + "max": 0.037824470549821854, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": -6.615836658359815e-06, + "std": 0.0036853567166835904, + "rms": 0.0036853626549499226, + "mean_abs": 0.002706917623678843, + "min": -0.03582677245140076, + "max": 0.03232936933636665 + }, + "mlp.up_proj.weight": { + "mean": 9.250769987071787e-08, + "std": 0.003794212333341261, + "rms": 0.0037942123344689885, + "mean_abs": 0.0028184043864409127, + "min": -0.033416759222745895, + "max": 0.03145444020628929 + }, + "mlp.down_proj.weight": { + "mean": -1.5978162082319614e-07, + "std": 0.0032707464357456407, + "rms": 0.003270746439648445, + "mean_abs": 0.0025838056268791356, + "min": -0.04027918726205826, + "max": 0.037824470549821854 + } + } + }, + "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": 287.0148811088875, + "dataset_tokens": 524288, + "tokens_per_second": 1826.6927414160662, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 40117289984, + "peak_reserved_bytes": 51361349632, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 16 + ], + [ + 17 + ] + ], + "retention_ratios": [ + 0.49296001567209896, + 0.507039984327901 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 6057, + 6231 + ], + "pair_score": 0.11846736168607752, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "d2ed544f73cf62e3ab17f0be58f92f865cd3605e6d229fe8b2bd23de52252508", + "self_attn.k_proj.weight": "787f7f67063f02e7d3fd3f715d589274faeccf7d41d87f074f9e5010c8fcab43", + "self_attn.v_proj.weight": "cbeea55153838935a713e0e697686d9e0494ecaa9faed73c9c9f3d742db218d2", + "self_attn.o_proj.weight": "6fbabb27e0f0a37a8c41a199de67ed0cdfbfc7f7d1187a7d4dd9519c6194c5f2", + "self_attn.q_norm.weight": "349a1ca5fc11e844626318e972364bf926df4415d34cde698fcdc1fed7bb86c3", + "self_attn.k_norm.weight": "68f81d391604fc4461e9297f19ca7a56b30cf90c5f8e0520137b7eb84d37ab91", + "input_layernorm.weight": "086e8d855b92cf3fb06fd4a34cdcedd527143c24144a737b1a49446c980dbd41", + "post_attention_layernorm.weight": "0b0aa8913baf6ec21771d1d6834adf8ce81c80a3a7719fa50a6a56f71d52e2a3" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "d2ed544f73cf62e3ab17f0be58f92f865cd3605e6d229fe8b2bd23de52252508", + "self_attn.k_proj.weight": "787f7f67063f02e7d3fd3f715d589274faeccf7d41d87f074f9e5010c8fcab43", + "self_attn.v_proj.weight": "cbeea55153838935a713e0e697686d9e0494ecaa9faed73c9c9f3d742db218d2", + "self_attn.o_proj.weight": "6fbabb27e0f0a37a8c41a199de67ed0cdfbfc7f7d1187a7d4dd9519c6194c5f2", + "self_attn.q_norm.weight": "349a1ca5fc11e844626318e972364bf926df4415d34cde698fcdc1fed7bb86c3", + "self_attn.k_norm.weight": "68f81d391604fc4461e9297f19ca7a56b30cf90c5f8e0520137b7eb84d37ab91", + "input_layernorm.weight": "086e8d855b92cf3fb06fd4a34cdcedd527143c24144a737b1a49446c980dbd41", + "post_attention_layernorm.weight": "0b0aa8913baf6ec21771d1d6834adf8ce81c80a3a7719fa50a6a56f71d52e2a3" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "d2ed544f73cf62e3ab17f0be58f92f865cd3605e6d229fe8b2bd23de52252508", + "self_attn.k_proj.weight": "787f7f67063f02e7d3fd3f715d589274faeccf7d41d87f074f9e5010c8fcab43", + "self_attn.v_proj.weight": "cbeea55153838935a713e0e697686d9e0494ecaa9faed73c9c9f3d742db218d2", + "self_attn.o_proj.weight": "6fbabb27e0f0a37a8c41a199de67ed0cdfbfc7f7d1187a7d4dd9519c6194c5f2", + "self_attn.q_norm.weight": "349a1ca5fc11e844626318e972364bf926df4415d34cde698fcdc1fed7bb86c3", + "self_attn.k_norm.weight": "68f81d391604fc4461e9297f19ca7a56b30cf90c5f8e0520137b7eb84d37ab91", + "input_layernorm.weight": "086e8d855b92cf3fb06fd4a34cdcedd527143c24144a737b1a49446c980dbd41", + "post_attention_layernorm.weight": "0b0aa8913baf6ec21771d1d6834adf8ce81c80a3a7719fa50a6a56f71d52e2a3" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 17, + "teacher_boundary_original_layer": 17 + }, + "lambda_init": "come", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "come", + "prior_mean": 1.0 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 1.0, + "per_tensor_mean": { + "mlp.gate_proj.weight": 1.0, + "mlp.up_proj.weight": 1.0, + "mlp.down_proj.weight": 1.0 + } + }, + "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": 1, + "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": 25.690417364239693, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 3.831600770354271e-05, + "fit": 287.1713652741164, + "materialize_save_layer": 0.4335646261461079, + "metadata_write": 0.0009943279437720776, + "teacher_snapshot": 0.3350776410661638, + "cycle_cleanup": 0.15339657571166754, + "cycle_total": 313.7855410212651 + }, + "tracked_component_total_seconds": 313.7848541252315, + "cycle_total_seconds": 313.7855410212651, + "ratios_of_tracked_components": { + "selection": 0.08187271318706367, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.2210916874990656e-07, + "fit": 0.9151855530908013, + "materialize_save_layer": 0.0013817257921986009, + "metadata_write": 3.1688207085203715e-06, + "teacher_snapshot": 0.0010678579181276683, + "cycle_cleanup": 0.0004888590819314911 + }, + "ratios_of_cycle_total": { + "selection": 0.08187253396261068, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.221089014453539e-07, + "fit": 0.9151835496927978, + "materialize_save_layer": 0.0013817227675150445, + "metadata_write": 3.168813771775075e-06, + "teacher_snapshot": 0.0010678555805203776, + "cycle_cleanup": 0.0004888580117886055 + } + }, + "recipient_original_layer": 16, + "removed_original_layer": 17, + "recipient_side": "left", + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 33, + 34, + 35 + ], + "fisher_computed": false, + "merge_initializer": "come", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 17 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_3/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_3/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..d057e73700a31825c6d4f6314018949e7cc45e8b --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_3/cycle_metadata.json @@ -0,0 +1,510 @@ +{ + "cycle": 3, + "layer_merged": 25, + "num_layers_before": 34, + "num_layers_after": 33, + "fused_layer_state": "fused_layer.pt", + "profile_no_save": false, + "dwce_score": null, + "dwce_scores": null, + "dwce_meta": { + "method": "come", + "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": 1, + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 1.9195377668022477, + "mean_abs": 4.386278063369294e-05, + "max_abs": 0.15239524841308594 + }, + "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": 150994944, + "mean": 4.834807075187402e-06, + "std": 0.002954291666716121, + "rms": 0.0029542956228833586, + "mean_abs": 0.0023312543829282126, + "min": -0.025260327383875847, + "max": 0.025104448199272156, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.5033686698491996e-05, + "std": 0.0027293740459918606, + "rms": 0.0027294154492619347, + "mean_abs": 0.0021729754904905954, + "min": -0.02162746898829937, + "max": 0.0205176193267107 + }, + "mlp.up_proj.weight": { + "mean": 1.5114774972365316e-07, + "std": 0.0027591918042724883, + "rms": 0.002759191808412404, + "mean_abs": 0.0021809920047720275, + "min": -0.024778185412287712, + "max": 0.025104448199272156 + }, + "mlp.down_proj.weight": { + "mean": -6.804132226534421e-07, + "std": 0.003334777247271745, + "rms": 0.003334777316685999, + "mean_abs": 0.0026397956535220146, + "min": -0.025260327383875847, + "max": 0.022698627784848213 + } + } + }, + "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": 275.03382919635624, + "dataset_tokens": 524288, + "tokens_per_second": 1906.2673182130352, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 37833298944, + "peak_reserved_bytes": 51449430016, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 26 + ], + [ + 27 + ] + ], + "retention_ratios": [ + 0.500755807036962, + 0.4992441929630379 + ], + "retained_attention_groups": [ + 5, + 3 + ], + "retained_mlp_neurons": [ + 6154, + 6134 + ], + "pair_score": 0.11813264054820892, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "e374ecba7e5771f2299e56089ddd77b8b27f79f973e8be4e6cee80b9eac2612d", + "self_attn.k_proj.weight": "cf81f8d90cec377c6663e4b11e3dc0b61a0381e37444c00eef678183b4297b44", + "self_attn.v_proj.weight": "08d06843a169474bcd7a1f077dab1521fd59dd7dc4f0cbb81b4c399d0a153f98", + "self_attn.o_proj.weight": "efccaf7cf05bb7a6242e5ceb3afe68109d2e1c0e094f812a140e810d1b447b9c", + "self_attn.q_norm.weight": "4f1a08be52e5dedcad350ef489a3f349c839f22f0c2ee184e5edc2a1d4a0ddd9", + "self_attn.k_norm.weight": "f9ee6e6f0ac01557912733c0a1e3e3fbc977bd73cc9b89f203f13d1798e07ba6", + "input_layernorm.weight": "18d7e105f8c8b1594f50e198525ed0ec0b52e763ad77399b17b78ead143a289e", + "post_attention_layernorm.weight": "aeb4c2bf8614b342c7e265383dc930e75db4283123cb51d99196d1bbf113fd8b" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "e374ecba7e5771f2299e56089ddd77b8b27f79f973e8be4e6cee80b9eac2612d", + "self_attn.k_proj.weight": "cf81f8d90cec377c6663e4b11e3dc0b61a0381e37444c00eef678183b4297b44", + "self_attn.v_proj.weight": "08d06843a169474bcd7a1f077dab1521fd59dd7dc4f0cbb81b4c399d0a153f98", + "self_attn.o_proj.weight": "efccaf7cf05bb7a6242e5ceb3afe68109d2e1c0e094f812a140e810d1b447b9c", + "self_attn.q_norm.weight": "4f1a08be52e5dedcad350ef489a3f349c839f22f0c2ee184e5edc2a1d4a0ddd9", + "self_attn.k_norm.weight": "f9ee6e6f0ac01557912733c0a1e3e3fbc977bd73cc9b89f203f13d1798e07ba6", + "input_layernorm.weight": "18d7e105f8c8b1594f50e198525ed0ec0b52e763ad77399b17b78ead143a289e", + "post_attention_layernorm.weight": "aeb4c2bf8614b342c7e265383dc930e75db4283123cb51d99196d1bbf113fd8b" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "e374ecba7e5771f2299e56089ddd77b8b27f79f973e8be4e6cee80b9eac2612d", + "self_attn.k_proj.weight": "cf81f8d90cec377c6663e4b11e3dc0b61a0381e37444c00eef678183b4297b44", + "self_attn.v_proj.weight": "08d06843a169474bcd7a1f077dab1521fd59dd7dc4f0cbb81b4c399d0a153f98", + "self_attn.o_proj.weight": "efccaf7cf05bb7a6242e5ceb3afe68109d2e1c0e094f812a140e810d1b447b9c", + "self_attn.q_norm.weight": "4f1a08be52e5dedcad350ef489a3f349c839f22f0c2ee184e5edc2a1d4a0ddd9", + "self_attn.k_norm.weight": "f9ee6e6f0ac01557912733c0a1e3e3fbc977bd73cc9b89f203f13d1798e07ba6", + "input_layernorm.weight": "18d7e105f8c8b1594f50e198525ed0ec0b52e763ad77399b17b78ead143a289e", + "post_attention_layernorm.weight": "aeb4c2bf8614b342c7e265383dc930e75db4283123cb51d99196d1bbf113fd8b" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 26, + "teacher_boundary_original_layer": 27 + }, + "lambda_init": "come", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "come", + "prior_mean": 1.0 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 1.0, + "per_tensor_mean": { + "mlp.gate_proj.weight": 1.0, + "mlp.up_proj.weight": 1.0, + "mlp.down_proj.weight": 1.0 + } + }, + "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": 1, + "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": 24.937685477081686, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 3.356672823429108e-05, + "fit": 275.1848141499795, + "materialize_save_layer": 0.42647176794707775, + "metadata_write": 0.0009624739177525043, + "teacher_snapshot": 0.30407008714973927, + "cycle_cleanup": 0.14147081039845943, + "cycle_total": 300.9961785771884 + }, + "tracked_component_total_seconds": 300.99550833320245, + "cycle_total_seconds": 300.9961785771884, + "ratios_of_tracked_components": { + "selection": 0.0828506897500797, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.115190336898073e-07, + "fit": 0.9142489058187191, + "materialize_save_layer": 0.0014168708706276537, + "metadata_write": 3.197635483274536e-06, + "teacher_snapshot": 0.0010102146999919123, + "cycle_cleanup": 0.00047000970606462026 + }, + "ratios_of_cycle_total": { + "selection": 0.08285050526210115, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.1151878536452289e-07, + "fit": 0.9142468700127043, + "materialize_save_layer": 0.0014168677156069342, + "metadata_write": 3.1976283629318056e-06, + "teacher_snapshot": 0.0010102124504938277, + "cycle_cleanup": 0.00047000865946934345 + } + }, + "recipient_original_layer": 26, + "removed_original_layer": 27, + "recipient_side": "left", + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 28, + 29, + 30, + 31, + 33, + 34, + 35 + ], + "fisher_computed": false, + "merge_initializer": "come", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 27 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_4/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_4/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..4fda2b535a013e1ee1d1dbeb40f3b91c9d9173c1 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_4/cycle_metadata.json @@ -0,0 +1,510 @@ +{ + "cycle": 4, + "layer_merged": 15, + "num_layers_before": 33, + "num_layers_after": 32, + "fused_layer_state": "fused_layer.pt", + "profile_no_save": false, + "dwce_score": null, + "dwce_scores": null, + "dwce_meta": { + "method": "come", + "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": 1, + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 0.5103952856501015, + "mean_abs": 4.802161230246485e-06, + "max_abs": 0.18325042724609375 + }, + "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": 150994944, + "mean": 2.1773275370328014e-07, + "std": 0.004527799256407125, + "rms": 0.00452779926164229, + "mean_abs": 0.003343291063275602, + "min": -0.04195663332939148, + "max": 0.042360153049230576, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.2623284722697765e-06, + "std": 0.004667664245278318, + "rms": 0.0046676644159710946, + "mean_abs": 0.0033581051975488663, + "min": -0.04188692569732666, + "max": 0.04206804931163788 + }, + "mlp.up_proj.weight": { + "mean": -2.837029266326378e-07, + "std": 0.005126653429482778, + "rms": 0.005126653437332669, + "mean_abs": 0.003825555555522442, + "min": -0.0383785143494606, + "max": 0.037312258034944534 + }, + "mlp.down_proj.weight": { + "mean": -3.2542728452729836e-07, + "std": 0.0036651373492196473, + "rms": 0.00366513736366698, + "mean_abs": 0.0028462124367554984, + "min": -0.04195663332939148, + "max": 0.042360153049230576 + } + } + }, + "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": 272.50738346390426, + "dataset_tokens": 524288, + "tokens_per_second": 1923.940530842336, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 38422417408, + "peak_reserved_bytes": 50077892608, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 15 + ], + [ + 16, + 17 + ] + ], + "retention_ratios": [ + 0.48481783779572774, + 0.5151821622042723 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 5957, + 6331 + ], + "pair_score": 0.12428857100770828, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "e144fc375feeba841fb893f66d6c6fa9ef04120dbfa4ddfc1a159bf86586ba61", + "self_attn.k_proj.weight": "355b2a930766fc9c33f032fc19c3d1c618a5cc70d08acf1492aea8d9dc474150", + "self_attn.v_proj.weight": "34f582d607f0468a641dc8622fa95cc0bdbfdc2f38b98a32e11e6ad55d7b2e37", + "self_attn.o_proj.weight": "2f832c98994cce37666e06e9fec044ca2ecf17cb00b5adb1f10358c4367d3070", + "self_attn.q_norm.weight": "92b6ba51de0e72d7322500ceb344593844994aa05de41a1566908d0036b72158", + "self_attn.k_norm.weight": "fe2847d3261818e9ce010ef6c3e5aaded6c3045337c7b2989470d6d405bde5d9", + "input_layernorm.weight": "a36bf9c9668635c84481fa731271a83870120a57b6610c2ff64274e6a96d9f3c", + "post_attention_layernorm.weight": "02c0294d3d2fc22669c98157d5514cddf1a41a4ff47925bc0c560e86a60aa425" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "e144fc375feeba841fb893f66d6c6fa9ef04120dbfa4ddfc1a159bf86586ba61", + "self_attn.k_proj.weight": "355b2a930766fc9c33f032fc19c3d1c618a5cc70d08acf1492aea8d9dc474150", + "self_attn.v_proj.weight": "34f582d607f0468a641dc8622fa95cc0bdbfdc2f38b98a32e11e6ad55d7b2e37", + "self_attn.o_proj.weight": "2f832c98994cce37666e06e9fec044ca2ecf17cb00b5adb1f10358c4367d3070", + "self_attn.q_norm.weight": "92b6ba51de0e72d7322500ceb344593844994aa05de41a1566908d0036b72158", + "self_attn.k_norm.weight": "fe2847d3261818e9ce010ef6c3e5aaded6c3045337c7b2989470d6d405bde5d9", + "input_layernorm.weight": "a36bf9c9668635c84481fa731271a83870120a57b6610c2ff64274e6a96d9f3c", + "post_attention_layernorm.weight": "02c0294d3d2fc22669c98157d5514cddf1a41a4ff47925bc0c560e86a60aa425" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "e144fc375feeba841fb893f66d6c6fa9ef04120dbfa4ddfc1a159bf86586ba61", + "self_attn.k_proj.weight": "355b2a930766fc9c33f032fc19c3d1c618a5cc70d08acf1492aea8d9dc474150", + "self_attn.v_proj.weight": "34f582d607f0468a641dc8622fa95cc0bdbfdc2f38b98a32e11e6ad55d7b2e37", + "self_attn.o_proj.weight": "2f832c98994cce37666e06e9fec044ca2ecf17cb00b5adb1f10358c4367d3070", + "self_attn.q_norm.weight": "92b6ba51de0e72d7322500ceb344593844994aa05de41a1566908d0036b72158", + "self_attn.k_norm.weight": "fe2847d3261818e9ce010ef6c3e5aaded6c3045337c7b2989470d6d405bde5d9", + "input_layernorm.weight": "a36bf9c9668635c84481fa731271a83870120a57b6610c2ff64274e6a96d9f3c", + "post_attention_layernorm.weight": "02c0294d3d2fc22669c98157d5514cddf1a41a4ff47925bc0c560e86a60aa425" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 16, + "teacher_boundary_original_layer": 16 + }, + "lambda_init": "come", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "come", + "prior_mean": 1.0 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 1.0, + "per_tensor_mean": { + "mlp.gate_proj.weight": 1.0, + "mlp.up_proj.weight": 1.0, + "mlp.down_proj.weight": 1.0 + } + }, + "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": 1, + "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": 24.25791518529877, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 3.815582022070885e-05, + "fit": 272.66365361306816, + "materialize_save_layer": 0.44021402206271887, + "metadata_write": 0.000993847381323576, + "teacher_snapshot": 0.31485095573589206, + "cycle_cleanup": 0.14770854776725173, + "cycle_total": 297.82605631416664 + }, + "tracked_component_total_seconds": 297.82537432713434, + "cycle_total_seconds": 297.82605631416664, + "ratios_of_tracked_components": { + "selection": 0.08145012909025554, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.281147394069859e-07, + "fit": 0.9155151881503948, + "materialize_save_layer": 0.0014780944137391847, + "metadata_write": 3.3370137906111523e-06, + "teacher_snapshot": 0.0010571663225379065, + "cycle_cleanup": 0.0004959568945425288 + }, + "ratios_of_cycle_total": { + "selection": 0.08144994257893244, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.281144460391322e-07, + "fit": 0.9155130917270868, + "materialize_save_layer": 0.0014780910290748772, + "metadata_write": 3.337006149237661e-06, + "teacher_snapshot": 0.0010571639017499747, + "cycle_cleanup": 0.0004959557588589192 + } + }, + "recipient_original_layer": 15, + "removed_original_layer": 16, + "recipient_side": "left", + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 28, + 29, + 30, + 31, + 33, + 34, + 35 + ], + "fisher_computed": false, + "merge_initializer": "come", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 16 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_5/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_5/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..51d83fb5a5c1a4003fa4e419252172a89c6fba27 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_5/cycle_metadata.json @@ -0,0 +1,508 @@ +{ + "cycle": 5, + "layer_merged": 26, + "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": "come", + "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": 1, + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 10.416070559929201, + "mean_abs": 0.00014571001843756271, + "max_abs": 1.5470943450927734 + }, + "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": 150994944, + "mean": 3.504058844959622e-06, + "std": 0.0028318628407741995, + "rms": 0.002831865008679988, + "mean_abs": 0.0022335324643386733, + "min": -0.026923593133687973, + "max": 0.029769256711006165, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0593326199644556e-05, + "std": 0.0026527072310847228, + "rms": 0.0026527283827050877, + "mean_abs": 0.00211204681545496, + "min": -0.023384634405374527, + "max": 0.021433265879750252 + }, + "mlp.up_proj.weight": { + "mean": -1.3555364830608596e-07, + "std": 0.002661194413471638, + "rms": 0.002661194416923996, + "mean_abs": 0.0020990585908293724, + "min": -0.01704355515539646, + "max": 0.017607910558581352 + }, + "mlp.down_proj.weight": { + "mean": 5.440398354039644e-08, + "std": 0.0031526900707367247, + "rms": 0.0031526900712061322, + "mean_abs": 0.002489491986731688, + "min": -0.026923593133687973, + "max": 0.029769256711006165 + } + } + }, + "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": 263.1926762089133, + "dataset_tokens": 524288, + "tokens_per_second": 1992.0311140566776, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 35835041792, + "peak_reserved_bytes": 48907681792, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 29 + ], + [ + 30 + ] + ], + "retention_ratios": [ + 0.5168892574349215, + 0.4831107425650785 + ], + "retained_attention_groups": [ + 5, + 3 + ], + "retained_mlp_neurons": [ + 6352, + 5936 + ], + "pair_score": 0.12363086149413535, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "52fbd62bd62d7e2eaac0d2200d13f871e3deb60c0fd528297ee4536e9d8dc086", + "self_attn.k_proj.weight": "8111ddc37251c97bb655b31cd12861532c4bfbebd575bf99d2b1fbe10c48e056", + "self_attn.v_proj.weight": "90ab892c075978b6c4da576a84726e0dd1b2c03a2693ae085e9fb4854f8f5cda", + "self_attn.o_proj.weight": "0bd5ffb8b1db91700ecef537352b4938c61ab309f0c133e406f70406ea3d5479", + "self_attn.q_norm.weight": "da82f14c18c6dd24be49f9ea70b0dba47f259589a8c36f25319404914cc93e30", + "self_attn.k_norm.weight": "e997dc8cf097fb2e1771403fe8dfd46c8e38290d07e3fc105cf003611032c7f4", + "input_layernorm.weight": "64e67fc0c3a1540d2fc0134655058358a78cc81e047873cf05afac1c6a2fc0d0", + "post_attention_layernorm.weight": "0a89cbbfd56094d174142e7b4ad773e644f7bb78c6b3539ebb3eab6c048680cd" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "52fbd62bd62d7e2eaac0d2200d13f871e3deb60c0fd528297ee4536e9d8dc086", + "self_attn.k_proj.weight": "8111ddc37251c97bb655b31cd12861532c4bfbebd575bf99d2b1fbe10c48e056", + "self_attn.v_proj.weight": "90ab892c075978b6c4da576a84726e0dd1b2c03a2693ae085e9fb4854f8f5cda", + "self_attn.o_proj.weight": "0bd5ffb8b1db91700ecef537352b4938c61ab309f0c133e406f70406ea3d5479", + "self_attn.q_norm.weight": "da82f14c18c6dd24be49f9ea70b0dba47f259589a8c36f25319404914cc93e30", + "self_attn.k_norm.weight": "e997dc8cf097fb2e1771403fe8dfd46c8e38290d07e3fc105cf003611032c7f4", + "input_layernorm.weight": "64e67fc0c3a1540d2fc0134655058358a78cc81e047873cf05afac1c6a2fc0d0", + "post_attention_layernorm.weight": "0a89cbbfd56094d174142e7b4ad773e644f7bb78c6b3539ebb3eab6c048680cd" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "52fbd62bd62d7e2eaac0d2200d13f871e3deb60c0fd528297ee4536e9d8dc086", + "self_attn.k_proj.weight": "8111ddc37251c97bb655b31cd12861532c4bfbebd575bf99d2b1fbe10c48e056", + "self_attn.v_proj.weight": "90ab892c075978b6c4da576a84726e0dd1b2c03a2693ae085e9fb4854f8f5cda", + "self_attn.o_proj.weight": "0bd5ffb8b1db91700ecef537352b4938c61ab309f0c133e406f70406ea3d5479", + "self_attn.q_norm.weight": "da82f14c18c6dd24be49f9ea70b0dba47f259589a8c36f25319404914cc93e30", + "self_attn.k_norm.weight": "e997dc8cf097fb2e1771403fe8dfd46c8e38290d07e3fc105cf003611032c7f4", + "input_layernorm.weight": "64e67fc0c3a1540d2fc0134655058358a78cc81e047873cf05afac1c6a2fc0d0", + "post_attention_layernorm.weight": "0a89cbbfd56094d174142e7b4ad773e644f7bb78c6b3539ebb3eab6c048680cd" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 27, + "teacher_boundary_original_layer": 30 + }, + "lambda_init": "come", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "come", + "prior_mean": 1.0 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 1.0, + "per_tensor_mean": { + "mlp.gate_proj.weight": 1.0, + "mlp.up_proj.weight": 1.0, + "mlp.down_proj.weight": 1.0 + } + }, + "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": 1, + "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": 23.5936328638345, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 3.8778409361839294e-05, + "fit": 263.3299042629078, + "materialize_save_layer": 0.41143939597532153, + "metadata_write": 0.0009734770283102989, + "teacher_snapshot": 0.30083209089934826, + "cycle_cleanup": 0.14136270014569163, + "cycle_total": 287.7788464468904 + }, + "tracked_component_total_seconds": 287.77818356920034, + "cycle_total_seconds": 287.7788464468904, + "ratios_of_tracked_components": { + "selection": 0.08198548121755407, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.3475103943212733e-07, + "fit": 0.9150447090774217, + "materialize_save_layer": 0.001429710170772501, + "metadata_write": 3.3827339384683155e-06, + "teacher_snapshot": 0.0010453610039796812, + "cycle_cleanup": 0.000491221045294071 + }, + "ratios_of_cycle_total": { + "selection": 0.08198529236994738, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.3475072904288624e-07, + "fit": 0.9150426013383348, + "materialize_save_layer": 0.00142970687753887, + "metadata_write": 3.382726146586157e-06, + "teacher_snapshot": 0.0010453585960664654, + "cycle_cleanup": 0.0004912199138020387 + } + }, + "recipient_original_layer": 29, + "removed_original_layer": 30, + "recipient_side": "left", + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 28, + 29, + 31, + 33, + 34, + 35 + ], + "fisher_computed": false, + "merge_initializer": "come", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 30 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_6/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_6/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..44c07eef458da09e0c5b3a82be34429b984795a8 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_6/cycle_metadata.json @@ -0,0 +1,508 @@ +{ + "cycle": 6, + "layer_merged": 23, + "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": "come", + "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": 1, + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 1.6286034611369704, + "mean_abs": 4.974205835929347e-05, + "max_abs": 0.09180885553359985 + }, + "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": 150994944, + "mean": 3.004043845875357e-06, + "std": 0.002940920321421633, + "rms": 0.0029409218556823553, + "mean_abs": 0.002319265363944901, + "min": -0.02507743053138256, + "max": 0.02854803204536438, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 8.660291011134783e-06, + "std": 0.002758917691235299, + "rms": 0.0027589312836044885, + "mean_abs": 0.0022007301449775696, + "min": -0.021901600062847137, + "max": 0.024919675663113594 + }, + "mlp.up_proj.weight": { + "mean": 3.8269778694181394e-07, + "std": 0.0027593195629921686, + "rms": 0.0027593195895308843, + "mean_abs": 0.0021812085372706256, + "min": -0.019312186166644096, + "max": 0.017826871946454048 + }, + "mlp.down_proj.weight": { + "mean": -3.085726045052676e-08, + "std": 0.003274372864827382, + "rms": 0.0032743728649727794, + "mean_abs": 0.002575857409586509, + "min": -0.02507743053138256, + "max": 0.02854803204536438 + } + } + }, + "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": 295.43956048227847, + "dataset_tokens": 524288, + "tokens_per_second": 1774.603235748615, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 35365853184, + "peak_reserved_bytes": 47737470976, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 25 + ], + [ + 26, + 27 + ] + ], + "retention_ratios": [ + 0.5023699918186109, + 0.49763000818138914 + ], + "retained_attention_groups": [ + 5, + 3 + ], + "retained_mlp_neurons": [ + 6174, + 6114 + ], + "pair_score": 0.12410008491195262, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "39f86798d44a14cf29c0724dc84fe0261eb909a05cd405ac91ac7d141f235a4e", + "self_attn.k_proj.weight": "e23576863e9742419b554ec91e06851542fa31624588dd0b0865c98ca756ef07", + "self_attn.v_proj.weight": "32df6f78cdcbd2eb1155384475ea6ded1079aee19486bca7713627278410d373", + "self_attn.o_proj.weight": "607f1bd80abb8a599c6b66c669658355b73eb737edc5366d0e1afc494609943f", + "self_attn.q_norm.weight": "a24069bc529bcd467f912646b8707018d31f4a0446da073b1b205c4db50ee145", + "self_attn.k_norm.weight": "9dab9cd5fae1f8d67c448cfcf98e579cbcfc38d8c416771282eb1fe691b20022", + "input_layernorm.weight": "1ac54bb5ca0b83123b8cffdb4badce519a1ce5ddd669f6243d10f00b493d445d", + "post_attention_layernorm.weight": "394b5889e1bf81ccb8c96b48f7f760df70a5d0b24835ffa47bdf1e053daeecea" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "39f86798d44a14cf29c0724dc84fe0261eb909a05cd405ac91ac7d141f235a4e", + "self_attn.k_proj.weight": "e23576863e9742419b554ec91e06851542fa31624588dd0b0865c98ca756ef07", + "self_attn.v_proj.weight": "32df6f78cdcbd2eb1155384475ea6ded1079aee19486bca7713627278410d373", + "self_attn.o_proj.weight": "607f1bd80abb8a599c6b66c669658355b73eb737edc5366d0e1afc494609943f", + "self_attn.q_norm.weight": "a24069bc529bcd467f912646b8707018d31f4a0446da073b1b205c4db50ee145", + "self_attn.k_norm.weight": "9dab9cd5fae1f8d67c448cfcf98e579cbcfc38d8c416771282eb1fe691b20022", + "input_layernorm.weight": "1ac54bb5ca0b83123b8cffdb4badce519a1ce5ddd669f6243d10f00b493d445d", + "post_attention_layernorm.weight": "394b5889e1bf81ccb8c96b48f7f760df70a5d0b24835ffa47bdf1e053daeecea" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "39f86798d44a14cf29c0724dc84fe0261eb909a05cd405ac91ac7d141f235a4e", + "self_attn.k_proj.weight": "e23576863e9742419b554ec91e06851542fa31624588dd0b0865c98ca756ef07", + "self_attn.v_proj.weight": "32df6f78cdcbd2eb1155384475ea6ded1079aee19486bca7713627278410d373", + "self_attn.o_proj.weight": "607f1bd80abb8a599c6b66c669658355b73eb737edc5366d0e1afc494609943f", + "self_attn.q_norm.weight": "a24069bc529bcd467f912646b8707018d31f4a0446da073b1b205c4db50ee145", + "self_attn.k_norm.weight": "9dab9cd5fae1f8d67c448cfcf98e579cbcfc38d8c416771282eb1fe691b20022", + "input_layernorm.weight": "1ac54bb5ca0b83123b8cffdb4badce519a1ce5ddd669f6243d10f00b493d445d", + "post_attention_layernorm.weight": "394b5889e1bf81ccb8c96b48f7f760df70a5d0b24835ffa47bdf1e053daeecea" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 24, + "teacher_boundary_original_layer": 26 + }, + "lambda_init": "come", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "come", + "prior_mean": 1.0 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 1.0, + "per_tensor_mean": { + "mlp.gate_proj.weight": 1.0, + "mlp.up_proj.weight": 1.0, + "mlp.down_proj.weight": 1.0 + } + }, + "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": 1, + "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": 22.97254299093038, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 3.9478763937950134e-05, + "fit": 295.6214603590779, + "materialize_save_layer": 0.4516429351642728, + "metadata_write": 0.0011811568401753902, + "teacher_snapshot": 0.40654892986640334, + "cycle_cleanup": 0.22615320794284344, + "cycle_total": 319.68031796766445 + }, + "tracked_component_total_seconds": 319.6795690585859, + "cycle_total_seconds": 319.68031796766445, + "ratios_of_tracked_components": { + "selection": 0.07186115477627013, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.2349479841395518e-07, + "fit": 0.9247430520181319, + "materialize_save_layer": 0.001412798873867046, + "metadata_write": 3.6948149162417263e-06, + "teacher_snapshot": 0.001271738857330283, + "cycle_cleanup": 0.0007074371646859846 + }, + "ratios_of_cycle_total": { + "selection": 0.07186098642849212, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.234945091050097e-07, + "fit": 0.924740885639947, + "materialize_save_layer": 0.0014127955641296513, + "metadata_write": 3.6948062604681962e-06, + "teacher_snapshot": 0.0012717358780515403, + "cycle_cleanup": 0.0007074355073862219 + } + }, + "recipient_original_layer": 25, + "removed_original_layer": 26, + "recipient_side": "left", + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 28, + 29, + 31, + 33, + 34, + 35 + ], + "fisher_computed": false, + "merge_initializer": "come", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 26 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_7/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_7/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..94dc06cd72794cb03029e6b6866eb1c9e0be08b7 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_7/cycle_metadata.json @@ -0,0 +1,506 @@ +{ + "cycle": 7, + "layer_merged": 18, + "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": "come", + "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": 1, + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 0.23740315356757863, + "mean_abs": 5.882513101419641e-06, + "max_abs": 0.027914047241210938 + }, + "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": 150994944, + "mean": 1.3507076851561174e-06, + "std": 0.003134056113070226, + "rms": 0.0031340564041325266, + "mean_abs": 0.002464224429180225, + "min": -0.029158497229218483, + "max": 0.030568668618798256, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 4.040793404177141e-06, + "std": 0.0028221248657079863, + "rms": 0.0028221277585642104, + "mean_abs": 0.002228420072545608, + "min": -0.029158497229218483, + "max": 0.030568668618798256 + }, + "mlp.up_proj.weight": { + "mean": -6.914443323087956e-07, + "std": 0.003002453443705404, + "rms": 0.003002453523322835, + "mean_abs": 0.002365610251824061, + "min": -0.025998085737228394, + "max": 0.022817036136984825 + }, + "mlp.down_proj.weight": { + "mean": 7.027739836000061e-07, + "std": 0.003533807563180072, + "rms": 0.003533807633060967, + "mean_abs": 0.0027986429631710052, + "min": -0.02480441704392433, + "max": 0.022958504036068916 + } + } + }, + "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": 277.19303956301883, + "dataset_tokens": 524288, + "tokens_per_second": 1891.418344510072, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 35199262720, + "peak_reserved_bytes": 46567260160, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 20 + ], + [ + 21 + ] + ], + "retention_ratios": [ + 0.47186972247563475, + 0.5281302775243653 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 5798, + 6490 + ], + "pair_score": 0.1278106997859605, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "100c474fa668596c16128a59e841aa485f057f3767c68833a4766a06e067a114", + "self_attn.k_proj.weight": "df3000d47df027011761b871c1d47491a2f13c4dd3363175be9e93970d1f9be5", + "self_attn.v_proj.weight": "bb7a683a3151ecc3ca6739b59f54dfcbdc6d328334af50213c274a5c4226ba18", + "self_attn.o_proj.weight": "663b0ca3ae6bbbb3c613ee1f9af319eec3b35f0dbc01efc7b6d774625a8db0e8", + "self_attn.q_norm.weight": "5aee4fb2de6a7f64cd3162db26cc0a06e004f6e91f8d1bfb0bb33a18e3c72eec", + "self_attn.k_norm.weight": "c27266ee8a88066155b72fae60bf106ecbce5880cc8a3d37dfce5e7a6b671567", + "input_layernorm.weight": "34a032c26054d427bf876a4574e76d16fe6275d6f951c1ff686f89def2c68581", + "post_attention_layernorm.weight": "2331ab53730e845fdf782fc2d6aab39a66b8e7bb31afed5212594790002946a0" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "100c474fa668596c16128a59e841aa485f057f3767c68833a4766a06e067a114", + "self_attn.k_proj.weight": "df3000d47df027011761b871c1d47491a2f13c4dd3363175be9e93970d1f9be5", + "self_attn.v_proj.weight": "bb7a683a3151ecc3ca6739b59f54dfcbdc6d328334af50213c274a5c4226ba18", + "self_attn.o_proj.weight": "663b0ca3ae6bbbb3c613ee1f9af319eec3b35f0dbc01efc7b6d774625a8db0e8", + "self_attn.q_norm.weight": "5aee4fb2de6a7f64cd3162db26cc0a06e004f6e91f8d1bfb0bb33a18e3c72eec", + "self_attn.k_norm.weight": "c27266ee8a88066155b72fae60bf106ecbce5880cc8a3d37dfce5e7a6b671567", + "input_layernorm.weight": "34a032c26054d427bf876a4574e76d16fe6275d6f951c1ff686f89def2c68581", + "post_attention_layernorm.weight": "2331ab53730e845fdf782fc2d6aab39a66b8e7bb31afed5212594790002946a0" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "100c474fa668596c16128a59e841aa485f057f3767c68833a4766a06e067a114", + "self_attn.k_proj.weight": "df3000d47df027011761b871c1d47491a2f13c4dd3363175be9e93970d1f9be5", + "self_attn.v_proj.weight": "bb7a683a3151ecc3ca6739b59f54dfcbdc6d328334af50213c274a5c4226ba18", + "self_attn.o_proj.weight": "663b0ca3ae6bbbb3c613ee1f9af319eec3b35f0dbc01efc7b6d774625a8db0e8", + "self_attn.q_norm.weight": "5aee4fb2de6a7f64cd3162db26cc0a06e004f6e91f8d1bfb0bb33a18e3c72eec", + "self_attn.k_norm.weight": "c27266ee8a88066155b72fae60bf106ecbce5880cc8a3d37dfce5e7a6b671567", + "input_layernorm.weight": "34a032c26054d427bf876a4574e76d16fe6275d6f951c1ff686f89def2c68581", + "post_attention_layernorm.weight": "2331ab53730e845fdf782fc2d6aab39a66b8e7bb31afed5212594790002946a0" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 19, + "teacher_boundary_original_layer": 21 + }, + "lambda_init": "come", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "come", + "prior_mean": 1.0 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 1.0, + "per_tensor_mean": { + "mlp.gate_proj.weight": 1.0, + "mlp.up_proj.weight": 1.0, + "mlp.down_proj.weight": 1.0 + } + }, + "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": 1, + "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": 22.65331547195092, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 4.218379035592079e-05, + "fit": 277.32526935311034, + "materialize_save_layer": 0.45385627914220095, + "metadata_write": 0.001124703325331211, + "teacher_snapshot": 0.34231374505907297, + "cycle_cleanup": 0.1763214492239058, + "cycle_total": 300.95303361164406 + }, + "tracked_component_total_seconds": 300.95224318560213, + "cycle_total_seconds": 300.95303361164406, + "ratios_of_tracked_components": { + "selection": 0.07527212700647741, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.401677219927062e-07, + "fit": 0.9214926143018624, + "materialize_save_layer": 0.0015080674406613426, + "metadata_write": 3.737148836061635e-06, + "teacher_snapshot": 0.0011374354330629213, + "cycle_cleanup": 0.0005858785013779262 + }, + "ratios_of_cycle_total": { + "selection": 0.07527192931101409, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.401673538548065e-07, + "fit": 0.9214901940844914, + "materialize_save_layer": 0.0015080634798580112, + "metadata_write": 3.7371390207767477e-06, + "teacher_snapshot": 0.0011374324456911826, + "cycle_cleanup": 0.0005858769626208008 + } + }, + "recipient_original_layer": 20, + "removed_original_layer": 21, + "recipient_side": "left", + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 18, + 19, + 20, + 22, + 23, + 24, + 25, + 28, + 29, + 31, + 33, + 34, + 35 + ], + "fisher_computed": false, + "merge_initializer": "come", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 21 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_8/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_8/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..30444908ec67e786a6e46f66f57feb95b739f892 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_8/cycle_metadata.json @@ -0,0 +1,506 @@ +{ + "cycle": 8, + "layer_merged": 23, + "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": "come", + "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": 1, + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 6.49169853930633, + "mean_abs": 9.474362013861537e-05, + "max_abs": 1.5315284729003906 + }, + "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": 150994944, + "mean": 4.591499305206526e-06, + "std": 0.0027378081098337064, + "rms": 0.002737811959966769, + "mean_abs": 0.0021497576704455745, + "min": -0.032534871250391006, + "max": 0.03337450698018074, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.311179221374914e-05, + "std": 0.0026171782407182786, + "rms": 0.0026172110848734155, + "mean_abs": 0.002076787098000447, + "min": -0.022585367783904076, + "max": 0.024974439293146133 + }, + "mlp.up_proj.weight": { + "mean": 6.339674503882028e-07, + "std": 0.002621912470452202, + "rms": 0.0026219125470975375, + "mean_abs": 0.0020654979161918163, + "min": -0.01963549107313156, + "max": 0.021688615903258324 + }, + "mlp.down_proj.weight": { + "mean": 2.873825148223356e-08, + "std": 0.002960172919978422, + "rms": 0.002960172920117922, + "mean_abs": 0.0023069879971444607, + "min": -0.032534871250391006, + "max": 0.03337450698018074 + } + } + }, + "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": 267.72440619114786, + "dataset_tokens": 524288, + "tokens_per_second": 1958.3123087615434, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 33519681536, + "peak_reserved_bytes": 45397049344, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 28 + ], + [ + 29, + 30 + ] + ], + "retention_ratios": [ + 0.46346630280250284, + 0.5365336971974971 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 5695, + 6593 + ], + "pair_score": 0.13028502202731498, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "36252b41be52e81d520f07dfc5c92c7933266cc8b572ca413af64b3d6d715629", + "self_attn.k_proj.weight": "da2a0f50a824c4ed95a852d28a0729890e6df83eeea7dcaed1383ee0a17c41c7", + "self_attn.v_proj.weight": "a097c0995b19020bc7d3bf86b42791bb50e8b0a0965f1c9d575fca0804816eec", + "self_attn.o_proj.weight": "2fd02a6653ed46d24683bacdf5074072c9e4564bc9e10224082af2787419a7e5", + "self_attn.q_norm.weight": "984494fcfbe0781014b23dc6f76c39fcc7a024d5474c3e993da11f808c4c6e5b", + "self_attn.k_norm.weight": "6a7a2aa47fc5932c85a04ec3f8126eec8459cbe3dda0f027ea100b437d4e5af7", + "input_layernorm.weight": "bef856a0d4f111bad8496c0bed2bfb65efbef1580f074bc4d9929d8185e8e9b7", + "post_attention_layernorm.weight": "4e0f51ab4f79e73bd1ca169a404e5308778535c28228aedb026fef9993e650c3" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "36252b41be52e81d520f07dfc5c92c7933266cc8b572ca413af64b3d6d715629", + "self_attn.k_proj.weight": "da2a0f50a824c4ed95a852d28a0729890e6df83eeea7dcaed1383ee0a17c41c7", + "self_attn.v_proj.weight": "a097c0995b19020bc7d3bf86b42791bb50e8b0a0965f1c9d575fca0804816eec", + "self_attn.o_proj.weight": "2fd02a6653ed46d24683bacdf5074072c9e4564bc9e10224082af2787419a7e5", + "self_attn.q_norm.weight": "984494fcfbe0781014b23dc6f76c39fcc7a024d5474c3e993da11f808c4c6e5b", + "self_attn.k_norm.weight": "6a7a2aa47fc5932c85a04ec3f8126eec8459cbe3dda0f027ea100b437d4e5af7", + "input_layernorm.weight": "bef856a0d4f111bad8496c0bed2bfb65efbef1580f074bc4d9929d8185e8e9b7", + "post_attention_layernorm.weight": "4e0f51ab4f79e73bd1ca169a404e5308778535c28228aedb026fef9993e650c3" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "36252b41be52e81d520f07dfc5c92c7933266cc8b572ca413af64b3d6d715629", + "self_attn.k_proj.weight": "da2a0f50a824c4ed95a852d28a0729890e6df83eeea7dcaed1383ee0a17c41c7", + "self_attn.v_proj.weight": "a097c0995b19020bc7d3bf86b42791bb50e8b0a0965f1c9d575fca0804816eec", + "self_attn.o_proj.weight": "2fd02a6653ed46d24683bacdf5074072c9e4564bc9e10224082af2787419a7e5", + "self_attn.q_norm.weight": "984494fcfbe0781014b23dc6f76c39fcc7a024d5474c3e993da11f808c4c6e5b", + "self_attn.k_norm.weight": "6a7a2aa47fc5932c85a04ec3f8126eec8459cbe3dda0f027ea100b437d4e5af7", + "input_layernorm.weight": "bef856a0d4f111bad8496c0bed2bfb65efbef1580f074bc4d9929d8185e8e9b7", + "post_attention_layernorm.weight": "4e0f51ab4f79e73bd1ca169a404e5308778535c28228aedb026fef9993e650c3" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 24, + "teacher_boundary_original_layer": 29 + }, + "lambda_init": "come", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "come", + "prior_mean": 1.0 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 1.0, + "per_tensor_mean": { + "mlp.gate_proj.weight": 1.0, + "mlp.up_proj.weight": 1.0, + "mlp.down_proj.weight": 1.0 + } + }, + "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": 1, + "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": 22.0020357160829, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 3.937911242246628e-05, + "fit": 267.8838376621716, + "materialize_save_layer": 0.4269840628840029, + "metadata_write": 0.001085143070667982, + "teacher_snapshot": 0.3373063183389604, + "cycle_cleanup": 0.1763750296086073, + "cycle_total": 290.8283663219772 + }, + "tracked_component_total_seconds": 290.82766331126913, + "cycle_total_seconds": 290.8283663219772, + "ratios_of_tracked_components": { + "selection": 0.07565317365471662, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.354035994172924e-07, + "fit": 0.9211085170239082, + "materialize_save_layer": 0.0014681686673905135, + "metadata_write": 3.731223702425334e-06, + "teacher_snapshot": 0.0011598151100844412, + "cycle_cleanup": 0.0006064589165984371 + }, + "ratios_of_cycle_total": { + "selection": 0.07565299078056355, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.3540327211022293e-07, + "fit": 0.9211062904558502, + "materialize_save_layer": 0.0014681651184303226, + "metadata_write": 3.7312146830499194e-06, + "teacher_snapshot": 0.001159812306498078, + "cycle_cleanup": 0.0006064574506234436 + } + }, + "recipient_original_layer": 28, + "removed_original_layer": 29, + "recipient_side": "left", + "active_original_layers": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 18, + 19, + 20, + 22, + 23, + 24, + 25, + 28, + 31, + 33, + 34, + 35 + ], + "fisher_computed": false, + "merge_initializer": "come", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 29 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_9/cycle_metadata.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_9/cycle_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..9d6ec359dd32f19008d273f0066faf6a136ff242 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/stage_metadata/cycle_9/cycle_metadata.json @@ -0,0 +1,504 @@ +{ + "cycle": 9, + "layer_merged": 16, + "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": "come", + "fisher_computed": false + }, + "fisher_num_batches": 0, + "merge_method": "reparam", + "merged_params": 3, + "num_sequences": 64, + "teacher_source": "previous_cycle_memory", + "teacher_cycle": 8, + "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": 1, + "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.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.up_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + }, + "mlp.down_proj.weight": { + "mean": 0.9998999834060669, + "std": 0.0, + "min": 0.9998999834060669, + "max": 0.9998999834060669, + "mean_abs_from_0_5": 0.4998999834060669 + } + } + }, + "lambda_final_summary": { + "num_tensors": 3, + "num_elements": 3, + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.up_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + }, + "mlp.down_proj.weight": { + "mean": 1.0, + "std": 0.0, + "min": 1.0, + "max": 1.0, + "mean_abs_from_0_5": 0.5 + } + } + }, + "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": 150994944, + "l2": 0.5486992756018507, + "mean_abs": 7.279721204314329e-06, + "max_abs": 0.08547437191009521 + }, + "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": 150994944, + "mean": -2.401146111373641e-06, + "std": 0.0028625390829901984, + "rms": 0.00286254009005097, + "mean_abs": 0.002229874281005727, + "min": -0.031118491664528847, + "max": 0.03590920567512512, + "per_tensor": { + "mlp.gate_proj.weight": { + "mean": -7.017540459249479e-06, + "std": 0.0026435958450601446, + "rms": 0.0026436051592273304, + "mean_abs": 0.0020676087588071823, + "min": -0.026987718418240547, + "max": 0.029445279389619827 + }, + "mlp.up_proj.weight": { + "mean": -3.4636233673760824e-07, + "std": 0.0026137689593844203, + "rms": 0.0026137689823334392, + "mean_abs": 0.0020307997862497964, + "min": -0.03019127808511257, + "max": 0.026006054133176804 + }, + "mlp.down_proj.weight": { + "mean": 1.6046446186616473e-07, + "std": 0.0032805442756951874, + "rms": 0.0032805442796196645, + "mean_abs": 0.0025912142979602018, + "min": -0.031118491664528847, + "max": 0.03590920567512512 + } + } + }, + "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": 251.94926179386675, + "dataset_tokens": 524288, + "tokens_per_second": 2080.92691467756, + "batch_size": 1, + "batches_per_epoch": 512, + "grad_accumulation": 1, + "peak_allocated_bytes": 33655689216, + "peak_reserved_bytes": 44226838528, + "gpu_total_bytes": 85094825984, + "actual_forward_shapes": { + "teacher:1x1024": 512, + "student:1x1024": 512 + } + }, + "ablation": { + "lambda": null, + "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": "CoMe_channel_merge", + "norm_initialization": "CoMe_pair_mean", + "CoMe": { + "source_lineage": [ + [ + 18 + ], + [ + 19 + ] + ], + "retention_ratios": [ + 0.43171495242956137, + 0.5682850475704386 + ], + "retained_attention_groups": [ + 3, + 5 + ], + "retained_mlp_neurons": [ + 5304, + 6984 + ], + "pair_score": 0.13059031313404124, + "minimum_retention": 0.0, + "adjusted_minimum": 0.0, + "power": 1.0, + "allow_repeat": true, + "sbi_metric": "angular_last", + "calibration_padding": "trim_right_padding_before_native_CoMe_scoring", + "teacher_mutated_during_initialization": false + }, + "norms_trainable": false, + "attention_norm_initialization": "CoMe_retention_weighted_QK", + "initialized_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "mlp.gate_proj.weight", + "mlp.up_proj.weight", + "mlp.down_proj.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_CoMe_parameters": [ + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "self_attn.q_norm.weight", + "self_attn.k_norm.weight", + "input_layernorm.weight", + "post_attention_layernorm.weight" + ], + "frozen_attention_norm_expected_sha256": { + "self_attn.q_proj.weight": "f2a853932fea15a5a825782f208d6ca3f77ccf896addd4d9e56f0e8e9082fe6b", + "self_attn.k_proj.weight": "5575d2b5c9f9213078cee249df0db1a0d912c10900df8a7636095e4835a61217", + "self_attn.v_proj.weight": "9f294925ca5d2ae3ada26843af7fde6baa73c1a158e80d0baf14a4871dffb000", + "self_attn.o_proj.weight": "cb2a380e6bebe924e97bca438e8be51a7557b79f87c3a9eff7f3d94816a19401", + "self_attn.q_norm.weight": "92f79f4e9257476501577f2a7519154db20b0859e33b071a9498bb47136dce8f", + "self_attn.k_norm.weight": "6714e2b2f504289ad5c98deb930db2b2ba947ad86b1bc6fe814f461ae93ef273", + "input_layernorm.weight": "0b6edcbe6fc1e1bf40352a8291be48de9315be9a8b60b0e5f6f79e926527c90c", + "post_attention_layernorm.weight": "dba76b7f863c3425bdc928b6d785d9d8b414258c7d2cac5c591cadce3d89bba5" + }, + "frozen_attention_norm_before_sha256": { + "self_attn.q_proj.weight": "f2a853932fea15a5a825782f208d6ca3f77ccf896addd4d9e56f0e8e9082fe6b", + "self_attn.k_proj.weight": "5575d2b5c9f9213078cee249df0db1a0d912c10900df8a7636095e4835a61217", + "self_attn.v_proj.weight": "9f294925ca5d2ae3ada26843af7fde6baa73c1a158e80d0baf14a4871dffb000", + "self_attn.o_proj.weight": "cb2a380e6bebe924e97bca438e8be51a7557b79f87c3a9eff7f3d94816a19401", + "self_attn.q_norm.weight": "92f79f4e9257476501577f2a7519154db20b0859e33b071a9498bb47136dce8f", + "self_attn.k_norm.weight": "6714e2b2f504289ad5c98deb930db2b2ba947ad86b1bc6fe814f461ae93ef273", + "input_layernorm.weight": "0b6edcbe6fc1e1bf40352a8291be48de9315be9a8b60b0e5f6f79e926527c90c", + "post_attention_layernorm.weight": "dba76b7f863c3425bdc928b6d785d9d8b414258c7d2cac5c591cadce3d89bba5" + }, + "frozen_attention_norm_after_sha256": { + "self_attn.q_proj.weight": "f2a853932fea15a5a825782f208d6ca3f77ccf896addd4d9e56f0e8e9082fe6b", + "self_attn.k_proj.weight": "5575d2b5c9f9213078cee249df0db1a0d912c10900df8a7636095e4835a61217", + "self_attn.v_proj.weight": "9f294925ca5d2ae3ada26843af7fde6baa73c1a158e80d0baf14a4871dffb000", + "self_attn.o_proj.weight": "cb2a380e6bebe924e97bca438e8be51a7557b79f87c3a9eff7f3d94816a19401", + "self_attn.q_norm.weight": "92f79f4e9257476501577f2a7519154db20b0859e33b071a9498bb47136dce8f", + "self_attn.k_norm.weight": "6714e2b2f504289ad5c98deb930db2b2ba947ad86b1bc6fe814f461ae93ef273", + "input_layernorm.weight": "0b6edcbe6fc1e1bf40352a8291be48de9315be9a8b60b0e5f6f79e926527c90c", + "post_attention_layernorm.weight": "dba76b7f863c3425bdc928b6d785d9d8b414258c7d2cac5c591cadce3d89bba5" + }, + "frozen_attention_norm_unchanged": true, + "source_feature_transport": false, + "initializer": "come", + "removed_count_per_cycle": 1, + "teacher_boundary_current_layer": 17, + "teacher_boundary_original_layer": 19 + }, + "lambda_init": "come", + "fisher_prior_input_summary": { + "computed": false, + "initializer": "come", + "prior_mean": 1.0 + } + }, + "reparam_gate_summary": { + "num_tensors": 3, + "num_elements": 3, + "global_mean": 1.0, + "per_tensor_mean": { + "mlp.gate_proj.weight": 1.0, + "mlp.up_proj.weight": 1.0, + "mlp.down_proj.weight": 1.0 + } + }, + "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": 1, + "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": 21.38497394369915, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 3.699399530887604e-05, + "fit": 252.14623595401645, + "materialize_save_layer": 0.47099668998271227, + "metadata_write": 0.0010089501738548279, + "teacher_snapshot": 0.2863558158278465, + "cycle_cleanup": 0.14028824819251895, + "cycle_total": 274.43056627037004 + }, + "tracked_component_total_seconds": 274.42989659588784, + "cycle_total_seconds": 274.43056627037004, + "ratios_of_tracked_components": { + "selection": 0.07792508837034483, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.3480308001336895e-07, + "fit": 0.9188001711246306, + "materialize_save_layer": 0.0017162732480137876, + "metadata_write": 3.6765315527577484e-06, + "teacher_snapshot": 0.0010434570700200358, + "cycle_cleanup": 0.0005111988523579143 + }, + "ratios_of_cycle_total": { + "selection": 0.07792489821498452, + "rebase": 0.0, + "source_feature_transport": 0.0, + "fisher": 1.3480275106246515e-07, + "fit": 0.9187979290382727, + "materialize_save_layer": 0.0017162690599074322, + "metadata_write": 3.676522581164688e-06, + "teacher_snapshot": 0.0010434545237418184, + "cycle_cleanup": 0.0005111976049136831 + } + }, + "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, + 18, + 20, + 22, + 23, + 24, + 25, + 28, + 31, + 33, + 34, + 35 + ], + "fisher_computed": false, + "merge_initializer": "come", + "fixed_span_merge_only": false, + "removed_original_layers": [ + 19 + ] +} diff --git a/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/training_elapsed.json b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/training_elapsed.json new file mode 100644 index 0000000000000000000000000000000000000000..cd9b2d7dc8e06541d65cb474e20c32fa24c9b8c3 --- /dev/null +++ b/runs/vast-paper_revision-come-attn-fit-20261126-62646539/20261126-qwen3-base-mka-come-mlp-fit/come/training_elapsed.json @@ -0,0 +1,4 @@ +{ + "wall_seconds": 2727.9755203723907, + "completed_utc": "2026-11-26T10:41:13Z" +}