Skip to content

feat: store the absorbed MLA latent as affine int8 on DeepSeek V2 - #3168

Merged
inureyes merged 6 commits into
mainfrom
feature/issue-3155-quantized-mla-latent
Nov 19, 2026
Merged

inureyes merged 6 commits into
mainfrom
feature/issue-3155-quantized-mla-latent

Conversation

@inureyes

@inureyes inureyes commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Phase 1 of #3158. --kv-cache-mode int8 (also --cache-type-k/v int8 and --kv-bits 8) on deepseek_v2 under absorbed decode now stores the MLA latent as affine group-64 8-bit with fp16 rope keys: 672 bytes per token per layer on V2-Lite against 1152 for the fp16 latent and 5120 for the decompressed int8 cache.

int4 is not shipped

It failed the gate, so int4 is not a mode and --kv-bits 4 uniform keeps its startup error.

candidate vs fp16 latent decided disagree top-1 disagree largest top-two gap at a disagreement ppl delta
int8, behind 1024 / 4096 0 / 209, 0 / 105 12 / 512, 3 / 256 0.078, 0.109 +0.29%, -0.63%
int4, behind 1024 / 4096 0 / 209, 0 / 105 45 / 512, 14 / 256 0.859, 0.859 -0.004%, +2.0%

Measured (M3 Ultra, Metal, V2-Lite)

