Repository navigation
Add the Qwen3.8-Flash-Next MTP drafter - #819
Open
jeanmatthieu wants to merge 4 commits into
Open
jeanmatthieu wants to merge 4 commits into
jeanmatthieu wants to merge 4 commits into
Conversation
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
4 of 5 tasks
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
jeanmatthieu
force-pushed
the
feat/qwen4-exp-mtp
branch
from
November 21, 2026 11:55
15f8a5a to
4c9241a
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
ChatSessionturns.Release builds, greedy, OptiQ-2bit target. Short prompts, 256 tokens,
median of 3 runs:
Long prompts on the M5 Ultra, 128 tokens:
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:
MambaCachecan hold and checkpoint any number of slots(
init(size:leftPadding:), N-slotsaveSpeculativeCheckpoint).Qwen4Exp's PLE layers checkpoint 4 slots.
rewindSpeculativePromptCachechecksmaxTrimCountinstead ofoffset. ACacheListreports no offset of its own, so the oldcheck refused every qwen4_exp attention layer. For plain KV caches
the two agree; a wrapped
RotatingKVCachenow returns 0 instead ofreaching the
preconditionFailure.finalizeShiftedMTPDrafterStatecompares leaf offsets(
mtpDrafterCacheIsAligned), since the head's cache is aCacheList.Qwen3.5's flat caches behave as before.
MTPChunkedPrefillModel. The iterator used to run a drafter'sprompt 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
LLMModelpreparejoins the chunks' hidden rows and runs the lasttoken alone, and only for conforming targets. Only
Qwen4ExpModelconforms here. Drafter heads chunk their own prompt pass with
mtpForwardInChunks.next seed with
asyncEval, asTokenIteratordoes. MTP decode on theM5 Ultra: Qwen3.8-Flash-Next +4%, Qwen3.8-27B unchanged within noise.
which held the prompt's hidden rows.
Not in this PR:
at about 2k prompt tokens. The follow-up PR, stacked on this one,
fixes that.
round.
Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changesAI usage
accurately describes the code changes.