Skip to content

perf(server): split batched prefill into compatible cohorts - #346

Merged
inureyes merged 2 commits into
mainfrom
perf/332-batched-prefill-cohorts
Jun 18, 2026
Merged

inureyes merged 2 commits into
mainfrom
perf/332-batched-prefill-cohorts

Conversation

@inureyes

Copy link
Copy Markdown
Member

Summary

Closes #332. When a collected prefill window held one incompatible request (unsupported model, any VLM embeddings, any adopted prompt-cache prefix, or length-incompatible rows on equal-length-only models), the batch scheduler fell the whole window back to sequential prefill, wasting eligible concurrent work. This splits the window into compatible cohorts so cold text rows still run batched while incompatible rows take their existing offset-aware handling.

What changed

  • New src/server/batch/prefill_cohort.rs: pure plan_prefill_cohorts planner that partitions a priority-ordered window into BatchedCold and Sequential cohorts, plus its types and unit tests. Order-preserving, offset-isolating, and contiguity-respecting by construction.
  • src/server/batch/scheduler.rs: execute_batched_prefill now drains the window, classifies each row (cold = no VLM/custom embeddings AND zero adopted-prefix offset), plans cohorts, and dispatches them in window order. The padded batched forward pass moved verbatim into a new run_padded_batched_prefill helper. Cold cohorts run batched even when the window contains incompatible rows; adopted-prefix and embedding-bearing rows take execute_full_prefill.
  • src/server/batch/mod.rs: declares the prefill_cohort module.
  • src/server/batch/scheduler_cohort_parity_tests.rs: new #[ignore] real-model qwen3 parity test.
  • src/server/batch/scheduler_prompt_cache_tests.rs: refreshed a now-stale comment about the old whole-window fallback.

Correctness (cache offsets)

A row is classified cold only when it has no embeddings AND prefill_start_offset == 0, which is exactly the zero-offset precondition the padded batched path assumes. The planner guarantees a BatchedCold cohort contains only cold rows, so an adopted prefix can never be folded into a batch and have its KV resumed at the wrong offset; it always takes the offset-aware execute_full_prefill. The refactor also routes the single-request and equal-length-only paths through begin_prefill, tightening two latent paths that previously reached execute_full_prefill in the Queued state and would have failed the Queued to Decoding transition.

Fairness

Cohorts dispatch in window order and the queue dequeues in priority order, so concatenating cohort members reproduces window order exactly (asserted by a unit test). Cold rows batch only where contiguous, so the split never hoists a lower-priority request ahead of a higher-priority one.

Scope

Batched-prefill support is unchanged (qwen3 / llama3 / qwen3.5). No new dense families were added; that expansion is deferred until cohort splitting is measured, per the issue.

Test plan

  • cargo test --release -p mlxcel --lib --features metal,accelerate prefill_cohort:: (11 pure planner tests pass: order preservation, offset isolation, all-cold no-regression, all-incompatible, equal-length-only, contiguity).
  • cargo check -p mlxcel --lib --tests and cargo clippy -p mlxcel --lib --tests -- -D warnings clean.
  • Orchestrator: full release build + scheduler_cohort_parity_tests against real qwen3 (--ignored), plus a mixed cold + prompt-cache-hit synthetic queue measuring prefill tok/s, TTFT, and head-of-line blocking vs the all-or-nothing fallback.

The batch scheduler collected a prefill window and, when it held one incompatible request (unsupported model, any VLM embeddings, any adopted prompt-cache prefix, or length-incompatible rows on equal-length-only models), fell the WHOLE window back to sequential prefill. That wasted the eligible concurrent work even when most of the window was cold text ready to batch.

Split the window into compatible cohorts instead. The new prefill_cohort module classifies each row and partitions the priority-ordered window: contiguous runs of cold text rows (zero KV-history offset, no custom embeddings) form batched cohorts, while adopted-prefix and embedding-bearing rows are routed to the existing offset-aware single-sequence path. The cold cohort runs as one padded batched prefill even when other rows in the window are incompatible.

Correctness: a row is cold only when it has no VLM/custom embeddings AND no adopted prompt-cache prefix, which is exactly the zero-offset precondition the padded batched path assumes. plan_prefill_cohorts guarantees a batched cohort contains only cold rows, so an adopted prefix can never be folded into a batch and have its KV resumed at the wrong offset; it always takes execute_full_prefill, which honors prefill_start_offset. This also tightens two latent paths that reached execute_full_prefill without begin_prefill (the single-request fast path and the equal-length-only fallback), which would have failed the Queued to Decoding transition.

Fairness: cohorts are dispatched in window order and the queue dequeues in priority order, so concatenating cohort members reproduces window order exactly. Cold rows batch only where contiguous, so the split never hoists a lower-priority request ahead of a higher-priority one.

execute_batched_prefill now drains the window, plans cohorts, and dispatches; the padded batched forward pass moved to run_padded_batched_prefill. Batched-prefill support is unchanged (still qwen3/llama3/qwen3.5); no new families were added.

Tests: prefill_cohort::tests pins the order-preservation, offset-isolation, no-regression (all-cold still one batch), all-incompatible, equal-length-only, and contiguity invariants as pure unit tests. scheduler_cohort_parity_tests adds an ignored real-model qwen3 test asserting a cold row batched inside a mixed window decodes identically to the same row prefilled alone.
@inureyes inureyes added type:performance Performance improvements priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) status:review Under review labels Jun 18, 2026
@inureyes

Copy link
Copy Markdown
Member Author

PR Finalization

Tests: 11 unit tests in prefill_cohort::tests all pass (empty window, all-cold, all-incompatible, mixed split, adopted-before-cold priority, isolated-cold fallback, two separate cold runs, single-row sequential, no-batched-support model, equal-length-only model, padded mixed lengths). The #[ignore] real-model parity test in scheduler_cohort_parity_tests.rs is wired and ready for the orchestrator. No coverage gap found.

Docs: docs/CONTINUOUS_BATCHING.md does not describe the batched-prefill all-or-nothing fallback behavior this PR replaces, so no doc update is needed and no new section was invented. No Korean mirror exists.

Lint/format: cargo fmt --check clean; cargo clippy -p mlxcel --lib --tests -- -D warnings clean. No fixes required.

No changes committed. Ready for merge.

…rence

