Repository navigation
fix(cuda): default paged sliding-window KV off on CUDA - #3676
Merged
Merged
Conversation
Since #3334, FP16 Gemma 3 and Gemma 4 scheduler sequences keep sliding layers in window-bounded paged blocks on every backend. On CUDA the paged single-row decode is slower than the ring storage it replaced: a paged-attention plus merge kernel pair per layer instead of one `sdpa_vector`, and four host arrays per layer per step that land in managed memory and force graph updates. Gemma 4 31B NVFP4 on a B200 decoded at 63.1 tok/s before #3334 and 50 to 51 tok/s at it (pp512/tg128, CUDA graphs on). `mlxcel_core::memory::paged_sliding_state_default()` reads MLXCEL_PAGED_SLIDING and otherwise defaults to on everywhere except CUDA; the Gemma 3 and Gemma 4 wrappers use it, and test builds keep paged storage on so the #3334 tests still run on every backend. Metal is unchanged. With it, current main decodes at 63.3 tok/s on the same measurement. Making the paged path allocation-free and graph-stable on CUDA is tracked by #3667 and #3668. Local validation on CUDA: the paged-sliding and Gemma 3/4 lib tests (168 passed) and the new default-resolution unit test; scripts/ci/check_env_var_docs.py lists the new variable as documented. Closes #3675
inureyes
added a commit
that referenced
this pull request
Dec 2, 2026
…xture The checked string fixture in tests/fixtures/webui/strings.json must list every key the feature string modules declare. This branch added settings.startup.diffusing_interval and #3676 added settings.startup.swa_full on main, but neither entry reached the fixture, so the WebUI drift and shell tests failed on the merged tree. Both entries now sit next to the same neighbours as in startup-strings.ts. The full WebUI vitest suite (858 tests) and the WebUI contract check pass. Refs #3660
inureyes
added a commit
that referenced
this pull request
Dec 2, 2026
ModelOpt leaves `self_attn` in bf16 in exports such as nvidia/Gemma-4-31B-IT-NVFP4, which is more than half of the bytes a decoded token streams. MLXCEL_DENSE_ATTN_QUANT=mxfp8|nvfp4 requantizes the dense text q/k/v/o projections at load and records their layout, and Gemma 4 now resolves attention projections through `quant_params_for`, since an 8-bit group-32 plane has the same packed shape as a 4-bit group-64 one. The dequantize + cuBLASLt prefill path also takes MXFP8. On a B200 (pp512/tg128): bf16 84.2 tok/s decode, MXFP8 87.8, NVFP4 90.6, with prefill 4444, 3658 and 3768 tok/s. Against bf16, the teacher-forced trace changes 0.68% of top-1 choices on decided positions for MXFP8 (none above a gap of 3.1) and 14.9% for NVFP4, so the switch stays opt-in and MXFP8 is the one to use. This also restores the environment-variable rows for the CUDA overlay switches that the rebase conflict resolution dropped, and records the #3334 regression bisect (fixed in #3676) in the report. Local validation: the Gemma 4 and sanitize lib tests (617 passed) including a new parse test, and scripts/ci/check_env_var_docs.py.
This was referenced Dec 2, 2026
inureyes
added a commit
that referenced
this pull request
Dec 2, 2026
On CUDA, batched decode now runs RoPE as one array-offset `fast::rope` launch per layer for the whole batch. On the pooled paged path it also appends K and V with one in-place indexed write per side per slab. Before, each row cost a slice, an op and a concatenate. `MLXCEL_BATCHED_DECODE_LAUNCHES` selects the batched forms and defaults on only for CUDA. The per-row code stays as the Metal, ROCm and CPU path and as the fallback, and a test walks every backend kind. The KV write is a new `InplaceScatterRows` primitive. Its output shares the slab buffer, and a JIT CUDA kernel copies each row. `PagedBlockPool::write_decode_rows` keeps the per-row block bookkeeping and routes rows that are not exclusive and already owned through the per-row write. The Gemma 4 q/k norm was already applied to the whole batch, and K and V differ in Gemma 4, so neither needed a change. Since #3676, Gemma 4 on CUDA decodes from dense rows by default, so on CUDA the batched write runs by default for the pooled families (Llama 3, Qwen 2/2.5/3, Helium) and for Gemma 4 only with MLXCEL_PAGED_SLIDING=1. GB10 nsys, launches per step at c=8: Gemma 4 12B RoPE 689 to 97 (the c=1 count). Copies 1661 to 515 on Llama 3.1 8B and 2028 to 214 on Gemma 4 paged. Greedy parity: Llama 3.1 8B 12/12 identical. Gemma 4 31B 11/12 and 12B paged 5 of 8 distinct rows identical, with every divergence a near-tie in main's own logprobs. The divergences trace to a one-ulp bf16 difference between MLX's general and single-row RoPE kernels, and a unit test checks the batched form is no less accurate than per-row against f32. Scoped core, paged and gemma4 tests and scoped clippy pass. The B200 per-step bound and serving table are deferred to the B200 follow-up measurement issue. Closes #3665
inureyes
added a commit
that referenced
this pull request
Dec 2, 2026
## Summary Stores the server's paged KV block pool as FP8 E4M3 on CUDA (sm_89+), selected by `--cache-type-k fp8 --cache-type-v fp8` (alias `fp8_e4m3`) or automatically when the checkpoint declares `kv_cache_quant_algo: FP8`. Halves pool bytes per token, so the same budget holds twice the blocks. Part of epic #3671. Closes #3666 ## Design - FP8 is a property of the pool (`PagedKvDtype`), not of a sequence. `KVCacheMode::Fp8E4m3` maps to `Fp16` for dense caches (`dense_storage_mode()`), so the pool-backing gates keyed on `Fp16` still route sequences into the pool, and layers kept in dense caches stay f16. - The pinned MLX has no float8 dtype; the slabs hold `uint8` E4M3 bytes written through `mlx::core::to_fp8` and read through `from_fp8`, with one scalar scale per layer and side (1.0 unless the checkpoint ships `k_proj.k_scale` / `v_proj.v_scale`; values beyond +-448 saturate, as in vLLM). - Encoding happens once at the float entry points: `write_prefill`, the batched `write_decode_rows` (the #3665 `InplaceScatterRows` path now moves E4M3 bytes), and a float block given to `write_block`. Bytes pass through unchanged, so copy-on-write forks and block transfers never re-encode. - `gather_visible` dequantizes to the layer's compute dtype before SDPA. Prefill attention uses the history from the pool plus the chunk just written at its computed precision. - Fused decode: the v2 partial kernel gets a CUDA fp8 port (`mlxcel_paged_attention_v2_partial_fp8`) that loads E4M3 bytes directly; the K scale folds into the softmax scale and the V scale multiplies the output. The v1 kernel and cascade have no fp8 port: v1 declines to the gather path and cascade falls back to the flat v2 launch. A one-time info line names the fp8 kernel when it runs. - Memory plan (#3664): `WorkerPlanRequest.pool_one_byte` makes pooled slabs, the block budget, and prompt-cache retained rows count one byte per element. It is set only when the model's KV actually lives in the pool (`DenseKvCache` layout on a paged decode backend, or a paged-sliding family) on a single-node server. Dense layers outside the pool are still planned at f16. The `KV capacity` log line carries `kv_pool_dtype`. - Shared K==V slab (#3664) is unaffected: Gemma 4's `attention_k_eq_v` layers store both K and V, each encoded with its own scale. ## Default paths FP8 affects - Pool-backed families on CUDA (Llama, Qwen and the other dense families that use the pool by default): every pooled layer stores FP8 once the flag or the checkpoint selects it. - Gemma 4 on CUDA: unaffected by default. Since #3676 (`MLXCEL_PAGED_SLIDING` unset) it decodes from dense per-sequence caches, which keep f16. FP8 applies only with `MLXCEL_PAGED_SLIDING=1`. This includes the Gemma 4 31B NVFP4 checkpoint: it is detected as declaring fp8, but on the default path the worker warns `fp8_e4m3 KV is not applied ...`, leaves the pool native, and plans f16. So the issue's KV-capacity and TPOT goals for the 31B need `MLXCEL_PAGED_SLIDING=1` (or a later default change) and are part of the B200 follow-up. - Any model whose KV is not in the pool (model-owned state, scheduler-owned state kept dense, the dense decode backend) and disaggregated prefill-only / decode-only nodes keep f16 with the same warning; the plan is not halved for them. - Models loaded by the router from `--models-dir` do not read the checkpoint declaration yet (explicit flags still apply). - `mlxcel generate`, `mlxcel run`, the chat REPL, IndicOCR and `bench_decode` keep dense caches and reject `fp8` with an error naming the command. `--kv-bits` with fp8 is rejected at server startup. ## How Metal stays unchanged - The explicit flag fails at startup on any device that is not CUDA sm_89+ (the message names the compute capability), and a WebUI load profile asking for fp8 is refused the same way. - A checkpoint that declares FP8 keeps f16 on Metal and older GPUs with an info line; no error, no behaviour change. - With fp8 never selected, the pool stays `PagedKvDtype::Native`, every new branch is a no-op (`encode_kv` / `decode_kv` return `None`), and the v2 kernel selection only takes the fp8 port when the slab dtype is `uint8`. The Metal kernel sources are not modified; a non-CUDA backend handed a `uint8` pool throws rather than misreading it. ## Changes after review - The one-byte plan rule now follows where the KV actually lives (review finding: model-owned families would have had their block budget doubled while storing f16), and a non-pooled or disaggregated run leaves the pool native and warns instead of claiming fp8. - `--kv-bits` counts as a KV flag, so it opts out of the checkpoint default. - Plan and pool agree by construction: `cli::kv_fp8::decide_paged_fp8` decides fp8 applicability and validates checkpoint scales (against the pool's layer count, which is the layer-state kind count for a paged-sliding pool) once, before the memory plan; `pool_one_byte` and the pool dtype both come from it. `CachePool::set_paged_kv_dtype` rejects bad scale values immediately, and the scheduler builder keeps the pool native with an error log if the switch ever fails. - `--cache-type-k/v fp8` together with `--kv-bits` is a startup error: batch KV quantization drives its own int8/Turbo layout, which the fp8 pool never backs. - Scales that do not fit (wrong layer count, non-finite or non-positive values, tensors past the pooled layers) fall back to 1.0 with a warning instead of silently; `CachePool::ensure_paged_pool` warns once on a layer-count mismatch, and the `from the checkpoint` log line appears only when validated scales reached the pool. - `mlxcel run` and the `mlxcel generate` chat REPL name themselves in the fp8 refusal instead of "this command". - New test `fp8_fused_decode_applies_scales_on_bf16`: non-unit K/V scales (4.0 / 0.25) through the fused v2 path on bf16 inputs, in the same process as f16 launches. ## Verification Narrow tests, server comparisons and numbers: see the status comment on this PR. ## Deferred to the B200 follow-up measurement issue - Gemma 4 31B NVFP4 startup with the FP8 pool and its memory plan on B200. - Logit trace of FP8 against f16 on the 31B. - Serving table at c=1/8/32 on B200 and c=32 TPOT. These need the 31B and B200 hardware; this PR validates on small models on GB10.
7 tasks done
inureyes
added a commit
that referenced
this pull request
Dec 2, 2026
## Summary Unit of epic #3671. On CUDA the scheduler's decode step no longer builds its per-step inputs as host arrays: token ids, RoPE offsets, paged page tables and plan arrays, KV write slots and token-bias rows are written to a pinned staging slot and uploaded with at most two `cudaMemcpyAsync` calls per step into one device buffer whose address is fixed for the scheduler's life (`mlxcel_core::step_inputs::StepInputBuffers`). Pooled decode steps are padded to bucket sizes from `decode_bucket_for`, the single source #3668 reuses. The CUDA allocator overlay counts the unified buffers it hands out (`mlxcel_core::memory::unified_alloc_count()`), and `/metrics` exposes that count and the padded steps. ## Path statement - Pooled families (Llama, Qwen): persistent inputs and padding are on by default on CUDA. Both the synchronous step (what a server with an explicit `--ctx-size` runs) and the lookahead pipeline (the default without it) are covered. - Gemma 4 on CUDA decodes from dense per-sequence caches by default (`MLXCEL_PAGED_SLIDING` off since #3676; that default is not changed here, the decision belongs to the end of #3668). Its host arrays (token ids, RoPE offsets, the pooled full-attention layers' page tables) move to the persistent buffer on both the default path and `MLXCEL_PAGED_SLIDING=1`. It is not padded: dense and scheduler-owned rows have no slot for a pad row without a model rewrite. - Metal, ROCm, CPU: unchanged. `step_inputs::enabled_from(env, backend)` is false off CUDA whatever the environment says, so the buffers are never constructed, and every consumer calls `stage_i32` / `stage_f32`, which are exactly `from_slice_*` when no step is active on the thread. Unit-tested for every backend; `cargo check -p mlxcel --lib --tests` at default features passes. `MLXCEL_STEP_INPUTS=0` and `MLXCEL_DECODE_PADDING=0` restore the old step on CUDA. ## What the measurement changed The issue's 99k `cudaMallocManaged` / `cudaFree` figures came from the unmerged #3650 branch, which released the allocator cache between steps. Main does not (`clear_cache_between_steps`, `MLXCEL_STEP_CACHE_CLEAR` and the Gemma4 sm100 report do not exist on main and are not added), so its size-keyed buffer cache already absorbs the host arrays: on GB10 main was under the issue's nsys thresholds before this PR. The arrays were still requested every step, which is what the counter shows and what #3668 cannot replay, so the counter counts requests, not driver calls. GB10, four concurrent requests (about 430 prompt tokens, greedy), 10 s steady window, `--parallel 8 --ctx-size 65536`. "Requests" is unified buffer requests per decode step from `/metrics` (before = same binary with `MLXCEL_STEP_INPUTS=0`); nsys counts are per window, with steps in the window in brackets. The nsys rows were taken on a19f081 plus the pad-row eviction change; the last commit adds only the two `/metrics` counters and tests, and the parity and counter runs below are on the final commit. | Config | Requests per step | `cudaMallocManaged` | `cudaFree` / `cudaFreeAsync` | `cudaMallocAsync` | `cudaMemcpyAsync` after | |---|---|---|---|---|---| | Llama 3.2 1B 4bit, pooled | 163 -> 0 | 18, 16 -> 0 | 0 / 6, 7 -> 0 / 0 | 0 -> 1 | 1990 (994 steps) | | Gemma 4 12B 4bit, `MLXCEL_PAGED_SLIDING=1` | 483 -> 0 | 0 -> 0 | 0 -> 0 | 204, 176 -> 176 (about 126 steps) | 254 | | Gemma 4 12B 4bit, default dense | 99 -> 0 | 0 -> 0 | 0 -> 0 | 322, 322 -> 322, 322 (about 118 steps) | 117 | The remaining `cudaMallocAsync` (1.4 to 2.7 per step on Gemma, under the issue's 8) is identical with and without this change, so it does not come from host arrays; it was not attributed further (the release binary is stripped and an unstripped run showed 2 calls in its window). `cudaGraphLaunch` per step on Llama is unchanged at 17.2. ## Deviations from the issue text - No `V2Context::from_persistent` and no `mlxcel_step_inputs_upload` function: `V2Context::build` and the other consumers call the staging helpers, and the upload is a lazy MLX node the staged views depend on, so ordering with the encoder comes from the graph and a failed copy surfaces as the step's eval error with the CUDA error string. - The buffers are created at the scheduler's first decode step (the server's startup warmup), because the slab sizes that size them are installed after construction. - A pad row is a real pool-backed sequence rewound to one token before each padded forward, not an empty CSR range: a zero-page request breaks the paged plan's chunk-per-request assumption and gives NaN rows. - The fused sampler's temperature, top-p, top-k and seed are scalars passed by value, so only the token-bias rows moved. The cascade launch (off by default), the per-row sampler chain, prefill and speculative or MTP verify steps keep host arrays. Sampled token readback needed no change: the allocator moves a token buffer to unified memory once and then reuses it, so moves are 0 in every steady window measured (the Gemma 4 lookahead test arm shows about 1030 moves during prefill and warmup, 0 in its measured window). - Fallbacks. A batch the buffers cannot hold (inputs past the capacity, which also covers a row with more blocks than the plan sized for): the rest of that step builds host arrays, logged once. KV pool growth during decode: the grown layer leaves the fused read as before (multi-slab decline, already logged once per outcome) and its gather indices still stage or fall back by size. Speculative and MTP verify steps (L > 1) never open a step scope, so they keep today's path; every caller of the padded entry points is a single-token decode tick. No pool slot or KV block for a pad row: the step runs unpadded, logged once. Pad rows give their slots and blocks back before a request is refused or anything is evicted: every block reclaim (decode reservation, prefill admission, chunked-prefill reservation) first calls `PagedBlockReclaimer::release_spare_blocks`, which closes the pad rows, and a pad row is not opened when no block is free beyond the real rows' need plus the admission headroom. Known minor gaps: the batched-prefill window (`paged_prefill_room`) and the prompt-lookup verify fit checks count free blocks without reclaiming, so pad rows can shrink a batched prefill or turn a verify step into a plain decode; surplus pad rows after a bucket shrink stay open until the batch empties or a reclaim runs, and they count in the `active_count()` gauge. ## FP8 KV pool (#3666, merged into this branch) The staging and padding do not branch on pool dtype; FP8 per-layer scales are scalars, not per-step host arrays. With `--cache-type-k fp8 --cache-type-v fp8` the persistent inputs and padding work unchanged (server smoke below). One observation that is not introduced here: with an FP8 pool, a request's greedy tokens depend on the batch shape late in a long generation. With `MLXCEL_STEP_INPUTS=0` and no padding, request 0 alone vs in a batch of 3 or 4 diverges near token 47 on Llama 3.2 1B, while the f16 pool does not; consequently padded vs unpadded FP8 runs diverge between about token 100 and 150 at 160 tokens (each arm is deterministic, and 64-token runs match). The FP8 arm of the padding test therefore compares the first 32 tokens; the f16 arm compares every token. This looks like an FP8 decode-kernel property from #3666 and is left for a follow-up. ## Test plan - [x] Server test `scheduler_step_inputs` (Llama 3.2 1B 4bit, 4 rows, 50 steady steps): +0 unified requests on the gather, fused v2 and lookahead arms. Checked failing first on main plus the counter (stage A commit): +12150, +8630, +12132 (all three arms ran the gather path at that commit; the fused arm got its slab size in stage B). Gemma 4 12B own-path arms: +0 with and without `MLXCEL_PAGED_SLIDING=1`. - [x] Padding: three rows in the 4-row bucket give the same 114 greedy tokens per request as with padding off (gather, fused, lookahead arms). `decode_bucket_for` unit tests cover 1..=32, 33..=64, the cap and the panic. - [x] `step_inputs` unit tests (13): values, fixed device address, an in-flight step surviving the next step's staging, stale evaluation error, overflow fallback, scopes dropped out of order, negative and oversized staging shapes, the gates. - [x] Greedy parity on `mlxcel-server` against the main 11f1c0a binary, 64 tokens, two repetitions each, compared repetition for repetition (main's own two repetitions differ in one row at c=5 and on Gemma, so each is matched to its counterpart): Llama c=4 4/4, c=3 (padded) 3/3, c=5 (padded to 8) 5/5; Gemma 4 12B default 4/4 and `MLXCEL_PAGED_SLIDING=1` 4/4. - [x] Server counters (Llama 3.2 1B): 0 unified requests over 566 steps at c=4, 673 at c=3 (672 padded), 374 at c=5 (all padded), 648 at temperature 0.7, and 790 pipelined steps without `--ctx-size`. Gemma 4 12B without `--ctx-size`: 0 over 74 steps (default) and 76 (`MLXCEL_PAGED_SLIDING=1`); it stays on the synchronous step there, so the Gemma pipeline is covered by the scheduler test only. - [x] After merging main (FP8 pool): `batch::scheduler` 349 passed; core `step_inputs` 13, `paged_` 285; `scheduler_step_inputs --ignored` 8/8 on the f16 pool and 8/8 on the FP8 pool (`MLXCEL_STEP_INPUTS_FP8=1`, test-only); `block_reclaim` 31 including 7 pad-row reclaim tests. Before the merge: core `paged_v2` 94, `paged_batch` 31, `engine::` 86, `memory::` 27, `sampling` 216; Gemma 3 `scheduler_real_batch_parity` 2 passed; scoped clippy on both crates, fmt, `make verify-*` contract checks. - [x] Server smoke after merging main, release binary, 4 concurrent greedy requests, 64 tokens, two prompt lengths, default vs `MLXCEL_STEP_INPUTS=0` on the same binary: token-identical 4/4 on Llama 3.2 1B 4bit (f16 pool), Llama 3.2 1B 4bit FP8 pool, Gemma 4 12B 4bit default, Gemma 4 12B 4bit `MLXCEL_PAGED_SLIDING=1` with FP8, and Qwen3 1.7B 4bit. Unified buffer requests over each whole run (prefill included), default vs kill switch: 161 vs 18458, 226 vs 18462, 1338 vs 13810, 1728 vs 61093, 351 vs 31544. No `unevaluated`, stale-view or capacity warnings in any server log. - Timing, indicative only (shared host, load 2.4 to 8.8, n=2): Llama 3.2 1B decode steps per second at c=8, main 93, 90 against this branch 90, 90 (paired -3.2%, -0.6%); padding on against off on this branch, c=3 119, 115 against 109, 112, c=5 78, 83 against 77, 81. The c=1/8/32 `serving_compare.py` table was not run, per the 2026-12-02 decision that timing is optional. ## Changes during review - Pad rows now release their KV blocks on every reclaim path (prefill admission and chunked-prefill reservation were missing), not only on the decode reservation and slot paths. - `StepInputScope` holds an `Rc` in the thread-local, so scopes dropped out of order cannot leave a dangling pointer; failed construction releases its pinned slots and events; `capacity_for` saturates instead of overflowing; staging rejects negative and oversized shapes and no longer builds a placeholder array per staged input. - A pad row is not opened when the pool has no block to spare, instead of opening and closing it every tick under pressure. - `docs/CONTINUOUS_BATCHING.md` gained a "Persistent step inputs and bucket padding on CUDA" section. ## Deferred to the B200 follow-up measurement issue - nsys over a 25 s c=8 512/128 window on Gemma 4 31B NVFP4 (managed plus `cudaFree` under 100, `cudaMallocAsync` per step at most 8). - The c=1, 8, 32 serving table with the 3% regression bound, and any 31B number (the 31B was not loaded here). - The cost of padding between buckets on a B200, including 5 to 7 rows padding to 8 past the 7-row amortizing kernel. - Remaining host arrays left for #3668: the one-element `params` array per paged v2 launch, the cascade launch arrays, and the FP8 `full_f32` scale constant when a checkpoint declares a scale other than 1.0. Closes #3667
inureyes
added a commit
that referenced
this pull request
Dec 2, 2026
#3676 turned MLXCEL_PAGED_SLIDING off on CUDA because the paged single-row decode of Gemma 4 measured slower than the dense ring storage on a B200. Decode graphs (#3668) replay only the paged path, and with them the paged path is no longer slower on GB10, so the default is on everywhere again and MLXCEL_PAGED_SLIDING=0 restores the ring storage. Evidence, Gemma 4 12B 4bit at the server's default launch flags, two interleaved rounds, paged against dense in steps/s: 16.5 and 16.6 against 15.9 and 15.9 at one request, 13.6 and 13.7 against 12.2 and 12.4 at four, 10.3 and 10.3 against 8.9 and 8.7 at eight, and 12.3 and 12.5 against 12.2 and 12.3 at four with a stochastic draw, which is not replayed. Greedy output is not always token-identical between the two storages; where they first differ the two candidate tokens are within 0.125 nats, one step of the logits' resolution. The B200 figure has not been re-measured with graphs. Gemma 3 follows the same default, and its single row changed its key every step like Gemma 4's did, so a decode-graph step now sends a plain single-row decode token through Gemma 3's batched forward too. Gemma 3 1B 4bit then replays one row, leaves four rows to the lookahead pipeline, and passes verify mode at one and four rows. A Gemma 4 checkpoint that declares FP8 KV now stores FP8 in the pool by default on CUDA; the documentation says so and that the 31B was not exercised. Comments and docs that described the dense CUDA default are updated. Validated on GB10: core memory, step_graph and decode_graphs tests (45), batch::scheduler (349), the Llama decode graph suite (17), Gemma 3 at one and four rows, Gemma 4 12B at one and four rows and across an admission, scoped clippy on both crates, the default-features check and the verify contract list. Refs #3668
inureyes
added a commit
that referenced
this pull request
Dec 2, 2026
The paged sliding default flipped for Gemma 4 also moved Gemma 3. Gemma 3's multi-row ticks run on the lookahead pipeline, which does not replay decode graphs, and there the paged path measured slower than the dense ring on GB10 (Gemma 3 1B 4bit, default launch, two interleaved rounds: 123.1 and 123.4 steps/s paged against 130.8 and 135.7 dense at four requests; one replayed row was faster, 102.2 and 97.5 against 78.1 and 79.2). Gemma 3 now reads gemma3_paged_sliding_state_default, which keeps the #3676 CUDA default off; MLXCEL_PAGED_SLIDING=1 still selects the paged path. Refs #3668
inureyes
added a commit
that referenced
this pull request
Dec 3, 2026
## Summary On CUDA an eligible decode step is now captured once as one CUDA graph and every later step with the same key launches it: one `cudaGraphLaunch`, one upload of the step inputs and one readback of the tokens, with no per-kernel graph or launch call. Part of epic #3671. - **Path.** Default on for pooled families on CUDA (Llama, Qwen and other families whose rows live in the paged pool). A replayed step is synchronous, so by default a tick of more than one row that the lookahead pipeline can run stays with the pipeline; a single row, and every tick the pipeline cannot run (`--ctx-size` or `--max-kv-size` set, a pending admission), is replayed, and `MLXCEL_DECODE_GRAPHS=always` replays the multi-row ticks too. Gemma 4 and Gemma 3 are graph-eligible through paged sliding state. This PR makes it the CUDA default again for Gemma 4 only (`MLXCEL_PAGED_SLIDING`, see below); Gemma 3 keeps dense sliding state on CUDA by default and `MLXCEL_PAGED_SLIDING=1` makes it eligible. Dense per-sequence caches, whose shapes grow every step, stay eager (tested). - **Mechanism.** A step-capture mode in the CUDA encoder overlay defers every commit of one evaluation, so its kernel nodes and cuBLAS child graphs land in one `cudaGraph_t` that is instantiated once. With MLX's CUDA graphs on, the nodes keep the dependencies the encoder derives; with `MLX_USE_CUDA_GRAPHS=0`, which mlxcel sets for Gemma 4 (#688), each node depends on the one before it, so the graph runs in the order the direct launches had. The graph owns what its step allocated plus the small host constants it was keyed by (the capture arena); pool slabs and weights stay solely owned by their owners. `cudaStreamBeginCapture` over direct launches was rejected by analysis, not measured: MLX's stream-ordered allocations and event records made during the evaluation would be captured into the graph. - **Key.** A hash of the step's lazy graph (primitive, shapes, topology, custom kernel name, grid and scalars), the device address of every evaluated input, the contents of small host constants, the staging layout and the sampler parameters, plus a per-primitive `is_equivalent` check and a direct comparison of every captured input's device address before each launch (strides and sizes are covered by the hash), so input identity does not rest on the 64-bit hash alone. A step that would hand the GPU anything else is evaluated; a key seen twice is captured. - **Step structure of a graph step.** Always the fused paged read, planned for the batch's page tier (a power of two) with the page table staged at the tier's size; fresh blocks through the batched in-place write; one row through the batched model entry and array-offset RoPE; the draw over every row of the bucket. For Gemma 4 the KV donor rows of a checkpoint with no KV-shared layer are not stored, since nothing reads them, and a single Gemma 3 or Gemma 4 row goes through the batched forward. - **Eligibility.** Pool-backed rows, one shared greedy draw, no penalty, structured-output mask, token override, logprobs or speculative dispatch. A token bias stays eligible. Everything else runs the eager step it ran before. - **Controls.** `MLXCEL_DECODE_GRAPHS` (`0`, `always`, `eager`, `verify`), `MLXCEL_DECODE_GRAPH_MAX_BS`, `MLXCEL_DECODE_GRAPH_DUMP`; four counters on `/metrics`. At most 24 graphs and 2 GiB of step buffers are kept per engine (a single graph over the byte cap is dropped after its step runs, and its bucket and larger ones run eagerly from then on); 64 eligible steps in a row that match no graph, or 24 evictions within 60 s, suspend the feature for 60 s, so a model whose step changes every time keeps its previous path; a CUDA error on a replay fails the step and disables graphs for that engine. - **Metal, ROCm, CPU unchanged.** `step_graph::mode_from` returns off for every backend but CUDA whatever the environment says (unit-tested per backend), so no structure scope, capture or graph is ever constructed there; the non-CUDA bridge is a refusing stub and the default-features check passes. ## Deviations and known limits - **The lazy graph is still built on every replayed step.** It is not evaluated. That build is the host plan, shared with the eager step, so the two cannot diverge. It costs 0.2 ms of a 4.7 ms step for one Llama 3.2 1B row and 1.0 ms of 74 ms for four Gemma 4 12B rows; the walk that keys it costs about the same again. - **Capture at first use, not at startup.** A key is captured at its second sighting and logs `Captured <n> decode graphs (buckets [...]) in <s> s, arena <GiB>`. - **No pipelined replay.** A replayed step is synchronous. For pooled families a tick of more than one row that the lookahead pipeline can run therefore stays eager by default, and `MLXCEL_DECODE_GRAPHS=always` replays it. Measured on GB10 with Llama 3.2 1B in a default launch: pipelined eager 134.3, 133.9 and 134.2 steps/s at four rows against 127.1, 125.5 and 126.3 replayed, and 100.5 against 94.8 at eight, while one row replayed at 205.6 and 207.4 against 179.8 and 180.5. The pipeline does not run Gemma 4 rows, so its multi-row ticks replay by default. - **A stochastic draw is not eligible.** Its random key advances on the host. - **Graph buffers are outside the startup memory plan.** They are capped at 24 graphs and 2 GiB per engine (554 MB for one 256-row Llama graph, 352 MB for two 8-row Gemma 4 12B graphs). - **Graphs on and graphs off can sample different tokens.** The graph step always takes the fused read with a tier plan; the off arm uses the gather path below the fused floor and a per-step chunk plan. Pinning both arms to the fused read and one chunk per request makes Llama identical (20 of 20 server rows, 32 of 32 rows of the 32-row test on f16 and FP8), so the cause is plan-shape numerics. - **Gemma 4 pinned residual.** Pinned the same way, Gemma 4 matches graphs off in 8 of 10 server rows. The remaining structural difference is the two KV donor layers (per-row gather in the off arm, fused read in the graph step); that attribution is not confirmed. ## Validation on GB10 (shared host, load 3 to 7) Replay against evaluation, token for token (`verify` mode plus replay vs the `eager` arm of the same structure), each over 70 to 280 steps crossing page and tier boundaries: | Model | Buckets and cases | Result | |---|---|---| | Llama 3.2 1B 4bit, f16 pool | 1, 4, 8, 32, 256, 3 rows padded to 4, logit bias, context past 1024, admission between replays | identical, no verify mismatch | | Llama 3.2 1B 4bit, FP8 pool | 1, 4, 32, 3 padded to 4 | identical | | Qwen3 1.7B 4bit | 1, 4 | identical | | Gemma 3 1B 4bit, paged sliding | 1, 4 | identical | | Gemma 4 12B 4bit, paged sliding | 1, 4, context past the 1024 window, admission; FP8 at 4 | identical | Eager fallbacks tested: stochastic draw, penalty, logprobs, structured-output mask, dense caches, bucket over the cap, graphs off, speculative dispatch. Core tests pass with CUDA graphs on (43) and with `MLX_USE_CUDA_GRAPHS=0` (29); `batch::scheduler` passes 349; scoped clippy on both crates, `cargo fmt`, the default-features check and the `verify-*` contract list pass. The nsys counts on the branch were rerun on the final head with the same result; the main-side counts are from 22ee939. Bucket 256 holds 554 MB of step buffers. With the slab-ownership fix reverted locally the admission test fails (the slabs move and the graphs hold 1.6 GB). A host constant above 4096 bytes is keyed by its address and read at launch, and the 24-graph cap evicts the least recently used graph, which is captured again after two sightings (both tested). A steady Gemma 4 batch captures two graphs per row count, one per page tier it crosses. Not run: Gemma 4 above four rows, the FP8 pool at 256 rows. nsys, four concurrent greedy requests, 10 s steady window, calls per decode step: | | graph build and update | graph or kernel launches | `cudaMemcpyAsync` | |---|---|---|---| | Llama 1B, main | 345 `AddKernelNode`, 17.2 each of `Create`, `ExecUpdate`, `AddDependencies`, `Destroy` | 17.2 `cudaGraphLaunch` | 2.0 | | Llama 1B, this PR | 0 on 1170 replayed steps | 1.0 `cudaGraphLaunch` | 2.0 | | Gemma 4 12B paged, main | none (`MLX_USE_CUDA_GRAPHS=0`) | 1341 direct kernel launches | 2.0 | | Gemma 4 12B paged, this PR | 0 | 1.0 `cudaGraphLaunch` | 2.0 | The Llama window also held one evaluated step and one capture (a page-tier crossing), which account for the 674 `AddKernelNode`, 18 `Create` and 1 `Instantiate` calls it recorded. mlxcel-server parity with `--parallel 8 --ctx-size 16384`, 64 to 96 tokens, two repetitions, rerun on the final head: graphs on against the `eager` arm is identical in every row (Llama f16 at 1, 4 and 5 requests, Gemma 4 paged at 1 and 4; Llama FP8 at 1 and 4 on the earlier build). Against `MLXCEL_DECODE_GRAPHS=0` Llama f16 matches in 17 of 20 rows and Gemma 4 paged in 5 of 10. The cause is plan-shape numerics: the off arm keeps the gather path below the fused floor and a per-step chunk plan. With both arms pinned to the fused read and one chunk per request (`MLXCEL_PAGED_ATTENTION_NATIVE=1 MLXCEL_PAGED_DECODE_V2_TARGET_CTAS=1`) Llama matches in 20 of 20 server rows, and the 32-row scheduler test, which matched 27 of 32 unpinned, matches 32 of 32 on the f16 pool and on the FP8 pool (also with one chunk per page). Gemma 4 paged matches 8 of 10 pinned; the remaining structural difference there is the two KV donor layers, which the off arm runs through per-row gather and the graph step through the fused read, and that was not isolated. A default launch with the prompt cache on ran `verify` mode at one and four requests, repeated so the second pass adopts cached prefixes, without a mismatch. In a default launch the default mode replays one Llama row (90 of 95 steps) and leaves four rows to the pipeline (93 of 95), `always` replays both, and all three arms give the same tokens as graphs off. Timing, indicative only. Llama 3.2 1B with `--ctx-size` set (no lookahead pipeline), median decode tick in one instrumented build, graphs off against on: 6.23 to 4.75 ms at one row, 9.06 to 7.76 ms at four, 12.0 to 10.9 ms at eight (n=1). The Gemma 4 comparison is in the next section. ## `MLXCEL_PAGED_SLIDING` on CUDA: on by default again #3676 turned paged sliding state off on CUDA for a B200 decode regression. The rule for this epic was to turn it back on only if paged is not slower, after a correctness check. Both hold on GB10 for Gemma 4, so its default is on everywhere and `MLXCEL_PAGED_SLIDING=0` restores the dense ring storage. They do not hold for Gemma 3 (below), which keeps the #3676 CUDA default through a separate `gemma3_paged_sliding_state_default`. Speed, Gemma 4 12B 4bit, final binary, default launch flags (`-m <model> --port <p> --metrics`, plus `--parallel 8` for eight requests), default graph mode, 20 s windows, two interleaved rounds, steps/s: | Requests | Dense, round 1 / 2 | Paged, round 1 / 2 | Paged steps replayed | |---|---|---|---| | 1 greedy | 15.9 / 15.9 | 16.5 / 16.6 | 510 of 516 | | 4 greedy | 12.2 / 12.4 | 13.6 / 13.7 | 423 of 429 | | 8 greedy | 8.9 / 8.7 | 10.3 / 10.3 | 317 of 323 | | 4 at temperature 0.7 | 12.2 / 12.3 | 12.3 / 12.5 | none (eager) | Correctness: greedy output is not always token-identical between the two storages (two of four chat requests matched over 64 tokens at four concurrent requests, none of one at a single request, the same with graphs off). With top-2 logprobs on both arms, the first differing token is a near-tie in every case: | Request | Token | Dense | Paged | |---|---|---|---| | 1 request, row 0 | 21 | ` frequently` -1.125, ` often` -1.25 | ` often` -1.125, ` frequently` -1.25 | | 4 requests, row 0 | 21 | same | both -1.125 | | 4 requests, row 1 | 42 | ` escapes` -0.6875, ` goes` -0.8125 | both -0.75 | The margin is at most 0.125 nats, one step of the logits' resolution, so the difference is kernel rounding. Knock-ons of the new Gemma 4 default: - A Gemma 4 checkpoint that declares FP8 KV, such as the 31B NVFP4, now stores FP8 in the pool by default on CUDA sm_89 and newer. That checkpoint was not exercised here; the 12B 4bit declares none and its default launch runs f16 (confirmed in its log). - Gemma 3 stays dense on CUDA by default. Its multi-row ticks run on the lookahead pipeline, which does not replay, and there its paged path was slower: Gemma 3 1B 4bit at the default launch, two interleaved rounds, 123.1 and 123.4 steps/s paged against 130.8 and 135.7 dense at four requests, while one replayed row was faster (102.2 and 97.5 against 78.1 and 79.2). With `MLXCEL_PAGED_SLIDING=1` it replays (one row: 121 of 126 steps; `verify` clean at one and four rows, and against dense the same tokens at one request and in three of four at four). Its default launch on the final binary is token-identical to main with 0 replays. - Gemma 4 12B at a default launch with no environment set: paged path, 60 of 63 steps replayed at one request and 121 of 126 after four, same tokens as the earlier `MLXCEL_PAGED_SLIDING=1` run. The B200 figure that motivated #3676 has not been re-measured with graphs. ## Branch against main with the switches off Final binary against the main binary (22ee939), default launch flags, 64 tokens, one and four concurrent greedy requests, two repetitions: Llama 3.2 1B with `MLXCEL_DECODE_GRAPHS=0`, Gemma 4 12B with `MLXCEL_PAGED_SLIDING=0`, and Gemma 3 1B with `MLXCEL_PAGED_SLIDING=0` (and at its new default) are token-identical to main in every row, with 0 replays and 0 captures in `/metrics`. This is also the server-level check that dense sliding state stays eager, which test builds cannot reach. After the flip, the tests of every module it touched pass (`kv_fp8` 11, `memory_estimate` 77, `memory_plan` 8, `models::gemma3` 74, `models::gemma4` 153, `model_worker` 46, core `paged_geometry` and `memory::`), and the Llama decode graph suite runs all 18 tests with no skip (bucket 256: 68 replays, one capture, 554 MB). ## Changes during review - A failed capture (instantiate failure, a throw mid-evaluation, a refusal after capture) could leave the step's arrays marked evaluated without any kernel having run, so the eager fallback returned unwritten tokens as a success. Every exit of `step_graph::capture` now either launches the captured nodes once and waits, or throws a `[step_graph] fatal:` error on which graphs are disabled and the step fails; graph edges are added at most once (tests for a refused strided output, a mid-step throw and an empty capture). - A step with a lazy node on another stream is refused before evaluation; address-keyed inputs are also keyed (hashed) by strides, data size and contiguity; replay compares captured input addresses directly. - Capture churn a client could drive by varying bucket and page tier is bounded (24 evictions in 60 s suspend graphs for 60 s), and the 2 GiB cap is enforced for a single oversized graph. - Merged main with #3692 (stalled-engine detection): a capture tick is one slower step and replayed ticks count as progress; with `--stall-timeout 3` no stall was reported on Llama 3.2 1B or Gemma 4 12B (capture took 10 ms and about 90 ms). - Tests: the #3667 step-input tests pin graphs off (graph steps always take the fused read), `dense_caches_run_eagerly` skips models whose sliding layers live in the pool, and the 256-row test accepts the Gemma 4 12B graph being dropped over the byte cap (its vocabulary reaches it at 256 rows; buckets 1, 4, 8 and 32 replay). Known limits found in review and left open: with one long row among short ones the uniform tier plan gives the long row about 1/B of the attention parallelism the per-step heuristic would (multi-row graph steps only); `held_bytes` counts the step's array outputs but not the encoder's scratch buffers; Gemma 4 12B at one request and temperature 0.7 (eager, not replayed) measured 15.45 and 15.46 tok/s paged against 15.74 and 15.78 dense, about 2% and inside GB10 noise, to be re-checked on the B200; `OxideFusedAddRmsNorm` (opt-in) defines no `is_equivalent`, so a step using it never replays. ## Deferred to the B200 follow-up measurement issue - Serving TPOT from `scripts/bench/serving_compare.py` (12.0 ms at c=1, 8.5 ms at c=8, 10.5 ms at c=32) and the c=1, 8, 32 serving table; no B200 or 31B number backs this PR. - nsys over 25 s at c=8 on Gemma 4 31B NVFP4. - Re-measuring paged against dense sliding state with graphs on the B200 and the 31B, including its FP8 pool. - Pipelined replay (which would let multi-row ticks replay by default), a device-side random key for stochastic draws, capture of every bucket at startup, and charging the graph buffers to the startup memory plan. Closes #3668
5 tasks
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.
Since #3334, FP16 Gemma 3 and Gemma 4 scheduler sequences keep sliding layers in window-bounded paged blocks on every backend. On CUDA the paged single-row decode is slower than the ring storage it replaced: a paged-attention plus merge kernel pair per layer instead of one
sdpa_vector, and four host arrays per layer per step that land in managed memory and force graph updates. Gemma 4 31B NVFP4 on a B200 decoded at 63.1 tok/s before #3334 and 50 to 51 tok/s at it (pp512/tg128, CUDA graphs on).mlxcel_core::memory::paged_sliding_state_default()reads MLXCEL_PAGED_SLIDING and otherwise defaults to on everywhere except CUDA; the Gemma 3 and Gemma 4 wrappers use it, and test builds keep paged storage on so the #3334 tests still run on every backend. Metal is unchanged. With it, current main decodes at 63.3 tok/s on the same measurement. Making the paged path allocation-free and graph-stable on CUDA is tracked by #3667 and #3668.Local validation on CUDA: the paged-sliding and Gemma 3/4 lib tests (168 passed) and the new default-resolution unit test; scripts/ci/check_env_var_docs.py lists the new variable as documented.
Closes #3675