Skip to content

perf: Flash Next prefill path on the grid, 1.4-2.5x faster prompts, still exact - #29

Closed
quigles1977 wants to merge 1 commit into
ashhart:mainfrom
quigles1977:flash-next-prefill
Closed

quigles1977 wants to merge 1 commit into
ashhart:mainfrom
quigles1977:flash-next-prefill

Conversation

@quigles1977

Copy link
Copy Markdown
Contributor

0.3.4.1 prefills Flash Next prompts through MLX's forward on the 2,048-token grid. It's exact across resumes, but
MLX's forward attends over every key, so prompts slow down as the context grows, and so do follow-up turns. A
follow-up turn prefills again from the last grid point. This PR adds a prefill path for prompt chunks of more than
16 rows. It runs on the same grid with the same exactness, and TF_FLASH_PREFILL=0 goes back to MLX's forward.

Measured on an M3 Ultra (256 GB, MLX 0.32.2) with the 4-bit MTP conversion, through the server at
--context 153600 --prompt-cache-gib 24. The follow-up is a turn of about 440 new tokens on the cached prefix,
which prefills 1.8k–2.2k tokens again from the grid point.

Prompt 0.3.4.1 cold TTFT This PR cold TTFT 0.3.4.1 follow-up This PR follow-up
30k 43.9 s (684 tok/s) 31.7 s (948) 3.08 s 1.95 s
100k 215.1 s (465) 105.8 s (945) 7.97 s 3.17 s
145k 386.7 s (375) 157.3 s (922) 10.39 s 3.32 s

Peak memory stays near the weights and caches, as 0.3.4.1 intends. In process at 32k and 100k, the prefill path
peaks at 113 / 115 GiB, against 110 / 113 GiB for MLX's forward.

What changed

  • Sparse attention in prompt chunks (SparseAttention._sparse_rows). A chunk past the indexer's budget uses
    the decode's own block selection (index_select: fp32 scores, radix top 512, ties to the lower block). A new
    grouped-query kernel, prefill.attention_rows_gqa, reads only each row's selected blocks and tail:

    • one threadgroup per KV head, row and quarter of the row's keys;
    • the 12 query heads of a KV head share each 16-key tile in threadgroup memory;
    • the quarters merge in order, as in the decode kernel.
  • Hyper-connections through the fused decode's kernels (prefill_hc.py), with MLX's matmuls between them. The
    n-gram rows come from the decode's lookup tables, bit-identical.

  • MLX's own 4-bit kernels with prefill tiles (prefill_mm.py, compiled at runtime from the headers MLX ships),
    bit-identical to MLX where they run:

    • qmm_t_impl with 64×64 or 64×32 tiles;
    • affine_gather_qmm_rhs with its alignment as template arguments (2–7% faster).

    They step aside, leaving the matmul to MLX:

    • where MLX splits K;
    • on GPUs with the M5's tensor units;
    • if they fail a once-per-process check against MLX's bits.
  • DeltaNet's four in-projections go through the fused decode's stacked matrix as one matmul.

  • The MoE sorts its rows by expert and sums the sorted outputs without unsorting them.

  • Slices of 2 layers are queued ahead of the GPU (prefill_hc.QUEUE_LAYERS). This mirrors 0.3.4.1's queue
    for MLX's forward, and the bits are the same however the graph is sliced (checked on the real model: hidden
    states and all 121 cache arrays).

  • Prefix-snapshot keys name the forward that prefilled them (FlashNext.prefill_key, via a prefill_key hook in
    families.kernel_version), so a snapshot from the other forward is never resumed.

  • Docs:

    • a Prefill section in the Flash Next recipe;
    • the recipe book's "A known limit" rewritten as "Resumed prompts" (since 0.3.4.1, resumed prompts are exact);
    • the README's link to it.

Exactness

