Skip to content

Add the Qwen3.8-Flash-Next MTP drafter - #819

Open
jeanmatthieu wants to merge 4 commits into
ml-explore:mainfrom
jeanmatthieu:feat/qwen4-exp-mtp
Open

jeanmatthieu wants to merge 4 commits into
ml-explore:mainfrom
jeanmatthieu:feat/qwen4-exp-mtp

Conversation

@jeanmatthieu

Copy link
Copy Markdown
Contributor

Proposed changes

Stacked on #818 (Qwen3.8-Flash-Next). Only the last commit, "Add the
Qwen3.8-Flash-Next MTP drafter", is new here; #818's commits drop out
when it merges.

This adds MTP speculative decoding for Qwen3.8-Flash-Next (qwen4_exp)
with the published head, mlx-community/Qwen3.8-Flash-Next-4bit-mtp.
Neither mlx-lm nor transformers implements the head, so it follows the
vLLM and SGLang Qwen4Exp MTP models. It drafts one token per round
(block size 2), greedy only, like Qwen3.5's head, and resumes across
ChatSession turns.

Release builds, greedy, OptiQ-2bit target. Short prompts, 256 tokens,
median of 3 runs:

Machine Prompt Plain MTP Speedup Acceptance
M3 Ultra prose 38.1 tok/s 49.2 tok/s 1.29x 75%
M3 Ultra code 38.0 tok/s 54.3 tok/s 1.43x 94%
M5 Ultra prose 51.6 tok/s 67.0 tok/s 1.30x 81%
M5 Ultra code 51.7 tok/s 71.2 tok/s 1.38x 93%

Long prompts on the M5 Ultra, 128 tokens:

Prompt tokens Plain prefill MTP prefill Plain peak MTP peak Plain MTP
1,986 1.4 s 1.3 s 77.2 GiB 77.2 GiB 46.5 tok/s 60.9 tok/s
7,860 5.8 s 5.6 s 77.4 GiB 77.5 GiB 35.9 tok/s 44.9 tok/s
31,623 29.5 s 30.6 s 78.6 GiB 79.2 GiB 21.1 tok/s 27.6 tok/s

On the bf16 checkpoint, speculative greedy is not bit for bit the same
as plain greedy. A two-token verify pass rounds its logits apart from a
one-token step, so a near tie can go the other way. Over 256 tokens of
the short prompts, two positions differed on each machine, all ties
with logit gaps of 0.125 or less. On long prompts the gaps grow (up to
0.875 at a top logit of about 17), but plain greedy with a 256-token
prefill chunk instead of 512 differs from itself by as much, so this is
the model's ordinary bf16 drift. On the tiny float32 test model the
tokens match exactly.

Shared code this touches:

  • MambaCache can hold and checkpoint any number of slots
    (init(size:leftPadding:), N-slot saveSpeculativeCheckpoint).
    Qwen4Exp's PLE layers checkpoint 4 slots.
  • rewindSpeculativePromptCache checks maxTrimCount instead of
    offset. A CacheList reports no offset of its own, so the old
    check refused every qwen4_exp attention layer. For plain KV caches
    the two agree; a wrapped RotatingKVCache now returns 0 instead of
    reaching the preconditionFailure.
  • finalizeShiftedMTPDrafterState compares leaf offsets
    (mtpDrafterCacheIsAligned), since the head's cache is a CacheList.
    Qwen3.5's flat caches behave as before.
  • New MTPChunkedPrefillModel. The iterator used to run a drafter's
    prompt in one forward. For Qwen4Exp that made the QSA indexer's
    scores grow with the square of the prompt and ran the LM head on every
    prompt row: at 32k tokens the peak was 150.5 GiB, against 79.2 GiB
    now (M3 Ultra). On M5 GPUs, one forward of 1024 or more queries with
    head dim 256 also fails to build MLX's d-split attention kernel. A
    conforming target keeps the caller's prefill chunking; the default
    LLMModel prepare joins the chunks' hidden rows and runs the last
    token alone, and only for conforming targets. Only Qwen4ExpModel
    conforms here. Drafter heads chunk their own prompt pass with
    mtpForwardInChunks.
  • Each MTP round now evaluates the target and drafter caches and the
    next seed with asyncEval, as TokenIterator does. MTP decode on the
    M5 Ultra: Qwen3.8-Flash-Next +4%, Qwen3.8-27B unchanged within noise.
  • A stream that falls back to plain decoding drops the drafter state,
    which held the prompt's hidden rows.

Not in this PR:

  • Qwen3.5 MTP still prefills in one forward, so on M5 GPUs it crashes
    at about 2k prompt tokens. The follow-up PR, stacked on this one,
    fixes that.
  • Compiled decode and verify, and drafting more than one token per
    round.

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

2 participants