Skip to content

models: Qwen3.8-Flash-Next MTP - #28243

Draft
danielhanchen wants to merge 11 commits into
ggml-org:masterfrom
danielhanchen:qwen4exp/mtp
Draft

models: Qwen3.8-Flash-Next MTP#28243
danielhanchen wants to merge 11 commits into
ggml-org:masterfrom
danielhanchen:qwen4exp/mtp

Conversation

@danielhanchen

Copy link
Copy Markdown
Contributor

Overview

Enables 1.3 to 2x faster MTP support for Qwen3.8-Flash-Next + shared MTP modules (re-uses embed_tokens to save disk space and VRAM / RAM). Builds on top of #27836

Additional information

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: Used Claude + local models for verification and testing

@github-actions github-actions Bot added model Model specific ggml changes relating to the ggml tensor library for machine learning CUDA Related to the CUDA backend conversion labels Sep 2, 2026
Comment thread include/llama.h Outdated
Comment on lines +343 to +344
// target for a draft head that declares nextn_shared_target_tensors; must outlive this model
const struct llama_model * model_shared;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The llama_context_params already support ctx_other. Reuse that logic instead of adding this.

Comment thread ggml/src/ggml-cuda/ggml-cuda.cu Outdated
Comment on lines +2586 to +2608
// a captured graph hard-codes its shapes, so with one key per split an alternating shape
// (a speculative verify batch) resets warmup forever. O(1) on purpose: walking nodes undoes the
// point of a cuda graph. A shape this fails to separate re-captures as before, so it cannot regress.
static uint64_t ggml_cuda_graph_get_key(ggml_cgraph * cgraph) {
// unlike the previous key this dereferences nodes[0], so an empty graph is not safe here
if (cgraph->n_nodes <= 0) {
return 0;
}

uint64_t key = (uint64_t) (uintptr_t) cgraph->nodes[0];

auto mix = [&key](uint64_t v) {
key = (key ^ v) * 0x100000001b3ull;
};

mix(cgraph->n_nodes);

for (int d = 0; d < GGML_MAX_DIMS; d++) {
mix(cgraph->nodes[0]->ne[d]);
mix(cgraph->nodes[cgraph->n_nodes - 1]->ne[d]);
}

return key;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Better keep the CUDA changes for a follow-up PR.

@danielhanchen

danielhanchen commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

@ggerganov thanks will check when I wake :))

@jesdga95

jesdga95 commented Sep 2, 2026

Copy link
Copy Markdown

Works great on dual consumer GPUs (5090 + 5060 Ti, 32 GB RAM): +25-40%, acceptance 0.77

9950X, 32 GB DDR5, RTX 5090 + RTX 5060 Ti (gen5 x8/x8), Ubuntu, CUDA 13.3, PR @ 2857e51.
Target: unsloth UD-IQ4_XS (auto-fit, host experts partly in page cache). Draft: shared Q4_K_M sidecar, dn-max 2, q8 KV, 65k ctx.

config t/s
no draft 36.4
MTP, 28k mixed gen (thinking + code) 45.3 avg
MTP, code sections 48-54
MTP, prose 27-28

Acceptance 0.767 (16849/21960), mean len 2.53.

One minor issue I encountered: the fitter can't measure the shared head (borrow_shared_tensor refusal at launch), so the draft loads unbudgeted and OOMs on the fuller GPU. Workaround: --fit-target to reserve room for it.

Thanks for all of your hard work!

@llbzow

llbzow commented Sep 3, 2026

Copy link
Copy Markdown

Validation: 2× RTX A6000 48GB (PCIe, no NVLink), Windows Server 2019, CUDA 12.6 (sm_86) — both heads draft at ~0.37 acceptance, no config beats baseline

Built this PR @ 2857e5114 with @JayToltTech's LLAMA_STATE_SEQ_FLAGS_ON_DEVICE checkpoint patch cherry-picked on top (applies cleanly, one commit).

