Repository navigation
feat: add a per-step token budget mixing decode and chunked prefill - #3717
Merged
Merged
Conversation
Add --max-num-batched-tokens (MLXCEL_MAX_NUM_BATCHED_TOKENS): when set, a pure planner (plan_budgeted_step) schedules every decoding row plus the parked prefill and queued admissions within the budget, and a new BudgetedStep run-loop arm executes decode then prefill in one tick. Unset keeps decide_tick byte for byte on every backend. Wire the flag through both server binaries, startup, config, provider and worker; report budgeted steps on /metrics; add ADR 0014 amending ADR 0005, the vLLM option mapping table and env var docs.
Add an ignored real-checkpoint test that runs the budgeted step through BatchScheduler, check the planned cursor before a continuation, and allowlist its model env var.
A continuation piece that does not fit the free paged blocks now first gets the non-preempting reclaim (spare decode pad rows, cold prompt-cache prefixes), then is halved, and when even a short piece does not fit it runs through the classic continuation reservation instead of being skipped until the batch drains. The parked prefill reservation is sized with the planner's chunk ceiling while a budget is engaged. The budget counters now record the prompt tokens the pieces ran rather than what was planned, warnings about a budget below --parallel and a superseded MLXCEL_MIXED_STEP move to the startup notices, the docs state what N bounds, and code comments cite ADR 0014.
When not even one token of a parked piece fits the free paged blocks, the fallback piece through the preempting reservation is now capped at the contended chunk instead of the full planned piece. A continuation whose request failed counts zero forwarded tokens, the queue snapshot is bounded by free slots, the budgeted arm no longer publishes metrics twice per tick, and the snapshot doc says the counter tracks tokens that ran.
The ADR still described the pre-review continuation fallback and called the prefill token counter planned tokens. It now matches fit_continuation_to_kv (reclaim without preemption, halve, then a contended-size piece) and the counter's ran-token semantics. CONTINUOUS_BATCHING.md now states that the ctx-size times parallel bound applies only when --ctx-size is set.
inureyes
marked this pull request as ready for review
December 3, 2026 02:24
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).
This was referenced Dec 3, 2026
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.
Summary
Adds
--max-num-batched-tokens N(envMLXCEL_MAX_NUM_BATCHED_TOKENS), a vLLM-style per-step token budget for the continuous-batching scheduler. With it set, every tick decodes each running row (one token each) and spends the rest of the budget on the parked chunked prefill and then on queued prompts, admitted in the same tick. Admission no longer waits behind a parked prefill. Unset, which is the default on every backend, the scheduler runsdecide_tickunchanged.Closes #3670
Design
src/server/batch/tick_policy.rs):plan_budgeted_step(&BudgetState) -> BudgetedStep.--prefill-chunk-size, default 2048), by--max-batch-prefillsequences and by free batch slots. The parked prompt's slot is reserved.decide_scheduler_tick(state, None)returns exactlydecide_tick(state). A test sweeps the full boolean state space against counter and interval pairs to prove it.src/server/batch/scheduler/budgeted_step.rs):--parallel 1/--no-cont-batching, with speculative decoding, or under the request-memory policy. These keep the classic tick.mlxcel serveandmlxcel-serveraccept the flag and the env var. It reaches the scheduler throughServerConfig,model_provider,WorkerSchedulerConfigandwith_max_num_batched_tokens. It also appears in runtime settings (read-only in the WebUI).0, or a value above--ctx-sizetimes--parallel, is a startup error.--parallel, when--prefill-grant-intervalorMLXCEL_MIXED_STEPis also set (both are ignored under a budget), and once when the budget cannot apply./metrics:mlxcel_batch_budgeted_steps_total,mlxcel_batch_budgeted_mixed_steps_totalandmlxcel_batch_budgeted_prefill_tokens_total. They count the prompt tokens the pieces actually ran, not the planned ones.docs/adr/0014-token-budget-scheduling.mdwith the formula, the decision rule and the GB10 indicative values. ADR 0005's status line is amended, and the ADR index updated.docs/CONTINUOUS_BATCHING.mdgets a budget section, including whatNdoes and does not bound, and the vLLM/SGLang option mapping table.docs/environment-variables.mdanddocs/llama-server-compat.md(no llama.cpp alias) are updated.Tests and results (GB10, sm_121,
test-fastprofile,--features cuda,--test-threads=1)tick_budget13 passed. The new tests cover: the unset path reproducingdecide_tickover the whole state space, the shipped default being unset, decode rows always scheduled, a split across a parked prefill plus two queued prompts, admission while parked, a budget below decode rows, multi-step chunking, uncached-suffix charging, unsplittable prompts, slot and sequence caps, closed admission, the chunk ceiling, and swept invariants.tick_policy32,cli_input173,runtime_settings14,routes::metrics7,structure_tests2,batch::queue24,batch::observability19,serve_tests15. All passed.batch::scheduler: 349 passed, 37 ignored.#[ignore]testscheduler_budgeton llama-3.2-1b-instruct-4bit with budget 96:cargo clippy --profile test-fast -p mlxcel --lib --tests --features cuda --no-deps -D warningsandcargo fmt --all --checkare clean.make verify-env-var-docs, verify-versions, verify-kernel-dtype-keys, verify-used-by, verify-kernel-port-dispatch, verify-llama-compat, verify-report-layout, verify-binary-assets, verify-windows-paths, verify-webui-contract.Greedy parity (server, temperature 0,
ignore_eos, 6 requests including two ~1150-token prompts, sequential and staggered arrival)--no-prompt-cache, N=256 / N=4096--kv-cache-budget(624 blocks), N=256--prefill-chunk-size 256, 6/6 both modesAfter the review fixes the final build was re-run on the tight-KV N=256, llama N=4096 and both unset arms. All are 6/6 identical to main in both modes. Earlier builds counted planned tokens: the tight-KV arm then reported 167 mixed steps and 41344 tokens, against 17 and 8145 that actually ran.
The e2b N=256 difference from main's default is the chunk size changing prefill reduction order. It reproduces exactly on main with a 256 chunk. The single staggered e2b N=4096 difference did not recur and depends on arrival timing. The unset branch matches main everywhere, which is the parity gate.
GB10 indicative serving numbers (not a decision input)
llama-3.2-1b-instruct-4bit,
--parallel 32 --ctx-size 65536,scripts/bench/serving_compare.py512x128, two interleaved rounds per arm. The host was shared: load average 5.8 to 8.4, 92 to 107 GB available.At c=32 the budget cuts mean TTFT by about 35% and costs about 7.5% TPOT and 4% throughput, because each step carries prefill. Whether a fused forward recovers that TPOT is the B200
savingquestion. The table used the build before the review fixes. Those fixes touch only the tight-KV continuation path and the counters, and the bench never ran under KV pressure.Metal unchanged
The default is
Noneon every backend (max_num_batched_tokens_default(), pinned byshipped_default_is_unset_on_every_backend). With the flag unset,budget_state()returnsNonebefore allocating anything and the tick isdecide_tick. The classicexecute_prefillpath behaves as before: theadmit_queue_headextraction keeps the #1982 deferred-decode branch.Deferred to the B200 follow-up (epic #3671)
D,D_lin,Pandsaving(nsys on the replayed decode graph) and evaluating the ADR 0014 rule for a fused ragged forward.--max-num-batched-tokens. The default stays unset until then.Deviations from the issue
--prefill-chunk-size, default 2048), not the contended 512.--parallel 1, with a warning.--parallelis warned about, not refused. Such a step is decode only, as the issue's acceptance tests specify.Review follow-ups applied
N.publish_metricscall is removed.Left as LOW follow-ups:
--no-batchcombined with the flag.--ctx-sizetimes--parallelupper bound is loose.