Skip to content

perf: join admissions to the decode pipeline and stream off-thread - #3723

Merged
inureyes merged 5 commits into
mainfrom
perf/3669-admission-join-output-thread
Dec 3, 2026
Merged

inureyes merged 5 commits into
mainfrom
perf/3669-admission-join-output-thread

Conversation

@inureyes

@inureyes inureyes commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

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 (ci: add clippy and cargo test gates to ci.yml via self-hosted macOS runner #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

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.

On CUDA an admission no longer tears the pipelined decode-graph tick down. Before a prefill (Prefill arm, prefill chunk, or a budgeted step's prefill pieces) the step in flight is read to the host and kept with its speculative append; the next decode tick commits it to the old rows and primes the step after over the whole batch, so a new row joins at step n+2. Preemption, a row stopping at step n, and a cancellation still unwind it. MLXCEL_PIPELINE_ADMISSION_JOIN=0 restores the teardown. New counters: mlxcel_batch_decode_lookahead_admission_joins_total and _teardowns_total.

Each CUDA worker also runs an output thread. A request with no stop strings, generation bound or token-only row is routed to it when it joins the decode batch: its detokenizer state and client sender move to the thread, the scheduler pushes each committed token through a bounded queue, and events keep their order through a private per-request channel. A slow client cannot stall the scheduler and a detokenization failure fails only its request. Preemption takes the request back. MLXCEL_OUTPUT_THREAD=0 keeps streaming inline.

The result-building half of take_generation_result moves into ResultTemplate so the output thread can build the final result where the detokenizer lives. The remaining synchronous host reads on the decode path (step_rows.rs and speculative_finalize.rs included) are documented in CONTINUOUS_BATCHING.md.
@inureyes inureyes added status:review Under review type:performance Performance improvements priority:medium Medium priority area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:linux Linux (CUDA / packaging) specific labels Dec 3, 2026
With admissions joining the pipeline, `lookahead_safe` no longer refuses a prime while a chunked prefill is parked. The `MLXCEL_MIXED_STEP` arm still discarded the lookahead before its decode, so on CUDA every mixed tick primed a graph step, ran the prefill chunk while that step was in flight (a failed launch would surface against the chunked prompt), and threw the step away on the next tick. The arm now keeps the lookahead through the decode and settles it with `prepare_admission` before the chunk, as `execute_budgeted_step` does. With the join off it discards as before.

On the output thread, a `Finish` record removed the row before flushing the tail and building the result, so a panic there left the client with a closed stream and no error, and kept the request in the failed set forever. The row now stays registered until `Done` is sent, and a failure on a terminal record (finish, detach, close) is not remembered.

Validated with the output-thread unit tests and the decode-graph pipeline tests on GB10.

Refs #3669
@inureyes inureyes added status:done Completed and removed status:review Under review labels Dec 3, 2026
The pad-row release reads and keeps the lookahead rather than tearing it down, the join's teardown list now matches finalize_completed (any finish or cancellation), the host-read table names release_decode_pad_rows, the output thread docs say it starts only in the standard serving loop and skips token-only drafter rows, and the join paragraph says step n+2 forwards the first token the prefill sampled.
@inureyes
inureyes marked this pull request as ready for review December 3, 2026 06:32
@inureyes
inureyes merged commit 9402cf8 into main Dec 3, 2026
29 of 36 checks passed
@inureyes
inureyes deleted the perf/3669-admission-join-output-thread branch December 3, 2026 06:33
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.

perf: Overlap scheduler host work with GPU decode on CUDA

1 participant