Repository navigation
fix(qwen4): align prefill pricing with execution route - #3482
Conversation
d9921fe to
c792e03
Compare
…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.
d6b122f to
48aad34
Compare
|
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
180 corrections in one ~45-minute session (2026-10-03), by shapeverbatim first / last: Two observations:
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: 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. |
|
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: i.e. the "Before" table in the PR description ( The reverse direction, mid-prefill, on the same request: And the steady-state Request ids available if you want them; the full DEBUG window is still in the log. |
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
left a comment
There was a problem hiding this comment.
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.
Summary
Qwen4-exp prefill execution chooses between mask-dense and gathered QSA from the concrete chunk shape:
query_tokens >= OMLX_QWEN4_GATHERED_MIN_QUERY(16 by default);cache_tokens + query_tokens > indexer_budget;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
53db88e8adds the deterministic route-accounting regression.c792e03fshares the query/cache route predicate and recomputes pricing through admission, adaptive sizing, the safety guard, chunked prefill, and restored-prefix handling.a683e02cmirrors the runtime mRoPE plane test for concrete VLM chunks and removes the obsolete request-leveltext_onlypreflight signal from scheduler, engine, and context-benchmark call paths.d6b122f3mirrors runtime's exactQSAKVCachetype 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:
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=gatheredon 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.position_idsand concrete cache types: broadcast-identical planes (text) gather only with exactQSAKVCacheinstances, while image-region chunks andQSAQuantizedKVCachestay dense-priced — mirroring_gathered_text_prefill_eligible._omlx_last_prefill_gatheredmarkers 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_idsand 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_onlyargument was internal preflight plumbing superseded by concrete per-chunk route prediction.OMLX_QWEN4_GATHERED_MIN_QUERYkeeps its existing behavior.Runtime validation
The real-model A/B below was run on
origin/main(aa8db734) and the then-current PR headc792e03f. 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:On PR head, the request produced zero
Qwen4 prefill pricing route corrected after executionmessages. 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:
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:
Before the implementation, it fails because
_qwen4_text_gathered_pricing()accepts onlytext_onlyand cannot represent the query/cache threshold that execution uses:At PR head:
The test passes and explicitly covers:
query=2048, cache=0, budget=2048;query=2048, cache=2048;QSAKVCacheand dense forQSAQuantizedKVCache.Tests
Key coverage:
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:
d6b122f3: 10,717 passed, 150 skipped, 19 deselected withMLX_ENABLE_TF32=0(integration tests excluded).omlxpackage and confirmed exactQSAKVCacheprices gathered whileQSAQuantizedKVCacheprices dense.c792e03f: route corrections fell from 2 on main to 0 on the tested PR head; cached continuation behavior was unchanged.codesign --verify --deep --strictpassed for the rebuilt bundle.git diff --checkclean.