Skip to content

feat: Store the absorbed MLA latent as affine int8/int4 on DeepSeek V2 #3155

Closed

Description

@inureyes

Part of #3158

Problem / Background

Absorbed MLA decode is the default for deepseek_v2 on Metal (fused kernel), CUDA (#3149) and ROCm (#3152). The cache then holds the shared latent ckv [B,1,S,kv_lora_rank] plus k_pe [B,1,S,qk_rope_head_dim], 1152 bytes per token per layer on DeepSeek V2-Lite. Any quantized KV request declines the latent and falls back to decompressed per-head K/V, so --kv-cache-mode int8 costs 5120 B (+scales), turbo4-asym about 7.2 KB, against 1152 B for the fp16 latent. The user who asks for a smaller cache gets a larger and slower one (GB10 16K decode: absorbed 72.85 vs decompressed 30.23 tok/s; gfx1151 16K: 36.49 vs 22.04). #3153 / PR #3154 make the sizing honest and add an interim substitution to the fp16 latent. This issue stores the latent itself quantized.

Target footprint on V2-Lite, with k_pe kept fp16 (128 B) for rope precision and ckv stored as MLX affine group-64 (fp16 scale and bias per group, 8 groups per 512-wide row = 32 B): int8 = 512 + 32 + 128 = 672 B (1.7x smaller than the fp16 latent), int4 = 256 + 32 + 128 = 416 B (2.8x smaller). kv_lora_rank = 512 is a multiple of the group size because ckv is stored apart from k_pe (the concatenated 576 is not a power of two).

Current Behavior

  • src/lib/mlxcel-core/src/mla/cache.rs:183 latent_layout_supports_mode accepts only KVCacheMode::Fp16; the module doc at cache.rs:48-56 explains why the per-token codecs do not fit a latent. MlaLatentCache::supports (cache.rs:215) calls it, and src/models/deepseek_v2.rs:452-458 takes the decompressed branch when it refuses.
  • src/models/deepseek_v2.rs:532-625 forward_absorbed: single-token and cost-model-approved multi-token steps call MlaLatentCache::attend (cache.rs:340) to attend_preprojected (cache.rs:285), which tries split-KV (mla/split_kv.rs, opt-in via split_kv_enabled, mla/mod.rs:272) and then absorbed_attention (mla/decode.rs:183). That function tries fused_absorbed_decode (decode.rs:124, Metal, dtype check at decode.rs:146-159), else composes rope_score_mask + attention(q_absorbed, ckv, ckv, ...) (decode.rs:213-214) for one query, or rope_folded_attention (mla/prefill.rs:75) for several. A cold prefill takes the else branch (deepseek_v2.rs:586-618), which reads the fp16 window back and up-projects it through kv_b_proj. Batched decode does the same per row at deepseek_v2.rs:627-700.
  • src/lib/mlxcel-core/src/cache.rs:260-293 KVCacheMode has no 4-bit affine variant. KVCacheMode::Int8 is per-token absmax (quantize_per_token, cache.rs:358; update_int8, cache.rs:1123), stored in keys/values with key_scales/val_scales (cache.rs:475-477).
  • src/lib/mlxcel-core/src/cache/batch_quant.rs:270-288 maps --kv-bits 8 to Int8 and --kv-quant-scheme turboquant --kv-bits 4 to Turbo4Asym; validate (batch_quant.rs:323-358) rejects --kv-bits 4 uniform because no Int4 mode exists. BatchQuantizedKVCache there is a documented test-only seam (batch_quant.rs:35-63), not on the live path; there is no quantized SDPA anywhere in the tree. The reusable pieces are the FFI quantize_weights(w, group_size, bits) triple (src/lib/mlxcel-core/src/lib.rs:3636, accessors at lib.rs:3664-3673), quantized_matmul (lib.rs:1368) and dequantize (lib.rs:1386), which run on Metal, CUDA and ROCm for the quantized weight path.
  • Mode resolution: resolve_kv_cache_mode_for_model (src/lib/mlxcel-core/src/cache/turbo/allowlist.rs:195) via resolve_effective_kv_cache_mode (src/cli/turbo_args.rs:465); the server's --kv-bits reconciliation is src/server/cli_input.rs:964-1010.
  • Sizing: deepseek_v2_latent_layout / deepseek_v2_caches_latent and classify (src/execution/kv_arch.rs:350-421, latent rate is kv_lora_rank + rope elements at the cache element width); kv_cache_bytes_per_token (src/execution/memory_estimate.rs:1141); prompt-cache sizing memory_left_after_model (src/server/prompt_cache/snapshot_sizing.rs:180); advisor src/execution/kv_cache_advisor.rs:221-240. PR fix(memory): size DeepSeek V2 KV through the non-FP16 mode decline #3154 changes all of these to take a KVCacheMode; build on its merged form.

Proposed Solution

Scope is deepseek_v2 only (including the deepseek_v2 decoder in DeepSeek-VL2). The latent-pair families (MLA_LATENT_CACHE_FAMILIES, mla/cache.rs:116) bypass MlaLatentCache and call KVCache::update_and_fetch directly (src/models/deepseek_v3.rs:317, src/models/mla_batched.rs:105, src/models/deepseek_v32.rs), so including them is per-family work; they keep the fp16 substitution here, and the PR records that decision in docs/turbo-kv-cache.md and names a follow-up issue.

  1. Modes. KVCacheMode::Int8 on a latent cache means affine group-64 8-bit ckv (not per-token absmax: quantized_matmul consumes the affine triple directly, which avoids dequantizing the window every step). Add KVCacheMode::Int4 (parse int4 / i4, display int4), which is valid only on an MLA latent cache. latent_layout_supports_mode accepts Fp16, Int8, Int4 and keeps refusing every Turbo mode with its current reason. Group size is fixed at 64 for the latent; --kv-group-size other than 64 on an absorbed V2 latent is rejected at startup with a message.
  2. Storage. The latent cache stores ckv as (packed uint32 [B,1,S,rank*bits/32], scales [B,1,S,rank/64], biases [B,1,S,rank/64]) produced by quantize_weights, and k_pe fp16 in the values slot. Reuse KVCache's growth/trim bookkeeping (step, offset, live_start, trim, trim_front) so the latent rows and scale rows move together; the per-head update_int8 path stays untouched for non-latent caches. MlaLatentCache::update_and_fetch returns a LatentWindow enum: Dense { ckv, kpe } or Quantized { ckv_q, scales, biases, kpe, bits, group_size }.
  3. Composed decode (one query). scores = quantized_matmul(q_absorbed, ckv_q, scales, biases, transpose=true, 64, bits) * scale + rope_score_mask(q_pe, kpe, scale, mask), softmax in fp32, o_latent = quantized_matmul(p, ckv_q, scales, biases, transpose=false, 64, bits). Shapes: q_absorbed [B,H,1,rank] against the single latent head broadcast over H. Records AbsorbedComposed (mla/stats.rs:45). fused_absorbed_decode and split-KV both decline a quantized window (the fused kernel is the Phase 2 sub-issue); they must decline before reading the window, not after.
  4. Multi-token steps and cold prefill. Dequantize the live window once per step (dequantize, lib.rs:1386) and pass it to the existing rope_folded_attention / kv_b_proj up-projection unchanged. The fresh chunk is quantized before it is read back, so prefill and decode see the same stored values. Measure and record the transient peak at a 16384-token prefill against the fp16 latent.
  5. Snapshot, detach/adopt and prompt-cache parking. Every path that copies, serializes, trims or restores a latent KVCache carries the packed/scales/biases triple and the mode; a restored quantized latent decodes identically to the original. Find these by following every KVCacheMode::Int8 => arm in cache.rs (e.g. cache.rs:1010, 3170, 4630) and the prompt-cache store under src/server/prompt_cache/.
  6. Mode resolution. On absorbed deepseek_v2, --kv-cache-mode int8|int4 and --kv-bits 8|4 (uniform) resolve to the quantized latent. BatchKvQuantConfig::base_mode maps (Uniform, 4) to Int4; validate stops rejecting it, and the model-aware step at cli_input.rs:984-1010 disables it with the existing style of warning on any model that cannot hold an Int4 cache, so non-MLA models keep fp16 rather than silently gaining a mode. Turbo modes on absorbed V2 stay substituted to the fp16 latent until Phase 3, with the fix(memory): size DeepSeek V2 KV through the non-FP16 mode decline #3154 warning reworded to name int8/int4 as the supported quantized latent modes. MLXCEL_MLA_ABSORBED=0 keeps today's behaviour (Int8 decompressed per-head; Int4 rejected or substituted to Int8 with a warning, since per-head Int4 does not exist).
  7. Sizing, advisor, inspect. Add a quantized-latent rate (rank*bits/8 + 2*2*rank/64 + 2*rope bytes per token per layer) to kv_arch for absorbed V2 under Int8/Int4 and use it in memory_estimate, prompt-cache sizing and the inspect KV figures. The advisor recommends int8 (or int4 if it passes the gate) for Medium/Long context on absorbed V2 instead of "Keep fp16".

Rejected: reusing per-token absmax Int8 for the latent (its scale is one value per 512-wide row, the case cache.rs:48-56 warns about, and it forces a full-window dequantize per step); routing through BatchQuantizedKVCache (it is not on the live path).

Scope

In scope: src/lib/mlxcel-core/src/cache.rs (mode, latent storage), mla/cache.rs, mla/decode.rs, mla/split_kv.rs (decline), cache/batch_quant.rs, cache/turbo/allowlist.rs, src/cli/turbo_args.rs, src/server/cli_input.rs, src/models/deepseek_v2.rs, src/execution/{kv_arch,memory_estimate,kv_cache_advisor}.rs, src/server/prompt_cache/, src/commands/inspect.rs, docs/turbo-kv-cache.md (rewrite "MLA latent caches are FP16 only", line 236), a new docs/benchmark_results/mla-quantized-latent-*.md.

Out of scope: fused Metal kernel reading a quantized latent (Phase 2 sub-issue), Turbo/WHT latent (Phase 3 sub-issue), latent-pair families (follow-up), paged backing for latents.

Implementation Notes

  • Reuse: quantize_weights / quantized_matmul / dequantize FFI; rope_score_mask, rope_folded_attention, stats::record; the test(bench): measure the 2026-11 memory and MLA changes on CUDA and ROCm #3133 trace tooling (examples/logit_trace.rs, scripts/compare_logit_traces.py) and the command block in docs/benchmark_results/mla-absorbed-default-m5max-2026-11-16.md.
  • Constraints: fp16 latent behaviour and numerics are bit-identical to today (pin with an existing decode test). The mode is fixed for a cache's lifetime, so a cache never mixes fp16 and quantized latent rows.
  • Edge cases: empty cache (first prefill chunk); trim for speculative decode landing mid-buffer; trim_front under --max-kv-size; S not a multiple of the growth step; batch rows with different modes must not occur (assert); all-zero latent rows (affine scale 0 must round-trip to 0).
  • Error handling: unsupported group size or Int4 without absorption is a startup error or a one-line warning plus substitution, never a panic in decode. A quantized_matmul failure on a backend is a hard error naming the backend; there is no silent fp16 fallback mid-run.
  • Quality gate: if int4 fails the trace/ppl bar below, do not ship KVCacheMode::Int4 or the (Uniform, 4) mapping; keep the existing rejection and record the int4 numbers in the results doc.

Acceptance Criteria

  • mlxcel generate / serve on V2-Lite with --kv-cache-mode int8 (and int4 if shipped) runs absorbed decode over a quantized latent: MLXCEL_TRACE_MLA_STATS=1 shows absorbed_composed for decode steps and no decompressed decode steps; --kv-bits 8|4 on serve does the same. Done for int8 (int4 not shipped, see the gate result below).
  • Teacher-forced trace (test(bench): measure the 2026-11 memory and MLA changes on CUDA and ROCm #3133 method, --decided 2) of int8 and int4 latent vs fp16 latent behind 1024 and 4096 on Metal: zero decided disagreements, every top-1 disagreement explained by a near-tie (reference top two within 0.11 logits), perplexity delta recorded. CUDA GB10 and ROCm gfx1151 rows are measured or marked "not measured" with the host gap stated. Done on Metal: int8 passes, int4 fails the near-tie bar (largest reference top-two gap at a disagreement 0.859 against 0.11). CUDA GB10 and ROCm gfx1151 are marked not measured (hosts unreachable from the M3 Ultra).
  • Decode tok/s at prompts 512/2048/16384 for int8/int4 latent vs fp16 latent (and vs decompressed int8) on each measured backend, plus the 16384 prefill transient peak, recorded in docs/benchmark_results/. Done on Metal in docs/benchmark_results/mla-quantized-latent-m3ultra-2026-11-19.md.
  • mlxcel inspect KV bytes for V2-Lite under int8/int4 equal the runtime nbytes of the allocated caches at the same token count (672 / 416 B per token per layer). Done for int8 (672 B per token per layer).
  • Unit tests: affine round trip within tolerance (including all-zero rows); composed quantized decode vs fp16-latent absorbed_attention within a stated tolerance; multi-token absorbed step parity; trim/trim_front/snapshot-restore of a quantized latent decodes identically; latent_layout_supports_mode accepts Fp16/Int8/Int4 and refuses each Turbo mode; resolver and --kv-bits mapping cases (absorbed V2, MLXCEL_MLA_ABSORBED=0, a non-MLA family, a latent-pair family); kv_arch/memory_estimate/advisor sizing. Done; the resolver and --kv-bits cases cover int8, and int4 / --kv-bits 4 uniform stay rejected.
  • Integrated into the real decode, prefill, prompt-cache, sizing, advisor and inspect flows; the fix(memory): size DeepSeek V2 KV through the non-FP16 mode decline #3154 interim substitution for int8 (and int4) is gone. One PR. Done for int8.

Verification

Implement everything in one PR, run the local gate once at the end, and keep pushes to a minimum.

cargo fmt --all -- --check
cargo test -p mlxcel-core --lib mla:: -- --test-threads=1
cargo test -p mlxcel-core --lib cache:: -- --test-threads=1
cargo test -p mlxcel --lib -- execution::kv_arch execution::memory_estimate execution::kv_cache_advisor
cargo test -p mlxcel --lib -- server::prompt_cache server::cli_input
cargo clippy --workspace --all-targets -- -D warnings
make verify            # macOS; make verify-test-cuda / make verify-rocm on the GPU hosts

GPU runs use the commands in docs/benchmark_results/mla-absorbed-default-m5max-2026-11-16.md with --kv-cache-mode int8|int4 added (mlxcel-bench-decode at 512/2048/16384; logit_trace 1024 and 4096; compare_logit_traces.py --decided 2). On GB10 wrap GPU runs in gpu-lock run.

Refs #3153, #3154, #3133, #3149, #3152.

Gate result (2026-11-19)

int8 passed the quality gate and ships. int4 failed it: zero decided disagreements, but top-1 flips at 45 / 512 and 14 / 256 positions with reference top-two gaps up to 0.859 logits, so KVCacheMode::Int4 and the (Uniform, 4) mapping are not shipped and --kv-bits 4 uniform keeps its startup rejection, as the Quality gate note above prescribes. Numbers: docs/benchmark_results/mla-quantized-latent-m3ultra-2026-11-19.md.

Activity

  1. added
    type:enhancement
    priority:high
    status:ready
    area:core
    area:inference
    area:models
    on Nov 18, 2026
  2. added
    status:in-progress
    status:review
    and removed
    status:ready
    status:in-progress
    on Nov 19, 2026
  3. added
    status:done
    and removed
    status:review
    on Nov 19, 2026
  4. added this to the 0.9 milestone on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:corearea:inferencearea:modelspriority:highstatus:donetype:enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions