Skip to content

perf: pipeline decode-graph replays on the lookahead pipeline on CUDA - #3719

Merged
inureyes merged 10 commits into
mainfrom
update/issue-3669-overlap-host-gpu-decode
Dec 3, 2026
Merged

inureyes merged 10 commits into
mainfrom
update/issue-3669-overlap-host-gpu-decode

Conversation

@inureyes

@inureyes inureyes commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

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 (perf: capture and replay the decode step as bucketed CUDA graphs #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. perf: capture and replay the decode step as bucketed CUDA graphs #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 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. /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.

  • 95b188d: 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.
  • f114564: 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]).
  • 8a420e4: 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).

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.
@inureyes inureyes added type:performance Performance improvements priority:medium Medium priority area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:linux Linux (CUDA / packaging) specific status:done Completed labels Dec 3, 2026
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.
@inureyes

inureyes commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

Implementation review summary

Intent

Pipeline CUDA decode-graph replays on the #632 lookahead state machine (issue #3669 item 1), with device-side token feedback and an async pinned readback.

Findings addressed

  • A stored lookahead torn down unread (discard_lookahead, stale id sets in the lookahead and prompt-lookup ticks, the synchronous graph branch) was trimmed while its pipelined replay could still be running. A CUDA failure then surfaced in an unrelated later evaluation, graphs stayed enabled, and the replay's adopted arrays carry no event. These sites now wait on the pending readback first and count a failure (MEDIUM, 95b188d).
  • A flush after an early upload in the same step re-copied the head from the host staging slot over a device-fed region, and the feed was not copied again. This is latent: it is reproduced at the step-input API and was not seen in a scheduler run. Feeds are now copied by every upload whose range covers them (MEDIUM, f114564).
  • When an armed tick's prime turned out not to be a graph step (graphs disabled, capped or suspended within the tick), a Gemma 4 row admitted only through the graph-tick gate was primed with an eager speculative append. It is now left unprimed (MEDIUM, 8a420e4).

Remaining items

  • read_seq_ is set after the copy and event are queued in launch_async, so a failed cudaEventRecord leaves a stale guard. Graphs are disabled on that error path anyway (LOW).
  • An adopt failure after a successful launch_async drops the pending read without a wait. matches() has already checked the signature, so this is not expected to happen (LOW).
  • The budgeted step (feat: Add a per-step token budget mixing decode and chunked prefill #3670) was checked by reading the code only: with prefill pieces planned, lookahead_safe() is false, so no prime happens before admissions. The test harness does not drive BudgetedStep (LOW).
  • The test counts in the PR body predate these commits.

Verification

  • All stated requirements implemented (item 1; items 2 and 3 deferred as stated)
  • No placeholder or mock code remaining
  • Integrated into the project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass. On GB10: core step_graph/step_inputs/decode_graphs filters pass, including the new flush test, which fails without its fix. The scheduler_decode_graphs_tests suite passes on Llama 3.2 1B 4bit (18 + 8 pipeline tests). On Gemma 4 12B 4bit, all 8 pipeline tests pass, plus the admission and default-mode tests. The new window test runs past 1024 tokens with a 1024 window, but it does not assert that a head block was retired. The armed-fallback test fails on Gemma without its fix. Scoped clippy for mlxcel and mlxcel-core is clean.

@inureyes

inureyes commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

Security and performance review at 8a420e4: no CRITICAL, HIGH or MEDIUM findings, so no code was changed.

Checked and found sound:

  • FFI bounds: wait_read refuses bytes > outputs_[0].bytes, and the read slots are sized by pinned_bytes_ (at least the largest output), so neither the D2H copy nor the host memcpy can overrun. A device feed's copy stays within [offset, offset + bytes) <= head_ <= capacity_; the dimension product is bounded by capacity_ before each multiply.
  • Lifetime: MlxStepGraphRead holds the shared_ptr<Graph>, so LRU eviction or disable() with a read outstanding defers the destructor, which syncs both read events before the pinned slots and owned buffers go. A feed holds its source array until its slot's event has completed, and State::release syncs slot events before feeds_ is destroyed.
  • Every drop site of a stored lookahead (run_decode_tick, run_lookahead_tick, discard_lookahead, the prompt-lookup tick, the finishing and readback-failure paths) waits on a pending replay before trimming.
  • Kill switch: the synchronous graph branch arms the engine around dispatch_sync_decode only, so no prime is submitted armed when MLXCEL_DECODE_GRAPH_PIPELINE is off. Off CUDA the mode is off and every new check short-circuits before allocating.

LOW, not fixed:

  • step_graph.rs:473 rows * 4 is unchecked; rows is the batch size, so it cannot overflow in practice. The read path allocates three small vectors per step (step_graph.rs:473, graph_pipeline.rs:103,115).
  • step_graph.cpp:615 allocates the read slots lazily with cudaHostAlloc on a graph's first pipelined launch, once per captured graph.
  • step_graph.cpp:659 and the destructor's cudaEventSynchronize are unbounded, the same as the existing synchronous readback.
  • Eligibility is evaluated twice per pipelined tick (decode_graph_tick, then graph_pipeline_tick).
  • Test gap: no test waits on a PendingTokens after its graph is dropped, or asks for more rows than the output holds.

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
inureyes marked this pull request as ready for review December 3, 2026 04:29
@inureyes
inureyes merged commit ac5716b into main Dec 3, 2026
27 of 36 checks passed
@inureyes
inureyes deleted the update/issue-3669-overlap-host-gpu-decode branch December 3, 2026 04:30
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:linux Linux (CUDA / packaging) specific priority:medium Medium priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant