Skip to content

fix(qwen4): align prefill pricing with execution route - #3482

Merged
jundot merged 6 commits into
jundot:mainfrom
mvdbos:fix/prefill-route-accounting
Oct 6, 2026
Merged

jundot merged 6 commits into
jundot:mainfrom
mvdbos:fix/prefill-route-accounting

Conversation

@mvdbos

@mvdbos mvdbos commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Qwen4-exp prefill execution chooses between mask-dense and gathered QSA from the concrete chunk shape:

  • gathered QSA requires query_tokens >= OMLX_QWEN4_GATHERED_MIN_QUERY (16 by default);
  • sparse selection must reduce work: cache_tokens + query_tokens > indexer_budget;
  • image-region chunks stay mask-dense: their mRoPE position planes differ, text chunks have broadcast-identical planes.

The scheduler instead priced every text-only Qwen4 request as gathered and every image-bearing request as mask-dense — regardless of what execution does per chunk. A long agent session with images in history was rejected by the preflight guard because of it: its text chunks executed gathered, but admission charged the dense route's flat-overhead ledger (~31 GB from one real dense chunk) and predicted ~109.8 GB against a 109.4 GB cap.

This PR shares the route predicate between execution and memory pricing, reevaluates it after chunk resizing, mirrors the mRoPE plane test so VLM text chunks price gathered while image-region chunks stay dense, and preserves the existing runtime marker correction as a safety net.

Commit scope

  • 53db88e8 adds the deterministic route-accounting regression.
  • c792e03f shares the query/cache route predicate and recomputes pricing through admission, adaptive sizing, the safety guard, chunked prefill, and restored-prefix handling.
  • a683e02c mirrors the runtime mRoPE plane test for concrete VLM chunks and removes the obsolete request-level text_only preflight signal from scheduler, engine, and context-benchmark call paths.
  • d6b122f3 mirrors runtime's exact QSAKVCache type gate so quantized QSA caches are dense-priced before execution, adds regression coverage, and finishes stale test/benchmark signature cleanup.

Before

For the default 2,048-token indexer budget, the first cold 2,048-token chunk was priced as gathered even though execution used mask-dense:

query=2048, cache=0     scheduler=gathered, execution=mask_dense
query=2048, cache=2048  scheduler=gathered, execution=gathered

Adaptive or guard-driven reductions below the 16-token gathered-query floor created the same mismatch at high context. The scheduler also retained the previous chunk's route in chunked prefill rather than predicting each new chunk, and restored prefixes could be omitted from route prediction when boundary snapshots were disabled.

In the other direction, any image-bearing conversation was priced mask-dense everywhere — admission, the throttle, and the guard — even though execution gathers its text chunks (predicted=mask_dense actual=gathered on every logged chunk of a 215k-token session). The post-execution marker corrected attribution only after the model call, so admission kept charging the dense ledger.

After

  • qwen4_gathered_prefill_route() is the shared execution/pricing predicate for query width, cache length, configured minimum width, and indexer budget.
  • Admission prices its actual floor chunk and pre-chunk KV length by the shared predicate alone; the request's media type no longer changes the price.
  • External prefill prices each concrete chunk with its sliced mRoPE position_ids and concrete cache types: broadcast-identical planes (text) gather only with exact QSAKVCache instances, while image-region chunks and QSAQuantizedKVCache stay dense-priced — mirroring _gathered_text_prefill_eligible.
  • Chunked prefill predicts the route for every concrete chunk (text-only by construction).
  • Route pricing is recomputed after adaptive sizing and again after the safety guard. If the guard crosses a route boundary, it runs once more using the corrected memory regime.
  • Restored-prefix token counts participate even when boundary snapshots are disabled.
  • Existing _omlx_last_prefill_gathered markers still verify the executed route and correct attribution if another structural eligibility condition differs.

The mid-prefill guard re-prices every real chunk with its actual position_ids and cache types, so image-bearing tails and quantized QSA caches are caught before Metal sees them even though admission assumes a text tail.

