Skip to content

feat(server): MLXCEL_MIXED_STEP prototype and ADR 0005 decision - #1010

Merged
inureyes merged 5 commits into
mainfrom
feature/issue-908-mixed-step-adr
Aug 3, 2026
Merged

inureyes merged 5 commits into
mainfrom
feature/issue-908-mixed-step-adr

Conversation

@inureyes

@inureyes inureyes commented Aug 3, 2026 •

Copy link
Copy Markdown
Member

Summary

Issue #908 is a design spike that delivers a decision. The decision is reject, for both candidate execution models: ragged mixing at the model level and kernel-level mixing. ADR 0005 is the artifact; the scheduler changes exist to make the decision provable rather than argued.

The premise did not survive reading the scheduler

Issue #908 assumes tick alternation makes decoding streams wait a full model forward per prefill chunk, and proposes to replace that alternation with mixing. There is no alternation. decide_action resolves a tick with a chunked prefill parked and any sequence decoding to Decode, and because the policy is a pure function of scheduler state that a decode does not change, it resolves that way on every subsequent tick until the batch drains. Decoding streams are never blocked by a chunked prefill; the chunked prefill is blocked by them, and a long prompt's time to first token is unbounded while other streams decode.

The behaviour had been asserted and mislabelled for some time. scheduler_tests.rs carried chunked_prefill_interleaving_pattern, whose third assertion expects Decode where its own comment reads "after decode, back to prefill continuation", annotated "(still interleaving because batch is non-empty)". The assertions were right and the name was not, because the tests re-implemented the policy in a local helper: a mirrored policy is only as truthful as the copy, and this copy tracked the code while its naming tracked the intent.

Two further facts bound the problem. The issue's own scenario is unreachable at the shipped --parallel 4, because a full batch means the admission branch never fires and a queued 8K prompt is never admitted. And when a slot is free, chunked prefill bounds the admission spike to exactly one forward, since decode reclaims every tick after chunk 0.

Why fusing the forward is rejected

Within a layer the two workloads fuse very differently. The projections and MLP are row-wise, so appending 4 decode rows to a 512-row chunk is 0.8% more rows for the same weight read, and that is the entire win. Attention does not fuse at all: each decode row attends to its own KV history, so a mixed step runs the same attention calls the two separate steps ran. The recoverable fraction of an admission window is therefore D_lin / (C/P + D), which across the plausible term ranges from the in-tree prefill tables spans roughly 3% to 20%, sits toward the low end at the shipped 512-token chunk, and falls further as the chunk grows.