Resumed equals fresh. I sent three two-turn conversations: 9k, 30k and 61k tokens of code, thinking on,
seeded sampling, 900-token replies. Each turn 2 resumed from turn 1's cache was compared with the same turn 2 sent
to a restarted server with nothing cached, including no saved session snapshots.

Result
This PR's prefill path on the grid 3 of 3 byte-identical
The same path prefilled anywhere (control) 0 of 3

Quality. The prefill path rounds differently from MLX's forward. Attention sums keys in another order, and
the hyper-connections use the fused decode's arithmetic. So the check is quality against MLX's own rounding
noise (its 1,024-token chunks instead of 2,048). The measure is teacher-forced NLL and top-1 accuracy on the next
1,024 tokens of real text:

Context MLX's forward Its 1,024-token chunks (noise) Prefill path
8k 1.8653 / 53.6% 1.8660 / 54.6% 1.8713 / 54.3%
32k 0.7838 / 78.2% 0.7839 / 78.0% 0.7817 / 78.5%
100k 0.5513 / 86.1% 0.5499 / 86.1% 0.5453 / 85.8%

Decoding is unchanged. Drafted replies were byte-identical to "draft": false at 40k, both greedy and seeded.
Without drafts, prose and code decode at 89.1 / 88.8 tok/s, against 89.0 / 88.7 on 0.3.4.1.