No HTTP API or setting changes. The removed text_only argument was internal preflight plumbing superseded by concrete per-chunk route prediction. OMLX_QWEN4_GATHERED_MIN_QUERY keeps its existing behavior.

Runtime validation

The real-model A/B below was run on origin/main (aa8db734) and the then-current PR head c792e03f. Both used the same donor environment, model, server settings, fresh temporary cache/base directories, and prompt sequence. Both ad-hoc signatures verified successfully; the PR bundle's embedded source contained the shared predicate. The later VLM/cache-type follow-ups are covered by the current-head unit suite and targeted rebuilt-bundle check under Tests.

Identical cold-prefill comparison

The workload starts with a prefix-cache miss and a 13,309-token Qwen4-exp prompt. Its first two 2,048-token chunks cross the sparse-budget boundary exactly.

On origin/main, the same request produced both correction directions on consecutive chunks:

predicted=gathered actual=mask_dense query=2048 kv_len=0
predicted=mask_dense actual=gathered query=2048 kv_len=2048

On PR head, the request produced zero Qwen4 prefill pricing route corrected after execution messages. Correction count for this identical workload fell from 2 to 0 (100%): the first chunk was predicted mask-dense, and the next chunk was predicted gathered, matching execution as cache state evolved. Later adaptively reduced chunks also produced no corrections.

Cold-prefill completion time was 17.19 seconds on main and 18.29 seconds on PR head, excluding model load. This single run shows no material throughput change; it is not used to claim a latency improvement.

Identical cached-prefix continuation

Both follow-up requests contained 13,351 prompt tokens and reused 12,288 tokens from six 2,048-token blocks:

paged cache hit, 12288 tokens in 6 blocks, 1063 tokens remaining, cache reconstructed
... served cached_tokens=12288, prompt=13351

Continuation time was 2.13 seconds on main and 2.06 seconds on PR head. PR head again produced zero route corrections, verifying that restored-prefix length participates in route prediction in the built application.

No OOM occurred in either run; that is a secondary safety observation, not the purpose of this fix. Concurrent-prefill behavior was not validated, so this PR makes no concurrency or queue-throughput claim.

Reproduce

The first commit contains only the deterministic regression:

git checkout 53db88e8
MLX_ENABLE_TF32=0 python -m pytest -q \
  tests/test_scheduler_prefill_memory_guard.py::test_qwen4_pricing_tracks_execution_route

Before the implementation, it fails because _qwen4_text_gathered_pricing() accepts only text_only and cannot represent the query/cache threshold that execution uses:

TypeError: Scheduler._qwen4_text_gathered_pricing() got an unexpected keyword argument 'query_tokens'

At PR head:

git checkout d6b122f3
MLX_ENABLE_TF32=0 python -m pytest -q \
  tests/test_scheduler_prefill_memory_guard.py::test_qwen4_pricing_tracks_execution_route

The test passes and explicitly covers:

  • dense at query=2048, cache=0, budget=2048;
  • gathered at query=2048, cache=2048;
  • dense below the default 16-token query floor;
  • gathered at the 16-token floor;
  • gathered for broadcast-identical mRoPE planes (VLM text chunks);
  • dense for differing mRoPE planes (image-region chunks);
  • gathered for exact QSAKVCache and dense for QSAQuantizedKVCache.

Tests

Key coverage:

MLX_ENABLE_TF32=0 python -m pytest -q \
  tests/test_scheduler_prefill_memory_guard.py \
  tests/test_qwen4_qsa_decode_gather.py \
  tests/test_qwen4_qsa_prefill_memory.py \
  tests/test_prefill_oom_graceful.py \
  tests/test_server_prefill_memory_handler.py \
  tests/test_mlx_vlm_qwen4_exp_compat.py \
  tests/test_qwen4_qsa_reserved_capacity.py \
  tests/test_qwen4_qsa_reservation_integration.py \
  tests/test_scheduler_chunked_prefill.py