That upper bound is taken seriously in the ADR rather than rounded away, and it still does not carry the decision: it applies only to admission windows, --prefill-chunk-size already spans the same ITL/TTFT frontier from the other direction for free, and this epic has watched op-level wins shrink on contact with their call sites (#899 measured 2.78x fused and 1.15x end to end). Against that, the tree has no ragged mechanism to build on. Every path that looks ragged pads to a shared length: plan_prefill_cohorts, Gemma 4's MTP left-padding, and both mask helpers, which each take one size for the whole batch axis. The only true cu_seqlens loops are in the vision towers, where attention is non-causal, cacheless, and needs no RoPE offset. Building it means a packed layout, per-token RoPE positions, a new segment-loop attention entry point, and shape churn in MLX's shape-keyed graph cache that is worst exactly where mixing is meant to help. Per family.

What changed

  • src/server/batch/tick_policy.rs (new) plus tick_policy_tests.rs: the policy decide_action used to inline, extracted as one pure decide_tick over a flattened TickState, called by both the scheduler and the tests so there is no copy left to drift. chunked_prefill_starves_until_active_batch_drains pins the starvation directly.
  • src/server/batch/scheduler.rs: decide_action delegates to decide_tick; new MixedStep arm in run() decodes the active batch and then advances the parked chunk within one tick; mixed_step_enabled read once at construction so the tick loop never touches the environment.
  • src/server/batch/sequence.rs: BatchSchedulerAction::MixedStep, unreachable with the flag unset.
  • src/server/batch/scheduler_tests.rs: both local policy mirrors now delegate to decide_tick. Assertions unchanged; the misleading comments are corrected and the misleading test name is kept deliberately, as a greppable marker referenced from the ADR.
  • src/server/batch/observability.rs, src/server/routes/metrics.rs: mlxcel_batch_mixed_steps_total, the dispatch proof.
  • scripts/bench_mixed_step_admission.py (new): the scenario bench_serving_concurrency.py cannot express, since it has neither staggered admission nor per-token timestamps.
  • docs/adr/0005-mixed-prefill-decode-step-execution.md (new), plus the ADR index, docs/CONTINUOUS_BATCHING.md, and docs/environment-variables.md.

The prototype is the scheduling half, on purpose

MLXCEL_MIXED_STEP=1 co-schedules the two workloads in one tick; it does not fuse them into one ragged forward. That split is what makes the experiment decisive instead of expensive, because total benefit decomposes as benefit(ragged fused step) = benefit(tick co-schedule) + D_lin per chunk. The prototype measures the first term end to end on a real server and the second is bounded by the formula and measurable from the same run, so the decision never required a per-family ragged execution path to exist first. If the first term is where the value is, the fused forward was never the interesting part; if the first term is small, the second is smaller still.

Fixing the starvation is deliberately not in this PR. Changing which workload wins a contended tick changes the latency profile of every concurrent workload and needs its own fairness policy and its own measurement; shipping it under a spike about mixed execution would bury it. It is split into a follow-up, and the ADR names MixedStep and a grant counter as the two candidate policies.

Default off, provably

mixed_step_off_is_identical_to_the_pre_908_policy compares decide_tick against a transcription of the pre-#908 policy over the complete 128-state space, so the unset path is proven unchanged rather than inspected. The flag alters behaviour only in the chunked_prefill_in_progress && !active_is_empty branch, so the pure-decode control (no chunked prefill parked) and the pure-prefill control (empty batch) take a byte-identical path with the flag on; the issue's "under 1% overhead when idle" bar is met structurally, not statistically. Speculative rounds still outrank mixed steps, pinned in both directions.

How to measure

No benchmarks were run for this PR. The ADR's Results section is deliberately unfilled and names the two cells that decide whether the rejection needs revisiting. Both arms, serving with --parallel above the stream count or the admitted request never leaves the queue:

./target/release/mlxcel-server -m models/llama-3.1-8b-4bit --parallel 8 --prefill-chunk-size 512 --metrics --port 8080
python3 scripts/bench_mixed_step_admission.py --expect baseline

MLXCEL_MIXED_STEP=1 ./target/release/mlxcel-server -m models/llama-3.1-8b-4bit --parallel 8 --prefill-chunk-size 512 --metrics --port 8080
python3 scripts/bench_mixed_step_admission.py --expect mixed

Following examples/sparse_paged_decode_bench.rs, the harness refuses to print a latency table when attribution fails and prints NOT COMPARABLE instead: no /metrics, a flat prefill-chunk counter (the prompt never entered the chunked path, usually because --parallel was not above --streams), or an arm whose mlxcel_batch_mixed_steps_total delta contradicts --expect. That last guard is the one #899 needed.

Test plan

  • cargo test --release --lib --features metal,accelerate server::batch::tick_policy (11 passed, including the exhaustive 128-state default-off parity proof)
  • cargo test --release --lib --features metal,accelerate server::batch::scheduler::tests (75 passed, unchanged)
  • cargo test --release --lib --features metal,accelerate server::batch::observability (13 passed)
  • cargo test --release --lib --features metal,accelerate server::batch::scheduler_prompt_cache_tests (24 passed)
  • cargo clippy --lib --tests --features metal,accelerate -- -D warnings (clean)
  • cargo fmt --all -- --check (clean)
  • python3 scripts/ci/check_cross_repo_refs.py (exit 0)
  • Harness guard path exercised with no server reachable (exits 2, prints NOT COMPARABLE)
  • Live A/B on a real checkpoint: no local model in this worktree, so the maintainer runs it serialized on a quiet machine per the commands above. Greedy token parity across the arms is argued structurally in the ADR and should be confirmed on that run.

Review round

A review pass found no wrong-token or memory defect but several ways the prototype and harness could report a number that was not the thing being measured, which matters here because the deliverable is a data-driven decision. Fixed in bf41cca0: the dispatch counter was over-counting (it fired even when continue_chunked_prefill returned early), the prototype was inflating its own ITL (a per-chunk clear_memory_cache() that was harmless with an empty batch landed on the decode hot path for the duration of a long prefill, against the decode path's deliberate cadence and ml-explore/mlx#2358), prefill_chunks_processed never counted chunk 0 and so read as zero for exactly the starved state this ADR is about, and the harness could pass four kinds of non-scenario: divergent admission windows between the arms, failed requests, a stale server binary missing the counter, and streams that were not actually decoding at the admission instant.

Closes #908

…rototype

Issue #908 asks whether mixing prefill and decode into one step is worth building. Answering it turned up a prior question: the scheduler does not interleave them at all today, contrary to what `decide_action` and its tests claim.

`decide_action` carried its policy inline, and `scheduler_tests.rs` re-implemented that policy in a local helper so the tests could run without a model. The copy drifted: a test named `chunked_prefill_interleaving_pattern` asserts, with a comment reading "still interleaving because batch is non-empty", that a parked chunked prefill yields the tick to decode. It does, unconditionally. The policy is a pure function of scheduler state and a decode changes none of the state it reads, so once a long prompt is admitted next to a live decode batch it runs chunk 0 and then makes no further progress until every decoding sequence has finished.

The policy now lives in `server::batch::tick_policy` as one pure `decide_tick` over a flattened `TickState`, which both `decide_action` and the tests call, so there is no copy left to drift. `chunked_prefill_starves_until_active_batch_drains` pins the starvation directly.

`MLXCEL_MIXED_STEP=1` adds `BatchSchedulerAction::MixedStep`: one tick decodes the active batch and then advances the parked chunk, so both workloads progress. This is the scheduling half of a mixed step, not a fused ragged forward; ADR 0005 (following commit) explains why that split is the decisive experiment. Default off, and `mixed_step_off_is_identical_to_the_pre_908_policy` compares the new policy against a transcription of the pre-#908 one over the complete 128-state space, so the unset path is provably unchanged.

`mlxcel_batch_mixed_steps_total` on `/metrics` is the dispatch proof: a mixed-step benchmark whose delta is zero measured the default policy, which is the failure mode #899 shipped.

Validated with `cargo test --release --lib --features metal,accelerate server::batch::tick_policy` (10 passed) and `cargo check --lib --tests --features metal,accelerate`.

Refs #908
…ion harness

ADR 0005 concludes issue #908, the design spike on mixed prefill/decode steps, with a reject for both candidate execution models: ragged mixing at the model level and kernel-level mixing.

The premise did not survive reading the scheduler. Issue #908 assumed tick alternation makes decoding streams wait a full model forward per prefill chunk. There is no alternation. A chunked prefill parked mid-prompt yields the tick to any active decode batch, and since the policy is a pure function of state that a decode does not change, it yields every tick until the batch drains. Decode streams are never blocked by a chunked prefill; the chunked prefill is blocked by them, and its time to first token is unbounded. The issue's own scenario is also unreachable at the shipped `--parallel 4`, where a full batch means a queued long prompt is never admitted.

What a fused ragged step could recover is bounded by which layers are row-wise. The projections and MLP fuse (appending 4 decode rows to a 512-row chunk is 0.8% more rows for the same weight read), attention does not fuse at all (each decode row attends to its own KV history, so the same attention calls run either way). The recoverable fraction of an admission window is `D_lin / (C/P + D)`, which on the in-tree prefill numbers is single digits to low teens of percent, and `--prefill-chunk-size` already spans that trade with more range and no new code. Against that, the tree has no ragged mechanism to build on: every path that looks ragged (batched prefill cohorts, Gemma 4 MTP, both mask helpers) pads to a shared length, and the only true `cu_seqlens` loops are in vision towers where attention is non-causal and cacheless.

`scripts/bench_mixed_step_admission.py` measures the scenario `bench_serving_concurrency.py` cannot express: it needs staggered admission and per-token timestamps, which that script has neither of. It reports per-stream ITL split into a quiet window and an admission window, the admitted request's TTFT, and whether that first token arrived only after every decode stream had ended, which is the starvation signature. Following `examples/sparse_paged_decode_bench.rs`, it refuses to print a latency table when attribution fails: no `/metrics`, a flat prefill-chunk counter (the prompt never entered the chunked path), or an arm whose mixed-step counter contradicts `--expect`.

Docs record the tick behaviour where operators will hit it, since `--prefill-chunk-size` is documented as bounding prefill's effect on decode latency and the actual shape is the inverse.

No benchmarks were run for this commit; the Results section names the two cells that decide whether the rejection needs revisiting and the reproduce steps for both arms.

Refs #908
The admission harness ran its requests on asyncio's default executor, which caps at `min(32, cpu_count + 4)`. On a small host a large `--streams` would silently queue requests instead of issuing them concurrently, and the admitted request could be the one waiting for a thread, so the run would measure client-side queueing and report it as server latency. The pool is now sized to `streams + 1` and shut down explicitly.

The per-stream ITL table also labelled its second window "admission window (prefill live)" even when the admitted request never produced a token, in which case the window has no upper bound and spans the rest of the run. That case is now labelled as never closed.

ADR 0005 gains the two sections issue #908 asked for and the first draft treated too briefly: MLX graph-cache churn under a packed ragged layout (the row count varies with both the decode batch and the terminal chunk, and the decode batch changes during the very window a long prefill occupies, so the churn is worst where mixing is meant to help), and greedy token parity between the arms, which is structural because the prototype changes only which tick a unit of work runs on, with the caveat that this is an argument from the code and the harness run is what confirms it. The recoverable-work estimate is also widened to the honest 3% to 20% span rather than the low-teens figure of the first draft, with the reasoning for why a 20% upper bound still does not carry the decision.

`tick_state()` documents why hoisting `should_preempt()` out of its original branch is safe: it takes `&self`, mutates nothing, and returns on `!enable_preemption` unless preemption is explicitly on.

Validated with `cargo test --release --lib --features metal,accelerate server::batch::tick_policy` (10 passed), `cargo clippy --lib --tests --features metal,accelerate -- -D warnings`, `cargo fmt --all -- --check`, and `python3 -m py_compile`.

Refs #908
@inureyes inureyes added type:enhancement New features, capabilities, or significant additions priority:low Low priority area:architecture Architecture and code structure changes status:review Under review labels Aug 3, 2026
…asurement

Review of the #908 spike found no wrong-token or memory defect, but several ways the prototype and its harness could report a number that was not the thing being measured. Since this issue's whole deliverable is a data-driven decision, those matter as much as correctness.

The dispatch proof was over-counting. `record_mixed_step()` fired unconditionally, but `continue_chunked_prefill` returns early on a drained sequence, a missing cache, an empty range, or an exhausted eval. ADR 0005 claims the counter moves only when a tick advanced both workloads; it now does, because the function reports whether a chunk actually ran and the counter is gated on that.

The prototype was inflating its own inter-token latency. `continue_chunked_prefill` cleared the MLX buffer cache on every chunk, which was harmless while it could only run with an empty batch, but `MixedStep` put that unconditional clear on the decode hot path for the whole duration of a long prefill. The decode path deliberately clears on a cadence instead (256 tokens on Metal, off by default on CUDA, since a per-step clear churns the pool and defeats CUDA-graph reuse, ml-explore/mlx#2358). The clear is now suppressed on mixed ticks only; every other caller keeps the pre-#908 behaviour.

`prefill_chunks_processed` never counted chunk 0, so it reported continuations only and read as zero for a prompt that ran its first chunk and was then starved, which is exactly the state a reader of this ADR needs to see. `start_chunked_prefill` now records too.

The harness had four ways to pass a run that was not the scenario. The admission window was closed by the admitted request's first token, which is correct in the mixed arm but lands after every stream has ended in the baseline arm, so the two arms compared different spans and the baseline's "prefill live" window covered most of a run with no prefill in it; the window is now clamped to the first stream end and labelled with how it closed. Failed requests printed and continued. A server built before this branch has no mixed-step counter, so `--expect baseline` passed on a stale binary; all three counters must now be present before and after. And nothing verified that the streams were actually decoding at the admission instant, which `--parallel` equal to `--streams` silently violates; every stream must now have produced a token on both sides of it.

Also in the harness: the admitted prompt is salted per run, because a byte-identical 8K prompt would be adopted wholesale by the prompt cache on the second run of an A/B and skip the chunked path entirely; SSE framing moved to `readline()` so per-byte GIL contention across the stream threads stops landing in the p95; gaps straddling the admission instant are charged to neither window; `--expect` is required, since `any` disables both dispatch guards; and `asyncio.gather` no longer deadlocks behind a blocking executor shutdown when a future raises.

ADR 0005 gains the two behaviour changes the prototype does introduce and parity does not cover: paged block availability (a decode batch and a chunked prefill now grow the pool concurrently, so exhaustion raises the request-failure rate under memory pressure) and the #734 head-of-line bound roughly doubling, since a mixed tick is two forwards. Both belong to the follow-up fairness issue.

`MLXCEL_MIXED_STEP` now trims and lowercases before matching, so `On` and ` yes ` behave like their canonical spellings rather than reading as a prototype that silently did not engage.

Validated with `cargo test --release --lib --features metal,accelerate` on `server::batch::tick_policy` (11 passed), `server::batch::scheduler::tests` (75), `server::batch::observability` (13), `server::batch::scheduler_prompt_cache_tests` (24), plus `cargo clippy --lib --tests --features metal,accelerate -- -D warnings` and `cargo fmt --all -- --check`.

Refs #908
…0005

Fills the empty Results section of ADR 0005 with a run on M1 Ultra and adds
the probe that produced it.

The ADR's harness reports ITL, and the machine available for this run was
carrying unrelated load, which would have made those numbers say more about
the load than the scheduler. Cell 1 asks whether the prefill makes progress,
not how fast it is, so it is measured as a counter comparison instead: sample
mlxcel_batch_prefill_chunks_total every 5s while four streams decode and one
~10k-token prompt is admitted. A pinned counter is a pinned counter no matter
how busy the machine is.

Baseline holds at chunk 1 of 19 for 20s while decode advances 138 to 394
steps, then finishes only after decode drains. The prototype advances chunks
from the first sample and completes all 19 by t=20s with decode reaching the
same step count. mixed_steps_total is 0 and 18 respectively, so neither arm is
measuring itself.

Cell 2, the ITL cost of interleaving, stays unmeasured and is called out as
such; it is the follow-up fairness policy's tuning input and should not be
taken from a contended machine. The rejection of ragged mixing is unaffected
either way, and contention pushes the same direction: it inflates C/P, which
shrinks D_lin / (C/P + D).
@inureyes
inureyes merged commit f834547 into main Aug 3, 2026
4 checks passed
inureyes added a commit that referenced this pull request Aug 3, 2026
ADR 0005's Consequences section promised a follow-up issue for the chunked-prefill starvation fix without naming it, which makes it unfindable from the decision that justifies it. It is #1011.

This commit was on #1010's branch but landed after that PR squashed, so it is split out rather than lost.
@inureyes inureyes self-assigned this Aug 31, 2026
@inureyes inureyes added status:done Completed and removed status:review Under review labels Sep 6, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…up#1010)

Design spike for issue lablup#908. The premise turned out to be inverted: tick
alternation does not stall decode, because decide_action returns Decode
whenever any sequence is active, so a chunked prefill never interleaves at
all. It waits for the batch to drain.

ADR 0005 rejects model-level ragged mixing and kernel-level mixing on the MLX
path. The ceiling for a fused ragged step is D_lin / (C/P + D), 3 to 20 percent
on these shapes, and it costs a second forward signature in every family.
--prefill-chunk-size already spans the same frontier for free.

The scheduler policy moves to src/server/batch/tick_policy.rs as one pure
decide_tick over a flattened TickState, called by both the scheduler and the
tests, so the mirrored-policy pattern that hid the starvation is gone. The
default policy is unchanged, proven exhaustively over the 128-state space
rather than by inspection.

MLXCEL_MIXED_STEP is the opt-in prototype, defaulted off, kept as executable
evidence rather than as an operator knob. Measured on M1 Ultra: baseline holds
the prefill at chunk 1 of 19 for 20 seconds while decode advances 138 to 394
steps; the prototype completes all 19 chunks by t=20s with decode reaching the
same count. The starvation fix itself is split out to its own issue, since
changing which workload wins a contended tick needs its own fairness policy
and its own measurement.
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…#1012)

ADR 0005's Consequences section promised a follow-up issue for the chunked-prefill starvation fix without naming it, which makes it unfindable from the decision that justifies it. It is lablup#1011.

This commit was on lablup#1010's branch but landed after that PR squashed, so it is split out rather than lost.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:architecture Architecture and code structure changes priority:low Low 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.

Mixed prefill/decode step execution: design spike and prototype

1 participant