Validation

  • tests/test_qwen4_exp_prefill.py has 19 GPU tests:
    • each kernel against MLX (bit for bit) or the reference module;
    • the index selection against the reference's fp32 scores;
    • the fall-back paths (M5 tensor units, a failed self-check, a kernel that doesn't build);
    • snapshot keys;
    • a 4-layer model end to end: the prefill path and the bf16 reference must land equally close to an fp32
      forward. It is mutation-checked: dropping the PLE term, or offsetting the indexer's RoPE, fails it.
  • Full suite: 322 passed, 69 skipped (CUDA), on MLX 0.32.2 and on 0.31.2 (the oldest allowed).
  • Server checks with the prefill path:
    • a passphrase found at 50% of a 100k prompt and at 20% and 80% of 145k ones;
    • a valid edit_file tool call on a 25k-token prompt;
    • a 5k-character file rewritten byte for byte after 31k and 61k tokens of other code.

Not measured, and possible next steps

  • Only the M3 Ultra was measured. On an M5, the matmuls stay MLX's, while the attention and hyper-connection
    kernels still apply; it's worth a run on the M5 Max.
  • A 4,096-token grid for Flash Next would be a little faster. On 0.3.4 with 4,096-token chunks, this path ran
    1,040–1,073 tok/s cold, and follow-ups at 100k–145k took 2.4–2.6 s. The 2,048 grid is kept here to match the
    engine.
  • The CUDA engine is untouched.

🤖 Generated with Claude Code

…till exact

0.3.4.1 prefills Flash Next prompts through MLX's forward on the 2,048-token grid. This adds a prefill path for
prompt chunks of more than 16 rows on the same grid (TF_FLASH_PREFILL=0: MLX's forward):

- Sparse attention through the decode's block selection and a grouped-query attention kernel
  (prefill.attention_rows_gqa) that reads only each row's selected blocks and tail; MLX's forward attends over
  every key, so its cost grows with the context.
- Hyper-connections through the fused decode's kernels (prefill_hc.py), with MLX's matmuls between them; the
  n-gram rows through the decode's lookup tables.
- MLX's own 4-bit kernels with prefill tiles (prefill_mm.py): the same bits, and they step aside where MLX splits
  K, on GPUs with the M5's tensor units, and if a once-a-process check against MLX fails. DeltaNet's
  in-projections as one stacked matmul; the MoE sums its expert-sorted outputs without unsorting them.
- Slices of 2 layers queued ahead of the GPU, so peak memory stays near the weights and caches (113-115 GiB).
- Prefix-snapshot keys name the forward that prefilled them (FlashNext.prefill_key).

M3 Ultra, server at --context 153600, cold time to first token at 30k / 100k / 145k 43.9 / 215.1 / 386.7 s ->
31.7 / 105.8 / 157.3 s; follow-up turns 3.08 / 7.97 / 10.39 s -> 1.95 / 3.17 / 3.32 s. Resumed conversations
stay byte-identical to the same conversation sent fresh (3 of 3 at 9k, 30k and 61k tokens). Next-1,024-token
NLL and top-1 stay within MLX's forward's rounding noise at 8k, 32k and 100k; decode is unchanged and drafted
replies stay byte-identical to serial. Docs: the recipe's Prefill section, and the recipe book's stale "A known
limit" rewritten as "Resumed prompts".

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@ivanfioravanti

Copy link
Copy Markdown
Contributor

It works great! I test it combined with PR #30
Screenshot 2026-09-27 at 14 04 14

@ashhart ashhart added the enhancement New feature or request label Sep 27, 2026
@ashhart

ashhart commented Sep 27, 2026

Copy link
Copy Markdown
Owner

Thanks @quigles1977 for the Flash Next prefill path. It's in final testing for 0.3.5, which ships tonight, as a commit authored by you, combined with 0.3.5's sparse prompt attention. This PR closes when the release is published.

ashhart pushed a commit that referenced this pull request Sep 27, 2026
0.3.4.1 prefills Flash Next prompts through MLX's forward on the 2,048-token grid. This adds a prefill path for
prompt chunks of more than 16 rows on the same grid (TF_FLASH_PREFILL=0: MLX's forward):

- Sparse attention through the decode's block selection and a grouped-query attention kernel
  (prefill.attention_rows_gqa) that reads only each row's selected blocks and tail.
- Hyper-connections through the fused decode's kernels (prefill_hc.py), with MLX's matmuls between them; the
  n-gram rows through the decode's lookup tables.
- MLX's own 4-bit kernels with prefill tiles (prefill_mm.py): the same bits, and they step aside where MLX splits
  K, on GPUs with the M5's tensor units, and if a once-a-process check against MLX fails. DeltaNet's
  in-projections as one stacked matmul; the MoE sums its expert-sorted outputs without unsorting them.
- Slices of 2 layers queued ahead of the GPU, so peak memory stays near the weights and caches.
- Prefix-snapshot keys name the forward that prefilled them (FlashNext.prefill_key).

M3 Ultra, server at --context 153600, cold time to first token at 30k / 100k / 145k 43.9 / 215.1 / 386.7 s ->
31.7 / 105.8 / 157.3 s; follow-up turns 3.08 / 7.97 / 10.39 s -> 1.95 / 3.17 / 3.32 s. Resumed conversations
stay byte-identical to the same conversation sent fresh (3 of 3 at 9k, 30k and 61k tokens).

From quigles1977's pull request #29, written against 0.3.4.1 and carried onto release-0.3.5 as submitted.
0.3.5 split the Flash Next kernels into modules, so the PR's calls into kernels.py now name base, hc,
attention and embed. Where 0.3.5 changed the same lines, both sides stay: the PR's prompt attention runs before
0.3.5's selection-kernel path, and the n-gram lookup tries the decode's tables before 0.3.5's memory-mapped
host tables. The README keeps 0.3.5's wording. The commits after this one reconcile the two prompt attentions
and carry the maintainers' corrections.
ashhart added a commit that referenced this pull request Sep 27, 2026
…1 before M5

- #29's prefill path combined with the sparse prompt attention: cold prefill faster than 0.3.4.1 from 1k to 128k,
  and the pause before the first decoded token after a long prompt is gone.
- Before M5, Flash Next's projections and hyper-connections use 0.3.4.1's per-row kernels at every row count, so
  single-stream decode matches 0.3.4.1 and concurrent streams still equal their solo runs.

Fixes #27
@ashhart

ashhart commented Sep 27, 2026

Copy link
Copy Markdown
Owner

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants