Skip to content

perf(models): release superseded KV buffers in DeepSeek V2 prefill - #3091

Merged
inureyes merged 2 commits into
mainfrom
perf/issue-3084-v2-mla-prefill-peak
Nov 15, 2026
Merged

inureyes merged 2 commits into
mainfrom
perf/issue-3084-v2-mla-prefill-peak

Conversation

@inureyes

Copy link
Copy Markdown
Member

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:

path live KV, 27 layers active at layer 26 allocator cache, layer 0 to 26 footprint
decompressed (default) 7.9 GB 17.21 GB 3.05 to 10.47 GB 27.94 GB
absorbed 0.9 GB 10.29 GB 3.18 to 4.32 GB 14.88 GB

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 (new cache/fp16_growth.rs) grows a dense FP16 buffer before the layer's graph is built, queues the copy with async_eval, and empties the allocator cache at the next layer's reservation. update_fp16 and 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.
  • DeepSeek V2 calls it before the decompressed and latent cache updates. Batching every layer into one reservation was tried and measured 27.97 GB, because it holds every old and new buffer at the same time.

Results (M5 Max, 28,705-token prompt, 48 greedy tokens)

cell peak main peak branch prefill main prefill branch output
default, 2048 pieces 27.98 GB 21.04 GB 42.18 s 42.77 s identical
absorbed, 2048 pieces 15.12 GB 14.35 GB 42.19 / 42.21 s 42.51 / 42.25 s identical
default, single pass 54.44 GB 54.43 GB 52.72 s 52.55 s identical

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

  • New cache::fp16_growth_tests (eager growth matches lazy growth across pieces and after a trim; declines for first fill, fit, decode and Int8), plus cache::kv_trim_tests, mla::, models::deepseek_v2::tests, and the create_causal_mask roster test
  • fmt, clippy for mlxcel-core and mlxcel, env-var docs, raw-log and kernel dtype-key checks

Closes #3084

@inureyes inureyes added status:done Completed type:performance Performance improvements priority:high High priority area:models Model architectures, weights, loading, metadata area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:macos macOS (Apple Silicon) specific labels Nov 15, 2026
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
inureyes force-pushed the perf/issue-3084-v2-mla-prefill-peak branch from 341eadb to 9a72391 Compare November 15, 2026 17:41
@inureyes
inureyes marked this pull request as ready for review November 15, 2026 17:41
@inureyes
inureyes merged commit 49ea6cc into main Nov 15, 2026
@inureyes
inureyes deleted the perf/issue-3084-v2-mla-prefill-peak branch November 15, 2026 17:42
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
Main against branch on M5 Max, 28K-token prompt, 2048-token pieces (order-reversed pairs) and single pass for qwen3-4b-4bit, meta-llama-3.1-8b-instruct-4bit and gemma-3-4b-it-4bit, plus DeepSeek V2 for consistency with #3091. Adds the CHANGELOG entry.

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
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
@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:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata platform:macos macOS (Apple Silicon) specific priority:high High priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(models): DeepSeek V2 default MLA prefill peaks 12.85 GB above the absorbed path

1 participant