Repository navigation
Description
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:183latent_layout_supports_modeaccepts onlyKVCacheMode::Fp16; the module doc atcache.rs:48-56explains why the per-token codecs do not fit a latent.MlaLatentCache::supports(cache.rs:215) calls it, andsrc/models/deepseek_v2.rs:452-458takes the decompressed branch when it refuses.src/models/deepseek_v2.rs:532-625forward_absorbed: single-token and cost-model-approved multi-token steps callMlaLatentCache::attend(cache.rs:340) toattend_preprojected(cache.rs:285), which tries split-KV (mla/split_kv.rs, opt-in viasplit_kv_enabled,mla/mod.rs:272) and thenabsorbed_attention(mla/decode.rs:183). That function triesfused_absorbed_decode(decode.rs:124, Metal, dtype check atdecode.rs:146-159), else composesrope_score_mask+attention(q_absorbed, ckv, ckv, ...)(decode.rs:213-214) for one query, orrope_folded_attention(mla/prefill.rs:75) for several. A cold prefill takes theelsebranch (deepseek_v2.rs:586-618), which reads the fp16 window back and up-projects it throughkv_b_proj. Batched decode does the same per row atdeepseek_v2.rs:627-700.src/lib/mlxcel-core/src/cache.rs:260-293KVCacheModehas no 4-bit affine variant.KVCacheMode::Int8is per-token absmax (quantize_per_token,cache.rs:358;update_int8,cache.rs:1123), stored inkeys/valueswithkey_scales/val_scales(cache.rs:475-477).src/lib/mlxcel-core/src/cache/batch_quant.rs:270-288maps--kv-bits 8toInt8and--kv-quant-scheme turboquant --kv-bits 4toTurbo4Asym;validate(batch_quant.rs:323-358) rejects--kv-bits 4uniform because no Int4 mode exists.BatchQuantizedKVCachethere 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 FFIquantize_weights(w, group_size, bits)triple (src/lib/mlxcel-core/src/lib.rs:3636, accessors atlib.rs:3664-3673),quantized_matmul(lib.rs:1368) anddequantize(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) viaresolve_effective_kv_cache_mode(src/cli/turbo_args.rs:465); the server's--kv-bitsreconciliation issrc/server/cli_input.rs:964-1010. - Sizing:
deepseek_v2_latent_layout/deepseek_v2_caches_latentandclassify(src/execution/kv_arch.rs:350-421, latent rate iskv_lora_rank + ropeelements at the cache element width);kv_cache_bytes_per_token(src/execution/memory_estimate.rs:1141); prompt-cache sizingmemory_left_after_model(src/server/prompt_cache/snapshot_sizing.rs:180); advisorsrc/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 aKVCacheMode; 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.
- Modes.
KVCacheMode::Int8on a latent cache means affine group-64 8-bitckv(not per-token absmax:quantized_matmulconsumes the affine triple directly, which avoids dequantizing the window every step). AddKVCacheMode::Int4(parseint4/i4, displayint4), which is valid only on an MLA latent cache.latent_layout_supports_modeacceptsFp16,Int8,Int4and keeps refusing every Turbo mode with its current reason. Group size is fixed at 64 for the latent;--kv-group-sizeother than 64 on an absorbed V2 latent is rejected at startup with a message. - Storage. The latent cache stores
ckvas(packed uint32 [B,1,S,rank*bits/32], scales [B,1,S,rank/64], biases [B,1,S,rank/64])produced byquantize_weights, andk_pefp16 in the values slot. ReuseKVCache's growth/trim bookkeeping (step,offset,live_start,trim,trim_front) so the latent rows and scale rows move together; the per-headupdate_int8path stays untouched for non-latent caches.MlaLatentCache::update_and_fetchreturns aLatentWindowenum:Dense { ckv, kpe }orQuantized { ckv_q, scales, biases, kpe, bits, group_size }. - 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 overH. RecordsAbsorbedComposed(mla/stats.rs:45).fused_absorbed_decodeand 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. - Multi-token steps and cold prefill. Dequantize the live window once per step (
dequantize,lib.rs:1386) and pass it to the existingrope_folded_attention/kv_b_projup-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. - Snapshot, detach/adopt and prompt-cache parking. Every path that copies, serializes, trims or restores a latent
KVCachecarries the packed/scales/biases triple and the mode; a restored quantized latent decodes identically to the original. Find these by following everyKVCacheMode::Int8 =>arm incache.rs(e.g.cache.rs:1010,3170,4630) and the prompt-cache store undersrc/server/prompt_cache/. - Mode resolution. On absorbed
deepseek_v2,--kv-cache-mode int8|int4and--kv-bits 8|4(uniform) resolve to the quantized latent.BatchKvQuantConfig::base_modemaps(Uniform, 4)toInt4;validatestops rejecting it, and the model-aware step atcli_input.rs:984-1010disables it with the existing style of warning on any model that cannot hold anInt4cache, 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 nameint8/int4as the supported quantized latent modes.MLXCEL_MLA_ABSORBED=0keeps today's behaviour (Int8 decompressed per-head; Int4 rejected or substituted to Int8 with a warning, since per-head Int4 does not exist). - Sizing, advisor, inspect. Add a quantized-latent rate (
rank*bits/8 + 2*2*rank/64 + 2*ropebytes per token per layer) tokv_archfor absorbed V2 under Int8/Int4 and use it inmemory_estimate, prompt-cache sizing and the inspect KV figures. The advisor recommendsint8(orint4if 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/dequantizeFFI;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 indocs/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);
trimfor speculative decode landing mid-buffer;trim_frontunder--max-kv-size;Snot 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_matmulfailure 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::Int4or the(Uniform, 4)mapping; keep the existing rejection and record the int4 numbers in the results doc.
Acceptance Criteria
-
mlxcel generate/serveon V2-Lite with--kv-cache-mode int8(andint4if shipped) runs absorbed decode over a quantized latent:MLXCEL_TRACE_MLA_STATS=1showsabsorbed_composedfor decode steps and nodecompresseddecode steps;--kv-bits 8|4onservedoes 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 indocs/benchmark_results/mla-quantized-latent-m3ultra-2026-11-19.md. -
mlxcel inspectKV bytes for V2-Lite under int8/int4 equal the runtimenbytesof 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_attentionwithin a stated tolerance; multi-token absorbed step parity;trim/trim_front/snapshot-restore of a quantized latent decodes identically;latent_layout_supports_modeaccepts Fp16/Int8/Int4 and refuses each Turbo mode; resolver and--kv-bitsmapping 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-bitscases cover int8, andint4/--kv-bits 4uniform 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
fix: resolve DeepSeek-VL2 KV rules through its deepseek_v2 decoder
fix(security): saturate the quantized MLA latent byte rate
fix(perf): read the k_pe window once per quantized decode step
docs(mla): mark the quoted int8 4096 trace row in the Turbo latent doc
feat: read the int8 MLA latent inside the fused Metal decode kernel (#…
feat: store a quantized MLA latent in the DeepSeekV3Attention families (
feat: store the absorbed MLA latent as affine int8 on DeepSeek V2 (la…
feat: store a quantized MLA latent in Kimi Linear and Kimi K3 (#3174)
feat: store a quantized MLA latent in LongCat-Flash and port GLM-4.7-…