The cohort parity test compared a cohort-batched (B=2) cold row against a single-prefill (B=1) reference and failed: qwen3 padded batched prefill is not bitwise-identical to single-sequence prefill on Metal, so an early greedy token flips and cascades (the documented #203/#325/#326 jitter class). The correct #332 invariant is that a cohort-split cold row decodes identically to the same row in an all-cold batched window of the same composition; the split only removes the incompatible sibling from the window and must not perturb the cold cohort's padded forward pass. Empirically confirmed on qwen3-0.6b-4bit: mixed-window cohort B equals all-cold batched B byte-identical, while single-prefill B differs by one early near-tie token. Rename the test, assert the batched-vs-batched invariant, keep the single-prefill values as a printed diagnostic only, and document at the cohort dispatch that a cold row which previously fell back to sequential now runs batched (the intended effect, not a regression).
@inureyes

Copy link
Copy Markdown
Member Author

Real-model validation (orchestrator)

Cohort parity test on qwen3-0.6b-4bit. The originally-authored assertion (cohort-batched cold row == single-prefill reference) failed, but that was the wrong invariant: a cohort-batched row runs at B=2, and qwen3 padded batched prefill is not bitwise-identical to single-sequence (B=1) prefill on Metal (the documented #203 / #325 / #326 jitter class, where an early near-tie greedy token flips and cascades). The correct #332 invariant is that a cohort-split cold row decodes identically to the same row in an all-cold batched window of the same composition. Empirically confirmed:

  • mixed-window cohort B (B=2, split from [A, B, adopted-C]) == all-cold batched B (B=2, window [A, B]): byte-identical. The cohort split is correct, cache offsets intact.
  • single-prefill B (B=1) differs by one early near-tie token, exactly the expected jitter.

Fixed in 095f28489: the test now asserts the batched-vs-batched invariant (mixed_window_cold_cohort_matches_all_cold_batched_qwen3), keeps the single-prefill values as a printed diagnostic only (never asserted), and documents at the cohort dispatch that a cold row which previously fell back to sequential prefill now runs batched (the intended effect of cohort splitting, not a regression). 11 planner unit tests pass; pr-reviewer and pr-security-checker approved (0 CRITICAL/HIGH). Cache-offset correctness holds by construction (a BatchedCold cohort contains only zero-offset, no-embedding rows).

Throughput acceptance item: the cold cohort now runs one padded batched forward instead of N sequential forwards, which is the established batched-prefill benefit now applying to mixed windows; a rigorous mixed-queue A/B against the all-or-nothing baseline is deferred (it needs a separate baseline binary), but the mechanism is proven correct and proven to batch the cold cohort in a mixed window.

Follow-up (separate issue, out of #332 scope): batched-prefill seed determinism. pr-reviewer noted that a seeded, non-greedy cold row in a batched cohort is governed by the last row's seed (last-seed-wins), which is a pre-existing property of the batched path that cohort splitting slightly widens. Output stays valid; only seed-reproducibility for seed+temperature>0 requests is affected.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Jun 18, 2026
@inureyes
inureyes merged commit fd5bb3d into main Jun 18, 2026
4 checks passed
@inureyes
inureyes deleted the perf/332-batched-prefill-cohorts branch June 18, 2026 04:04
inureyes added a commit that referenced this pull request Jun 18, 2026
…#356)

A batched prefill cohort runs every row's begin_prefill (which seeds the global MLX RNG when the request carries a seed) up front, before any row reaches finish_prefill (which samples the first token). The fused first-token sampler draws from the process-global RNG with no per-call key, so the last seeded row's seed governed first-token sampling for the whole cohort ("last-seed-wins"): a seeded row's first token depended on its siblings' seeds rather than its own. PR #346 (#332 cohort splitting) widened this, since cold rows that previously fell back to sequential prefill now run inside a BatchedCold cohort.

Reseed the global RNG to the row's own seed inside finish_prefill, immediately before the first-token sample, so each row's first token depends only on its own seed. begin_prefill keeps its seeding (harmless once overwritten here, and still reached from the disaggregated handoff path). Greedy / temperature == 0 / top_k == 1 rows take the argmax path and consume no RNG, so the reseed is a no-op for them. finish_prefill is the single per-row first-token chokepoint for every prefill path, so this one insertion covers both the pre-existing all-cold case and the #332 cohort-split case.

The batched fused decode path samples all rows in one fused_sample draw over [B, vocab] from the shared global RNG and is left unchanged: a seeded row's multi-token decode output across batch sizes is the pre-existing, documented batched-vs-B=1 jitter class, and making it byte-identical would require threading a per-row RNG key into fused_sample (follow-up).

Add a real-model regression test (qwen3-0.6b-4bit, ignored, soft-skip when absent) that holds cohort composition constant and varies only seed values to isolate the RNG variable: a seeded row's first token is invariant to sibling seeds (the bug-discriminating check), depends on its own seed (positive control, non-vacuous), greedy is unaffected, and a cohort-split mixed window matches the all-cold window of the same cold composition.
@inureyes inureyes added this to the 0.3 milestone Jun 21, 2026
@inureyes inureyes self-assigned this Aug 31, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
* perf(server): split batched prefill into compatible cohorts

The batch scheduler collected a prefill window and, when it held one incompatible request (unsupported model, any VLM embeddings, any adopted prompt-cache prefix, or length-incompatible rows on equal-length-only models), fell the WHOLE window back to sequential prefill. That wasted the eligible concurrent work even when most of the window was cold text ready to batch.

Split the window into compatible cohorts instead. The new prefill_cohort module classifies each row and partitions the priority-ordered window: contiguous runs of cold text rows (zero KV-history offset, no custom embeddings) form batched cohorts, while adopted-prefix and embedding-bearing rows are routed to the existing offset-aware single-sequence path. The cold cohort runs as one padded batched prefill even when other rows in the window are incompatible.

Correctness: a row is cold only when it has no VLM/custom embeddings AND no adopted prompt-cache prefix, which is exactly the zero-offset precondition the padded batched path assumes. plan_prefill_cohorts guarantees a batched cohort contains only cold rows, so an adopted prefix can never be folded into a batch and have its KV resumed at the wrong offset; it always takes execute_full_prefill, which honors prefill_start_offset. This also tightens two latent paths that reached execute_full_prefill without begin_prefill (the single-request fast path and the equal-length-only fallback), which would have failed the Queued to Decoding transition.

Fairness: cohorts are dispatched in window order and the queue dequeues in priority order, so concatenating cohort members reproduces window order exactly. Cold rows batch only where contiguous, so the split never hoists a lower-priority request ahead of a higher-priority one.

execute_batched_prefill now drains the window, plans cohorts, and dispatches; the padded batched forward pass moved to run_padded_batched_prefill. Batched-prefill support is unchanged (still qwen3/llama3/qwen3.5); no new families were added.

Tests: prefill_cohort::tests pins the order-preservation, offset-isolation, no-regression (all-cold still one batch), all-incompatible, equal-length-only, and contiguity invariants as pure unit tests. scheduler_cohort_parity_tests adds an ignored real-model qwen3 test asserting a cold row batched inside a mixed window decodes identically to the same row prefilled alone.

* test(server): assert lablup#332 cohort parity against all-cold-batched reference

The cohort parity test compared a cohort-batched (B=2) cold row against a single-prefill (B=1) reference and failed: qwen3 padded batched prefill is not bitwise-identical to single-sequence prefill on Metal, so an early greedy token flips and cascades (the documented lablup#203/lablup#325/lablup#326 jitter class). The correct lablup#332 invariant is that a cohort-split cold row decodes identically to the same row in an all-cold batched window of the same composition; the split only removes the incompatible sibling from the window and must not perturb the cold cohort's padded forward pass. Empirically confirmed on qwen3-0.6b-4bit: mixed-window cohort B equals all-cold batched B byte-identical, while single-prefill B differs by one early near-tie token. Rename the test, assert the batched-vs-batched invariant, keep the single-prefill values as a printed diagnostic only, and document at the cohort dispatch that a cold row which previously fell back to sequential now runs batched (the intended effect, not a regression).
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…lablup#356)

A batched prefill cohort runs every row's begin_prefill (which seeds the global MLX RNG when the request carries a seed) up front, before any row reaches finish_prefill (which samples the first token). The fused first-token sampler draws from the process-global RNG with no per-call key, so the last seeded row's seed governed first-token sampling for the whole cohort ("last-seed-wins"): a seeded row's first token depended on its siblings' seeds rather than its own. PR lablup#346 (lablup#332 cohort splitting) widened this, since cold rows that previously fell back to sequential prefill now run inside a BatchedCold cohort.

Reseed the global RNG to the row's own seed inside finish_prefill, immediately before the first-token sample, so each row's first token depends only on its own seed. begin_prefill keeps its seeding (harmless once overwritten here, and still reached from the disaggregated handoff path). Greedy / temperature == 0 / top_k == 1 rows take the argmax path and consume no RNG, so the reseed is a no-op for them. finish_prefill is the single per-row first-token chokepoint for every prefill path, so this one insertion covers both the pre-existing all-cold case and the lablup#332 cohort-split case.

The batched fused decode path samples all rows in one fused_sample draw over [B, vocab] from the shared global RNG and is left unchanged: a seeded row's multi-token decode output across batch sizes is the pre-existing, documented batched-vs-B=1 jitter class, and making it byte-identical would require threading a per-row RNG key into fused_sample (follow-up).

Add a real-model regression test (qwen3-0.6b-4bit, ignored, soft-skip when absent) that holds cohort composition constant and varies only seed values to isolate the RNG variable: a seeded row's first token is invariant to sibling seeds (the bug-discriminating check), depends on its own seed (positive control, non-vacuous), greedy is unaffected, and a cohort-split mixed window matches the all-cold window of the same cold composition.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) 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(server): split batched prefill into compatible cohorts instead of all-or-nothing fallback

1 participant