Repository navigation
perf: pipeline decode-graph replays on the lookahead pipeline on CUDA - #3719
Merged
Merged
Conversation
A decode-graph tick that the lookahead pipeline can run now runs the #632 state machine with the engine armed for graphs. Step n+1 is built in the replayable structure, fed step n's tokens by a device-to-device copy into the step-input buffer, and launched with an asynchronous readback into a pinned slot before step n's tokens are read, so the host commits step n while the GPU runs step n+1. Rows whose every layer is pool-backed layer state (Gemma 4 with paged sliding state) join the pipeline on these ticks. MLXCEL_DECODE_GRAPH_PIPELINE=0 restores the synchronous replay routing of #3668. Metal, ROCm and CPU never reach it because the decode-graph mode is off there.
The prime after a prefill runs outside a graph tick, so its step used the eager structure. A pipelined graph tick committed it, and that one step rounds differently from the replayable structure, so long runs drifted from the synchronous replay. The tick now unwinds such a lookahead first, as the synchronous graph path does.
When the next tick is a pipelined decode-graph tick, a prime issued outside it runs the eager structure and is unwound by that tick, so it only costs a forward and a trim. The pipeline tests now count the KV checks they make, the stop-string test no longer claims an EOS it does not reach, and the graph-tick assertion reports why a tick was declined.
…rlap-host-gpu-decode
A device-fed region (stage_from_device, issue #3669) was copied only by the first upload that saw it. When something in a step evaluates early, the first generation uploads, and a later flush of a second generation re-copies the whole head from the host staging slot. The slot's bytes for the fed region were never written, so they replaced the fed tokens with whatever the slot last held, and the feed was not issued again. The upload now issues every feed that lies inside the head range its host copy covers, after that copy, so a flush puts the device bytes back. Feeds are only read by uploads inside their own step, before the next launch of the graph that writes their source. a_flush_after_an_early_upload_keeps_a_device_fed_region reproduces it: without the fix the fed view reads [-7, -7, -7, -7] (the slot's stale bytes) instead of the source's [101, 102, 103, 104].
A stored lookahead torn down without being read (discard_lookahead on an admission, preemption or completion, a stale id set in the lookahead and prompt-lookup ticks, the synchronous graph branch) was trimmed and dropped while its pipelined replay could still be running. A CUDA failure of that launch then surfaced in some later, unrelated evaluation, decode graphs were not disabled, and the arrays the replay adopted (which carry no event) could be read before the step completed. These sites now go through unwind_stored_lookahead, which waits on a pending replay's readback event first, counts a failure against the eval-failure guard (the wait itself disables decode graphs on a CUDA error), then trims as before. Eager lookaheads keep the stream-ordered trim without a wait. Tests: a_discarded_in_flight_replay_is_waited_for_and_its_failure_counted injects a readback failure into a discard with a replay in flight; rows_that_stop_after_the_window_slid_match_the_synchronous_path runs the three arms with staggered stops past 1024 tokens, which on Gemma 4 unwinds two appends after the sliding window retired head blocks. Both pass on Llama 3.2 1B and Gemma 4 12B 4bit.
A row the eager pipeline refuses (Gemma 4 with pool-backed layer state) joins the lookahead pipeline only on a pipelined graph tick. When such a tick's prime is not a decode-graph step after all, submit_graph_padded returns Ok(None) and the prime fell back to an eager submit_padded, an eager speculative append the gate never admitted. This is reachable whenever graphs stop accepting the bucket within the tick: a CUDA failure disables them, a capture over the byte cap lowers the bucket cap, or a churn suspension starts. prime_lookahead_with_input now returns no lookahead in that case, before anything is appended, so the next tick decodes synchronously. Rows the eager pipeline accepts still fall back to the eager prime. an_armed_tick_that_is_not_a_graph_step_does_not_prime_a_graph_only_row_eagerly caps the graphs below the bucket and primes on an armed tick: it fails on Gemma 4 12B without the guard and passes with it, and on Llama 3.2 1B the eager prime is still stored.
Member
Author
Implementation review summaryIntent
Findings addressed
Remaining items
Verification
|
Member
Author
|
Security and performance review at 8a420e4: no CRITICAL, HIGH or MEDIUM findings, so no code was changed. Checked and found sound:
LOW, not fixed:
|
The pipelined-replay paragraph in CONTINUOUS_BATCHING.md said only `verify` mode never pipelines; `DecodeGraphMode::pipelines` excludes `eager` as well. The `MLXCEL_DECODE_GRAPHS` row in environment-variables.md said a replay error disables graphs for the process, while the state is per engine, and its counter list omitted `mlxcel_batch_decode_graph_pipelined_replays_total`.
inureyes
marked this pull request as ready for review
December 3, 2026 04:29
inureyes
added a commit
that referenced
this pull request
Dec 3, 2026
…3723) ## Summary Second half of #3669 (part 1 merged as #3719). On CUDA the decode pipeline now survives admissions, and detokenization and streaming move to a per-worker output thread. Metal, ROCm and CPU are unchanged: both paths are gated on pipelined decode graphs or the CUDA backend. Closes #3669 ## Changes ### Item 2: admissions join the pipeline - `prepare_admission` (new `scheduler/admission_join.rs`) replaces the unconditional `discard_lookahead` before a prefill in the run loop's Prefill arm and in `execute_budgeted_step` (`--max-num-batched-tokens`). With the join on and a decode-graph lookahead stored, it reads the step in flight to the host and keeps it with its speculative append (the prefill would wait for that step on the shared stream anyway). Otherwise it is the old teardown. - The next decode tick takes a new arm in `run_lookahead_tick`, `pipelined_join_decode`. It applies when `seq_ids` is the lookahead's rows plus newly admitted live rows. It commits step n+1 to the old rows and primes step n+2 over the whole batch, so a new row joins at step n+2. If a row stops on step n+1's token, the old rows unwind and the tick runs synchronously, as a stale lookahead does. - `lookahead_safe` on an armed pipelined tick now only rejects a pending preemption. `preempt_sequence` unwinds a kept lookahead before releasing the victim. `release_decode_pad_rows` waits for a kept step before giving pad blocks back. - New kill switch: `MLXCEL_PIPELINE_ADMISSION_JOIN=0`. New counters: `mlxcel_batch_decode_lookahead_admission_joins_total` and `mlxcel_batch_decode_lookahead_admission_teardowns_total`. ### Item 3: output thread - New `batch/output_thread.rs`: one thread per worker with a bounded queue (4096 records). A request is routed in `finish_prefill` when it has no stop strings, no generation bound and no token-only row, and the worker does not dispatch speculative decoding (`output_thread::routable`, `route_output`). - On routing, the request's `StreamingDecodeState` and client sender move to the thread. Its `response_tx` becomes a private channel that the routed link drains before each token, so scheduler-sent events keep their order with the routed tokens. - `SequenceFinishHooks::stop_text` pushes the token instead of detokenizing. `finalize_completed` hands the thread a `ResultTemplate`, which is the non-detokenizer half of `take_generation_result`, now factored out in `sequence.rs`. The thread streams the tail, builds the result, records the completion telemetry and sends `Done`. - Failure handling: each record runs under `catch_unwind`. A panic fails only that request: the client gets an error and the request is marked cancelled for the scheduler. A client that never reads cannot stall the scheduler. - Preemption detaches the request and returns its sender (`unroute_output`). - `spawn_model_worker_with_batch_config` starts the thread with `enable_output_thread`. The kill switch is `MLXCEL_OUTPUT_THREAD=0`. ### Item 4: audit of synchronous reads - `step_rows.rs` performs no device reads: the row hooks read host state only. - `speculative_finalize.rs` performs none directly: speculative rounds verify on the host inside the drivers. - The table of reads that remain on the decode path, and why each stays, is in `docs/CONTINUOUS_BATCHING.md`. ### Docs - `docs/environment-variables.md`: rows for both new variables. - `docs/CONTINUOUS_BATCHING.md`: three paragraphs (the join, the output thread, the audit table), and the outdated "no pending admission or chunked prefill" condition is corrected. ## Tests (GB10, test-fast profile, `--test-threads=1` under `gpu-lock`) - Unit tests, 9/9 pass: - output thread vs scheduler thread, 4 multi-byte replies - a detokenization failure fails only its request, and the scheduler sees that request as cancelled - event order is kept - a client that never reads does not stall the scheduler - detach hands the client back - requests that must stay inline are not routed - both CUDA-only gate tests (output thread and admission join) - `scheduler_decode_graphs_tests::pipeline`, all pass on Llama 3.2 1B 4bit and on Gemma 4 12B 4bit. New tests in that module: - `an_admission_during_the_pipeline_joins_at_the_step_after_next`, with no budget and with `--max-num-batched-tokens` 256. Both late rows join, no admission teardown, the KV invariant holds, slabs do not move, and tokens match the teardown arm row for row. - `a_natural_end_of_sequence_with_the_next_step_in_flight_matches_the_synchronous_path` - `four_concurrent_multibyte_requests_stream_the_same_on_the_output_thread`. It uses the Llama 3 chat format and skips on other tokenizers. - `cargo fmt --all --check`: clean. - Scoped clippy (`--features cuda --lib --tests -D warnings`): clean. - `cargo check -p mlxcel --lib --tests` at default features: clean. - Contract checks (`make verify-*`): all pass. ## Greedy parity (server) - Setup: `mlxcel-server`, Llama 3.2 1B 4bit, `--parallel 8`, 8 chat prompts x 64 tokens, temperature 0, streamed. Two traffic shapes: a burst and staggered arrivals (150 ms apart). Each run was done with no budget and with `--max-num-batched-tokens 256`. - Arms: - main `ac5716b8f` - this branch at its defaults - this branch with both switches off - a second main run as a null control - Result: across two full runs of the matrix, the branch output was byte-identical to main in all 8 cells (4 per run). - Null control: main-vs-main changed one prompt (#5) in one cell per run, a 256-budget burst in run 1 and a 256-budget stagger in run 2. The branch with both switches off showed the same change once. This is existing batching-timing variance under the budget, not something this PR introduces. | Run 2 counters | joins | admission teardowns | pipelined replays | |---|---|---|---| | branch, no budget | 5 | 0 | 209 | | branch, budget 256 | 7 | 0 | 209 | | branch with switches off, no budget | 0 | 6 | 197 | | branch with switches off, budget 256 | 0 | 5 | 198 | | main, no budget | n/a | n/a | 207 | ## Review - pr-reviewer: no CRITICAL or HIGH findings. Two MEDIUM findings fixed in 4685a81: - The `MLXCEL_MIXED_STEP` arm now keeps the joined lookahead through its decode and calls `prepare_admission` before the chunk, as the budgeted step does. Before the fix it primed a graph step that the chunk then ran under, and the step was thrown away on the next tick. - A routed row now stays registered until `Done` is sent, so a panic while finishing still sends the client an error. - pr-security-checker: no CRITICAL, HIGH or MEDIUM findings. One LOW finding fixed: the `output_worker` field's required drop order is now documented. LOW findings left as they are: - Taking back a preempted routed request blocks for up to 10 s (`DETACH_TIMEOUT`) if the output thread is that far behind. - `record_admission_teardown` also counts eager teardowns. - The membership check in `admission_join_applies` is quadratic in batch size, on mismatched ticks only. ## Deferred - The B200 measurements for #3669 need a B200 host: nsys idle-gap numbers, steps/s at 1/4/8/64 rows, and a c=1/8/32 serving table. GB10 is the only validation target in this wave, and this PR shows GB10 correctness and parity only. ## Notes - Joining reads step n+1 to the host before the prefill instead of feeding it on the device. The prefill syncs the stream anyway, so nothing is lost. In exchange, no mixed host/device staging is needed and the KV invariant keeps the speculative append on the old rows only. - An admission whose decode tick is not an armed graph tick (eager steps, Metal, ROCm, CPU) still tears down as before.
12 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.
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.
run_lookahead_tickwith the engine armed. Step n+1 is built in the replayable structure (Engine::submit_graph_padded). When it matches a captured graph,StepGraph::launch_asynclaunches 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.step_inputs::stage_i32_from_device, issued inupload()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.PendingTokens::wait). A sequence number per slot refuses a read whose slot a later launch reused.quiesce_lookahead), unwinds the speculative append withapply_lookahead_trim, and re-runs the tick synchronously. For a graph tick that rerun is a synchronous replay.MLXCEL_DECODE_GRAPHS=always).MLXCEL_DECODE_GRAPH_PIPELINE=0restores main's routing.MLXCEL_DECODE_GRAPH_PIPELINE=0restores perf: Capture and replay the whole decode step as bucketed CUDA graphs #3668's routing exactly: a synchronous replay, and multi-row ticks the pipeline can run stay eager./metricsgainsmlxcel_batch_decode_graph_pipelined_replays_total.verifyandeagermodes never pipeline. A CUDA error while waiting fails that step's rows like a failed synchronous readback and disables graphs for the engine.step_graph::mode_from), andpipeline_fromrequires a replay mode.pipelined_replay_is_cuda_only_and_has_a_kill_switchtests this gate. The non-CUDA C++ stubs throw or return null.docs/CONTINUOUS_BATCHING.md(the decode-graphs section gains a "Pipelined replay" paragraph, and the Controls paragraph lists the new metric) anddocs/environment-variables.md(the newMLXCEL_DECODE_GRAPH_PIPELINErow and the updatedMLXCEL_DECODE_GRAPHStext).Scope narrowed from the issue
apply_lookahead_trimand touchesadmission.rs, which sibling #3670 is editing in the same wave.finish.rsownership:decode_state,boundsandresponse_txwould 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.read_lookahead) and the teardown wait (quiesce_lookahead), which replaced the twotry_evalcalls in the steady path. The eager pipeline keepsread_lookahead_tokenson its lazy array, unchanged.step_rows.rsandspeculative_finalize.rswere 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.
discard_lookahead, the stale-id-set arm ofrun_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_lookaheadnow 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.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]).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).read_seq_is set after the copy and event are queued inlaunch_async; anadoptfailure after a successfullaunch_asyncdrops the read without a wait;rows * 4unchecked; read slots allocated lazily on first pipelined launch;cudaEventSynchronizeis 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_lookaheadbeforeexecute_decode_step, so the in-flight replay is waited for and unwound before rows change, andlookahead_safe()is false while prefill is queued, so nothing is primed during admissions.budgeted_steps_decode_and_prefill_together_on_a_real_model(Llama 3.2 1B): passes with the pipeline on and withMLXCEL_DECODE_GRAPH_PIPELINE=0; classic vs budgeted first divergenceNonefor all 4 requests in both.--max-num-batched-tokens 256, 8 requests arriving 0.3 s apart with 0/120/240-word prompts: pipelined vsPIPELINE=08/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=0arm: 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-lockwith--test-threads=1.mlxcel-core,step_graph step_inputs decode_graphsfilters): 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.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=0withGRAPHS=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.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.scheduler_decode_graphs_tests, ignored):the_default_mode_pipelines_multi_row_replaysreplaces the old yield test. It checks more than 80% pipelined replays at four rows and at one row, thatpipeline=falserestores the yield, and thatforce_syncgives synchronous replays only.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-pathspassed.cargo fmt --all --checkis clean for this PR's files.src/loading/vlm_lfm3_vl.rsis flagged on main too and is not touched here.cargo clippy --profile test-fast -p mlxcel-core --lib --tests --features cuda --no-deps -- -D warningsand the same for-p mlxcelare clean.cargo check -p mlxcel --lib --testsat default features (no CUDA, so it compiles the non-CUDA stubs) passed.Gemma 4 e2b is not graph-eligible
gemma-4-e2b-it-4bithas 20 KV-shared layers. Its rows are declined byEngine::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-serverof 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.PIPELINE=0 GRAPHS=alwaysGRAPHS=eagerGRAPHS=0Every request finished on
lengthat 64 tokens. The baseline arms are the same binary withMLXCEL_DECODE_GRAPH_PIPELINE=0, which is #3668's routing. ### Against a main binarymlxcel-serverbuilt from origin/main (beedecb, includes #3714 and #3717) vs this branch's final head, default launch, same 8 greedy requests:MLXCEL_DECODE_GRAPHS=alwaysMain'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.MLXCEL_DECODE_GRAPH_PIPELINE=0(#3668 routing), rounds 1/2At this setting,
PIPELINE=0runs multi-row ticks on the eager lookahead pipeline, which was main's default.Deferred to the B200 follow-up
scripts/bench/serving_compare.pytable 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.Remaining for #3669
These go to a follow-up unit; #3669 stays open.
decode_state,boundsandresponse_txto an output thread), with the multi-byte UTF-8 acceptance test on 4 requests.step_rows.rs,speculative_finalize.rsand the eager pipeline'sread_lookahead_tokens.serving_compare.pytable, 31B parity).