Skip to content

perf(qwen4_exp): batched QSA decode/verify without per-row re-pooling or dense masked SDPA - #4070

Merged
jundot merged 5 commits into
jundot:mainfrom
AureliusClaw:qwen4-batched-qsa
Oct 9, 2026
Merged

jundot merged 5 commits into
jundot:mainfrom
AureliusClaw:qwen4-batched-qsa

Conversation

@AureliusClaw

@AureliusClaw AureliusClaw commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Now standalone on main cc1fdc9 — no longer stacked on #3963/#4030. Four commits: the two
changes, 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.

Numbers below are re-measured on this head against plain main (2026-10-09). The earlier
stacked-build table is kept at the end for comparison.

Problem

With two or more requests in a batch, every Qwen4 QSA layer takes the BatchQSAKVCache branch of
the indexer and then a dense SDPA over the left-padded width:

  1. Qwen4ExpQSAIndexer.from_projected builds a fresh singleton QSAKVCache per row, per layer,
    per step
    . Its first update_indexer copies the row's whole raw-key history into a new buffer, and
    pooled_indexer_keys re-pools every completed block of it (fp32 mean, k_layernorm, RoPE).
  2. The row masks are padded to the batch width and the attention runs dense over that width.

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.

  • Build. This head, 2f5b826 (main cc1fdc9 + the four commits), with oMLX's defaults: no
    local settings, multi-request MTP as on main.
  • Baseline. The same build with 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.
  • Load.
    • A 100K-token shared prompt, warmed once and then served from the prefix cache. Stream i adds
      i × 2K unshared tokens.
    • N streams start together and generate 768 tokens each, at temperature 0.7 with seed i.
  • Metric. Steady aggregate tok/s: tokens over the window in which every stream is decoding.
  • Runs. Two runs per cell, in ABBA order per MTP setting (baseline, PR, PR, baseline with MTP off;
    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.
  • Reproduction. Our client sends the load above as streaming OpenAI-compatible chat
    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.
sessions 1 2 4 8
baseline, MTP off 98.4 (98.3 / 98.4) 87.5 (87.6 / 87.3) 93.0 (93.2 / 92.7) 89.4 (89.9 / 88.9)
this PR, MTP off 98.2 (98.0 / 98.4) 134.5 (134.7 / 134.2) +54% 163.4 (163.4 / 163.4) +76% 191.9 (191.9 / 191.9) +115%
baseline, Lightning MTP on 123.8 (123.1 / 124.4) 77.0 (77.8 / 76.1) 87.7 (87.3 / 88.0) 83.7 (86.2 / 81.2)
this PR, Lightning MTP on 123.7 (122.7 / 124.7) 111.5 (110.6 / 112.3) +45% 142.1 (145.0 / 139.1) +62% 157.3 (158.4 / 156.2) +88%

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:

2K prompt baseline this PR
MTP off, 1 session 107.3 (101.7 / 112.8) 113.2 (112.6 / 113.7)
MTP off, 8 sessions 296.3 (300.0 / 292.6) 284.4 (287.7 / 281.0)
MTP on, 1 session 131.6 (131.2 / 132.0) 131.7 (131.3 / 132.1)
MTP on, 8 sessions 241.5 (248.8 / 234.1) 220.8 (217.8 / 223.8)

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=0
isolates 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:

rows decode step: dense + row banks + gathered arm 4-row verify: dense + gathered
2 15.4 ms 7.2 5.1 30.5 12.5
8 64.5 ms 24.6 12.2 119.2 35.6
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,gather

Changes

1. perf(qwen4_exp): keep per-row QSA pooled banks across batched steps. BatchQSAKVCache
keeps 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_ids stay plain-attribute-like properties; assigning either from
    outside (state, merge, cache restore, fallbacks) drops the bank, while append, rollback,
    filter, extend and trim write the backing fields and keep it;
  • trim clamps each row's watermark on the host (like _QSAIndexerCache._trim_indexer);
    finalize() clamps by the right padding prepare() announced (the rejected tail of a vector
    rollback, or the padding of a right-padded prompt appended in between) before the roll;
  • filter/extend carry it with their rows; nbytes counts it; the indexer is held weakly;
  • an index-key dtype change keeps the fresh-cache path.

Masks, outputs and cache state are bit-identical to the fresh-cache path.
OMLX_QWEN4_QSA_BATCH_ROW_BANKS=0 restores it.

2. perf(qwen4_exp): attend batched decode/verify rows over their QSA selection. Batched decode
steps 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_selection scores every row's bank
in FP32 and keeps each query's top block_topk causal blocks (all of them below the crossover) plus
its incomplete tail; one gather pulls those ≤ token_budget + ratio − 1 K/V rows per query out of the
padded 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=0 keeps 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_decode marker, or
the 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 state array_equal to the
    fresh-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 the
    dense 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.
  • Wide suite on this head: CPU-only run (Linux, mlx[cpu] 0.32.3) of every tests/ file matching
    qwen4/qsa/mtp/scheduler/cache/batch: 2717 passed on main, 2734 on this head (the 17 new
    tests), 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.
  • Metal (M5 Ultra, macOS 27.0, mlx 0.32.3), full suite without slow/integration, same interpreter:
    main cc1fdc9 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 PR
    touches no cluster code.
  • Served, on this head with upstream defaults: temperature-0 identity (cold vs warm) is
    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_topk blocks score above zero — one argpartition over the batch
may 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; the
batch layout is shared by all layers, so it could be read once per forward. Left for a follow-up.

Related

Earlier stacked build (for comparison)

main 3a400dd + #3963/#4030 + an earlier revision of these commits; one run per cell. #4030's
capacity ladder removed the per-step concatenation of the raw-key bank; that probably explains the
higher 8-session cells there (not measured separately).

sessions 1 2 4 8
baseline, MTP off 94.0 81.1 93.8 93.3
this PR, MTP off 93.5 124.1 161.3 228.3
baseline, Lightning MTP on 119.4 77.3 78.8 84.7
this PR, Lightning MTP on 115.5 107.1 123.2 150.9

🤖 Generated with Claude Code

@AureliusClaw
AureliusClaw marked this pull request as ready for review October 1, 2026 07:22
pierre427 added a commit to pierre427/mlx2 that referenced this pull request Oct 3, 2026
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>
AureliusClaw and others added 4 commits October 8, 2026 23:42
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>
@yeeeeff

yeeeeff commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Tested head 2f5b826a standalone on an M3 Ultra 256 GB (g15d), macOS 26.6.2, mlx 0.32.3 as pinned.

Kernel-level (bench_qwen4_qsa_batched_decode.py --bits 4 --batch 1,2,4,8), dense→gather step time: 32.9→8.0 ms (B=2), 64.3→11.8 ms (B=4), 124.9→18.7 ms (B=8) — 4.1x/5.5x/6.7x; B=1 unchanged. With --verify 4 --rollback: 60.1→22.7, 116.1→41.8, 235.5→74.2 ms (2.7x/2.8x/3.2x); rollback is arm-independent as expected. pytest tests/test_qwen4_qsa_batch_gather.py tests/test_qwen4_qsa_batch_row_banks.py → 17 passed.

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 max_concurrent_requests=8, so the batch scaling is exactly the gap we care about. +1 from a happy M3 Ultra user.

@AureliusClaw

Copy link
Copy Markdown
Contributor Author

Re-measured this head (2f5b826) against plain main on the M5 Ultra and replaced the tables in the description. One build, baseline via the two switches, ABBA with two runs per cell, upstream defaults.

Steady aggregate tok/s at 100K context, 2 / 4 / 8 sessions:

  • MTP off: 87.5 / 93.0 / 89.4 → 134.5 / 163.4 / 191.9 (+54% / +76% / +115%)
  • MTP on: 77.0 / 87.7 / 83.7 → 111.5 / 142.1 / 157.3 (+45% / +62% / +88%)

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

@yeeeeff

yeeeeff commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

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: OMLX_QWEN4_QSA_BATCH_ROW_BANKS=0 drops just that arm and keeps the long-context gains.

Mergeability heads-up: the PR reads dirty against main right now. Merging 2f5b826 into current main (370d944) conflicts only in docs/TESTING.md — both sides inserted a new section at the same spot (your "Batched Qwen4 QSA decode and verify tests" vs upstream's "Structured output Unicode tests"); keeping both resolves it, and all six code files merge clean. We rebased it locally with that doc hunk resolved and ran your 17 tests plus the scheduler / chunked-prefill suite: 251 passed; 8-way codeword fan-out 8/8 with MTP on; temp-0 identity holds.

@AureliusClaw

Copy link
Copy Markdown
Contributor Author

Metal suite on this head is done (M5 Ultra, mlx 0.32.3, everything except slow/integration, same interpreter for both):

  • main cc1fdc9: 17222 passed, 659 skipped
  • this head: 17238 passed, 1 failed, 659 skipped

The 17 new tests account for the difference, and all 17 pass on Metal. The one failure was test_cluster_cli.py::test_cluster_pipeline_smoke_json_is_runnable with [ring] Couldn't bind socket (error: 48), a port already in use from the run before it. It passed 3/3 on rerun, and this PR touches no cluster code. The description is updated.

🤖 Generated with Claude Code

@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.

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.

@jundot
jundot merged commit 5ec8ef3 into jundot:main Oct 9, 2026
jundot added a commit that referenced this pull request Oct 9, 2026
- 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.
yoyo930021 added a commit to yoyo930021/omlx that referenced this pull request Oct 11, 2026
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>
jundot pushed a commit that referenced this pull request Oct 19, 2026
…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>
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