Coverage includes admission estimates, external and chunked prefill, adaptive/guard sizing, route-local transient/reclaim accounting, QSA execution compatibility, cache markers, mRoPE plane pricing, and restored-prefix reservation.

Validation:

  • Unit suite at PR head d6b122f3: 10,717 passed, 150 skipped, 19 deselected with MLX_ENABLE_TF32=0 (integration tests excluded).
  • Focused scheduler/prefill/engine coverage: 233 passed.
  • Freshly rebuilt and ad-hoc-signed PR app bundle directly imported its embedded omlx package and confirmed exact QSAKVCache prices gathered while QSAQuantizedKVCache prices dense.
  • Identical real-model built-app workload at c792e03f: route corrections fell from 2 on main to 0 on the tested PR head; cached continuation behavior was unchanged.
  • Concurrent-prefill behavior was not validated.
  • codesign --verify --deep --strict passed for the rebuilt bundle.
  • git diff --check clean.

@mvdbos
mvdbos marked this pull request as draft September 6, 2026 14:36
@mvdbos
mvdbos force-pushed the fix/prefill-route-accounting branch from d9921fe to c792e03 Compare September 6, 2026 14:55
@mvdbos
mvdbos marked this pull request as ready for review September 6, 2026 14:55
@mvdbos
mvdbos marked this pull request as draft September 7, 2026 15:28
…ia type

The route predicate shared with execution (qwen4_gathered_prefill_route)
was gated on text_only, so image-bearing conversations were always priced
mask-dense even though their text chunks execute gathered QSA. A
215k-token agent session with images in history was rejected by the
preflight guard because the dense ledger's flat-overhead charge (~31GB
from a real dense-route chunk) was applied to chunks that would have run
gathered.

Admission now prices the floor chunk by the shared predicate alone, and
the external prefill loop prices each concrete chunk with its sliced
mRoPE position_ids: broadcast-identical planes (text) gather, differing
planes (image region) stay dense-priced, exactly mirroring
_gathered_text_prefill_eligible. The plane predicate moved to
omlx.memory_monitor so execution and pricing share one implementation;
the mid-prefill guard re-prices every real chunk, so an image-bearing
tail is still caught before Metal sees it.
@mvdbos
mvdbos force-pushed the fix/prefill-route-accounting branch from d6b122f to 48aad34 Compare September 11, 2026 11:48
@mvdbos
mvdbos marked this pull request as ready for review September 11, 2026 12:16
@andjiang0083

Copy link
Copy Markdown

Confirming this on 0.7.0 (release) with a real long-context session — the runtime marker correction fires on essentially every request, so on this model the "safety net" is doing all the pricing work.

Environment

  • omlx 0.7.0, M5 Max 128 GB, macOS 27
  • Qwen3.8-Flash-Next-oQ4e-mtp (48 layers: 12 full-attn + 36 linear-attn, 24 Q heads, 2 KV heads, head_dim 256, indexer budget 2048, TurboQuant KV 4 bit, block_size=8192)
  • Text-only agent session, no image tokens (the only vision lines in the log are the startup feature-cache scan), context 104k → 122k, prefix cache hits (98.3 % of prompt tokens)

180 corrections in one ~45-minute session (2026-10-03), by shape

174x  predicted=gathered actual=mask_dense query=4     kv_len=104068 … 122148
  2x  predicted=gathered actual=mask_dense query=2048  kv_len=0
  1x  predicted=gathered actual=mask_dense query=2
  1x  predicted=gathered actual=mask_dense query=7
  2x  predicted=mask_dense actual=gathered query=6144

verbatim first / last:

18:37:48 Qwen4 prefill pricing route corrected after execution: rid=bf46d4e7-0c05-47a9-97e8-79f26bc48580 predicted=gathered actual=mask_dense query=2048 kv_len=0
21:26:06 Qwen4 prefill pricing route corrected after execution: rid=7f7423b4-0105-488b-9c16-ca56a35492bd predicted=gathered actual=mask_dense query=4 kv_len=122148

