Skip to content

perf: capture and replay the decode step as bucketed CUDA graphs - #3714

Merged
inureyes merged 20 commits into
mainfrom
feature/issue-3668-decode-step-graphs
Dec 3, 2026
Merged

inureyes merged 20 commits into
mainfrom
feature/issue-3668-decode-step-graphs

Conversation

@inureyes

@inureyes inureyes commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

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 (bug(gemma4/cuda): decode collapses to <pad> after 1-3 tokens (single-query maskless attention + quantized GEMV); mlx_lm decodes coherently #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 feat(server): detect stalled engines and support model-card lookup #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 perf: Remove device and managed allocations from the CUDA decode step #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

On CUDA the host cost of a decode step is the evaluation of its lazy MLX graph: one cudaGraphAddKernelNode per kernel and a graph update, instantiate or destroy per commit. An eligible step is now captured once as a single CUDA graph and later steps with the same key launch it (#3668).

The CUDA encoder overlay gets a step-capture mode that defers every commit, so one evaluation becomes one graph whose buffers stay owned by the capture. mlxcel_core::step_graph wraps it and keys a step by a hash of its lazy graph (primitives, shapes, topology), the device address of every evaluated input, the contents of small host constants, the step-input staging layout and the sampler parameters. A replayed step still builds its lazy graph, which is the host plan shared with the eager step, then uploads the staged inputs, launches the graph, reads the tokens back and gives the build's lazy arrays the captured buffers.

A decode-graph step is built in a replayable structure: always the fused paged read, a plan for the batch's page tier, a page table staged at the tier's size, fresh blocks written through the batched in-place write, and a draw over every row of the bucket. The engine runs it for pool-backed rows with one greedy fused draw; the scheduler routes such ticks to the synchronous step. MLXCEL_DECODE_GRAPHS (0, eager, verify) and MLXCEL_DECODE_GRAPH_MAX_BS control it, and the gate is off on every backend but CUDA.

Validated on GB10 with Llama 3.2 1B 4bit at four rows over 279 steps crossing page and tier boundaries: verify mode reports 275 replays and no mismatch, replay matches the eager arm of the same structure token for token, and each replayed step is one graph launch. Core step_graph and decode_graphs tests pass (16).

Refs #3668
@inureyes inureyes added status:in-progress Currently being worked on type:performance Performance improvements priority:high High priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:linux Linux (CUDA / packaging) specific labels Dec 2, 2026
The step signature hashes primitive types, shapes and inputs, but not the parameters MLX's own primitives hold (a slice's bounds, an axis). A captured graph now keeps its step's primitives, and a step is replayed only when each of its primitives is equivalent to the captured one; a custom kernel's name, grid and scalar arguments go into the signature instead. A step that matches a graph's structure but not its parameters is evaluated and counted.

A single row now runs as a decode-graph step too: it goes through the batched model entry, the array-offset RoPE launch and the batched KV write, so its offset and slot are staged data. A token bias stays eligible, since its ids and values are staged.

The scheduler tests cover buckets 1, 4, 8, 32 and 256, three rows padded to four, a request logit bias, and the eager fallbacks (stochastic draw, penalty, logprobs, structured-output mask, dense caches, bucket cap, graphs off, speculative dispatch). On GB10 with Llama 3.2 1B 4bit all 15 pass on the f16 pool, and buckets 1, 4, 32 and the padded case pass on the FP8 pool: verify mode reports no mismatch, replay matches the eager arm token for token, and every replayed step is one graph launch.

Refs #3668
A captured graph held a reference to every buffer its step touched, pool slabs included. MLX donates a buffer to slice_update only from its sole owner, so a prefill write into a fresh block after the first capture could have copied the whole slab and moved it away from the address every graph holds.

A graph now owns only what its step allocated and the small host constants it was keyed by. A node whose output shares an address-keyed input (an in-place write into a slab, a staged view) records that input instead, and a replayed step's node takes the replayed step's own input buffer. The walk drops its references to the step's inputs before any evaluation, and identifies them during a capture through weak references.

Also in this commit: eligible steps that match no graph 64 times in a row suspend decode graphs for 60 s, so a family whose step changes every time keeps the lookahead pipeline; graphs are evicted beyond 2 GiB of held buffers; MLXCEL_DECODE_GRAPH_DUMP writes the description of unmatched steps; a core test checks the uniform tier plan against the host reference for unequal rows on f32 and f16 pools.

Validated on GB10: a request admitted after replays began leaves the first and last layer's K and V slabs at their addresses and matches the eager arm token for token; core step_graph, decode_graphs, paged_v2 launch and step_inputs tests pass (43).

Refs #3668
mlxcel runs Gemma 4 on CUDA with MLX_USE_CUDA_GRAPHS=0 (the graph hazard of #688), so the encoder launches its kernels directly and the step capture of #3668 was refused there. The capture now works in that mode too: each captured node depends on the one encoded before it, so the graph runs the kernels in the order the direct launches had and does not rely on the dependency tracker. With CUDA graphs on, the tracker's dependencies are used as before.

Gemma 4 with paged sliding state needed two more things to keep one step shape. The two KV donor layers of a checkpoint with no KV-shared layer took a per-row path that gathers each row's window; a decode-graph step skips it, since nothing reads the stored rows. A single row goes through the pooled attention entry of scheduler-owned layer state, like a batch.

Validated on GB10: the capture primitive and policy tests pass with CUDA graphs on (43) and with MLX_USE_CUDA_GRAPHS=0 (29); on Gemma 4 12B 4bit with MLXCEL_PAGED_SLIDING=1 at four rows, verify mode reports 275 replays and no mismatch over 279 steps, replay matches the eager arm token for token, and each replayed step is one graph launch.

Refs #3668
A single Gemma 4 row with paged sliding state changed its key every step: the single-row forward hands RoPE offsets and write slots over as host values. A decode-graph step now sends a plain decode token through the batched forward, and the proportional RoPE takes the array-offset launch for one row.

The server sets a KV cap from the context size, and the scheduler declined such ticks while the engine still ran them as graph steps, so the counters on /metrics stayed at zero. A front trim moves a row's page table, which is staged data, so the decline is gone and the counters are published after every graph tick.

Validated on GB10 with Gemma 4 12B 4bit and MLXCEL_PAGED_SLIDING=1: one row gives 275 replays and no verify mismatch over 279 steps; two rows whose context crosses 1024 tokens give 195 of 199; a request admitted after replays began leaves the slabs in place and matches the eager arm. Qwen3 1.7B passes at one and four rows, and the Llama 3.2 1B suite passes (16).

Refs #3668
…sion

The continuous batching guide and the environment variable table now carry what a replayed step costs on the host (GB10: 0.2 ms of build and of walk in a 4.7 ms step for one Llama 3.2 1B row, 1.0 and 1.2 ms of 74 ms for four Gemma 4 12B rows), the graph and byte caps, the per-primitive parameter check and the suspension after 64 unmatched steps.

MLXCEL_PAGED_SLIDING stays off on CUDA. Decode graphs replay Gemma 4 only with paged sliding state, and on GB10 that path with graphs decoded faster than the dense default (14.0 and 13.7 against 12.1 and 12.4 steps/s at four rows), but its greedy output is not token-identical to the dense path's, with or without graphs, and the B200 regression that turned it off has not been re-measured. The doc comment of paged_sliding_state_default and the variable's row say so.

Also fixes an unused assignment in the capture primitive test that scoped clippy rejected.

Refs #3668
@inureyes inureyes added status:review Under review and removed status:in-progress Currently being worked on labels Dec 2, 2026
A replayed step is synchronous, so a graph tick gives up the lookahead pipeline's overlap of one step's sampling and bookkeeping with the next step's GPU work. In a default-launch server on GB10 with Llama 3.2 1B, where the pipeline is active, that cost more than replay saved at four and eight rows (pipelined eager 134 and 100 steps/s against 126 and 95 replayed, three and one paired rounds), while one row replayed faster (206 against 180).

The default mode now leaves a tick of more than one row to the lookahead pipeline whenever the pipeline can run it, and replays a single row and every tick the pipeline cannot run (a KV cap from --ctx-size or --max-kv-size, a pending admission). MLXCEL_DECODE_GRAPHS=always replays the multi-row ticks too. The scheduler arms the engine for the ticks it chose, so a tick left to the pipeline keeps the eager step structure whole.

A model that does not batch keeps the eager step: a graph step sends even one row through the batched model entry, which would drop the sequence id such a model is decoded with.

The paged sliding notes now say what was observed (not token-identical to the dense path, the same with graphs off, cause not investigated) and that the speed criterion was met.

Validated on GB10: the Llama 3.2 1B decode graph suite passes (18 with the new policy test), batch::scheduler 349, and the core step_graph, decode_graphs, paged_v2, step_inputs and engine tests 211.

Refs #3668
Two reviewer questions about captured decode graphs had no test.

A host-built constant above the 4096-byte content-hash limit is keyed by its device address, and the captured graph reads that address at launch. The new test feeds 64 KiB of fresh host data per step: a step whose constant lands on the recycled address replays (11 of 16) and samples from the new contents, and one that lands elsewhere is evaluated.

Beyond 24 graphs the least recently launched one is dropped. The new test captures 27 keys, checks three evictions, that the newest key still replays, and that an evicted key is captured again after two sightings.

Both pass on GB10 with CUDA graphs on and with MLX_USE_CUDA_GRAPHS=0.

Refs #3668
#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
A step capture defers every commit, so once mx::eval returns every array of the step is marked evaluated while no kernel has run. Several exits from step_graph::capture() dropped the captured nodes without launching them, and the Rust fallback then evaluated a step whose arrays were already marked evaluated: it returned whatever the unwritten token buffer held as Ok, skipped the step's paged KV writes, and left the pool bookkeeping advanced.

Every exit after the evaluation has started now either launches the captured nodes exactly once (and waits for them, or hands the buffers to a completion handler behind the launch), so the ordinary evaluation that follows is valid, or throws an error prefixed "[step_graph] fatal:". DecodeGraphs::capture disables decode graphs and fails the step on that prefix instead of evaluating it.

In the encoder, end_step_capture leaves the capture open when it throws, and abort_step_capture instantiates and launches the nodes directly in both chain and graphs-on mode, adding the graph's edges at most once (a graph_edges_ state reset with the graph state; CUDA rejects an existing edge), and leaves the encoder clean even when it fails. In capture(), the pinned readback buffer is allocated before the evaluation, a capture refused after end_step_capture (an output with no contiguous buffer) launches the graph once and synchronizes before it is dropped, and a failed abort or a failed begin is fatal.

Also: a step with a node on a stream other than the default GPU stream is refused before anything is evaluated, and an address-keyed leaf's strides, data size and contiguity flags are part of the signature, so a strided view at the same address no longer shares a key with its base.

Tests: a strided output is refused, runs exactly once, and leaves the output and the in-place slab write equal to the reference; the same step through DecodeGraphs::run returns the right tokens every round; a node on the CPU stream is refused with nothing launched; a transposed leaf gets another signature; a capture that adds no node fails cleanly and the next capture works.

Refs #3668
The abort path of a step capture (the evaluation throws after some kernels were captured) had no test. A staged view whose decode step has ended throws in eval_gpu, so a long kernel chain added to such a view throws mid-capture with the chain already captured.

The test asserts the capture returns a non-fatal error, launches exactly one graph (the captured chain, run once by abort_step_capture), and leaves the chain holding the values an eager evaluation computes. It passes with CUDA graphs on and with MLX_USE_CUDA_GRAPHS=0.

Refs #3668
@inureyes

inureyes commented Dec 2, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Capture an eligible CUDA decode step once as one CUDA graph and replay it for every later step with the same key, without baking any per-step value into the graph, and turn MLXCEL_PAGED_SLIDING back on by default on CUDA (Metal unchanged).

Findings Addressed

  • A failed capture could leave the step marked evaluated with nothing launched (HIGH). mx::eval under step capture marks every array evaluated before any kernel runs. An instantiate failure in end_step_capture re-ran finish_graph_edges on the same graph inside abort_step_capture (CUDA rejects an existing edge), the error was swallowed, and the two throws after end_step_capture in step_graph::capture dropped the graph unlaunched. The Rust fallback evaluate(tokens) was then a no-op: unwritten tokens came back as Ok, the step's KV writes were skipped and the pool bookkeeping had advanced. Fixed in c9b08f4 (mid-step throw test added in bcb83ae): every exit launches the captured nodes once (edges added at most once) and waits before the held buffers go, or throws a [step_graph] fatal: error on which DecodeGraphs::capture disables graphs and fails the step. Tested with a strided output that is refused and still yields reference values.
  • A lazy node on a stream other than the capture encoder's would run outside the graph at capture and never on replay (MEDIUM). Now refused before anything is evaluated (c9b08f4, tested with a CPU-stream node).
  • Address-keyed leaves were keyed without their strides (LOW). Strides, data size and contiguity flags are now in the signature (c9b08f4, tested with a transposed leaf).

Remaining Items

  • dense_caches_run_eagerly fails with MLXCEL_DECODE_GRAPHS_MODEL=models/gemma-4-12b-it-4bit (20 replays). Not a correctness bug: paged sliding state does not depend on DecodeStorageBackend::Dense, so the Gemma 4 rows are pool-backed and eligible. The test only covers plain-cache families, and the Gemma 4 dense path (MLXCEL_PAGED_SLIDING=0) cannot be reached in test builds (cfg!(test) forces paged sliding on); its eligibility rests on graph_rows requiring every layer state to be pool-backed. (LOW)
  • OxideFusedAddRmsNorm (opt-in MLXCEL_CUDA_OXIDE_FUSED_NORM) has no is_equivalent, so a step using it never replays and decode graphs suspend after 64 misses. Safe, performance only. (LOW)
  • Gemma 4 paged with graphs matches graphs off in 8 of 10 pinned server rows; unattributed (the two KV donor layers are the suspected difference). Replay against the eager arm of the same structure is exact, which is the gate for baked values. (MEDIUM, open)
  • The paged sliding flip makes FP8 KV the default on CUDA for Gemma 4 checkpoints that declare it (31B NVFP4) with no run behind it; deferred with the B200 follow-up. One request at temperature 0.7 on Gemma 4 12B, release binary at d6f7d9f, two interleaved rounds: dense 15.74 and 15.78 tok/s, paged 15.45 and 15.46 (about 2 percent slower, n=2, host load 4 to 5). Within the GB10 noise floor, but same sign both rounds; worth re-checking on the B200. (MEDIUM, open)

Deviations judged

Capture at the second sighting of a key, the lazy graph rebuilt as the host plan on every replay, no pipelined replay (multi-row pipelined ticks stay eager by default, measured), stochastic draws ineligible (host-advanced key), graph buffers capped at 24 graphs / 2 GiB outside the startup memory plan, and the Gemma 3 / Gemma 4 single-row routing through the batched forward (gated by structure_active(), so it changes nothing outside a graph step) are all sound as described.

Key audit

The unique primitives of a Llama 3.2 1B and a Gemma 4 12B graph step (from MLXCEL_DECODE_GRAPH_DUMP) are StepInputsView/Upload, Transpose, Reshape, QuantizedMatmul, Slice, RMSNorm, Add, Multiply, RoPE, InplaceScatterRows, CustomKernel, Contiguous, AsType, Compiled, Squeeze, Gather, GatherAxis, ScatterAxis, Quantize, Broadcast, Full and ArgReduce. Each one's is_equivalent covers every parameter it holds; Compiled's name carries its inlined constants; CustomKernel's name, source hash, grid, block, shared memory and scalars are hashed; InplaceScatterRows takes only shape-derived launch values; RoPE offsets, page tables, plan chunk arrays and write slots are staged arrays; the per-row write path that takes slots by value notes them into the key. No per-step value is baked into a replayed graph.

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 (GB10, after c9b08f4: core step_graph decode_graphs paged_v2 step_inputs engine:: 219 passed, with MLX_USE_CUDA_GRAPHS=0 133 passed; scheduler_decode_graphs_tests --ignored on Llama 3.2 1B f16 18 of 18, FP8 pool 4 of 4, Gemma 3 1B 2 of 2, Gemma 4 12B 3 of 3 replay tests plus the dense-caches item above; at bcb83ae the core filters pass 220 and the MLX_USE_CUDA_GRAPHS=0 step_graph decode_graphs subset 25)

A request mix that keeps changing the decode bucket and the page tier can cycle through more step keys than the 24 graphs the engine keeps. Every capture then pays instantiation and fresh step buffers only to evict another graph, stalling the decode tick for every row. The cumulative thrash rule (more captures than replays) cannot fire once a server has replayed for a while, so nothing bounded this. Twenty-four evictions within 60 s now suspend decode graphs for 60 s, as the miss-streak rule already does.

The byte cap also kept the newest graph however large it was, so one graph at a large bucket could hold more than the 2 GiB the cap promises, outside the startup memory plan. A graph that alone exceeds the cap is now dropped after its step has run, and its bucket and larger ones are evaluated from then on.

Core decode_graphs tests (14, with and without MLX CUDA graphs), step_graph (15) and paged_v2 (96) pass on GB10; scoped clippy and fmt pass.

Refs #3668
@inureyes

inureyes commented Dec 2, 2026

Copy link
Copy Markdown
Member Author

Security and performance review

No CRITICAL or HIGH finding. The pr-reviewer's failed-capture fix (c9b08f4, bcb83ae) holds: every exit of step_graph::capture either launches what was captured once and waits, or throws kCaptureFatal, on which DecodeGraphs::capture disables graphs and fails the step. The failure tests pass with MLX CUDA graphs on and off.

Checked and sound

  • Buffer lifetime: intermediates and outputs are held by the graph and shared into adopted arrays (copy_shared_buffer), so eviction cannot free a buffer a live array uses. Address-keyed leaves are not held, but a replay only matches when the current step has a live leaf at the same address, and the walk keeps it alive until read_output synchronizes.
  • Threads: MLX default streams and CUDA command encoders are thread-local here, so another thread cannot commit into an open step capture. The step-chain path takes capture_lifetime_mutex per node like the CUDA-graphs path.
  • Cross-request data: a replay reads the current step's staged inputs and slabs. The tier-padded page table is zero-filled and indexed through indptr. Small constants are matched by content.
  • Default path cost: stochastic steps never walk the graph, a replay adds no stream synchronize over the eager step, and the walk costs about as much as the lazy build.

Fixed in 706d093 (MEDIUM, local)

  • Capture churn (engine/decode_graphs.rs): a request mix that keeps changing the bucket and the page tier (paged_v2/plan.rs:501) can cycle through more than 24 keys. Each capture then evicts another graph. The cumulative thrash rule cannot fire once replays have built up. Twenty-four evictions within 60 s now suspend graphs for 60 s.
  • Byte cap: the newest graph was always kept, however large. A graph over 2 GiB on its own is now dropped after its step has run, and its bucket and larger ones are evaluated.

Open, not changed

  • MEDIUM: the uniform tier plan (paged.rs:2427, plan.rs:277) gives every row the long row's chunk count. With one long row among short ones, the long row gets about 1/B of the attention parallelism that the heuristic gives it. This applies to multi-row graph steps (by default, ticks with --ctx-size set or with an admission pending).
  • MEDIUM: held_bytes (step_graph.cpp:504) counts walked array outputs only. Encoder scratch temporaries in capture_.held are not counted. A capture also reuses no buffer within the step, and all of this sits outside the startup memory plan.
  • MEDIUM, carried over: Gemma 4 at temperature 0.7 is about 2% slower on the paged path than dense (n=2). Stochastic steps are never graph steps, so the paged-sliding flip alone causes this.
  • LOW: the replay's soundness rests on a 64-bit FNV-1a signature (step_graph.cpp:64). mismatch (:540) could also compare the captured address-keyed leaf addresses as a cheap defence in depth. The note hash takes user-chosen sampler values, but only for argmax draws, where a collision changes nothing.
  • LOW: on a graph step, a fresh or recycled row is written in place (paged_batch_write.rs:151). This bypasses perf(cache): write paged KV rows in place under lookahead decode #1965's copy rule for a lazy reader such as extract_paged_blocks that outlives the block's release. No such reader was found on the decode path.
  • LOW: reserve_elems in step_inputs_stage_i32 (lib.rs:2108) is always 0.

Tests (GB10)

Core decode_graphs 14 (with and without MLX_USE_CUDA_GRAPHS=0), step_graph 15, paged_v2 96. Scoped clippy on mlxcel-core, cargo fmt --check and the verify-* contract list also pass.

…ooled Gemma

The decode graph replay check now also compares the device address and kind (content or address) of every evaluated input of the step against the ones the graph was captured with, so a collision of the 64-bit FNV-1a signature cannot launch a graph over other buffers. A test walks a step over a second slab, gives it the captured signature, and expects the "leaf address" refusal.

`dense_caches_run_eagerly` skips with a message for a model whose sliding layers live in the pool in test builds (Gemma 3 and 4 under `cfg!(test)`), since its rows are graph eligible whatever the storage backend says. A plain-cache family such as Llama still asserts eager execution. The docs state the address comparison.

Validation:
- mlxcel-core step_graph decode_graphs paged_v2 step_inputs engine:: memory::, 250 passed; step_graph decode_graphs with MLX_USE_CUDA_GRAPHS=0, 28 passed
- batch::scheduler, 349 passed; scheduler_decode_graphs --ignored on Llama 3.2 1B (f16 and FP8) and Gemma 3 1B, 18 passed

Refs #3668
The #3667 step-input tests count the eager step's allocations and its gather or fused read choice. With decode graphs on by default they ran graph steps, which always take the fused read planned per page tier, so two of them failed on Llama 3.2 1B (a gather-path assertion and a padded-versus-unpadded token comparison that differs in the last bit). Their scheduler now pins the decode graph mode to off; graph steps stay covered by the scheduler_decode_graphs tests.

Two graph tests assumed a small pooled family. The default-mode test now asks the scheduler whether the lookahead pipeline can run the checkpoint, and for Gemma 4 (whose scheduler-owned sliding state cannot unwind a speculative append) it asserts the documented opposite: every four-row tick replays. The 256-row replay test accepts a graph dropped over the per-engine byte cap, which the 12B model's vocabulary reaches at that bucket, and reports it instead of failing.

Validation:
- scheduler_step_inputs --ignored on Llama 3.2 1B, 8 passed
- Gemma 4 12B 4bit: dense_caches_run_eagerly (skipped by design), the_default_mode_yields_multi_row_ticks_to_the_lookahead_pipeline and bucket_256 (reported as over the cap), 3 passed
- Llama 3.2 1B dense_caches_run_eagerly and the_default_mode_yields_multi_row_ticks_to_the_lookahead_pipeline passed
- cargo clippy -D warnings (cuda, mlxcel and mlxcel-core), cargo check at default features, cargo fmt --check, make verify-* all clean

Refs #3668
@inureyes inureyes added status:done Completed and removed status:review Under review labels 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
inureyes marked this pull request as ready for review December 3, 2026 00:35
@inureyes
inureyes merged commit 517ede2 into main Dec 3, 2026
1 of 38 checks passed
@inureyes
inureyes deleted the feature/issue-3668-decode-step-graphs branch December 3, 2026 00:35
inureyes added a commit that referenced this pull request Dec 3, 2026
…#3719)

Part of #3669 (item 1 only; the issue stays open for the rest, see "Remaining for #3669").

## Summary

On CUDA a decode-graph replay (#3668) was synchronous: launch, wait for the tokens, then do the step's host bookkeeping while the GPU idled. This PR pipelines replays on the existing #632 lookahead state machine, so the host commits step n (stop checks, detokenization, streaming) and builds step n+1 while the GPU runs step n+1's graph.

- **Submit.** A decode-graph tick that the lookahead pipeline can run now runs `run_lookahead_tick` with the engine armed. Step n+1 is built in the replayable structure (`Engine::submit_graph_padded`). When it matches a captured graph, `StepGraph::launch_async` launches the graph and queues a D2H copy of its sampled tokens into one of two per-graph pinned slots, followed by an event. The step's arrays are adopted right away and are never read on the host through MLX.
- **Feedback on the device.** Step n+1's input tokens are step n's sampled tokens, copied device-to-device into the token slot of the persistent step-input buffer (`step_inputs::stage_i32_from_device`, issued in `upload()` after the host bytes and before the slot event). The staged layout equals a host-staged step's, so the pipelined step keys like the synchronous one and replays the same graph.
- **Collect.** Step n's tokens are read from its pinned copy after its event (`PendingTokens::wait`). A sequence number per slot refuses a read whose slot a later launch reused.
- **Teardown waits for the in-flight step.** A row that stops at step n (length, EOS, stop string, cancellation), an admission, a preemption or a changed id set waits for the in-flight step (`quiesce_lookahead`), unwinds the speculative append with `apply_lookahead_trim`, and re-runs the tick synchronously. For a graph tick that rerun is a synchronous replay.
- **Gemma 4 rows** whose every layer is pool-backed layer state (paged sliding, the CUDA default) join the pipeline on graph ticks only. The pool's block tables unwind their appends exactly, which the eager pipeline cannot assume for scheduler-owned state.
- **An eager lookahead never feeds a graph tick.** A lookahead primed outside a graph tick ran the eager step structure, which does not round like the replayable one (#3714 section 4.2). A pipelined graph tick unwinds it first, and a prime that such a tick would unwind is not issued. Without this, long runs drifted from the synchronous replay by one near-tie token.
- **Multi-row replay is now the default on CUDA.** Before this PR a multi-row tick that the eager lookahead pipeline could run stayed eager; with the pipeline on, such ticks run as pipelined graph replays. #3714 measured multi-row replay as not always token-identical to the eager structure (Llama 17/20 rows identical), because the replayable step rounds differently. The same effect shows in the main-binary comparison below (Llama 7/8 vs main's default, 8/8 vs main with `MLXCEL_DECODE_GRAPHS=always`). `MLXCEL_DECODE_GRAPH_PIPELINE=0` restores main's routing.
- **Kill switch and observability.** `MLXCEL_DECODE_GRAPH_PIPELINE=0` restores #3668's routing exactly: a synchronous replay, and multi-row ticks the pipeline can run stay eager. `/metrics` gains `mlxcel_batch_decode_graph_pipelined_replays_total`. `verify` and `eager` modes never pipeline. A CUDA error while waiting fails that step's rows like a failed synchronous readback and disables graphs for the engine.
- **Metal, ROCm and CPU are unreachable.** The decode-graph mode is off on every backend but CUDA (`step_graph::mode_from`), and `pipeline_from` requires a replay mode. `pipelined_replay_is_cuda_only_and_has_a_kill_switch` tests this gate. The non-CUDA C++ stubs throw or return null.
- **Docs.** `docs/CONTINUOUS_BATCHING.md` (the decode-graphs section gains a "Pipelined replay" paragraph, and the Controls paragraph lists the new metric) and `docs/environment-variables.md` (the new `MLXCEL_DECODE_GRAPH_PIPELINE` row and the updated `MLXCEL_DECODE_GRAPHS` text).

## Scope narrowed from the issue

| Issue item | Status | Reason |
| --- | --- | --- |
| 1. Graph-replay lookahead with device-side token feedback and async readback | Delivered, default on CUDA | |
| 2. Admissions join at step N+2 without teardown | **Not delivered** | An admission still tears the pipeline down, as before. The admission test now runs through the pipelined arm and checks token equality and pool-slab stability. Joining without teardown changes the membership invariant of `apply_lookahead_trim` and touches `admission.rs`, which sibling #3670 is editing in the same wave. |
| 3. Off-thread detokenization and streaming | **Not delivered** | This is a separate change to `finish.rs` ownership: `decode_state`, `bounds` and `response_tx` would move to an output thread. Its acceptance test (multi-byte UTF-8 on 4 requests) is not delivered either. With item 1 in place, detokenization already overlaps the next step's GPU work on the scheduler thread. |
| 4. Audit of synchronous host reads | Partial | On a pipelined graph tick the step loop's reads are the pinned-slot wait (`read_lookahead`) and the teardown wait (`quiesce_lookahead`), which replaced the two `try_eval` calls in the steady path. The eager pipeline keeps `read_lookahead_tokens` on its lazy array, unchanged. `step_rows.rs` and `speculative_finalize.rs` were not changed. Speculative ticks never take this path. |

## Review fixes (after the merge of main)

pr-reviewer found three MEDIUM issues, all fixed with tests; pr-security-checker found no CRITICAL, HIGH or MEDIUM issues.

- **95b188d46: wait for an in-flight replay before dropping it unread.** `discard_lookahead`, the stale-id-set arm of `run_lookahead_tick`, the synchronous graph branch and the stale arm of the prompt-lookup tick trimmed a pending graph read without waiting, so a CUDA error from that launch surfaced in a later unrelated evaluation and did not disable graphs. `unwind_stored_lookahead` now waits first (disabling graphs and counting an eval failure on error), then trims. Tests: `a_discarded_in_flight_replay_is_waited_for_and_its_failure_counted`, `rows_that_stop_after_the_window_slid_match_the_synchronous_path`.
- **f114564fe: re-copy a device-fed step input on every covering upload.** A second upload in the same step (an early evaluation followed by `flush`) re-copied the head from the host slot, whose bytes for the device-fed region were never written, and skipped the feed. Test: `a_flush_after_an_early_upload_keeps_a_device_fed_region` (without the fix it reads `[-7, -7, -7, -7]`).
- **8a420e459: never prime a graph-only row on the eager structure.** On an armed tick whose prime turned out not to be a graph step (graphs disabled, capped or suspended mid-tick), a Gemma 4 row admitted only through the graph-tick gate fell back to an eager speculative append. Test: `an_armed_tick_that_is_not_a_graph_step_does_not_prime_a_graph_only_row_eagerly` (fails on Gemma 4 12B without the guard).
- LOW, not fixed: `read_seq_` is set after the copy and event are queued in `launch_async`; an `adopt` failure after a successful `launch_async` drops the read without a wait; `rows * 4` unchecked; read slots allocated lazily on first pipelined launch; `cudaEventSynchronize` is unbounded like the existing synchronous readback; eligibility checked twice per tick.

## Combined with the token budget (#3670, merged from main)

A budgeted step that plans prefill pieces calls `discard_lookahead` before `execute_decode_step`, so the in-flight replay is waited for and unwound before rows change, and `lookahead_safe()` is false while prefill is queued, so nothing is primed during admissions.

- The 8 pipeline tests pass on the merged tree (Llama 3.2 1B 4bit).
- `budgeted_steps_decode_and_prefill_together_on_a_real_model` (Llama 3.2 1B): passes with the pipeline on and with `MLXCEL_DECODE_GRAPH_PIPELINE=0`; classic vs budgeted first divergence `None` for all 4 requests in both.
- Server smoke, Llama 3.2 1B, `--max-num-batched-tokens 256`, 8 requests arriving 0.3 s apart with 0/120/240-word prompts: pipelined vs `PIPELINE=0` 8/8 identical, no errors in either server log. Pipelined arm: 358 of 379 replays pipelined, 378 budgeted steps, 8 budgeted mixed steps, 1027 budgeted prefill tokens. `PIPELINE=0` arm: 0 pipelined, 336 budgeted steps, 9 mixed. A repeat of the pipelined arm gave the same 8 outputs.

## Tests

All tests ran on GB10 (sm_121) under `gpu-lock` with `--test-threads=1`.

- **Core (`mlxcel-core`, `step_graph step_inputs decode_graphs` filters):** 44 passed. New tests:
  - `a_pipelined_replay_feeds_the_next_step_on_the_device`: three device-fed async launches keep the captured signature, a read whose slot was reused is refused, values are exact, and a prefix read works.
  - `a_device_feed_needs_an_evaluated_source_of_the_same_item_size`.
  - `pipelined_replay_is_cuda_only_and_has_a_kill_switch`: the Metal, ROCm and CPU gate.
- **New scheduler tests (`scheduler_decode_graph_pipeline_tests.rs`, ignored, GPU and checkpoint).** 8 tests at the final head, 8/8 on Llama 3.2 1B 4bit and on Gemma 4 12B 4bit. Three arms run the same requests: pipelined replay, synchronous replay (`PIPELINE=0` with `GRAPHS=always`) and the evaluated structure (`GRAPHS=eager`). Tokens, text and finish reason must be equal across all three. After every tick, each live row's layer-0 KV length must equal prompt plus committed minus one, plus one when the stored lookahead covers the row. The test asserts that this check ran with and without a step in flight.
  - Staggered `max_tokens` (17/30/44/64), so rows stop while the others' next step is in flight and the batch shrinks to one row and then to none.
  - A stop string matched with the next step already launched. One of its rows honours EOS, but EOS is not reached within 48 tokens, so a natural EOS with a step in flight is not exercised.
  - A cancellation at tick 20 with the next step in flight.
  - A single row to its length limit.
  - Eight rows, and five rows padded to bucket 8.
- **Existing decode-graph suite (`scheduler_decode_graphs_tests`, ignored):**
  - The replay arm is now pipelined and must equal a synchronous-replay arm as well as eager.
  - `the_default_mode_pipelines_multi_row_replays` replaces the old yield test. It checks more than 80% pipelined replays at four rows and at one row, that `pipeline=false` restores the yield, and that `force_sync` gives synchronous replays only.
  - Llama 3.2 1B 4bit: 22 of 22 passed, including buckets 1/3/4/8/32, the 1024-token crossing, the admission between replays, logit bias, and the eligibility tests.
  - Gemma 4 12B 4bit: 14 of 14 passed on the selected subset (buckets 1/3/4, admission, logit bias, speculative, default mode, all pipeline tests).
- **Contract checks:** `make verify-versions verify-kernel-dtype-keys verify-used-by verify-env-var-docs verify-kernel-port-dispatch verify-llama-compat verify-report-layout verify-binary-assets verify-windows-paths` passed.
- **Lint:** `cargo fmt --all --check` is clean for this PR's files. `src/loading/vlm_lfm3_vl.rs` is flagged on main too and is not touched here. `cargo clippy --profile test-fast -p mlxcel-core --lib --tests --features cuda --no-deps -- -D warnings` and the same for `-p mlxcel` are clean. `cargo check -p mlxcel --lib --tests` at default features (no CUDA, so it compiles the non-CUDA stubs) passed.

### Gemma 4 e2b is not graph-eligible

`gemma-4-e2b-it-4bit` has 20 KV-shared layers. Its rows are declined by `Engine::graph_rows` ("a row keeps KV outside the paged pool, or the bucket is over the cap"). This PR does not change that gate, and the Verify arm replays nothing on it either. So the pipeline never engages on e2b, and the Gemma 4 graph evidence above comes from the 12B 4bit (the model #3714 validated on). The e2b server smoke below checks only that its default path is unchanged.

## Server smoke (greedy parity)

The release `mlxcel-server` of this branch was run at its default launch with `--parallel 8 --metrics`. Each arm sent 8 concurrent chat requests, 64 tokens each, at temperature 0. The comparison is text, finish reason and completion tokens.

| Model | Pipelined vs `PIPELINE=0 GRAPHS=always` | Pipelined vs `GRAPHS=eager` | Pipelined vs `GRAPHS=0` | Pipelined replays (default arm) |
| --- | --- | --- | --- | --- |
| Llama 3.2 1B 4bit | 8/8 identical | 8/8 identical | 8/8 identical | 61 of 62 replays |
| Gemma 4 12B 4bit | 8/8 identical | not run | 4/8 identical (paged structure vs graphs-off, the known #3714 difference) | 61 of 62 replays |
| Gemma 4 e2b 4bit | 8/8 identical | not run | 8/8 identical | 0 (not graph-eligible) |

Every request finished on `length` at 64 tokens. The baseline arms are the same binary with `MLXCEL_DECODE_GRAPH_PIPELINE=0`, which is #3668's routing. ### Against a main binary

`mlxcel-server` built from origin/main (beedecb, includes #3714 and #3717) vs this branch's final head, default launch, same 8 greedy requests:

| Model | Branch default vs main default | Branch default vs main `MLXCEL_DECODE_GRAPHS=always` | Replays (main default / branch) |
| --- | --- | --- | --- |
| Llama 3.2 1B 4bit | 7/8 identical (row 6 differs) | 8/8 identical | 0 / 62 (61 pipelined) |
| Gemma 4 12B 4bit | 8/8 identical | not run | 60 / 62 (61 pipelined) |

Main's default keeps Llama's multi-row ticks on the eager lookahead pipeline, so its one differing row is the replay vs eager rounding difference #3714 measured, not a pipeline effect: against main forced to replay, the branch is identical. Gemma 4 12B already replayed synchronously on main and is identical.

## Indicative timing (not a benchmark)

This is one 2-round interleaved pair on GB10 with Llama 3.2 1B 4bit and `--parallel 8`, 256 tokens per request. Throughput is wall clock over the whole request batch, prefill included. Host state: load average 5.5 (other work on the host), 106 GiB of memory available.

| Concurrency | Branch default (pipelined), rounds 1/2 | Branch `MLXCEL_DECODE_GRAPH_PIPELINE=0` (#3668 routing), rounds 1/2 |
| --- | --- | --- |
| 4 | 490.0 / 487.4 tok/s | 436.1 / 438.4 tok/s |
| 8 | 809.2 / 808.9 tok/s | 620.6 / 638.4 tok/s |

At this setting, `PIPELINE=0` runs multi-row ticks on the eager lookahead pipeline, which was main's default.

## Deferred to the B200 follow-up

- nsys idle gaps between consecutive decode graphs at c=8 (median under 100 us, p99 under 500 us) on Gemma 4 31B NVFP4.
- The `scripts/bench/serving_compare.py` table at c=1, 8 and 32 before and after on B200, including the c=1 regression bound and the c=8 and c=32 TPOT targets.
- Greedy parity on the 31B (not loaded here by the wave rules).

## Remaining for #3669

These go to a follow-up unit; #3669 stays open.

- **Item 2:** admissions join at step N+2 without tearing the pipeline down, with its acceptance test.
- **Item 3:** off-thread detokenization and streaming (moving `decode_state`, `bounds` and `response_tx` to an output thread), with the multi-byte UTF-8 acceptance test on 4 requests.
- **Rest of item 4:** audit the remaining synchronous host reads in `step_rows.rs`, `speculative_finalize.rs` and the eager pipeline's `read_lookahead_tokens`.
- The B200 measurements listed above (nsys gaps, `serving_compare.py` table, 31B parity).
- A natural EOS with a step in flight (the EOS row in the stop-string test did not reach EOS).
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) platform:linux Linux (CUDA / packaging) 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: Capture and replay the whole decode step as bucketed CUDA graphs

1 participant