Skip to content

Prefill Qwen3.5 MTP prompts in chunks - #820

Open
jeanmatthieu wants to merge 5 commits into
ml-explore:mainfrom
jeanmatthieu:fix/qwen35-mtp-chunked-prefill
Open

jeanmatthieu wants to merge 5 commits into
ml-explore:mainfrom
jeanmatthieu:fix/qwen35-mtp-chunked-prefill

Conversation

@jeanmatthieu

@jeanmatthieu jeanmatthieu commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

Stacked on #819 (Qwen3.8-Flash-Next MTP), which adds
MTPChunkedPrefillModel and mtpForwardInChunks. Only the last
commit, "Prefill Qwen3.5 MTP prompts in chunks", is new here.

On M5 (NAX) GPUs, MLX 0.33 fails to build its d-split attention kernel
for a forward with head dim 256, a causal or array mask, and 1024 or
more queries. The JIT passes a BV template argument that
attention_nax_dsplit does not take. Qwen3.5 MTP ran the whole prompt
in one forward, through the target and then through the head, so
Qwen3.8-27B with its MTP head crashed on a 2k-token prompt:

steel_attention_nax.h:950: explicit instantiation of 'attention_nax_dsplit' does not refer to a function template

This PR keeps every Qwen3.5 MTP forward under that limit:

  • Qwen35TextModel, Qwen35Model (and so Qwen35MoEModel) and the
    Qwen3.5 VLM conform to MTPChunkedPrefillModel. Their prepare
    already gathers each chunk's hidden rows, so the iterator now keeps
    the caller's prefill chunking.
  • Both Qwen3.5 heads run the prompt, and a resumed suffix, in 512-token
    chunks.

Qwen3.8-27B-4bit with Qwen3.8-27B-MTP-4bit on an M5 Ultra, release
build, greedy, 128 tokens:

Prompt tokens Plain MTP Speedup
1,986 49.1 tok/s 64.8 tok/s 1.32x
7,860 48.4 tok/s 61.9 tok/s 1.28x

Greedy tokens, prefill time and peak memory match plain decoding.
Before this change, MTP crashed at both lengths. I have not run the
Qwen3.5 VLM with a real checkpoint; its path is covered by unit tests.

The MLX fix is a one-line change in jit_kernels.cpp (leave out bv
for the d-split template). I checked it against a patched local MLX:
the kernel then runs at 1024 to 4096 queries and matches a float32
reference. Until it ships in an mlx-swift release, any head-dim-256
model still crashes on M5 when the caller sets a prefill step size of
1024 or more; the default is 512.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

AI usage

  • I have read this PR description in full and approve it as my own, and it
    accurately describes the code changes.
  • AI usage disclosure: Claude Opus 5.5 was used to guide coding session

Port mlx-lm's qwen4_exp model
(ml-explore/mlx-lm@c4c9c76) to MLXLLM.
The port is text only: it drops the MTP head and the vision tower.

The model loads the HF, mlx-vlm, TensorFold and mlx-lm checkpoint
layouts. A checkpoint stores each n-gram table as equal row shards,
and stores the block inject apart from the mix down projection. The
port keeps one table per head and one fused projection, so
prepareCheckpoint moves each layer's per-layer quantization to the
layer that holds its rows. mlx-lm infers bits and group size from
the tensor shapes; the Swift loader reads them from the config, so
without this the OptiQ checkpoint's 4-bit, group 32 tables would
load with the default group size and fail. A merge of layers
quantized differently is refused.

The model refuses a bounded KV cache and rejects configurations the
port cannot run. It declares .xmlFunction tool calls and
QwenReasoningProtocol.tagged, as the published chat template prompts.
No hard budget transition has been measured for it.

Qwen4ExpTests compare a tiny model with values from
tools/qwen4-exp-reference.py, and cover the checkpoint layouts,
caches and right-padded batches. Qwen4ExpCheckpointTests runs the
published mlx-community/Qwen3.8-Flash-Next-OptiQ-2bit checkpoint
against tools/qwen4-exp-checkpoint-reference.py. They are skipped
unless MLX_QWEN4_EXP_CHECKPOINT and MLX_QWEN4_EXP_REFERENCE_FILE are
set, and need about 80 GB. On that checkpoint Swift gives the same
greedy answer as mlx-lm and the same chat template tokens. With
mlx-lm on the gated delta kernel that MLXLMCommon picks, the two
match bit for bit through layer 33. After that, bf16 rounding in
shared kernels makes them drift, so the tests compare tokens and
not logits.