Two observations:

  1. query=4 is the steady state, not an edge case. With a restored 110k prefix, the only prefill in a turn is a 4-token continuation; it is priced gathered and executes mask_dense, i.e. the "adaptive or guard-driven reductions below the 16-token gathered-query floor" case in the PR description. Because this is the only prefill a normal long-context agent turn performs, the scheduler prices the wrong route on every turn of the session.
  2. The two query=6144 predicted=mask_dense actual=gathered rows are the opposite direction, on a session with no images — consistent with the "retained the previous chunk's route in chunked prefill rather than predicting each new chunk" half of the fix (the 6144-token chunk executed gathered, was priced dense).

The corrections are applied after execution, so admission never sees the right route. In the same session the dense price for a large chunk at high context is what produces an adaptive throttle: chunk 8192 -> 1024 (usage 79.96GB vs sizing target 92.56GB, per_token=1860.0KB) at kv_len 110150, with predicted=14.53GB and [prefill-eviction] ... evicted=0 (no idle model, release_ane insufficient headroom).

If it helps the PR, I can rerun one 110k turn at DEBUG and attach the admission/sizing lines per chunk alongside the executed route — that would show the two halves of the mismatch on the same request.

@andjiang0083

Copy link
Copy Markdown

Appendix from the same 0.7.0 run (fresh engine, DEBUG on) — the two halves of the mismatch the PR describes both reproduce, and one of them fires on every cold start:

21:35:37,530 predicted=gathered actual=mask_dense query=512  kv_len=0
21:35:39,745 predicted=gathered actual=mask_dense query=251  kv_len=0
21:35:40,916 predicted=gathered actual=mask_dense query=445  kv_len=0
21:35:42,107 predicted=gathered actual=mask_dense query=576  kv_len=0
21:35:44,928 predicted=gathered actual=mask_dense query=1971 kv_len=0

i.e. the "Before" table in the PR description (query=2048, cache=0 scheduler=gathered, execution=mask_dense) reproduces for every cold first chunk smaller than the 2,048-token indexer budget, not just the 2,048 case.

The reverse direction, mid-prefill, on the same request:

21:35:48,863 predicted=mask_dense actual=gathered query=896  kv_len=1280
21:35:55,155 predicted=mask_dense actual=gathered query=1024 kv_len=1920

And the steady-state query=4 case off a long prefix (the only prefill a long-context agent turn performs) also appears here, from a different session hitting 110k+ prompts during the window:

21:34:43,449 predicted=gathered actual=mask_dense query=4 kv_len=131639
21:35:23,657 predicted=gathered actual=mask_dense query=4 kv_len=133577
21:35:28,830 predicted=gathered actual=mask_dense query=4 kv_len=134230

Request ids available if you want them; the full DEBUG window is still in the log.

jundot added 2 commits October 6, 2026 16:46
Resolve conflicts with atomic_prefix in the external prefill loop, video_tokens in VLM preflight, and the shared flat-overhead accounting, and drop text_only from test_stale_idle_preflight_refreshes_before_eviction.

@jundot jundot left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ran a late-image sequence on main and on this branch merged onto current main (Qwen3.8-Flash-Next-oQ4e-mtp: a 36k text turn, a 2048x2048 image turn, a resend, then follow-up turns). Route corrections went from 9 to 0. The text chunk right after the image (2048 tokens at kv 40960, measured +10.5 GB) is now guarded at 6.3 GB instead of 2.8 GB on main, and the 6-token tail chunks price at 2.0 GB instead of 5.3 GB, closer to the 0.06 to 1.4 GB they actually allocate.

I pushed a merge commit on top of your branch that resolves the conflicts with main (atomic_prefix in the external loop, video_tokens in VLM preflight), plus a one-line commit that drops text_only from two tests added on main since. After the merge I'll do a small cleanup on main: the unused _gathered_min_query_tokens import, the write-only state.qwen4_gathered_core, the inline QSAKVCache import, and the re-guard block that's duplicated across the external and chunked loops. LGTM, merging.

@jundot
jundot merged commit 9dc9212 into jundot:main Oct 6, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants