Repository navigation
perf(qwen4_exp): batched QSA decode/verify without per-row re-pooling or dense masked SDPA - #4070
Conversation
c346a6e to
797ae8f
Compare
A left-padded batch keeps only the blocks every row has closed in the pooled-key prefix, so beside a long row a short row's padding made each forward re-pool the long row's whole closed history (idea from jundot/omlx#4070). Keep the tail past the prefix with the ledger width and per-row padding it was pooled at, and re-pool only the blocks a row closed since then plus the grown grid. Every lifecycle exit drops it with the other QSA cycle state. New counter qsa_pooled_key_tail_hits; kill switch MLX_QWEN4_QSA_POOLED_TAIL. Probe harness and step-1 analysis included. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
d8821af to
fadeb8c
Compare
The BatchQSAKVCache branch of the QSA indexer builds a fresh singleton cache for every row, every layer, every step. Its first update_indexer copies the row's whole raw-key history into a new buffer, and pooled_indexer_keys then re-pools every completed block of that history (fp32 mean, k_layernorm, RoPE): O(context) memory traffic per row per layer per step, the dominant cost of batched long-context decode. BatchQSAKVCache now keeps one completed-block bank for the batch, [B, blocks, D], each row left-aligned and anchored at its first real token exactly as the fresh row cache pools; each step pools only the blocks completed since the last one. The bank is derived state, never serialized: - appends keep it; the public index setters (state, merge, fallback paths) drop it; - trim clamps each row's watermark on the host by the tokens it lost, like _QSAIndexerCache._trim_indexer; finalize() clamps by the right padding that prepare() announced -- the rejected tail of a vector rollback, or the padding a right-padded prompt appended in between -- before rolling it into left padding, which keeps rows anchored; - filter and extend carry it with their rows; nbytes counts it; the owning indexer is held weakly; - an index-key dtype change keeps the fresh-cache path (its cast). Masks, layer outputs and cache state stay bit-identical to the fresh-cache path (tests drive right-padded chunked prompt prefill, decode, verify windows, ragged rollback, reorder/drop filters, extend, trim and state restore, at the tiny and the served ratio 4 / top-k 512 shape). OMLX_QWEN4_QSA_BATCH_ROW_BANKS=0 restores the per-step fresh caches. On an M5 Ultra at the served shapes (12 QSA layers, rows of 100K-114K tokens) a batched decode step's attention drops from 65 ms to 25 ms at 8 rows, 16 ms to 8 ms at 2. Co-authored-by: Sören Sanders <81529835+w-Teilchen@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ection As soon as two requests share a batch, every QSA layer runs a dense SDPA over the full left-padded width behind the sparse boolean mask, so the attention cost of a step grows with the sum of all rows' contexts while a batch-one row reads only token_budget + tail keys. Batched decode steps and Lightning MTP verify windows (up to 16 query rows) now project, rotate and append both caches batched exactly as the dense path does. The indexer scores every row's persistent completed-block bank at once in FP32, keeps each query's top block_topk causal blocks (all of them below the crossover) plus its incomplete tail, and one gather pulls those at most token_budget + ratio - 1 K/V rows per query from the padded bank for one bool-masked SDPA: a fixed number of ops per layer whatever the batch size, no per-row Python loop. The keys each query attends are the ones the dense path's sparse mask leaves visible, with one caveat: blocks whose scores tie exactly at the top-k cut (possible only just past the crossover, where fewer than block_topk blocks score above zero) may be ordered differently by one argpartition over the batch than by the per-row selection. Eligibility fails closed: only the masks the batch builds itself (the left-padded decode marker or the verify window's left-padded causal mask), text positions, an indexer bank aligned with the K/V bank, every row's first real token cached, and at least one row past the crossover. Row-exact verify (batch-one) keeps its own arms. OMLX_QWEN4_QSA_GATHERED_BATCH=0 keeps the dense masked path. On an M5 Ultra at the served shapes, 8 rows of 100K-114K tokens: attention per decode step 64 ms (dense) -> 25 ms (banks) -> 12 ms, a 4-row verify window 116 ms -> 33 ms. Served aggregate decode, 8 sessions at 100K, same build with both switches off vs on: 93 -> 228 tok/s (MTP off), 85 -> 151 tok/s (Lightning MTP on). Co-authored-by: Sören Sanders <81529835+w-Teilchen@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Black reflows long lines in both files; Ruff's isort moves the sibling test import into the third-party block. No test logic changes. Co-authored-by: Sören Sanders <81529835+w-Teilchen@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Times one batched step through the served model's QSA attention layers (random weights, fabricated per-row history) for three arms: fresh per-row indexer caches with dense SDPA (main), persistent row banks, and the gathered arm. --verify N --rollback adds Lightning MTP verify windows with a ragged accept. Each line reports how often the gathered arm ran, so a run shows the changed path was taken. Co-authored-by: Sören Sanders <81529835+w-Teilchen@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fadeb8c to
2f5b826
Compare
|
Tested head Kernel-level ( End-to-end (streaming client, 8 concurrent streams, 256 tokens each, ~26.7K context, MTP on, both arms on one build via your two env switches, A/B/A with a fresh server per arm): dense 86.9 / gather 105.5 / dense 85.4 tok/s aggregate → +21% over A, +24% over A', with the two dense arms within 2% of each other. Same load at ~2K context shows no difference in either arm, which matches the cost model. Our server runs |
|
Re-measured this head (2f5b826) against plain Steady aggregate tok/s at 100K context, 2 / 4 / 8 sessions:
N=1 is unchanged, TTFT is unchanged, and served identity plus the 8-way codeword fan-out pass on this head with MTP on and off. One thing I can't rule out: at 2K context with 8 sessions, steady throughput is 4% (MTP off) and 9% (MTP on) lower with this PR. That is about the size of the baseline's own run-to-run spread, and only the row banks are active at that length. Details are in the description. @yeeeeff thanks for the M3 Ultra run; your +21–24% at 26.7K × 8 with MTP on fits between our 2K and 100K numbers. 🤖 Generated with Claude Code |
|
Thanks for the re-measure — the 2K caveat is the useful part. One M3 Ultra data point on it: MTP on, 8 streams, ~2K context, our A/B/A on a single build showed no difference between arms (145–167 tok/s in both). Only the row banks are active at that length for us too, so the 4–9% may be M5-specific — or inside the run-to-run spread you mentioned. Either way it is cheaply contained: Mergeability heads-up: the PR reads |
|
Metal suite on this head is done (M5 Ultra, mlx 0.32.3, everything except
The 17 new tests account for the difference, and all 17 pass on Metal. The one failure was 🤖 Generated with Claude Code |
jundot
left a comment
There was a problem hiding this comment.
Checked this head on an M5 Max (128 GB) with Qwen3.8-Flash-Next-oQ4e-mtp, main vs main + this PR, 4 concurrent streams with 12K-24K prompts in ABBA order. Aggregate decode while all four streams were decoding went from 104.2 to 116.8 tok/s with MTP off and from 94.5 to 106.3 tok/s with Lightning MTP on, and TTFT didn't change. Every run returned its own codeword with no cross-row leaks, and the attention-only bench reproduces as well (B=8 decode step 121.7 -> 18.4 ms at ~100K rows).
LGTM. I pushed one merge commit on top to clear the docs/TESTING.md conflict, and I'll drop the two new env switches and move the tests into the existing QSA test modules in a follow-up on main.
- Drop the OMLX_QWEN4_QSA_BATCH_ROW_BANKS and OMLX_QWEN4_QSA_GATHERED_BATCH env switches; the flags stay as module constants for the tests. - Move the batched row-bank and gather tests into test_qwen4_qsa_decode_gather.py and drop the kill-switch test. - Remove the batched decode benchmark now that benchmarks/ is gone from main.
BatchQSAKVCache concatenated the whole raw indexer-key bank and its position ids on every append. Each step left the previous exact-width bank in MLX's pool, where it can never satisfy a later (larger) request. Raw keys and positions now live in a buffer on the batch KV capacity ladder of jundot#4312 (minimum grain 1024 columns): - appends write in place; the rank promotion of _append_indexer_positions runs ahead of the write, and a dtype promotion falls back to concatenate - a ragged finalize rolls only the logical prefix - trim moves index_offset and keeps the buffer - extend and filter land their result on the ladder in one copy index_keys / index_position_ids still read and assign as exact-width arrays, and the completed-block bank (jundot#4070) is carried as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…er, and stop extracted rows doubling (#3963) * fix(qwen4_exp): back the BatchQSAKVCache indexer with a capacity buffer BatchQSAKVCache concatenated the whole raw indexer-key bank and its position ids on every append. Each step left the previous exact-width bank in MLX's pool, where it can never satisfy a later (larger) request. Raw keys and positions now live in a buffer on the batch KV capacity ladder of #4312 (minimum grain 1024 columns): - appends write in place; the rank promotion of _append_indexer_positions runs ahead of the write, and a dtype promotion falls back to concatenate - a ragged finalize rolls only the logical prefix - trim moves index_offset and keeps the buffer - extend and filter land their result on the ladder in one copy index_keys / index_position_ids still read and assign as exact-width arrays, and the completed-block bank (#4070) is carried as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(qwen4_exp): keep extracted batch rows from doubling on first append BatchQSAKVCache.extract returns an exact-width, caller-sized row copy but left it marked for geometric growth, unlike QSAKVCache.extract. The row's first append then grew it to max(step, 2 * capacity). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Now standalone on
maincc1fdc9 — no longer stacked on #3963/#4030. Four commits: the twochanges, a test format pass and a benchmark. The two changes are separable; if it is easier to
review, I can split the row banks (bit-identical) into a PR of their own.
Problem
With two or more requests in a batch, every Qwen4 QSA layer takes the
BatchQSAKVCachebranch ofthe indexer and then a dense SDPA over the left-padded width:
Qwen4ExpQSAIndexer.from_projectedbuilds a fresh singletonQSAKVCacheper row, per layer,per step. Its first
update_indexercopies the row's whole raw-key history into a new buffer, andpooled_indexer_keysre-pools every completed block of it (fp32 mean,k_layernorm, RoPE).Both costs grow with every row's context, so at long context aggregate decode stops scaling with
the batch.
Measurements
Setup. Mac Studio M5 Ultra, 256 GB, macOS 27.0, mlx 0.32.3. Model: Qwen3.8-Flash-Next oQ4e.
maincc1fdc9 + the four commits), with oMLX's defaults: nolocal settings, multi-request MTP as on
main.OMLX_QWEN4_QSA_BATCH_ROW_BANKS=0 OMLX_QWEN4_QSA_GATHERED_BATCH=0,which is
main's code path. One build for both arms, so build noise is out.i × 2K unshared tokens.
PR, baseline, baseline, PR with MTP on), each arm on a freshly started server with an empty SSD
cache, all in one window. Cells show the mean; the two runs are in brackets.
completions. It builds the prompts from a private corpus, so it is not attached; any streaming
client sending the same load reproduces the table. Toggle the two switches for the baseline.
The attention-only numbers below come from the benchmark this PR adds.
N=1. The gathered arm needs two or more rows; at N=1 both arms match within 0.2%.
Short context. Below the crossover the gathered arm is not eligible, so only the row banks are
active. At 2K-token prompts, 256 tokens each:
The 8-session cells are 4% (MTP off) and 9% (MTP on) lower with this PR. The baseline's own two
runs differ by 2.5% and 6%, so I am not sure this is real; whole-request throughput (including
prefill and the ramp) for the same cells is +7.5% and −1.1%. I have not profiled it. If it is real, it
would come from the row banks, the only change active at this length;
OMLX_QWEN4_QSA_BATCH_ROW_BANKS=0isolates it.
TTFT is unchanged. At 100K the slowest of 8 streams, which queues behind the others' prefills,
gets its first token after 32.0 / 32.2 s against 32.8 / 32.7 s with MTP off, and 33.1 / 34.4 s against
34.8 / 34.9 s with MTP on.
Attention alone. 12 QSA layers at the served shapes with 4-bit projections and random weights,
rows of 100K–114K tokens, median step time after 4 warm-up steps, on this head:
python benchmarks/bench_qwen4_qsa_batched_decode.py --bits 4 --batch 2,8 python benchmarks/bench_qwen4_qsa_batched_decode.py --bits 4 --batch 2,8 \ --verify 4 --rollback --arms dense,gatherChanges
1.
perf(qwen4_exp): keep per-row QSA pooled banks across batched steps.BatchQSAKVCachekeeps one completed-block bank
[B, blocks, D], each row left-aligned from its first real token(what the fresh row cache pooled), and pools only newly completed blocks. It is derived state and
never serialized:
index_keys/index_position_idsstay plain-attribute-like properties; assigning either fromoutside (
state,merge, cache restore, fallbacks) drops the bank, while append, rollback,filter,extendandtrimwrite the backing fields and keep it;trimclamps each row's watermark on the host (like_QSAIndexerCache._trim_indexer);finalize()clamps by the right paddingprepare()announced (the rejected tail of a vectorrollback, or the padding of a right-padded prompt appended in between) before the roll;
filter/extendcarry it with their rows;nbytescounts it; the indexer is held weakly;Masks, outputs and cache state are bit-identical to the fresh-cache path.
OMLX_QWEN4_QSA_BATCH_ROW_BANKS=0restores it.2.
perf(qwen4_exp): attend batched decode/verify rows over their QSA selection. Batched decodesteps and Lightning MTP verify windows (≤16 query rows) project, rotate and append both caches batched
exactly as the dense path does, then
qsa_fast.batched_causal_block_selectionscores every row's bankin FP32 and keeps each query's top
block_topkcausal blocks (all of them below the crossover) plusits incomplete tail; one gather pulls those ≤
token_budget + ratio − 1K/V rows per query out of thepadded bank for one bool-masked SDPA. A fixed number of ops per layer at any batch size (graph build
0.6 ms per step at 8 rows, against 3.7 ms for the dense path).
OMLX_QWEN4_QSA_GATHERED_BATCH=0keeps the dense masked path.Each verify query gathers its own selection, so a window holds
rows × queries × (token_budget + ratio − 1)K/V rows per layer transiently: ~0.3 GB at 8 rows × 16 queries with 2 KV heads × 256 in bf16.
Eligibility fails closed: only the masks the batch builds itself (the
left_padded_decodemarker, orthe verify window's left-padded causal mask by shape), text positions, an indexer bank aligned with
the K/V bank, every row's first real token cached, at least one row past the crossover; row-exact
verify (armed only for batch-one) keeps its own arms.
Correctness
tests/test_qwen4_qsa_batch_row_banks.py(8): layer output and cache statearray_equalto thefresh-cache path through right-padded chunked prompt prefill, decode, verify windows, ragged vector
rollback, reorder and drop filters, extend, trim, state restore; MRoPE and text positions; the served
ratio 4 / top-k 512 shape; only new blocks pooled; rollback re-pools exactly the cut block.
Mutation-checked on this head: dropping the rollback clamp, the trim clamp, the filter permutation
or the extend join each fail it.
tests/test_qwen4_qsa_batch_gather.py(9): outputs allclose (2e-5; 5e-5 at the served shape) to thedense masked path with identical cache state through decode, verify windows and ragged rollback;
each query reads ≤ budget + tail keys; a row matches its batch-one result; kill switches; every
fail-closed case.
mlx[cpu]0.32.3) of everytests/file matchingqwen4/qsa/mtp/scheduler/cache/batch: 2717 passed on
main, 2734 on this head (the 17 newtests), and the identical 149 failures + 7 errors on both, nearly all "No Metal back-end" or
CPU-unsupported GatherMM; the rest fail the same way on plain
main.slow/integration, same interpreter:maincc1fdc9 17222 passed, 659 skipped; this head 17238 passed, 1 failed, 659 skipped(the 17 new tests account for the difference). The one failure,
test_cluster_cli.py::test_cluster_pipeline_smoke_json_is_runnable,was
[ring] Couldn't bind socket (error: 48)(port in use); it passed 3/3 on rerun, and this PRtouches no cluster code.
token-identical with MTP on and off; an 8-session fan-out with codewords, 27K–49K-token prompts of
different lengths (right-padded batched prefill, past the crossover), answers 8/8 own codewords
with 0 leaks, cold and warm, with MTP on and off.
Known difference. When block scores tie exactly at the top-k cut — possible only just past the
crossover, where fewer than
block_topkblocks score above zero — oneargpartitionover the batchmay keep a different one of the tied blocks than the per-row selection does.
Not in this PR
Under Lightning MTP the vector rollback's
finalize()rolls every row's whole K/V bank (12 layers)whenever rows accept different draft counts: ~110 ms per verify cycle at 8 rows × 100K on the M5 Ultra,
against 36 ms for the verify attention with this PR. That is now the largest batched-MTP cost
(#4141).
Both the old branch and this one read
cache.left_padding.tolist()once per QSA layer per step; thebatch layout is shared by all layers, so it could be read once per forward. Left for a follow-up.
Related
its anchoring (each row pooled from its first real token) exactly.
BatchQSAKVCache; this one does not depend on them.qwen4_expdecode measurements and uptime decay.Earlier stacked build (for comparison)
main3a400dd + #3963/#4030 + an earlier revision of these commits; one run per cell. #4030'scapacity ladder removed the per-step concatenation of the raw-key bank; that probably explains the
higher 8-session cells there (not measured separately).
🤖 Generated with Claude Code