Claude Opus 5.5 was used to guide coding session
In a right-padded batch, the Qwen3Next and Qwen3.5 (LLM and VLM)
GatedDeltaNets kept the last conv inputs of the whole padded
sequence. A short row stored the masked padding as its conv state,
and its next decode step started from zeros.

When the cache has lengths, keep the conv inputs that end at each
row's last real token, as mlx-lm's qwen3_next and qwen3_5 do with
cache.lengths. Without lengths the state is unchanged. The fused and
compiled decode paths never see lengths: a cache with lengths builds
an SSM mask, and both paths need none. The MTP checkpoint path is
unchanged, because speculative verify steps have no lengths.

The new tests run a right-padded batch and compare each row with
the row run alone. They fail without the fix.

Claude Opus 5.5 was used to guide coding session
Once the context passes indexer_budget, the indexer pooled every past
key block again at every step, in each of the 12 attention layers,
though a complete block never changes. Qwen4ExpIndexerKeyCache now
keeps the pooled blocks next to the raw keys, and the indexer pools
only the blocks completed since the last step. Trim drops the blocks
that lost a token, and copy keeps the pooled blocks. A restored prompt
cache rebuilds them from the raw keys, so the saved format is
unchanged. Without a cache the indexer pools every block, as before.

Per block, the mean, k_layernorm and RoPE do not depend on other
blocks, so the masks and logits match pooling every block, bit for
bit. testPooledBlocksMatchPoolingEveryStep checks this at each decode
step past the budget, after a trim that rewrites a block, and after a
copy. It fails if trim keeps the stale block or if a new block gets
the wrong RoPE position.

At the released dimensions, one decode step of the indexer took
0.36 ms at 4k tokens and 1.48 ms at 256k when it pooled every block,
and 0.32 ms and 0.56 ms with the pooled blocks cached, measured in
Python on the same MLX core.

Claude Opus 5.5 was used to guide coding session
Add Qwen4ExpMTPDraftModel, the qwen4_exp multi-token prediction
head, after the vLLM and SGLang Qwen4Exp MTP models. Neither mlx-lm
nor transformers implements it. Each of the target's four
hyper-connection streams goes through a shared fc_hidden, and
fc_embedding of the next token is added to every stream. One full
attention layer with the QSA indexer and MoE follows, then the
head's own mixer and the target's LM head. Like Qwen3.5's head, it
drafts one token per round, keeps its own cache, and resumes at the
next ChatSession turn. Qwen4ExpMTPRegistration registers it for
MTPDrafterModelFactory under the checkpoint's qwen4_exp model type.

The published head stores its norms as w for a 1 + w scale, so
loading adds one, unless the file's metadata declares the scale
convention. Loading reads only the mtp tensors, even from a full
checkpoint, and merges each block inject into its mix down
projection, as the target does.

On request, the target now returns its streams before the final
mixer. Its linear layers use a MambaCache, so a rejected draft
rewinds to a checkpoint taken after the verify pass's first token.
In a PLE layer the checkpoint also holds the PLE conv state and
the n-gram context. MambaCache can now hold and checkpoint any
number of slots. The indexer cache keeps raw keys, so an ordinary
trim rewinds it.

A CacheList reports no offset of its own, and every qwen4_exp
attention layer, in the target and in the head, is one. So
rewindSpeculativePromptCache now checks maxTrimCount instead of
offset, and the shared drafter finalize compares the offsets of the
cache's leaves. For plain KV caches nothing changes; rotating and
rewindable caches report the tighter bound that an exact rewind
needs.

