Skip to content

[Metal] Prefill-row invariance scope: prompt chunks round like the reference rows (opt-in, per thread) - #71

Draft
jonathan308 wants to merge 1 commit into
mainfrom
perf/prefill-row-invariance
Draft

jonathan308 wants to merge 1 commit into
mainfrom
perf/prefill-row-invariance

Conversation

@jonathan308

@jonathan308 jonathan308 commented Nov 21, 2026 •

Copy link
Copy Markdown

Draft, not for merge yet. Part of a stack of three: this PR, then Layr-Labs/mlx-swift#78 (submodule bump and Swift scope), then Layr-Labs/mlx-swift-lm#495 (the engine builds each prompt chunk inside the scope).

What changes

A per-thread "prefill rows" scope. ThreadPrefillRows in C++, mlx_metal_set_thread_prefill_rows(rows, &previous) and mlx_metal_thread_prefill_rows() in C (next to mlx_metal_set_thread_qmm_steel_tile in command_buffer_limits.h).

  • quantized_matmul and fast::scaled_dot_product_attention read the scope when the op is built and store it in the primitive (QuantizedMatmul::prefill_rows(), ScaledDotProductAttention::prefill_rows()). The route follows the thread that built the graph, not the thread that evaluates it. One evaluation can then hold prompt-chunk products built inside the scope and decode products built outside it.
  • is_equivalent compares the value, so products from inside and outside a scope are never merged. The vjp and jvp of a quantized matmul build their products with the same value. The compile cache keys each trace by the thread's value, so a function traced in a scope is traced again outside it. state() is unchanged, so an exported graph imports with 0.
  • Quantized matmul, in a scope: a transposed, non-batched x @ w.T with two or more rows goes to qmm_splitk, with the K split counted for the reference rows instead of M. It skips the NAX split-K route, because that route picks its split from M. With 4,096 reference rows, every product with N >= 128 gets one K partition, the split that a 4,096-row chunk gets today.
  • Attention, in a scope: head-dim 256 causal or masked attention takes the fused NAX kernel from 16 queries instead of 1,024 (use_fallback). Nothing changes on GPUs without neural accelerators.

The idea is the batch-invariant kernels of Thinking Machines (2025): fix each row's reduction order so that it does not depend on how many rows share the call. Here it is applied to the chunks of a chunked prompt.

Bits

  • Outside a scope, and with 0 rows: every op takes the route it took before. The new test checks this bit for bit for ops built outside a scope, including ops evaluated while a scope is active.
  • Inside a scope: each row of a product with two or more rows has the bits of the same row in a 4,096-row product. Head-dim 256 attention on NAX takes one kernel for every chunk of 16 queries or more.
  • Not covered: one-row products keep qmv. Attention with 8 or fewer queries keeps the vector kernels. On NAX, chunks of 9-15 queries keep the composed path. Rows up to 32 on NAX take qmm_nax with a 32-row tile, and this PR does not test whether that tile rounds like the 64-row one.

Tests (this branch, M3 Ultra, 2026-11-21)

tests/prefill_rows_tests.cpp:

  • An op built outside a scope keeps its bits and its primitive (prefill_rows() == 0, is_equivalent to an op that never saw a scope), also when it is evaluated inside a scope. An op built inside a scope keeps its route after the scope ends.
  • Short products in a scope equal the same rows of a 4,096-row product. Shapes are the Qwen 3.5 9B projections (N x K = 1024 x 4096, 4096 x 12288, 12288 x 4096; 4-bit affine, group 64), in bfloat16 and float16, at 20 row counts from 2 to 2,048. Outside the scope, 13, 7 and 3 of those row counts gave other bits on this GPU, the dependence the scope removes.
  • A compiled function is traced again inside a scope and matches direct ops both inside and outside.
  • Head-dim 256 attention: on NAX, a 128-query chunk in a scope has the bits of the same queries in a 2,048-query call. Without NAX the scope changes nothing.

Results (Release build, -DMLX_METAL_JIT=OFF):

  • tests --test-case="*prefill rows*": 4 of 4 cases, 134 of 134 assertions passed.
  • Full tests binary: 327 of 327 cases, 10,746 assertions passed, 0 skipped.
  • ctest (346 entries): 345 passed. test array shared buffer failed: it prints SUCCESS and then segfaults at process exit, only under ctest. The same ctest entry fails the same way on an older fork build without this change (c6bf6d64), so this change did not cause it.
  • scripts/check_forkdiff.py: 150 of 150 changed files described. Merge-base check not run locally (no upstream remote).
  • Not run here: the M5 GPUs (the NAX branches of the attention test and of the product route), CPU-only and CUDA builds, and the Python tests.

Measured evidence (research build, not this branch)

From the local research build (patches with process-wide switches, same routes; FINDINGS 22.53-22.59, 2026-11-20):

  • Qwen 3.5 9B, M3 Ultra: with short chunks routed like long ones, every partition of a 6,000- or 2,779-token prompt whose cuts are on multiples of 128 gave the same digest. That digest equals today's 4,096-row stripe digest. Today the same prompts give 3 (6,000 tokens) and 4 (2,779 tokens) different digests across partitions. Cuts off the 128 grid still differ.
  • M5 Max: same result once head-dim 256 attention is fused from 16 queries, and the digest is today's stripe digest.
  • Qwen 3.8 27B, M3 Ultra: all four short-chunk partitions equal the 4,096-chunk digest, and that digest is unchanged from today. Gemma 4 26B QAT: improved but not exact, so it is not qualified.
  • Cost, time to first token, medians: unchanged on today's 4,096 stripes (M3 Ultra 4,970 vs 4,972 ms). 0.4-0.6 % on all-256-token partitions (M3 Ultra). No measurable cost on the M5 Max.
  • Prefix-cache reuse proof (recorded Qwen 3.5 9B conversations: 12 on the M5 Max, 5 on the M3 Ultra): 268 of 268 follow-ups and 17 of 17 first turns equal the cold run across both GPUs, against 69 of 268 and 1 of 17 today. The median first-token speedup of reuse is unchanged: 7.8x on the M3 Ultra, 11.1x on the M5 Max.

Measurements on builds from this stack's branches (M3 Ultra and M5 Max, 2026-11-21) are on Layr-Labs/mlx-swift-lm#495: the same bits as the research build, today's bits with the switch off, and no measurable cost on today's stripes.

Owner decisions open

  1. Default-on per family. The library gate is off by default, and this PR changes nothing until a caller opens a scope.
  2. Short-prompt bits. Inside a scope, prompts or prompt tails of 256 rows or fewer (M3 Ultra), or under 1,024 queries / up to 512 rows (M5), move from today's bits to the long-chunk rounding.
  3. M5 attention route. This PR fuses head-dim 256 attention from 16 queries in a scope, which keeps today's long-chunk bits. The alternative is composed attention everywhere, which also gives one set of bits across partitions, but different bits from today.

AI usage

  • AI usage disclosure: Claude Code (Claude Opus 5.5) wrote the code, the tests and this description, and ran the tests, at the request of the repository's maintainer.

🤖 Generated with Claude Code

A thread-local scope (`ThreadPrefillRows`, C: `mlx_metal_set_thread_prefill_rows`)
names a number of reference rows. `quantized_matmul` and
`fast::scaled_dot_product_attention` read it when the op is built and keep
it in the primitive, so the route follows the thread that built the graph.
`is_equivalent` compares it, autograd keeps it, and the compile cache keeps
traces made inside and outside a scope apart. `state()` is unchanged.

Inside a scope, a transposed non-batched quantized `x @ w.T` of two or more
rows takes `qmm_splitk` with the K split that the reference rows would get
and skips the NAX split-K route, so a row's bits do not depend on how many
rows share the call. Head-dim 256 causal or masked attention takes the fused
NAX kernel from 16 queries instead of 1024. This applies the batch-invariant
kernel idea (Thinking Machines, 2025) to prompt chunks.

Ops built outside a scope, or with 0 rows, take the routes they took before.
One-row products keep `qmv`; attention of 8 or fewer queries keeps the
vector kernels.

tests/prefill_rows_tests.cpp checks that ops built outside a scope keep
their bits, that short products in a scope equal the same rows of a
4096-row product, that compiled functions trace again in a scope, and the
head-dim 256 attention route.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
GumbiiDigital added a commit that referenced this pull request Dec 4, 2026
…AX path

Address jonathan308's review comments on #73:

- Default MLX_NAX_KSPLIT to 0 (opt-in) in mlx/utils.h and update
  docs/src/usage/environment_variables.rst and fork.yaml so M5 output bits
  at 8..16 affine rows stay identical to production unless explicitly opted in.
- Factor the K-split gate into use_qmm_nax_ksplit(bool allow_ksplit = true)
  and thread an optional allow_ksplit parameter through qmm() -> qmm_nax(),
  ready for #71 to pass allow_ksplit = (ref_rows <= 0) when
  qmm_splitk falls through to qmm at split_k <= 1.
- Log GPU architecture and metal::is_nax_available() in
  tests/nax_quantized_kernel_tests.cpp, assert bitwise M<=16 vs M=17 parity
  when K-split is off (default) and bitwise K-split dispatch on NAX when
  MLX_NAX_KSPLIT=1, replace ctest nax_ksplit_disabled with nax_ksplit_enabled
  (MLX_NAX_KSPLIT=1), and run it in .github/workflows/fork-tests.yml.
- Document AGENTS.md (from 56e12b0 on main) under Fork tooling in fork.yaml
  so Fork Diff Check passes after rebasing onto main.

This branch has not been deployed

No deployments
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.

1 participant