Skip to content

fix(memory): size DeepSeek V2 KV through the non-FP16 mode decline - #3154

Merged
inureyes merged 5 commits into
mainfrom
fix/issue-3153-v2-kv-mode-sizing
Nov 18, 2026
Merged

inureyes merged 5 commits into
mainfrom
fix/issue-3153-v2-kv-mode-sizing

Conversation

@inureyes

@inureyes inureyes commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Summary

DeepSeek V2 KV was sized as the absorbed MLA latent under any non-INT8 mode, while the runtime keeps decompressed per-head K/V for every mode mla::latent_layout_supports_mode refuses (all but FP16). A Turbo run on V2-Lite was estimated at 1152 bytes per token per layer against 10240 actually cached (8.9x undercount, the unsafe direction for the prompt-cache store budget and the --estimate-memory abort).

Fixing the estimate exposed a second problem: since absorbed MLA became the default on Metal, CUDA (#3149) and ROCm (#3152), choosing a quantized KV mode on DeepSeek V2 to save memory produced a larger cache than the default. On V2-Lite that is about 5120 bytes per token per layer for int8 and about 7.2 KB for turbo4-asym against 1152 for the fp16 latent, with slower long-context decode. This PR stops that inversion and leaves a real quantized latent cache to epic #3158.

Sizing follows the layout the runtime builds

  • The KV estimator takes a KvSizing (a KVCacheMode plus whether the last layer stays FP16) instead of an int8 flag; callers holding only a KVCacheMode convert through From. deepseek_v2_latent_layout(absorbed, mode) calls the runtime rule rather than comparing to FP16. INT8 halves the element width; Turbo keeps the FP16 width (overestimates, as scoped in fix(memory): size DeepSeek V2 KV through the non-FP16 cache-mode decline #3153).
  • The mode flows from the real callers: the inspect/generate/serve preflights, --recommend-quant (through advise_quantization and the KV-cache advisor), and serve startup sizing of the prompt-cache snapshot store, state-checkpoint budget and KV store.
  • --kv-bits / --kv-quant-scheme are now honoured by the serve --estimate-memory preflight and prompt-cache sizing. Shared helpers in src/server/cli_input.rs (disable_batch_kv_quant_for_family, kv_mode_for_batch, effective_serve_kv_cache_mode) hold the rule startup already applied, so startup, preflight and sizing cannot drift. Under --kv-bits 8 with the default --kv-skip-last-layer, the estimate charges the FP16 last layer (exact on dense stacks and on stacks whose last layer is global, rounded up otherwise).
  • MemoryEstimate gains kv_mode so the banner's per-token line follows the same mode as the total; kv_dtype_int8, the banner label and the inspect JSON schema are unchanged. The paged-pool helpers keep their dtype flag.

DeepSeek V2 no longer trades the latent for a larger quantized cache

  • resolve_kv_cache_mode_for_model_with(requested, model_type, absorbed): when deepseek_v2 runs with absorbed MLA and the requested mode would decline the latent, the mode resolves to fp16 with a warning that names MLXCEL_MLA_ABSORBED=0 as the way to keep the quantized decompressed layout. With absorption off the request is unchanged, and deepseek_v2 is not added to MLA_LATENT_CACHE_FAMILIES. --kv-bits follows through the same resolver, so the batch quant table is disabled for absorbed V2.
  • The advisor classifies against the resolved mode, so absorbed V2 is advised to keep fp16 for any quantized request.
  • kv_modes_do_not_advertise_runtime_fp16_downgrades checks the registry against the host-independent rule (absorption off): kv_modes is a static table published by mlxcel arch --json, so on absorbed hosts it still lists int8/turbo4 for deepseek_v2 while a request for them is substituted with a warning.
  • Docs: docs/turbo-kv-cache.md, docs/mla-absorbed-decode.md and the MLXCEL_MLA_ABSORBED row in docs/environment-variables.md; CHANGELOG Unreleased.

Known limits

  • INT8 width still omits the per-token (single stream) or per-group (batch) scale bytes, a few percent undercount that predates this PR.
  • An env-only LLAMA_ARG_KV_BITS is applied after the serve preflight runs, so that preflight sizes FP16 (overestimate).
  • The estimate assumes absorption succeeds; a kv_b_proj with a bias would refuse it (predates this PR, no known checkpoint).

Test plan

  • cargo test -p mlxcel --lib on execution::kv_arch, execution::kv_cache_advisor, execution::memory_estimate, execution::quant_advisor, execution::request_memory, server::prompt_cache, server::cli_input, server::startup_tests, models::registry, cli::turbo_args: all pass on Metal
  • cargo test -p mlxcel-core --lib cache::turbo::allowlist and mla::cache -- --test-threads=1: pass, including the paged-backed decline test and deepseek_v2_absorbed_resolves_quantized_modes_to_fp16
  • cargo test -p mlxcel --bin mlxcel serve_preflight: pass
  • cargo fmt --all -- --check and cargo clippy --workspace --all-targets -- -D warnings: clean
  • Manual mlxcel inspect (Metal, absorbed by default) on a config-only V2-Lite directory at --max-tokens 32768, run on the first commit before the fp16 substitution: 972.0 MiB of KV (latent) with fp16, 8.44 GiB (decompressed) with --cache-type-v turbo4-asym, 4.22 GiB with int8; a pre-change binary reported 972.0 MiB for the Turbo case. With the substitution, absorbed hosts now resolve the quantized requests to fp16 and report 972.0 MiB; the decompressed figures apply with MLXCEL_MLA_ABSORBED=0. No V2-Lite checkpoint is on this host, so the serve prompt-cache log check was not run.

Closes #3153

The estimator sized DeepSeek V2 as the absorbed MLA latent whenever absorption was on and the KV cache was not INT8, but the runtime keeps decompressed per-head K/V for every mode `latent_layout_supports_mode` refuses, Turbo included. A Turbo run on V2-Lite was sized at 1152 bytes per token per layer against 10240 actually cached, so the prompt-cache KV store, the inspect report and the `--estimate-memory` preflights undercounted by 8.9x.

The estimator now takes `KVCacheMode` instead of an int8 flag: `deepseek_v2_latent_layout(absorbed, mode)` calls the runtime rule, INT8 still narrows the element width, and Turbo keeps the FP16 width (overestimate). `estimate_total_memory`, `kv_cache_bytes_per_token`, the prompt-cache sizing entry points and the KV-cache advisor take the mode too. The callers pass the mode the run builds: the inspect/generate/serve preflights use their resolved mode, `--recommend-quant` passes generate's mode, and serve startup passes the batch KV-quant base mode when `--kv-bits` is on and `kv_cache_mode` otherwise. `MemoryEstimate` carries the mode so the banner's per-token line matches the total. The paged-pool helpers keep their dtype flag.

Tests cover every declining mode, the absorption-off case, the KV-store entry size under Turbo and FP16, the advisor classification, the startup mode choice, and the paged-backed decline in `MlaLatentCache::supports`.

Closes #3153
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:high High priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Nov 18, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Size DeepSeek V2 KV from the KVCacheMode the run builds, declining the absorbed latent for every mode mla::latent_layout_supports_mode refuses, and feed that mode from every real caller.

Findings Addressed

None required a fix: no CRITICAL or HIGH findings.

Remaining Items

  • The serve --estimate-memory preflight (src/commands/serve.rs run_serve_memory_preflight) sizes for the resolved --kv-cache-mode only and ignores the --kv-bits base mode, so deepseek_v2 with --kv-bits 8 or --kv-quant-scheme turboquant is still estimated as the latent on an absorbed build while the scheduler builds decompressed rows (MEDIUM). Pre-existing and outside the brief's literal step 4, but the same unsafe-direction gap the prompt-cache path now closes via prompt_cache_sizing_kv_mode; a follow-up can apply the same rule there.
  • src/execution/kv_cache_advisor.rs around line 226: a comment line was extended past the surrounding width instead of being reflowed (LOW, cosmetic).

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass

Ran on Metal, serially: cargo test -p mlxcel --lib filtered to execution::kv_arch, execution::kv_cache_advisor, execution::memory_estimate, execution::quant_advisor, server::prompt_cache and the new startup sizing test (358 passed), cargo test -p mlxcel-core --lib mla::cache (11 passed), and cargo fmt --all -- --check. MemoryEstimate is not Serialize, so the added kv_mode field does not touch the inspect JSON schema; recommend_state_checkpoint_capacity takes the mode only to share the same memory-left budget as the other stores.

The serve `--estimate-memory` preflight sized only `--kv-cache-mode` and ignored `--kv-bits` / `--kv-quant-scheme`, which the scheduler prefers, so a DeepSeek V2 run could be undercounted. The startup family rule is now one shared helper set in `server::cli_input` (`disable_batch_kv_quant_for_family`, `kv_mode_for_batch`, `effective_serve_kv_cache_mode`) used by `into_startup_config`, the preflight and `prompt_cache_sizing_kv_mode`, with the startup warning text unchanged. `generate` has no `--kv-bits` flag, so its preflight has no equivalent gap.

With absorbed MLA decode on, any non-fp16 mode on `deepseek_v2` made the run store the decompressed per-head cache, which is larger than the fp16 latent. The mode resolver now substitutes fp16 with a warning in that case (`MLXCEL_MLA_ABSORBED=0` keeps the quantized layout), `--kv-bits` follows because it goes through the same resolver, and the advisor classifies against the resolved mode. `deepseek_v2` stays out of `MLA_LATENT_CACHE_FAMILIES`.

Also reflows an over-wide comment in the KV advisor, and updates docs/turbo-kv-cache.md and the changelog.

Validated with the allowlist, advisor, kv_arch, memory_estimate, snapshot sizing and serve_preflight tests, clippy with -D warnings, and fmt.
kv_modes_do_not_advertise_runtime_fp16_downgrades failed on any host where absorbed MLA decode is on (Metal with the fused kernel, CUDA, ROCm): the new deepseek_v2 rule in resolve_kv_cache_mode_for_model resolves int8 and turbo4 to fp16 there, while the registry advertises both for the family.

kv_modes is a static capability table published through mlxcel arch --json and the recipes/registry snapshots, so it cannot follow a per-host decision. The test now evaluates the family rules with absorbed decode off, where deepseek_v2 does hold int8 and turbo4 (MLXCEL_MLA_ABSORBED=0), and documents why.

Verified on Metal: models::registry, cli::turbo_args, execution::kv_arch, execution::kv_cache_advisor, execution::memory_estimate, server::prompt_cache::snapshot_sizing, server::startup_tests and server::cli_input (352 passed); cargo fmt --check clean.

Refs #3153
@inureyes

Copy link
Copy Markdown
Member Author

Security and Performance Review

No security-relevant surface (no new input parsing beyond existing validated CLI flags). Findings are memory-sizing correctness and test integrity.

Fixed

  • HIGH, src/models/registry.rs kv_modes_do_not_advertise_runtime_fp16_downgrades: failed on every host with absorbed MLA on (Metal with the fused kernel, CUDA, ROCm) because the new deepseek_v2 substitution resolves int8/turbo4 to fp16 while the static registry advertises both. kv_modes is a host-independent table (mlxcel arch --json, recipes/registry/*.json), so the test now checks the rules with absorption off, where V2 does hold those modes. Commit 37af4c1.

Remaining

  • MEDIUM, src/server/startup.rs prompt_cache_sizing_kv_mode and src/server/cli_input.rs effective_serve_kv_cache_mode: with --kv-bits 8 and the default --kv-skip-last-layer true, every layer is sized as INT8 while the last layer runs FP16 (BatchKvQuantConfig::resolve_layer_modes). That undercounts by half of one layer (about 1.5% on 32 layers); the doc comment claiming "keeps the estimate on the larger side" holds for Turbo (FP16 width) but not INT8. Previously these paths sized FP16, so this is a small regression in the unsafe direction. The INT8 element width also ignores per-token scales (pre-existing). A per-layer correction in kv_arch would close both.
  • LOW: the serve preflight runs before build_startup_input applies the LLAMA_ARG_KV_BITS/MLXCEL_* env fallbacks, so an env-only --kv-bits is sized FP16 (overestimate, safe).
  • LOW: the estimate assumes absorption succeeds whenever absorbed_enabled() holds; MlaAbsorbedProjections::from_kv_b_proj declines a biased kv_b_proj, leaving decompressed FP16 sized as the latent. Pre-existing, no shipped checkpoint affected.

Checked, no issue

  • absorbed_enabled() is OnceLock-cached (env, fused-kernel availability, backend), and the loader reads the same value, so resolution-time and runtime decisions cannot differ within a process.
  • Startup, serve preflight and prompt-cache sizing share disable_batch_kv_quant_for_family and kv_mode_for_batch; no drift found.
  • Sizing arithmetic in sum_groups is saturating; no new panics.
  • No per-request cost: the resolver runs at startup, inspect, advisor and profile load only.

Tests

Metal, serially: 352 lib tests across models::registry, cli::turbo_args, execution::{kv_arch,kv_cache_advisor,memory_estimate}, server::prompt_cache::snapshot_sizing, server::startup_tests, server::cli_input; mlxcel-core cache::turbo::allowlist (16); bin serve_preflight (7); cargo fmt --check.

The serve preflight and prompt-cache sizing charged every layer at the batch base mode. With --kv-bits 8 and the default --kv-skip-last-layer, resolve_layer_modes keeps the last layer at FP16, so the estimate undercounted by half of one layer, the unsafe direction for a memory budget. The previous doc comment claiming the base mode errs large was wrong for INT8.

Add kv_arch::KvSizing (mode plus fp16_last_layer). The estimators now take impl Into<KvSizing>, so callers holding only a KVCacheMode are unchanged. kv_mode_for_batch and effective_serve_kv_cache_mode return it, carrying the skip-last-layer decision. For INT8 the estimate adds the widest layer's FP16-minus-INT8 delta: exact for dense stacks and for Gemma-style stacks whose last layer is global, and a round-up for stacks whose last layer is narrower or holds no KV. Turbo modes stay at the FP16 width.

INT8 per-token scale bytes are not included: kv_arch groups carry no head_dim, and the batch affine path stores scales and biases per group_size, so it is not a contained change.

Tests compare the estimate with the bytes the runtime layer modes imply on a dense llama and a Gemma 4 style stack, and check skip off sizes all INT8.

Refs #3153
The MLXCEL_MLA_ABSORBED entry and the absorbed decode guide still said a non-FP16 KV mode simply keeps the decompressed path. They now state that, with absorption on, a quantized KV request on deepseek_v2 resolves to fp16 with a warning because the decompressed quantized layout is larger than the fp16 latent, that MLXCEL_MLA_ABSORBED=0 keeps it, that the memory estimate sizes the resolved layout, and that a quantized latent cache is future work (#3158). No Korean counterparts exist for these pages, and the CLI help text makes no MLA savings claim.

Refs #3153
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 18, 2026
@inureyes
inureyes merged commit 9ede15d into main Nov 18, 2026
32 checks passed
@inureyes
inureyes deleted the fix/issue-3153-v2-kv-mode-sizing branch November 18, 2026 21:09
@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) priority:high High priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(memory): size DeepSeek V2 KV through the non-FP16 cache-mode decline

1 participant