Decode tok/s at 512 / 2048 / 16384: fp16 latent 163.6 / 146.7 / 109.9, int8 latent 138.9 / 127.6 / 70.7 before the rope-score change and 129.5-130.1 / 71.3 at 2048 / 16384 after it, decompressed int8 121.0 / 88.5 / 25.4. The int8 latent decodes on the composed path (#3156 is the fused kernel). The rope-score change leaves the int8 trace byte-identical. 16384 prefill peak: 11.23 GB against 11.45 GB for fp16. Full rows, the measured single-query layouts and end-to-end checks: docs/benchmark_results/mla-quantized-latent-m3ultra-2026-11-19.md.

Not done

  • CUDA GB10 and ROCm gfx1151 are not measured (hosts unreachable); the path uses only quantize_weights, quantized_matmul and dequantize.
  • Folding the heads into the latent score measured +3% at 512 and 2048 and +13% at 16384, but one top-1 flip lands at a 0.219-logit gap, outside the 0.11 near-tie bar, so it is not shipped. Removing the per-step f32 cast of the group scales and biases needs f32 sidecars (704 bytes per token per layer) or an fp16 query. Both are recorded in the results doc and need a decision.
  • No assert that batch rows share a mode: an existing test batches fp16 and int8 rows, and each row attends over its own cache.
  • mlxcel serve does not print MLXCEL_TRACE_MLA_STATS; the serve check is the prompt-cache store's byte count and cached-token reuse.

Test plan

  • cargo test -p mlxcel-core --lib -- mla:: cache:: --test-threads=1
  • cargo test -p mlxcel --lib for the sizing, advisor, CLI, prompt-cache and models::deepseek_v2 modules
  • cargo test --test deepseek_v2_greedy_parity on the real checkpoint (fp16 default unchanged)
  • generate, inspect and serve runs with int8 on V2-Lite
  • Teacher-forced traces behind 1024 and 4096 rerun after the rope-score change
  • make verify-clippy (workspace, all targets, -D warnings), cargo fmt --check

Closes #3155

A quantized KV request on an absorbing deepseek_v2 used to decline the latent and store decompressed per-head K/V (5120 bytes per token per layer for int8 on V2-Lite), and #3154 substituted fp16 in the interim. An int8 cache now stores the latent itself as an MLX affine group-64 triple with fp16 rope keys, 672 bytes against 1152 for the fp16 latent.

- Storage reuses the four buffers a per-head INT8 cache has (packed latent, k_pe, group scales, group biases), so trim, trim_front, gather, detach/adopt and the prompt-cache store carry it. Two hard-coded width-1 scale slices now read the width from the array.
- MlaLatentCache::update_and_fetch returns a LatentWindow (Dense, or Quantized with bits and group size). A single query runs both contractions through quantized_matmul on the packed rows; a multi-token step and a cold prefill dequantize the window once. The fused kernel and split-KV are not tried on a quantized window.
- The resolver keeps int8 on an absorbing deepseek_v2 and still substitutes fp16 for Turbo modes there and for every quantized mode on the latent-pair families. kv_arch sizes the quantized latent, which inspect, the memory preflights, the prompt-cache budget and the advisor read. --kv-group-size other than 64 fails server startup for such a model.
- generate and mlxcel-bench-decode honour MLXCEL_TRACE_MLA_STATS=1, and logit_trace applies MLXCEL_TRACE_KV_CACHE_MODE to caches the model does not own.

A 4-bit latent was measured and failed the trace gate, so int4 is not a mode and --kv-bits 4 uniform stays rejected.

Validated with the core mla and cache tests, the sizing, CLI, prompt-cache and deepseek_v2 unit tests, the V2 greedy parity test, clippy and fmt.

Refs #3155, #3158
Rewrite the MLA latent section of docs/turbo-kv-cache.md now that deepseek_v2 holds an affine int8 latent, and record there that the latent-pair families keep the fp16 substitution until #3160-#3163. Update docs/mla-absorbed-decode.md with the slot layout and the composed decode, document MLXCEL_TRACE_MLA_STATS, and add the CHANGELOG entry.

docs/benchmark_results/mla-quantized-latent-m3ultra-2026-11-19.md holds the teacher-forced traces, decode throughput at 512, 2048 and 16384 tokens, the 16384 prefill peak and the end-to-end checks. int8 shows no decided disagreement and all top-1 disagreements within 0.109 logits; int4 flips top-1 at gaps up to 0.859 and is recorded as not shipped. CUDA and ROCm are marked not measured.

Refs #3155
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:high High 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
DeepSeek-VL2 runs a deepseek_v2 decoder that now stores an int8 latent at runtime, but the mode resolver, kv_arch and the advisor keyed on the top-level model_type (deepseek_vl_v2) and kv_arch never looked under language_config. A Turbo request therefore stayed Turbo and pushed the decoder onto the larger decompressed cache, and VL2 was not sized as a latent at all.

The VL2 loader's language_config builder is now shared (loading::deepseek_vl2_language_config), and execution::config_fields gains kv_decoder_config / kv_decoder_model_type on top of the existing text_config rule. kv_arch sizes and the advisor classifies the decoder section; the CLI resolver keys the deepseek_v2 rule on the decoder type, so VL2 gets the fp16 latent substitution for Turbo, the 672 B int8 latent rate and the int8 advice. stores_latent_through_view no longer string-matches the VL2 wrapper names.

kv_arch also sizes an absorbed V2 whose kv_lora_rank is not a multiple of 64 as decompressed per-head int8 under int8, matching MlaLatentCache::supports declining it, instead of the latent rate.

examples/mla_absorbed_decode_bench matches on LatentWindow::Dense after update_and_fetch changed its return type, and fails loudly on a quantized window.

Tests: new VL2 cases in kv_arch, the advisor and turbo_args; the rank-96 test asserts the decompressed layout.

Refs #3155
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Store the absorbed DeepSeek V2 MLA latent as affine group-64 int8 (int4 measured and not shipped per the quality gate), wired through decode, prefill, prompt-cache, sizing and advice.

Findings Addressed

  • examples/mla_absorbed_decode_bench.rs did not compile against the new LatentWindow return type of MlaLatentCache::update_and_fetch; it now matches Dense and panics on a quantized window (HIGH)
  • DeepSeek-VL2 was not resolved as its deepseek_v2 decoder: a Turbo request stayed Turbo and landed on the larger decompressed cache, and kv_arch never read language_config, so VL2 was not sized or advised as a latent. The loader's language_config builder is now shared, config_fields::kv_decoder_config / kv_decoder_model_type extend the existing text_config rule, and the resolver, kv_arch and the advisor key the deepseek_v2 rule on the decoder type. stores_latent_through_view no longer string-matches the VL2 names (HIGH)
  • kv_arch sized an absorbed V2 whose kv_lora_rank is not a multiple of 64 as the latent under int8, while MlaLatentCache::supports declines it and the run stores decompressed per-head int8. It now sizes the decompressed layout (MEDIUM)

Remaining Items

  • The int8 path stores k_pe as fp16 and dequantizes ckv to fp16 even on a bf16 model, where the fp16 latent keeps bf16. MLX promotes the mixed operands, and the measured gate ran on this bf16 checkpoint, so it is correct. It may cost some speed. Not changed because any change would invalidate the recorded measurements (LOW)

Verification

  • All stated requirements implemented (int8; int4 is withheld per the gate)
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (targeted modules below; no workspace-wide run)

Notes: fp16 latent numerics are unchanged. The Dense arm returns the same tensors as before, and the width-1 scale slices in trim_front and DetachedKVCache::trim_to now read shape[3], which is 1 for per-head INT8. uses_scale_sidecars() matches exactly Int8. A batch that mixes fp16 and int8 latent rows cannot come out of the live scheduler, because every row in a layer gets its mode from the scheduler-wide per-layer table. A restored entry carries its own mode through install_detached, and the batched decode wraps and attends each row through its own cache, so the per-cache invariant holds where the issue's assert would fire wrongly. Detach, adopt, trim_to and partial adopt of the uint32/fp16 triple are covered by a_detached_and_adopted_quantized_latent_decodes_identically. The prompt cache parks detached handles in memory only, so no on-disk dtype path exists.

Tests run: clippy -D warnings on mlxcel (lib, tests, the bench example) and mlxcel-core (lib, tests); cargo check -p mlxcel --examples --bins; cargo test -p mlxcel --lib for kv_arch, kv_cache_advisor, config_fields, turbo_args, cli_input, prompt_cache snapshot_sizing, memory_estimate, loading and the deepseek_vl2 modules (782 passed); cargo test -p mlxcel-core --lib for mla::, cache::latent_quant and the allowlist (96 passed).

`quantized_latent_bytes_per_token` multiplied `kv_lora_rank` by the bit width unchecked. `execution::kv_arch` feeds it straight from `config.json`, so a crafted whole-group rank (for example 2^62) panicked in a debug build and wrapped to a small rate in release, undercounting the KV estimate that `inspect`, `memory_estimate` and the prompt-cache budget build on. The rate now returns `usize::MAX` on overflow or a zero group size and saturates the remaining terms, which turns a hostile config into an overestimate.

Tests: `mla::quant_latent` saturation case and a `kv_arch` hostile-rank case; `cargo test -p mlxcel-core --lib mla:: cache::latent_quant cache::detach` and `cargo test -p mlxcel --lib` for kv_arch, memory_estimate, kv_cache_advisor and prompt_cache snapshot_sizing pass.

Refs #3155
The one-query int8 latent step computed the rope score as `[B, H, 1, d] @ [B, 1, d, S]`, which broadcasts the single rope head so every query head reads the whole `k_pe` window. The score now puts the heads on the row axis (`[B, 1, H, d]`), one product per step. The trace behind 1024 is byte-identical to the measured int8 trace and the 4096 comparison reproduces the recorded figures, so the quality gate result stands. Decode on V2-Lite (M3 Ultra) goes from 127.5-128.5 to 129.5-130.1 tok/s behind 2048 and from 70.5-70.9 to 71.3 behind 16384.

Folding the heads into the latent score as well measured 3% to 13% faster but moves one top-1 flip to a 0.219-logit gap, outside the gate's 0.11 near-tie bar, so it is recorded in the results doc and left out. Folding the value sum measured slower at every length.

Refs #3155
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

No CRITICAL or HIGH findings. pr-reviewer findings were not revisited.

Fixed

  • MEDIUM quantized_latent_bytes_per_token multiplied an untrusted kv_lora_rank unchecked; kv_arch passes config.json values in, so a crafted rank panicked in debug and wrapped to an undercount in release (inspect, memory_estimate, prompt-cache budget). It now saturates (0130e0a).
  • LOW The one-query quantized step broadcast the single k_pe head over every query head, so each head read the rope window. The heads now sit on the row axis. Trace byte-identical to the gated int8 trace; +1% to 1.5% decode (8a0137a).

Checked, no change needed

  • Runtime geometry: MlaGeometry::check bounds kv_lora_rank to non-zero and i32, and check_quantizable requires whole groups of 64 before any shape math, so packed and scale widths are exact and the group size is a constant.
  • --kv-group-size other than 64 with a quantized latent fails at startup; --kv-bits 4 uniform and int4 stay rejected; Turbo modes resolve to fp16.
  • Detach/adopt, trim, trim_front, gather_* and nbytes move and count all four slots; no new shared mutable state (latent_quant and quant_latent hold no statics).
  • Single-query decode never dequantizes the window. Multi-token steps and cold prefill dequantize once per step, as designed.

Open (needs a decision, not changed)

  • Folding the heads into the latent score contraction measured +3% (512, 2048) and +13% (16384) decode, but one top-1 flip lands at a 0.219-logit gap, outside the 0.11 near-tie bar (0 decided disagreements, ppl -0.20%). Numbers are in the results doc, "Single-query decode layout".
  • The per-step f32 cast of the group scales and biases is what MLX does internally for an f32 query; removing it needs f32 sidecars (704 B/token/layer) or an fp16 query, both of which change the gated numerics.

Tests: mlxcel-core mla::, cache::latent_quant, cache::detach; mlxcel kv_arch, memory_estimate, kv_cache_advisor, prompt_cache snapshot_sizing; clippy -D warnings on mlxcel-core lib and tests; gate traces behind 1024 and 4096 with compare_logit_traces.py --decided 2.

@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 08:08
@inureyes
inureyes merged commit 43f1c8d into main Nov 19, 2026
32 checks passed
@inureyes
inureyes deleted the feature/issue-3155-quantized-mla-latent branch November 19, 2026 08:39
inureyes added a commit that referenced this pull request Nov 20, 2026
Since #3168 the absorbed DeepSeek V2 cache stores its latent as affine int8, so `--kv-bits 8` resolves to Int8 in the serve preflight. The test still expected the pre-#3168 fp16 answer and failed in the 2026-11-19 nightly, the one failure #3186 did not cover.

Refs #3146
@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:high High 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 the absorbed MLA latent as affine int8/int4 on DeepSeek V2

1 participant