The MTP iterator ran a drafter's prompt in one forward, to get one
hidden row per token. Past 2048 keys the QSA indexer then builds
scores that grow with the square of the prompt, and the LM head ran
on every prompt row: at 32k tokens the peak rose from 79 to 151 GiB.
On an M5 Ultra a 2k-token prompt also failed to build MLX's d-split
attention kernel, which breaks at 1024 or more queries. A target that
conforms to MTPChunkedPrefillModel now keeps the caller's prefill
chunking: the default LLMModel prepare joins each chunk's hidden rows
and runs the last token alone. Qwen4ExpModel conforms, and the head
prefills in 512-token chunks too, through mtpForwardInChunks. Each
round now evaluates the target and head caches and the next seed, as
TokenIterator does, so no chain of cache writes outlives a round. A
stream that falls back to plain decoding drops the head's state.

Qwen4ExpMTPTests check that a rewound verify pass leaves every
cache slot as a run over the first token alone, and that greedy
speculative decoding of a tiny model gives plain greedy's tokens,
with both accepted and rejected drafts, and with the prompt in one
forward or in chunks. They also check that a chunked prefill
returns every hidden row, that the head prefills a long prompt in
chunks as one forward would, that it finalizes and resumes at a
turn boundary, and that the loader skips every target tensor of a
full checkpoint. The new testPublishedMTPHeadKeepsGreedyTokens test
pairs the OptiQ-2bit target with the head from
mlx-community/Qwen3.8-Flash-Next-4bit-mtp. It is skipped unless
MLX_QWEN4_EXP_CHECKPOINT and MLX_QWEN4_EXP_MTP_CHECKPOINT are set. A
two-token verify pass rounds its bf16 logits apart from a one-token
step, so a near tie can go either way: the test accepts a token that
is greedy's choice or within |top| / 64 of it. Over 96 tokens it
accepted 46 of 48 drafts, with no ties.

AI usage disclosure: Claude Opus 5.5 was used to guide coding session
On M5 (NAX) GPUs, MLX 0.33 fails to build its d-split attention
kernel when a forward has head dim 256 and 1024 or more queries:
the JIT passes a BV template argument that attention_nax_dsplit
does not take. The MTP iterator ran a Qwen3.5 prompt in one
forward, so Qwen3.8-27B with its MTP head crashed on a 2k-token
prompt.

Qwen35TextModel, Qwen35Model and the Qwen35 VLM now conform to
MTPChunkedPrefillModel. Their prepare already gathers each chunk's
hidden rows, so the iterator keeps the caller's prefill chunking.
Both Qwen3.5 heads run the prompt and a resumed suffix in 512-token
chunks, through mtpForwardInChunks.

On an M5 Ultra, Qwen3.8-27B-4bit with Qwen3.8-27B-MTP-4bit now runs
1,986 and 7,860-token prompts. MTP decodes at 64.8 and 61.9 tok/s,
against 49.1 and 48.4 tok/s plain, with the same greedy tokens and
the same prefill time and peak memory.

New tests check that both targets' chunked prefill returns the
hidden rows and last logits of one forward, and that both heads
prefill a 600-token prompt, and the text head resumes a 600-token
suffix, as one forward would.

AI usage disclosure: Claude Opus 5.5 was used to guide coding session
@aleroot

aleroot commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Nice find on the NAX kernel. I think the Qwen3.5 fix should land before #819, not on top of it:* it fixes models people already run, and it only needs MTPChunkedPrefillModel and mtpForwardInChunks.

P.S. Is there an MLX PR for the jit_kernels.cpp fix? Linking it would tell us when the cap can go.

@jeanmatthieu

jeanmatthieu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Nice find on the NAX kernel. I think the Qwen3.5 fix should land before #819, not on top of it:* it fixes models people already run, and it only needs MTPChunkedPrefillModel and mtpForwardInChunks.

👍

P.S. Is there an MLX PR for the jit_kernels.cpp fix? Linking it would tell us when the cap can go.

ml-explore/mlx#4903
and this also comes to mind wrt to performance: ml-explore/mlx#4941

@davidkoski

Copy link
Copy Markdown
Member

Once the mlx changes are in a tag, I will update mlx-swift and cut a release. Potentially we need an mlx-c release at the same time, but I will arrange that. All the mlx changes flow into mlx-swift automatically, just with a delay for tags and integration work.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants