Skip to content

feat: store a quantized MLA latent in Kimi Linear and Kimi K3 - #3174

Merged
inureyes merged 5 commits into
mainfrom
feature/issue-3162-kimi-quantized-latent
Nov 19, 2026
Merged

inureyes merged 5 commits into
mainfrom
feature/issue-3162-kimi-quantized-latent

Conversation

@inureyes

@inureyes inureyes commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Kimi Linear and Kimi K3 built their model-owned MLA caches fp16 with no mode table, so rule 1 of the KV mode resolver substituted every quantized request with fp16. This change ports the #3160 pattern to both hybrid KDA + MLA families.

  • Mode plumbing: both models (and the Kimi K3 VLM wrapper) implement set_kv_cache_layer_modes / kv_cache_layer_modes through KvCacheLayerModes; MLA layers build KVCache::new_with_mode from their table entry, KDA layers ignore theirs, and kv_cache_storage_modes reports what the builder stores. A Turbo entry builds fp16 (mla_batched::latent_pair_cache_mode).
  • Write and read: the MLA write goes through mla_batched::store_latent_step. A one-query absorbed step over a quantized window calls mla::quantized_absorbed_attention (fused perf: Read an int8 MLA latent inside the fused Metal decode kernel #3156 kernel when unmasked, composed otherwise) with the caller mask cast to the score dtype and added to the rope-score term; multi-token steps dequantize once. Batched decode opts into the quantized rows of mla_latent_decode_rows. fp16 caches keep the unchanged update_and_fetch path.
  • Allowlist and sizing: kimi_linear and kimi_k3 join mla::QUANTIZED_LATENT_FAMILIES, so the resolver keeps int8, the advisor recommends it and the registry lists fp16 and int8. kv_arch now charges the latent on MLA layers only (linear_attn_config.kda_layers); it charged all 27 layers of Kimi-Linear-48B before.
  • Activation dtype: LatentWindow::into_dense returns fp16, which MLX promotes against a bf16 query to float32; on the KDA hybrids that float32 then persisted in the recurrent state and slowed every later decode step. mla_batched::dense_latent_in casts the dense window back to the query dtype in both the Kimi Linear and Kimi K3 forwards.
  • These families opt out of APC (server::prompt_cache::hybrid_ssm) and do not implement snapshots, so there is no parked latent to carry.

Measurements

Measured on Kimi-Linear-48B-A3B (M3 Ultra; results in docs/benchmark_results/mla-quantized-latent-kimi-m3ultra-2026-11-19.md): 0 decided disagreements behind 1024 (0 / 201) and 4096 (0 / 52), so the gate passes and the family stays on int8. Five flips per prefix lie outside 0.11 (largest 0.500 and 0.312), within the int8 fused-against-composed noise (16 flips, largest 0.438); Kimi's fp16 decode has no kernel choice, so its own floor is zero. Perplexity +0.29% and -0.40%. int8 decode against fp16: +1.5% at 512, -4.7% at 2048, -23.3% at 16384, with prefill and peak unchanged. The first sweep found a bf16 to float32 promotion over the dequantized window (int8 decode 61% slower), fixed in the second commit with a test that fails without it. Kimi K3 is not measured: the only MLX export is an expert-pruned 2-bit conversion. CUDA and ROCm are not reachable from this host.

Test plan

  • models::kimi_linear::latent_tests and models::kimi_k3::latent_tests (new): int8 table builds int8 MLA caches with unchanged KDA state, masked and unmasked quantized decode tracks the fp16 latent and takes absorbed paths, batched decode over quantized rows matches single-row decode, no MLA cache is paged-backed, rank-512 runtime row size equals the kv_arch rate
  • Mode tables that differ on a KDA index alone leave the MLA cache mode unchanged (Kimi Linear and Kimi K3); bf16 layers keep bf16 over an int8 latent (both models; each fails with the cast reverted)
  • models::kimi_linear, models::kimi_k3, models::deepseek_v3, models::mla_batched, models::model_owned, models::registry, execution::kv_arch, execution::kv_cache_advisor, cli::turbo_args, server::cli_input, server::prompt_cache (Metal, serial)
  • mlxcel-core: mla:: and cache::turbo::allowlist
  • cargo fmt --all -- --check, clippy -D warnings on mlxcel-core and mlxcel (--lib --tests)
  • Kimi-Linear-48B trace and decode sweep

Closes #3162

Kimi Linear and Kimi K3 built their model-owned MLA caches fp16 with no mode table, and rule 1 of the KV mode resolver substituted every quantized request with fp16. Both now take the resolved per-layer table (`set_kv_cache_layer_modes`, forwarded by the Kimi K3 VLM wrapper) and build each MLA layer's cache in its mode; KDA layers ignore their entry. The MLA write goes through `mla_batched::store_latent_step`, so an int8 cache stores the #3155 affine group-64 latent. A single-token absorbed step over a quantized window calls `mla::quantized_absorbed_attention` (fused #3156 kernel when unmasked and short enough, composed otherwise, with the additive mask cast to the score dtype and added to the rope-score term); multi-token steps dequantize once. Batched decode opts into the quantized rows of `mla_latent_decode_rows`. fp16 caches take the unchanged `update_and_fetch` path.

`kimi_linear` and `kimi_k3` join `mla::QUANTIZED_LATENT_FAMILIES`, so the resolver keeps int8, the advisor recommends it, the registry lists fp16 and int8, and Turbo modes still resolve to fp16 (a table carrying one builds fp16 caches). `kv_arch` now counts only the MLA layers of a KDA hybrid (`linear_attn_config.kda_layers`); it charged every layer before.

Tests: tiny Kimi Linear and Kimi K3 models with an int8 table build int8 MLA caches and unchanged KDA state, masked and unmasked quantized decode tracks the fp16 latent, batched decode over quantized rows matches single-row decode, and the rank-512 runtime row size equals the `kv_arch` rate.

Refs #3162
Move Kimi Linear and Kimi K3 from the fp16-only latent-pair families to the quantized-latent ones in docs/turbo-kv-cache.md (mode table, advisor table, decision, limits), add the CHANGELOG entry, and add the results doc for Kimi-Linear-48B-A3B with the setup, the sizing correction (7 of 27 layers hold KV) and the Kimi K3 not-measured reason. The trace and decode sections are pending: the checkpoint was still downloading.

Refs #3162
@inureyes inureyes added type:enhancement New features, capabilities, or significant additions status:review Under review priority:low Low priority area:models Model architectures, weights, loading, metadata area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Nov 19, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Store the affine int8 MLA latent in the model-owned MLA layers of Kimi Linear, Kimi K3 and the K3 VLM, through the per-layer mode table, with sizing that counts only MLA layers.

Findings Addressed

None required a fix: no CRITICAL or HIGH findings.

Remaining Items

  • --kv-bits 8 sizing on a KDA hybrid whose last layer is KDA: fp16_last_layer_extra charges one fp16 MLA layer, but the runtime's fp16 entry would land on a KDA layer and be ignored, so the estimate is one layer's delta high (LOW, conservative; Kimi-Linear-48B ends on MLA layer 27, so it does not apply there)
  • The tests inject a uniform table; none puts a distinct mode only on a KDA index, and the K3 VLM forwarding of set_kv_cache_layer_modes has no direct test (LOW)
  • Logit traces, decode sweep and path counters on Kimi-Linear-48B are pending the checkpoint download (tracked by the PR, not a review finding)

Verification

  • All stated requirements implemented (measurements excepted, see above)
  • No placeholder/mock code remaining
  • Integrated into project code flow (scheduler and direct-engine injection, VLM forwarding, batched decode opt-in, allowlist, registry, advisor, kv_arch)
  • Project conventions followed (mirrors feat: store a quantized MLA latent in the DeepSeekV3Attention families #3172 and the bailing_moe_linear table plumbing)
  • Existing modules reused where applicable (store_latent_step, quantized_absorbed_attention, KvCacheLayerModes, LayerKv::stored_mode)
  • No unintended structural changes (fp16 path still update_and_fetch; non-MLA KV untouched)
  • Tests pass: clippy -p mlxcel --lib --tests -D warnings clean; 342 targeted lib tests (kv_arch, turbo_args, registry, allowlist, kimi, deepseek_v3_latent, mla_batched) pass serially on Metal

Checked specifically: kda_layers is 1-indexed in both model configs (is_linear_layer tests idx + 1) and in the real Kimi-Linear-48B config (20 KDA, 7 MLA of 27), matching the 1..=num_layers filter in kda_hybrid_mla_layers; the K3 nested text_config is covered by the sizing test; the masked one-token step casts the mask to the q_pe dtype and takes the composed path; multi-token steps dequantize once and run the dense code.

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review (ef68501)

No CRITICAL or HIGH findings, so no fix commits were pushed. Measurement sections were out of scope.

Checked:

  • kv_arch MLA-only layer counting: kda_hybrid_mla_layers dedupes through a HashSet, drops 0, out-of-range and non-integer entries, and uses saturating_sub, so the count stays in 0..=num_layers and matches the model's kda_layers.contains(&(idx + 1)) rule. fp16_last_layer_extra skips zero-layer groups and the byte math saturates. cargo test -p mlxcel --lib kv_arch passes (48 tests).
  • Mode tables of the wrong length: KvCacheLayerModes::mode_for_layer falls back to fp16 for a missing index, and latent_pair_cache_mode builds fp16 for any mode the latent layout refuses, so a Turbo entry cannot reach a latent cache. No new panic or assert depends on user input.
  • Rank and group constraints: a rank that is not a multiple of 64, or a paged-backed cache, is refused by MlaLatentCache::supports with an Err and falls back to the per-token path with a one-time warning. Sizing applies the same rule through rank_quantizable.
  • No new unsafe in non-test code.
  • Decode hot path: the quantized branch runs only for an absorbed single query, does not dequantize the window, and computes embed_q once. Prefill and other multi-token steps dequantize once per step, as in feat: Store a quantized MLA latent in the DeepSeekV3Attention families #3160. Batched decode passes select = None, which the quantized-row assert requires.

LOW, not fixed:

  • mla_mask_in_dtype and cast_to copy the mask even when its dtype already matches, adding one graph copy per MLA layer on masked single-query steps. The dense path already did this, and unmasked decode passes None.
  • With --kv-bits 8, the fp16 last-layer sizing assumes the last layer is MLA. If it is KDA, the estimate is one layer too high, which errs on the safe side.
  • Older code outside this diff: kda_layers[0] - 1 (src/models/kimi_linear.rs, ssm_layer_idx) underflows on a config whose first entry is 0. That panics in debug builds and wraps in release, but the value is unused (_ssm_layer_idx). This belongs in a separate cleanup.

The first Kimi-Linear-48B sweep decoded int8 61% slower than fp16, with prefill 14% to 21% slower and 7.9 GB of buffer-cache growth. The checkpoint is bf16, and a dequantized window comes back FP16, so a multi-token step promoted to float32. The KDA layers then carried float32 in their recurrent state into every decode step.

Both Kimi forwards now cast the dense window to the activation dtype through `mla_batched::dense_latent_in`. A new bf16 test fails without the cast (float32 prefill output) and passes with it.

The results doc, the CHANGELOG and turbo-kv-cache.md now carry the measurements from the re-run. The trace has 0 decided disagreements behind 1024 and 4096, five flips over 0.11 behind each (largest 0.500), and perplexity +0.29% and -0.40%. int8 decode against fp16 is +1.5% at 512 tokens, -4.7% at 2048 and -23.3% at 16384. The decode CSV keeps the pre-fix rows.

Refs #3162
Add a Kimi Linear and a Kimi K3 test that a mode table differing from fp16 on the KDA indices alone leaves the MLA caches fp16, and that int8 on the MLA indices alone builds int8 caches whatever the KDA entries hold.

Add a Kimi K3 bf16 regression test for the dense_latent_in cast. It fails without the cast (float32 prefill output) and passes with it. The environment-variables note for MLXCEL_MLA_ABSORBED now names the Kimi Linear and Kimi K3 MLA layers beside the DeepSeekV3Attention families.

Validation: cargo test -p mlxcel --lib kimi (192 passed, serial, under the GPU lock), cargo clippy -p mlxcel --lib --tests --features metal,accelerate -D warnings clean, cargo fmt --check clean.

Refs #3162
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 19, 2026
@inureyes
inureyes marked this pull request as ready for review November 19, 2026 16:35
@inureyes
inureyes merged commit c540d79 into main Nov 19, 2026
32 checks passed
@inureyes
inureyes deleted the feature/issue-3162-kimi-quantized-latent branch November 19, 2026 16:59
inureyes added a commit that referenced this pull request Nov 22, 2026
…2 and V3 (#3202)

* fix: cast the dequantized MLA latent to the query dtype in DeepSeek V2 and V3

A multi-token step over an int8 latent dequantized the window with
LatentWindow::into_dense, which returns FP16. On a bf16 checkpoint those keys
met bf16 queries, MLX promoted the attention to float32, and the float32
carried through o_proj into the residual stream for that step. Both sites now
go through mla_batched::dense_latent_in with the step's q_pe dtype, as the
Kimi and GLM-4.7-Flash sites do (#3174, #3176). A dense (fp16) window is
returned untouched.

Closes #3177.

* fix: cast the dequantized latent on DeepSeek V2's absorbed multi-token step

A multi-token step that the cost model absorbs (a short chunk behind a long enough cache, such as a speculative verify or a chunked prefill tail) reaches MlaLatentCache::attend_preprojected, whose quantized arm dequantized the window to FP16 and ran absorbed_attention with the step's bf16 queries. On a bf16 checkpoint that promoted the step to float32, the same defect #3177 fixes at the decompressed site. The window is now cast to the q_pe dtype there too, for every latent width (int8 and the int4 option of #3189 both take this arm).

The V2 test now also runs a 2-token absorbed step behind the 5-token prefill and checks it stays bf16; it fails without the cast (float32 output). It also restores the tiny_harness_model doc comment that the new test had absorbed.

Refs #3177, #3202

---------

Co-authored-by: Jeongkyu Shin <[email protected]>
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata priority:low Low priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Store a quantized MLA latent in Kimi Linear and Kimi K3

1 participant