feat: Phase 41 — Multi-Head Latent Attention (MLA) - #48
Merged
Conversation
Add a third attention kind (LatentMLA) to the HybridAttentionSchedule, completing the attention family v3 began (Gated DeltaNet = linear, DSA = sparse, MLA = latent KV compression). MLA layers cache a single low-rank latent vector (c_kv) plus a small dedicated rotary key slice per token, reconstructing per-head keys and values at attention time through trained up-projection weights that are never cached — cutting KV-cache memory per token substantially at long context without discarding per-head expressiveness. A schedule with zero MLA layers reproduces v3.0.0 exactly. See ROADMAP_V4.md §41, ARCHITECTURE_V4.md §55, SELF_LEARNING_V4.md §42.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Implements Phase 41 — Multi-Head Latent Attention (MLA) from
ROADMAP_V4.md§41 (ARCHITECTURE_V4.md§55). MLA is the third andfinal attention kind in the v4 hybrid schedule, completing the family v3
began: Gated DeltaNet (linear), DSA (sparse), and now MLA
(latent KV compression). MLA layers cache a single low-rank latent
vector (
c_kv) plus a small dedicated rotary key slice per token, andreconstruct per-head keys and values at attention time through trained
up-projection weights that are never cached — cutting KV-cache
memory per token substantially at long context while preserving
per-head expressiveness.
A schedule with zero
mla_layersreproduces v3.0.0 exactly, holdingthe backward-compatibility discipline every attention change since v1
has kept.
Bumps the workspace version 3.0.0 → 4.0.0-alpha.1 (the Phase 41
milestone tag).
What changed
aarambh-studio-coreAttentionKind::LatentMLAvariant.QatTarget::Mlavariant (added toQatConfig::default().targets).MlaConfig { latent_dim, nope_head_dim, rope_head_dim, n_heads, value_head_dim }withresolve()/validate()/cache_width().HybridAttentionScheduleextended withmla_layers: Vec<usize>andmla: Option<MlaConfig>.kind_for_layergives MLA precedenceover both the
full_attention_every_nrule and the DSA override.New
validate()+resolved_mla()helpers.aarambh-studio-nn(newmla.rs)MlaCache— compressedc_kvlatent +k_ropeslice, dynamic andpreallocated paths (mirror of
KVCache).MlaAttentionwith decoupled RoPE (dedicatedrope_head_dimRoPE cache; the host transformer's head-dim RoPE is not reused because
a compressed latent cannot carry an already-rotated key). Projections:
q_proj,kv_a_proj(down →c_kv),kv_a_norm(RMSNorm over thelatent),
up_k/up_v(per-head up-projection weights, trained butnever cached),
k_rope_proj(rotary key slice, shared across heads,cached),
o_proj.Methods:
forward,forward_train,forward_decode_batch,forward_with_capture,named_tensors,get_weight.TokenMixer::Mla+HybridKvCache::Mlawired throughblock.rs,kvcache.rs,lib.rs(as_mla/as_mla_mutaccessors). Reuses thecandle fallback attention kernel, which tolerates
value_head_dim != nope_head_dim + rope_head_dim.aarambh-studio-modelbuild_mla()helper +LatentMLAbuild arm.empty_kv_cache_with_capacity()allocatesMlaCachefor MLA layers.insert_mixer_tensors()exportsblocks.{i}.mla.*checkpoint names.get_weight()resolves themla.prefix.kv_cache_report()+KvCacheLayerReportpowering--kv-cache-report.aarambh-studio-weightsRetrofitLoadReport.initialized_mla_tensors..mla.tensor init path inload_retrofit_into_varmap_with_moe(shared tensors still load bit-exactly; MLA tensors are freshly
initialised, same pattern as
.deltanet./.dsa.).aarambh-studio(CLI)eval --kv-cache-reportflag +run_kv_cache_report()— printsper-layer bytes/token by attention kind. No checkpoint required,
only the config.
Configs / scripts / docs
configs/mla_smoke.toml,configs/medium_hybrid_mla.toml,configs/large_hybrid_mla.toml.scripts/phase41_prepare_mla_retrofit.sh,scripts/phase41_smoke.sh.docs/phase41_mla.md(new).CHANGELOG.md§4.0.0-alpha.1; README (MLA capability row + version +docs links);
ROADMAP_V4.md§41 status note;ARCHITECTURE_V4.md§55status note;
SELF_LEARNING_V4.md§42 status note.Backward compatibility
A schedule with an empty
mla_layersand nomlablock reproducesv3.0.0
kind_for_layerexactly, andresolved_mla()returnsNone—verified by
schedule_with_zero_mla_layers_matches_v3_exactly. Fiveexisting
HybridAttentionScheduleconstruction sites in tests wereupdated with the new (defaulted) fields; behaviour unchanged.
Tests
All roadmap-required Phase 41 proof obligations are implemented and pass:
schedule_with_zero_mla_layers_matches_v3_exactlymla_layers== v3.0.0mla_layers_take_precedence_over_every_n_and_dsa_overridemla_config_resolves_derived_dimensions/_rejects_odd_rope_head_dimmla_reconstructed_kv_matches_reference_full_attention_within_tolerancedecoupled_rope_nope_split_preserves_relative_position_encodingmla_kv_cache_bytes_per_token_is_smaller_than_full_or_gqa_baseline(latent_dim + rope_head_dim) < 2 * n_kv_heads * head_dimpartial_checkpoint_load_preserves_non_mla_layer_weights_exactlymla_model_forwards_and_cached_forward_matches_full_forwardmla_training_backward_reaches_mla_parameterskv_a_proj/kv_a_norm/up_v/o_proj(SELF_LEARNING_V4 §42 reachability)mla_kv_cache_report_shows_compressed_footprint--kv-cache-reportreports the compressed MLA footprintCI gates (all green locally)
cargo fmt --all --checkcargo check --workspace --all-targets --lockedcargo clippy --workspace --all-targets --locked -- -D warnings -D clippy::undocumented_unsafe_blockscargo test --workspace --no-fail-fast --locked→ 444 passed, 0 failedRUSTDOCFLAGS="-D warnings -D missing_docs" cargo doc --workspace --no-deps --lockedscripts/phase28_release_audit.sh→ passed foraarambh-studio 4.0.0-alpha.1find scripts -name '*.sh' | bash -ncargo build --release -p aarambh-studio --locked--version+ all 10 subcommand--help+eval --kv-cache-reportMLA smoke (verified end-to-end)
mla_smoke.toml): loss 4.91 → 4.73, ppl 136 → 113.blocks.0.mla.*tensors +blocks.1.deltanet.*(verified via safetensors header parse).1024-element GQA baseline — a ~1.94× reduction on retrofitted layers.
How to review
git fetch && git checkout feat/phase-41-mlacargo test --workspace --no-fail-fast --locked(444 pass)cargo run -p aarambh-studio -- eval --config configs/mla_smoke.toml --kv-cache-reportdocs/phase41_mla.mdfor the full mechanism, config, and retrofit recipe.Scope / non-goals
fallback attention path (mechanism + memory win are in place).
full-attention layers; MLA's dedicated
rope_head_dimslice uses base RoPE.multi-node, test-time scaling, RLAIF, tool execution, multi-agent, RAG,
model merging, public server, chat templating, red-team, model card, final
release) remain on the v4 roadmap.
Refs:
ROADMAP_V4.md§41 ·ARCHITECTURE_V4.md§55 ·SELF_LEARNING_V4.md§42