Skip to content

feat: add a per-step token budget mixing decode and chunked prefill - #3717

Merged
inureyes merged 10 commits into
mainfrom
feature/issue-3670-token-budget-step
Dec 3, 2026
Merged

inureyes merged 10 commits into
mainfrom
feature/issue-3670-token-budget-step

Conversation

@inureyes

@inureyes inureyes commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds --max-num-batched-tokens N (env MLXCEL_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 runs decide_tick unchanged.

Closes #3670

Design

  • Pure planner (src/server/batch/tick_policy.rs): plan_budgeted_step(&BudgetState) -> BudgetedStep.
    • Decode rows are scheduled first.
    • The remaining budget goes to the parked prompt, then to queued prompts in dequeue order (priority lane first). Each piece is capped by the idle chunk size (--prefill-chunk-size, default 2048), by --max-batch-prefill sequences and by free batch slots. The parked prompt's slot is reserved.
    • The plan ends at the first prompt it cannot finish, so at most one prompt is parked and arrival order holds.
    • Unsplittable prompts (VLM embeddings, models without chunked prefill) run whole when they fit, or as the first prefill of a step.
    • Only the uncached suffix of a prompt-cache hit is charged.
    • decide_scheduler_tick(state, None) returns exactly decide_tick(state). A test sweeps the full boolean state space against counter and interval pairs to prove it.
  • Executor (src/server/batch/scheduler/budgeted_step.rs):
    • The decode step runs first (the replayed CUDA decode graph from perf: Capture and replay the whole decode step as bucketed CUDA graphs #3668 where it applies), then the parked continuation, then admissions. Two or more prompts finished whole share one batched cohort prefill.
    • The plan is advisory. Every admission re-checks the queue head id, slot availability, the parked slot and LoRA compatibility.
    • A continuation that does not fit the free paged KV blocks first gets the non-preempting reclaim (spare decode pad rows, cold prompt-cache prefixes), then is halved. When nothing fits, it falls back to a contended-size piece through the classic continuation reservation, so a parked prompt never waits for the batch to drain.
    • The prefill piece size is pinned through a scoped override and restored on every path.
  • Disengaged with a one-time warning at --parallel 1 / --no-cont-batching, with speculative decoding, or under the request-memory policy. These keep the classic tick.
  • CLI and config:
    • Both mlxcel serve and mlxcel-server accept the flag and the env var. It reaches the scheduler through ServerConfig, model_provider, WorkerSchedulerConfig and with_max_num_batched_tokens. It also appears in runtime settings (read-only in the WebUI).
    • 0, or a value above --ctx-size times --parallel, is a startup error.
    • Startup warns when the budget is below --parallel, when --prefill-grant-interval or MLXCEL_MIXED_STEP is 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_total and mlxcel_batch_budgeted_prefill_tokens_total. They count the prompt tokens the pieces actually ran, not the planned ones.
  • Docs:
    • New ADR docs/adr/0014-token-budget-scheduling.md with 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.md gets a budget section, including what N does and does not bound, and the vLLM/SGLang option mapping table.
    • docs/environment-variables.md and docs/llama-server-compat.md (no llama.cpp alias) are updated.

Tests and results (GB10, sm_121, test-fast profile, --features cuda, --test-threads=1)

  • tick_budget 13 passed. The new tests cover: the unset path reproducing decide_tick over 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.
  • Other filters on the same binary: tick_policy 32, cli_input 173, runtime_settings 14, routes::metrics 7, structure_tests 2, batch::queue 24, batch::observability 19, serve_tests 15. All passed. batch::scheduler: 349 passed, 37 ignored.
  • Real-model #[ignore] test scheduler_budget on llama-3.2-1b-instruct-4bit with budget 96:
    • The long prompt arriving while two rows decode was forwarded as pieces of 94, 94, 42 and 8 tokens.
    • 30 budgeted steps ran, 3 of them mixed.
    • All four requests completed and match the classic run token for token.
  • cargo clippy --profile test-fast -p mlxcel --lib --tests --features cuda --no-deps -D warnings and cargo fmt --all --check are clean.
  • Contract targets pass: 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)

Model / arm vs main@517ede2d7 Budget counters
llama-1b, branch unset 6/6 identical, both modes 0 budgeted steps
llama-1b, N=4096 / N=256 6/6, both modes 621 / 628 steps, 5 mixed
llama-1b --no-prompt-cache, N=256 / N=4096 6/6, both modes 12 / 5 mixed
llama-1b, tight --kv-cache-budget (624 blocks), N=256 6/6, both modes final build: 687 steps, 17 mixed, 35 chunks, 8145 prefill tokens run, no errors
gemma-4-e2b-it-4bit, branch unset 6/6, both modes 0
gemma-4-e2b, N=4096 6/6 seq; staggered 5/6 in one run and 6/6 in a repeat 506 steps
gemma-4-e2b, N=256 identical to main run with --prefill-chunk-size 256, 6/6 both modes 512 steps

After 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.py 512x128, two interleaved rounds per arm. The host was shared: load average 5.8 to 8.4, 92 to 107 GB available.

c arm mean TTFT ms (r1 / r2) mean TPOT ms output tok/s
1 main 47.6 / 48.1 5.92 / 5.78 159.4 / 163.0
1 N=4096 47.6 / 46.6 5.82 / 5.76 162.0 / 163.8
8 main 312.4 / 299.0 13.36 / 13.01 508.6 / 523.7
8 N=4096 283.7 / 292.6 12.94 / 13.14 524.7 / 518.1
32 main 970.1 / 961.0 51.47 / 51.79 545.0 / 539.4
32 N=4096 623.8 / 638.8 54.77 / 56.30 529.2 / 515.1

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 saving question. 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 None on every backend (max_num_batched_tokens_default(), pinned by shipped_default_is_unset_on_every_backend). With the flag unset, budget_state() returns None before allocating anything and the tick is decide_tick. The classic execute_prefill path behaves as before: the admit_queue_head extraction keeps the #1982 deferred-decode branch.

Deferred to the B200 follow-up (epic #3671)

  • Measuring D, D_lin, P and saving (nsys on the replayed decode graph) and evaluating the ADR 0014 rule for a fused ragged forward.
  • The CUDA default sweep for --max-num-batched-tokens. The default stays unset until then.
  • The vLLM 290 ms TTFT reference comparison.
  • The 8192x128 long-prompt TPOT cell.
  • The c=32 TTFT and TPOT improvement criterion.

Deviations from the issue

  • The ADR is numbered 0014, because 0011 to 0013 already exist on main.
  • Decode and prefill run as back-to-back forwards in one tick, not as one fused forward. The ADR records the rule that would reopen this.
  • The per-prompt ceiling is the idle chunk size (--prefill-chunk-size, default 2048), not the contended 512.
  • The budget is disengaged under speculative decoding, the request-memory policy and --parallel 1, with a warning.
  • KV shortening happens in the executor, not the planner, because only the executor sees blocks after the decode step.
  • The plan stops at the first prompt it cannot finish, so at most one prompt is parked.
  • A budget below --parallel is warned about, not refused. Such a step is decode only, as the issue's acceptance tests specify.

Review follow-ups applied

  • A parked continuation no longer stalls under tight KV: non-preempting reclaim first, then halving, then a contended-size fallback.
  • The parked reservation is sized by the planner's ceiling.
  • The counters record what ran.
  • Warnings moved to the startup notices.
  • The documentation states the limits of N.
  • The queue snapshot is bounded by free slots.
  • The duplicate publish_metrics call is removed.
  • Code comments cite ADR 0014.

Left as LOW follow-ups:

  • The fit check ignores tile padding; the reservation covers it.
  • The warn-once is per process.
  • There is no startup notice for --no-batch combined with the flag.
  • The --ctx-size times --parallel upper bound is loose.

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.
@inureyes inureyes added type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:inference Generation, sampling, decoding (incl. speculative, DRY) area:cli Command-line interface / CLI flags status:review Under review labels Dec 3, 2026
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.
@inureyes inureyes added status:done Completed and removed status:review Under review labels Dec 3, 2026
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
inureyes marked this pull request as ready for review December 3, 2026 02:24
@inureyes
inureyes merged commit beedecb into main Dec 3, 2026
36 checks passed
@inureyes
inureyes deleted the feature/issue-3670-token-budget-step branch 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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli Command-line interface / CLI flags area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Add a per-step token budget mixing decode and chunked prefill

1 participant