Target: unsloth/Qwen3.8-Flash-Next-UD-Q3_K_XL, -ngl 99 -fa on -ctk q8_0 -ctv q8_0 -ot per_layer_token_embd.weight=CPU -c 524288 (YaRN ×2) -t 24 -b 2048 -ub 512. No-spec baseline on identical prompts: 41–42.5 tok/s decode.

Arm 1 — shared Q4_K_M sidecar, -ngld 99 --spec-type draft-mtp --spec-draft-n-max 3: loads and drafts, but acceptance is only 0.32–0.38 (mean len ≈ 2.1), even with temp 0 / top_k 1. Decode 23–24 t/s @ temp 0.6, best greedy run 39.6 t/s — never beats baseline.

Arm 2 — same but without -ot per_layer_token_embd.weight=CPU: draft load crashes: invalid vector subscript immediately after loading draft model. So on this setup the shared-embed borrow path only works when the target's embed tensor is CPU-resident; GPU-resident embed breaks the load entirely. (Possibly related: arm 1's low acceptance could also be a symptom of the borrow path misbehaving with the UD-Q3_K_XL embed.)

Arm 3 — standalone Q8_0 grafted head (the drluoto file that gave 82–95% acceptance on #27836 @ 1d8de7c1, same target, same box): first OOM'd at 512K (draft KV cache wants 1 GiB on device 1; the 90 GB target leaves ~6–9 GiB free). Re-tested at -c 65536: loads, drafts, but acceptance is again 0.36–0.39 even greedy — same collapse as the shared head. Greedy decode 40–42 t/s ≈ baseline, temp 0.6 drops to 25–28 t/s.

Same draft file, same target, same prompts: 0.82–0.95 acceptance on #27836 vs ~0.37 on this branch — so something between 1d8de7c1 and 2857e5114 (this PR's changes or the newer post-#27941 master base) appears to regress draft-mtp acceptance on this hardware/quant combo. Happy to rerun any fix quickly; the box rebuilds in ~6 min.

Side note: draft compute buffer (2253 MiB) initially OOMs on device 1 next to the 90 GB target, recovered by retrying without pipeline parallelism — harmless here, but worth knowing for tight-VRAM multi-GPU setups.

giveen added a commit to giveen/llama-cpp-turboquant that referenced this pull request Sep 3, 2026
The CUDA graph cache keyed captured graphs by the raw memory address of
their first node (cgraph->nodes[0]). A captured graph hard-codes its
shapes, but speculative decoding constantly alternates between
different batch shapes (draft steps, verify batches, catch-up decodes)
on the same context - when a new shape happens to reuse the same first-
node address as a stale cached graph for a different shape, capture
either reuses the wrong graph or thrashes, permanently resetting
warmup instead of ever converging to steady-state replay.

Hash node count and both endpoint tensors' shapes into the key instead
(O(1) - walking all nodes would defeat the point of a CUDA graph), add
LRU eviction capped at 64 graphs so the map can't grow unbounded now
that distinct shapes get distinct entries. A shape this still fails to
separate re-captures exactly as before, so it can't regress anything.

Cherry-picked from ggml-org#28243 (open, unmerged), which
found this while working on qwen4exp MTP performance - the effect is
generic to any speculative-decoding workload on this fork, not
qwen4exp-specific, so pulling in just this piece rather than the rest
of that PR (which also reworks qwen4exp trunk/draft tensor sharing and
doesn't fix the mixer/export-timing bugs already fixed on this branch).

Verified: qwen4exp MTP speculative decoding still produces correct,
byte-identical (temp 0) output after this change. Speed effect is hard
to isolate cleanly from the dominant MoE-cache warmup effect already
documented on this branch, but the fix is justified on its own
correctness merits regardless of measured delta.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Comment thread src/llama-model-loader.cpp Outdated
Comment on lines +1133 to +1134
throw std::runtime_error(format("%s: this model is a draft head without its own '%s'; "
"load it as a draft of its target model, not on its own", __func__, name.c_str()));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This triggers when loading with --fit on as the draft model is loaded independently as part of that. Everything still works though: it's later loaded again together with the target model.

@ovidiu-morar

Copy link
Copy Markdown

Metal data point on this exact head (2857e51): dn=2 is greedy-identical, dn=5 is slower and diverges

All validations above are CUDA, so here is Apple Silicon. M5 Pro 64 GB, Metal, built at 2857e5114 (the same commit as the fork branch the Unsloth docs point to). Target: Qwen3.8-Flash-Next-UD-IQ3_XXS (original 3-shard file). Draft: the official mtp-Qwen3.8-Flash-Next-shared-Q8_0.gguf. llama-cli -ngl 48 -ot "^output=CPU" -c 2048 -n 200 --temp 0 --seed 7 --no-warmup --single-turn, same Romanian prompt for every run, 3 interleaved runs per arm, medians. Identity = sha256 of the generated token stream.

arm gen t/s vs no-spec token stream at temp 0
no spec 26.8 reference dea1d100
--spec-type draft-mtp --spec-draft-n-max 2 26.3 -2% identical
--spec-draft-n-max 5 (the value the model page recommends) 22.1 -18% diverges (a19b4630, 3/3 runs)

Three things worth separating:

  • The divergence is not new to this head. I measured the same greedy divergence at n-max >= 3 on qwen4exp : add NextN/MTP draft head (--spec-type draft-mtp) for Qwen3.8-Flash-Next #27836 (Aug 30, report) and on the fork at 586b15e (Sept 1), and the divergent stream here is byte-identical to the one from Sept 1. The reference stream is also byte-identical across the two heads, so the target itself has not moved. The diff between 586b15e and 2857e5114 does not touch the accept/reject path (common_sampler_sample_and_accept_n is unchanged; the changes are the shared-embedding borrow, the DFlash fusion and the Metal tuning tables), which is consistent with the result.
  • On this hardware the page's recommended setting is both slower and not greedy-identical, while n-max 2 is identical and roughly neutral. That matches the page's own caveat about smaller gains on lower-bandwidth Macs, and it may be worth stating n-max 2 as the safe default there until the n-max >= 3 divergence is understood.
  • Every report so far, here and on the model page, measures speed and acceptance. None checks identity. If someone on CUDA or Vulkan can run the same prompt at temp 0 with and without the draft at n-max 5 and compare the token streams, that would tell whether the divergence is Metal-specific or just unmeasured elsewhere.

Happy to rerun on any later head; the harness is three commands.

@jeverson-bmi

jeverson-bmi commented Sep 3, 2026

Copy link
Copy Markdown

I have been trying this and the baseline from master actually has faster token gen than with MTP on, both shared and standalone. Using 5090+A6000(Ampere) + 128GB DDR5.

ryanmonsurate and others added 10 commits September 3, 2026 20:04
Adds the MTP head's own hyper-connection mixer tensor names and lists the
NextN tensors under the qwen4exp architecture.
Adds --spec-type draft-mtp support for Qwen3.8-Flash-Next.

The MTP head folds the next token's embedding into the trunk's wide
hyper-connection residual, runs one trunk-style block (dense attention +
MoE) over it, and collapses the result with its own mixer before reusing
the trunk's LM head.

- read nextn_predict_layers so n_layer() excludes the MTP block
- load the trailing block through the existing trunk path: is_recr() and
  is_ple() are already false past the trunk, so it needs no special casing
- eh_proj fuses the checkpoint's fc_embedding and fc_hidden side by side,
  so one matmul computes fc_embedding@e + fc_hidden@h
- the head carries its own hyper-connection mixer, mirroring the trunk's
  hc_head_*, which stands in for the output norm qwen4exp does not have
- export the wide pre-collapse residual as t_h_nextn from both graphs, so
  the driver can feed it back for the next draft step
- route MTP contexts to a plain KV cache filtered to the trailing layer

The draft block attends densely for now: the trunk's QSA only prunes
context past a 2048-token budget, so dense is a numerical superset and
drafts are verified either way. Indexer tensors are still loaded.
The MTP block is one trunk-shaped block (dense attention + MoE wrapped in
hyper-connections) plus a head-level combiner, so once _QwenMtpMixin renames
mtp.layers.0.* to the trailing block index its tensors ride the existing
qwen4exp mappings unchanged. Two head-level pieces need handling:

- fc_embedding and fc_hidden fuse into the eh_proj the shared NextN code
  expects, since W_e@e + W_h@h == [W_e|W_h] @ concat(e, h)
- mtp.hyper_connection_mixer.* is the head's own copy of the trunk's
  hc_head_* output mixer, unindexed in the checkpoint and per-block in the
  GGUF

compress_ratios is read with length block_count, so it gains a trailing 0
for the MTP block, which attends densely.

--no-nextn drops the head; --mtp exports it on its own.
A NextN/MTP draft exported with --mtp carries the token embeddings, output
norm and lm head so it can be loaded as a standalone model. For every current
sidecar those three tensors are most of the file: ggml-org/Qwen3.8-27B-GGUF
mtp-Qwen3.8-27B-Q4_0.gguf is 1.565 GiB, of which 1.332 GiB (85%) is the copy,
against 0.223 GiB for the MTP block itself.

Add an opt-in --mtp-shared-embd that leaves them out and marks the file with
nextn_shared_target_tensors. The loader then resolves those names against the
already loaded target model. The graph side needs no change: the nextn blocks
of twelve archs already fall back to model.tok_embd and model.output.

The borrow is gated on the new key, so a sidecar published before this change
cannot reach it and keeps its current behaviour. Shapes are checked against
the target and a mismatch is refused, as is loading such a file on its own.
_QwenMtpMixin is not a ModelBase subclass, so it re-declares the
attributes it reads off cls for the type checker. filter_tensors reads
cls.mtp_shared_embd without a matching declaration, which ty reports as
unresolved-attribute.

The declaration is a bare annotation, matching no_mtp and mtp_only
above it. That creates no class attribute, so it cannot shadow
ModelBase.mtp_shared_embd even though the mixin precedes the model
class in the MRO; a default value here would have.

Assisted-by: Claude
A draft-only export declares the full block count but ships the MTP
block alone, so the trunk tensors load as null and only the MTP graph
is buildable. Context reservation builds the trunk graph, which walked
those nulls and segfaulted.

A shared-embedding draft is caught earlier by the borrow check, since
it has no token_embd of its own. A self-contained draft keeps one, so
it passed that check and reached here.

Assisted-by: Claude
Reuses the existing llama_context_params::ctx_other plumbing instead of adding a
model_shared load parameter and a nextn_shared_target_tensors metadata key.

A draft-only export now simply omits token_embd/output, and the qwen4exp MTP graph
resolves them against the target context at graph build, following dflash and
gemma4-assistant. Loading such a file on its own reports that it needs -md.

Assisted-by: Claude
@ovidiu-morar

This comment was marked as spam.

@gabrielfreire

Copy link
Copy Markdown

Pulled the latest commits on this PR and started getting this error in the logs and it seems MTP wasn't activated

45.08.275.530 E decode: failed to initialize batch
45.08.275.531 E llama_decode: failed to decode, ret = -1
45.08.275.532 E spec        draft: llama_decode[1] returned -1
45.08.371.747 E init: the tokens of sequence 0 in the input batch have inconsistent sequence positions:
 - the last position stored in the memory module of the context (i.e. the KV cache) for sequence 0 is X = 84307
 - the tokens for sequence 0 in the input batch have a starting position of Y = 84307
 for M-RoPE, it is required that the position satisfies: X < Y
45.08.371.752 E decode: failed to initialize batch
45.08.371.753 E llama_decode: failed to decode, ret = -1
45.08.371.754 E spec        draft: llama_decode[1] returned -1
45.08.469.748 E init: the tokens of sequence 0 in the input batch have inconsistent sequence positions:
 - the last position stored in the memory module of the context (i.e. the KV cache) for sequence 0 is X = 84309
 - the tokens for sequence 0 in the input batch have a starting position of Y = 84309
 for M-RoPE, it is required that the position satisfies: X < Y
45.08.469.752 E decode: failed to initialize batch
45.08.469.752 E llama_decode: failed to decode, ret = -1
45.08.469.754 E spec        draft: llama_decode[1] returned -1
45.08.566.593 E init: the tokens of sequence 0 in the input batch have inconsistent sequence positions:
 - the last position stored in the memory module of the context (i.e. the KV cache) for sequence 0 is X = 84311
 - the tokens for sequence 0 in the input batch have a starting position of Y = 84311
 for M-RoPE, it is required that the position satisfies: X < Y
45.08.566.597 E decode: failed to initialize batch
45.08.566.598 E llama_decode: failed to decode, ret = -1
45.08.566.599 E spec        draft: llama_decode[1] returned -1
45.08.669.020 I slot print_timing: id  0 | task 17766 | n_gen =    100, tg =  15.11 t/s, tg_3s =  15.26 t/s
45.08.673.694 E init: the tokens of sequence 0 in the input batch have inconsistent sequence positions:
 - the last position stored in the memory module of the context (i.e. the KV cache) for sequence 0 is X = 84312
 - the tokens for sequence 0 in the input batch have a starting position of Y = 84312
 for M-RoPE, it is required that the position satisfies: X < Y
45.08.673.697 E decode: failed to initialize batch
45.08.673.698 E llama_decode: failed to decode, ret = -1
45.08.673.699 E spec        draft: llama_decode[1] returned -1
45.08.768.871 E init: the tokens of sequence 0 in the input batch have inconsistent sequence positions:
 - the last position stored in the memory module of the context (i.e. the KV cache) for sequence 0 is X = 84314
 - the tokens for sequence 0 in the input batch have a starting position of Y = 84314
 for M-RoPE, it is required that the position satisfies: X < Y
45.08.768.875 E decode: failed to initialize batch
45.08.768.876 E llama_decode: failed to decode, ret = -1
45.08.768.877 E spec        draft: llama_decode[1] returned -1
45.08.859.902 I slot print_timing: id  0 | task 17766 | prompt eval time =    6649.72 ms /   178 tokens (   37.36 ms per token,    26.77 tokens per second)
45.08.859.907 I slot print_timing: id  0 | task 17766 |        eval time =    6741.95 ms /   103 tokens (   66.10 ms per token,    15.13 tokens per second)
45.08.859.908 I slot print_timing: id  0 | task 17766 |       total time =   13391.67 ms /   281 tokens
45.08.859.909 I slot print_timing: id  0 | task 17766 |    graphs reused =      11160
45.08.859.913 I slot print_timing: id  0 | task 17766 | draft acceptance = 0.81395 (   35 accepted /    43 generated), mean len =  1.81
45.08.861.454 I slot      release: id  0 | task 17766 | stop processing: n_tokens = 84316, truncated = 0

A qwen4exp draft that borrows the target's embeddings sets ctx_other but keeps
its own memory, so it must be caught up and rolled back like any other draft.
Treating it as memory-shared skipped the catch-up decode and placed every draft
token at the same position, which the M-RoPE position check rejects.

Assisted-by: Claude
@danielhanchen

Copy link
Copy Markdown
Contributor Author

@gabrielfreire Apologies it should be fixed now

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

Labels

conversion CUDA Related to the CUDA backend ggml changes relating to the ggml tensor library for machine learning model Model specific

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants