Repository navigation
perf(models): release superseded KV buffers in DeepSeek V2 prefill - #3091
Merged
Merged
Conversation
3 tasks done
Each chunked-prefill piece grew every layer's dense KV cache by concatenating it into a larger buffer inside the lazy graph. The freed old buffer went to MLX's allocator cache, where no later request in the piece could reuse it (they all ask for the larger size), so the whole previous cache stayed resident until the engine's per-piece flush. On DeepSeek V2's default path, which caches decompressed per-head K/V, that was 7.4 GB at a 28.7K-token prompt. KVCache::reserve_rows (new cache/fp16_growth.rs) grows the buffer before the layer's graph is built through the same growth rule update_fp16 now shares, queues the copy with async_eval, and empties the allocator cache at the next layer's reservation. DeepSeek V2 calls it on both the decompressed and the latent caches. deepseek-v2-lite-chat-4bit-mlx on M5 Max, 2048-token pieces: peak 27.98 to 21.04 GB (absorbed path 15.12 to 14.35 GB), prefill about 2% slower, greedy output byte-identical in every cell; single pass unchanged. New unit tests check the eager growth leaves buffers byte-identical to the lazy growth, including after a trim. Closes #3084
inureyes
force-pushed
the
perf/issue-3084-v2-mla-prefill-peak
branch
from
November 15, 2026 17:41
341eadb to
9a72391
Compare
inureyes
marked this pull request as ready for review
November 15, 2026 17:41
This was referenced Nov 15, 2026
inureyes
added a commit
that referenced
this pull request
Nov 15, 2026
A chunked-prefill piece grows every layer's dense FP16 KVCache, and each superseded buffer lands in MLX's allocator cache, where no later request in the piece can reuse it, until the engine flushes after the piece (#672). #3091 fixed this for DeepSeek V2 only, through explicit KVCache::reserve_rows calls. The release now lives in the shared FP16 growth inside update_fp16: a multi-token growth of an existing buffer empties the allocator cache, builds the grown buffer, and queues its copy with async_eval. First fills, decode rows, appends that fit, and the quantized, rotating and pool-backed layouts are unchanged. The grown buffer is the one the lazy growth built, so outputs are byte-identical. DeepSeek V2's explicit calls and reserve_rows are removed. Unit tests cover growth, trim, no-growth, decode, INT8 and pool-backed caches; tests/kv_growth_release.rs guards the allocator-cache effect against a lazy-growth control (and fails with the release disabled). Refs #3092
inureyes
added a commit
that referenced
this pull request
Nov 15, 2026
…ill (#3096) ## Summary A chunked-prefill piece grows every layer's dense FP16 `KVCache`, and each superseded buffer sat in MLX's allocator cache until the engine flushed after the piece (#672). #3091 released those buffers for DeepSeek V2 only, through explicit `KVCache::reserve_rows` calls. The release now runs inside the shared FP16 growth in `KVCache::update_fp16`, so every model on the dense cache gets it without per-model calls. - A multi-token growth of an existing buffer empties the allocator cache (returning what earlier layers' growths released), builds the grown buffer with the same rule as before, and queues its copy with `async_eval`. Growth is still per layer at append time; reserving every layer at forward start was rejected in #3091. - First fills, decode rows, appends that fit, and the INT8/Turbo, rotating and pool-backed layouts do not take this path. The grown buffer is the one the lazy growth built, so outputs are byte-identical. - DeepSeek V2's two `reserve_rows` calls and `reserve_rows` itself are removed; its decompressed and latent caches both reach `update_fp16`, and its peak is unchanged against main. ## Measurements (M5 Max, 28K-token prompt, 2048-token pieces, order-reversed pairs) | model | peak, main | peak, branch | prefill change | output | |---|---|---|---|---| | qwen3-4b-4bit | 10.94 GB | 7.26 GB | -1.1% | identical | | meta-llama-3.1-8b-instruct-4bit | 10.39 GB | 8.09 GB | +2.9% | identical | | gemma-3-4b-it-4bit | 5.25 GB | 4.86 GB | +2.7% | identical | | deepseek-v2-lite-chat-4bit-mlx | 20.20 GB | 20.20 GB | +0.2% | identical | Single pass is unchanged in peak and output for all three families. Gemma's smaller saving is expected: only its 5 global layers use `KVCache`. Details and raw rows are in `docs/benchmark_results/kv-growth-release-all-models-m5max-2026-11-15.md`. Arithmetic is unchanged (same buffers, same writes), so no logit trace applies; greedy output is byte-identical in every cell. ## Test plan - [x] `cache::fp16_growth_tests` (growth across pieces, trim, no-growth, decode, first fill, INT8, pool-backed), `cache::kv_trim_tests`, `mla::`, causal-mask roster test - [x] `tests/kv_growth_release.rs`: the releasing piece parks 151 MB against 403 MB for the lazy-growth control; with the release disabled it reads 403 MB and fails - [x] Narrow clippy for `mlxcel-core` (lib and tests) and `mlxcel`, `cargo fmt --check`, env-var docs, benchmark raw-log and kernel dtype-key checks Closes #3092
This was referenced Nov 15, 2026
inureyes
added a commit
that referenced
this pull request
Nov 16, 2026
…nt (#3118) ## Summary The issue gives the rule: the latent MLA cache becomes DeepSeek V2's default only if absorbed decode holds throughput within a few percent and the teacher-forced trace shows no material disagreement. Measured on deepseek-v2-lite-chat-4bit-mlx (M5 Max), the trace condition holds and the throughput condition does not, so the default stays decompressed and `MLXCEL_MLA_ABSORBED=1` stays opt-in. No model code changes. | measurement | decompressed (default) | absorbed | |---|---|---| | decode pp512/tg128, median tok/s (5 samples each) | 200.6 | 180.7 (-9.9%) | | decode behind 2048-token prompt, tg128 | 168.1 | 161.9 (-3.7%) | | decode behind 16384-token prompt, tg128 | 70.9 | 111.2 (+57%) | | peak at 28,705 tokens, 2048-token pieces | 20.20 GB | 13.52 GB | | peak at 28,705 tokens, single pass | 48.55 GB | 41.02 GB | | trace, decided positions that disagree (gap >= 2) | reference | 0 of 3,653 | The traces run at prefill width 2048 (cold and behind 2048 cached) and decode width 1 (behind 1024 and 8192). `MLXCEL_TRACE_MLA_STATS` counters confirm that the absorbed arm took `absorbed_composed` on every traced decode step. Prefill time could not be compared because concurrent compiles on the shared host spread one cell from 59 to 95 s. Earlier quiet-host runs (#3084, #3091) found no prefill difference between the layouts. Greedy text differs between the arms only at a near-tie digit inside an answer both arms get wrong, and which arm gets which text swaps between chunk modes. ## Changes - `docs/mla-absorbed-decode.md`: new "Default layout for DeepSeek V2" section with the numbers, the reason, and what would change the decision (the absorbed step's fixed per-step cost, about 0.55 ms at 512 context, which pays back only past about 3K tokens). The environment-variable row and CHANGELOG Known Issues entry point to it. - `docs/benchmark_results/mla-v2-default-layout-m5max-2026-11-15.md` plus `decode.csv`, `prefill.csv`, `logit_trace.csv`. - `examples/logit_trace.rs`: the `MLXCEL_TRACE_BATCH_ROWS` arm returned before `MLXCEL_TRACE_MLA_STATS` was read, so width-one decode traces printed no path counters. Both arms now print them. No other family shares the choice: only `deepseek_v2` reads the flag, V3 and V3.2 always absorb, and `minicpm3` and `dots1` have no absorbed path. ## Test plan - [x] `cargo fmt --check`, `cargo clippy -p mlxcel --example logit_trace --features metal,accelerate -- -D warnings` - [x] `check_env_var_docs.py`, `check_benchmark_raw_logs.py`, `make verify-kernel-dtype-keys` - [x] `utils::tests::create_causal_mask_roster_count_matches_repo` - [x] The rebuilt `logit_trace` batched arm prints `# mla_paths` (counters quoted above) Closes #3102
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
DeepSeek V2's default MLA path does not re-expand the latent cache per piece: it caches decompressed per-head K/V and appends to them. A per-layer MLX memory probe on the last full 2048-token piece (26,624 tokens cached) splits the 12.85 GB gap to the absorbed path into two parts:
About 7.0 GB is the decompressed layout itself. The other ~6.2 GB is dead KV: each layer's growth concatenates its cache into a larger buffer, and the freed old buffer sits in MLX's allocator cache, where nothing later in the piece can reuse it, until the engine's per-piece flush. Attention transients are already bounded (about 2.1 GB per layer).
Change
KVCache::reserve_rows(newcache/fp16_growth.rs) grows a dense FP16 buffer before the layer's graph is built, queues the copy withasync_eval, and empties the allocator cache at the next layer's reservation.update_fp16and the reservation share one growth helper, so the grown buffer is byte-identical to the lazy one. It does nothing for decode rows, first fills, appends that fit, and quantized or paged layouts.Results (M5 Max, 28,705-token prompt, 48 greedy tokens)
One diagnostic binary with a mode switch (off as control) puts the prefill cost at about 2% (off 41.97 / 42.15 s, shipped 43.13 / 42.87 s). Arithmetic is unchanged and every cell's output is byte-identical, so there is no logit trace. Details and raw rows:
docs/benchmark_results/mla-v2-prefill-cache-growth-m5max-2026-11-15.md.Test plan
cache::fp16_growth_tests(eager growth matches lazy growth across pieces and after a trim; declines for first fill, fit, decode and Int8), pluscache::kv_trim_tests,mla::,models::deepseek_v2::tests, and thecreate_causal_maskroster testmlxcel-coreandmlxcel, env-var docs, raw-log and kernel dtype-key checksCloses #3084