Skip to content

spec : add adaptive MTP draft depth (draft-mtp-adaptive) - #27210

Open
stew675 wants to merge 8 commits into
ggml-org:masterfrom
stew675:adaptive-mtp
Open

stew675 wants to merge 8 commits into
ggml-org:masterfrom
stew675:adaptive-mtp

Conversation

@stew675

@stew675 stew675 commented Aug 17, 2026 •

Copy link
Copy Markdown

Overview

Implements adaptive mtp with a new option --spec-type draft-mtp-adaptive

Suggested configuration to use is: --spec-type draft-mtp-adaptive --spec-draft-n-max 12

Note: It is not recommended to set spec-draft-n-max to values lower than 7 with the Adaptive MTP algorithm. In this instance the algorithm isn't able to reach depths high enough to provide the benefits it aims to achieve. If you find yourself in a situation where insufficient VRAM prevents you from setting a depth of at least 7, or more preferably 8+, then it's generally going to be best to just stick with regular MTP.

The algorithm is a counting based state machine with a climb counter and a weighted drop-pressure accumulator. The depth climbs one step after a number consecutive verifies that accepted every drafted token; any miss adds (N - acceptance) to the drop pressure and the depth drops one step once it exceeds a certain amount. High depths fall quickly (a total miss adds N), low depths hold, and at the floor no pressure accumulates at all. The specific climb difficulty and drop pressure values were empirically determined over a wide range of tests.

--spec-draft-n-max bounds the upper adaptive range and both the floor and the cold-start depth default to 3. The default floor of 3 may be adjusted with --spec-draft-n-min-adaptive, although in testing 3 seems to be the best value to choose here.

Overview of the climb-cost algorithm

It was experimentally determined that a draft MTP depth of 2 or 3 is close to optimal for reasoning and prose.
More typically an MTP depth of 3 was found to be optimal, and so this was chosen as the baseline default.

When the depth is less than three the algorithm allows for an easy transition from a depth of 1 to 2.
A slightly higher cost from 2 to 3 is used to minimise the depth oscillating between two and three.

To climb past a depth of three requires passing a hardened barrier. The hardened barrier is in place to
minimise easily reaching a depth of four which is known to be harmful to performance for reasoning and prose.

Beyond a depth of four the barrier to climb higher is gradually reduced.
This allows for predictive runs to quickly ascend as the admission rates indicate that this is useful.

Latest Testing and Performance Results

(Updated 23 Aug 2026)

Latest performance results can be seen here: #27210 (comment)

Extended discussion of results can be seen here: #27210 (comment)

Test Setup

  • Model: Qwen3.8-27B Q8_0 (Qwen3.8-27B-Q8_0.gguf
  • Hardware: 2x AMD Radeon AI PRO R9700 (32.6 GiB each), tensor split, Ryzen 9
    9950X3D2, ROCm, HIP_VISIBLE_DEVICES=0,2, GGML_CUDA_DISABLE_GRAPHS=0
  • Server: llama-server from branch adaptive-mtp (build 10459, 0c6426b,
    freshly rebuilt)
  • Decode: greedy (temp 0.0, seed 675), top-k 20, top-p 0.95, min-p 0.001,
    ctx 262144, f16 KV, --parallel 1, mlock, reasoning on
    (--reasoning-budget 65536 --reasoning-preserve)
  • 2 repeats per cell; tok/s = mean of timings.predicted_per_second
    (generation only, >= 4000 tokens per request)

Configurations Tested

ID spec type args
C0 none -
C1 draft-mtp, fixed 3 --spec-draft-n-max 3
C2 draft-mtp, fixed 12, p-min --spec-draft-n-max 12 --spec-draft-p-min 0.75
C3 draft-mtp-adaptive 3..12 --spec-draft-n-min-adaptive 3 --spec-draft-n-max 12
C4 adaptive 3..12 + p-min C3 + --spec-draft-p-min 0.75
C5 ngram-mod --spec-ngram-mod-n-match 24 --spec-ngram-mod-n-min 48 --spec-ngram-mod-n-max 64
C6 adaptive + ngram-mod C3 args + C5 args
C7 fixed 3 + ngram-mod C1 args + C5 args
C8 fixed 12 + p-min + ngram-mod C2 args + C5 args

Results

config reasoning prose code recall
C0 baseline 30.03 30.08 30.03 29.93
C1 fixed 3 51.68 55.89 69.28 81.94
C2 fixed 12 + p-min 0.75 38.59 43.46 71.46 151.25
C3 adaptive 3..12 51.42 56.64 78.03 147.46
C4 adaptive + p-min 0.75 40.67 43.35 70.92 147.43
C5 ngram-mod 30.03 30.10 29.98 292.88
C6 adaptive + ngram-mod 51.48 56.61 73.06 321.25
C7 fixed 3 + ngram-mod 51.65 55.90 68.36 324.10
C8 fixed 12 + p-min + ngram-mod 41.34 43.73 64.39 325.68

Additional information

The total diff size is +519/-35

This PR touches on 15 files which seems large at first, but this mostly arises from integrating the new command line options. The bulk of the functional changes take place within speculative.cpp After the recent code-review (Ref: #27210 (comment) ), I rewrote the MTP vs Adaptive MTP invocations to keep the original MTP behaviour exactly the same as before, even if the code-path to get there has now changed. I also believe that I successfully argued for why the GDN changes should remain: Ref: #27210 (comment)

218 lines are for the unit test file. 92 lines are for the header file that contains the algorithm itself.

The rest of the line changes are the wiring of the algorithm into the llama.cpp code base, and the command line option handling.

I tried to keep the size of the functional changes to llama.cpp itself as small as possible, and I tried to keep this diff as independent as I could so that unless it's specifically activated, it won't interfere with normal llama.cpp operations.

"Horses for Courses"

While Adaptive MTP generally works well for most hardware and models, it can make performance worse on older hardware that cannot run the deep drafting and acceptance steps fast enough to realise the potential gains it offers. In these instances it is generally better to not enable Adaptive MTP and just stick with regular MTP with a low fixed depth.

Dense Models generally receive the most benefit, but gains on MoE models are generally weaker. For MoE models it's generally preferable to lower the maximum depth to no more than 8 and then assess. If the performance is no better than using a fixed MTP depth, then that's fine. Just use a fixed MTP depth instead.

Related Issues/PRs

I searched known issues and open PRs and did not find anything precisely mentioning this sort of feature at first.

@Us5rName pointed out in the comments below that they have a similar feature PR here: https://github.com/Us5rName/llama.cpp/tree/draft-adaptive-length-rolling-window

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: Yes. I designed the exact algorithm. AI chose the best place for it, and added it. I then went over it all, reviewed it, cleaned up and changed half of it to better reflect my intent, and then tested and refined the algorithm manually over the day.

@github-actions github-actions Bot added server testing Everything test related labels Aug 17, 2026
@stew675
stew675 marked this pull request as ready for review August 17, 2026 16:41
@stew675
stew675 requested review from a team and ggerganov as code owners August 17, 2026 16:41
@Us5rName

Us5rName commented Aug 17, 2026 •

Copy link
Copy Markdown

Hi!

I've also created a fork with adaptive length for mtp and dflash with a rolling window based heuristic.

https://github.com/Us5rName/llama.cpp/tree/draft-adaptive-length-rolling-window

and this PR #25726 with the groundwork.

Would you like to colab?

@theIvanR

Copy link
Copy Markdown

Excellent job! I would propose to merge this with my fix for a more robust datatype selection in MTP implementation for nvidia cards.

(bug)
#25713
(and solution)
#25680

@stew675

stew675 commented Aug 18, 2026 •

Copy link
Copy Markdown
Author

Excellent job! I would propose to merge this with my fix for a more robust datatype selection in MTP implementation for nvidia cards.

(bug) #25713 (and solution) #25680

I corrected a different MTP issue in this commit to my personal fork's working branch here: stew675@b2655d3

I really should file a PR for that, but its exposure range is pretty narrow. My fix targets which custom kernel runs for F32-activation small batches. It fixes a corner case for the handling of BF16 KV caches though (most of the work in my branch there targets adding BF16 KV to the ROCm backend), and my code exposed that latent bug.

It appears there is a handful of inconsistencies in the mainline MTP code for certain corner cases and you have found another. I do see that your PR got closed. Did you ever work on a more targetted fix as per the reviewer's suggestion?

@stew675

stew675 commented Aug 18, 2026 •

Copy link
Copy Markdown
Author

Hi!

I've also created a fork with adaptive length for mtp and dflash with a rolling window based heuristic.

https://github.com/Us5rName/llama.cpp/tree/draft-adaptive-length-rolling-window

and this PR #25726 with the groundwork.

Would you like to colab?

Thank you for bringing your PR up. I searched for similar PR's and I don't know why yours didn't show up.

I've looked over your branch and groundwork PR. There's a number of conceptual similarities, both being counting based heuristics. Both are sliding window approach, with yours being explicit, and mine being implicit. Both employ a form of "depth stickiness". Yours has a lot more knobs where I made a conscious effort to keep the knobs to a minimum. I do like your Bias knob though. That could be a genuinely useful knob for users to tweak for certain models to adjust the level of depth stickiness. The falling back approaches do differ significantly in concept. I spent quite a bit of time trying difference approaches, and then dialing in the one I settled on.

Your personal branch seems to target DFlash too, right?

I'm fine with us combining efforts, but we'd need to settle on what the UX approach should be. I'm a big fan of KISS. Years ago I would've had knobs for everything, but nowadays I'm a firm believer of use as few knobs as possible.

Do you have any performance comparisons of your implementation and how it affects both prose and code? I tried pretty hard to ensure that prose performance was affected as little as possible, so I'm curious to see results on how you solved that issue.

At the end of the day though, we both need one of the maintainers to offer some guidance on what they'd like to see. That will ultimately set the direction on what the next steps will be here.

Edited to correct my earlier statement of both being implicit sliding windows. That was my mistake earlier.

giveen added a commit to giveen/llama-cpp-turboquant that referenced this pull request Aug 18, 2026
Chained MTP drafting (PR ggml-org#27173 backport):
- All N draft tokens produced in one fused GPU decode via in-graph argmax
- Deferred catch-up rows merged into first draft decode
- --spec-chain N flag enables chain mode and sets depth (default: off)
- New llama_set_mtp_chain() API for graph mode switching
- Per-shape scheduler pool (LLAMA_SPEC_CHAIN env var still works)

Adaptive MTP draft depth (PR ggml-org#27210 backport):
- --spec-type draft-mtp-adaptive with hysteresis state machine
- Depth climbs after consecutive full accepts, drops on misses
- --spec-draft-n-min-adaptive for floor depth (default: 3)

Results on RTX 5090, Qwen3.8-27B Q4_K_P:
- Code: 206 t/s (chain n=8) vs 156 t/s (MTP n=3) vs 69 t/s (no MTP)
- Chain delivers 3.0x over no-MTP, +31% over standard MTP on code

Assisted-by: Claude
@simongonzalezdc

Copy link
Copy Markdown

Numbers from our side supporting adaptive draft depth, measured on a Strix Halo APU (gfx1151, Ryzen AI Max+ 395) serving Qwen3.8-27B with draft-mtp + ngram-mod speculative decoding (datapost: #27154):

At --spec-draft-n-max 12, draft acceptance splits sharply by workload class:

  • code / low-reasoning traffic: ~0.96 acceptance. Deep drafts pay off; going from n-max 3 to n-max 12 was the difference between ~40 and ~60 tok/s class generation on this chip.
  • heavy thinking/reasoning traffic: ~0.5 acceptance. Deep drafts mostly miss, so most drafted tokens become wasted verification work that adds per-token cost.

The second lane replicates independently on a different Strix Halo system: acceptance "way below 50%" under xhigh-reasoning coding traffic, with n-max 12 regressing generation (peak ~26 t/s, dips into the ~5-6 t/s range) versus lower n-max values — that user is now moving down to n-max 2 (comment: #27154 (comment)).

So a fixed n-max serves one lane and starves the other: deep enough for the ~0.96-acceptance lane, or shallow enough to cap wasted verification in the ~0.5-acceptance lane, but not both. Acceptance-driven draft depth is the knob that spans both, which is exactly what this PR adds.

@theIvanR

This comment was marked as abuse.

@stew675

stew675 commented Aug 18, 2026

Copy link
Copy Markdown
Author

I went over all the check failures and it appears that they are all pre-existing/known flaky tests unrelated to my code changes.

Now, I do have another commit that's almost ready which actually solves the 3% performance regression on hard prose, and actually boosts normal prose. The question I have is shall I wait for this PR to go ahead and file a followup, or shall I attach that change to this same PR. I'm fine either way.

@mndodd

mndodd commented Aug 18, 2026

Copy link
Copy Markdown

Overview

Implements adaptive mtp with a new option --spec-type draft-mtp-adaptive

How does this compare with draft-mtp and spec-draft-p-min? I've been playing with pretty deep n-max values (8-16) and p-min>0.5 with good results.

@ghost

This comment was marked as low quality.

@stew675

stew675 commented Aug 18, 2026

Copy link
Copy Markdown
Author

I went over all the check failures and it appears that they are all pre-existing/known flaky tests unrelated to my code changes.
Now, I do have another commit that's almost ready which actually solves the 3% performance regression on hard prose, and actually boosts normal prose. The question I have is shall I wait for this PR to go ahead and file a followup, or shall I attach that change to this same PR. I'm fine either way.

If this is working, then you don’t really have many options.

Yeah, I'll cover it in a followup PR. That will give me more time to refine it further.

@dormosh

dormosh commented Aug 18, 2026

Copy link
Copy Markdown

Getting this error with plain draft-mtp:

 invalid adaptive draft range: n_min_adaptive=3, n_max=2 (n_min_adaptive must be in [1, n_max])                                                                                                

It occurs whenever the effective n_max < 3 (e.g. --spec-draft-n-max 2). The range check added in
speculative.cpp:1401 runs unconditionally in the ctor, but the ctor is shared by both draft-mtp and draft-mtp-adaptive, and n_min_adaptive (default 3) is only used in adaptive mode. To fix it, I moved the check inside the if (adaptive) block.

@stew675

stew675 commented Aug 18, 2026

Copy link
Copy Markdown
Author

Getting this error with plain draft-mtp:

 invalid adaptive draft range: n_min_adaptive=3, n_max=2 (n_min_adaptive must be in [1, n_max])                                                                                                

It occurs whenever the effective n_max < 3 (e.g. --spec-draft-n-max 2). The range check added in speculative.cpp:1401 runs unconditionally in the ctor, but the ctor is shared by both draft-mtp and draft-mtp-adaptive, and n_min_adaptive (default 3) is only used in adaptive mode. To fix it, I moved the check inside the if (adaptive) block.

Thank you for catching this. I'll be pushing a fix shortly.

@ghost

This comment was marked as low quality.

@stew675

stew675 commented Aug 18, 2026 •

Copy link
Copy Markdown
Author

Overview

Implements adaptive mtp with a new option --spec-type draft-mtp-adaptive

How does this compare with draft-mtp and spec-draft-p-min? I've been playing with pretty deep n-max values (8-16) and p-min>0.5 with good results.

You've provided both a broad range (8-16) and an ambiguous range of p-min > 0.5

I'm guessing you meant --spec-draft-p-min, and not --min-p?

Just to be clear, what's your ask here? For me to test all depths from 8-16 and vaguely a number of --spec-draft-p-min values as a matrix? Wouldn't that be highly dependent on what exactly it is you're doing? It's kind of the point of this PR that you don't need to be fiddling about trying to dial in the perfect depth and p-value each time.

It's also been my experience that raising --spec-draft-p-min, whether it be normal or adaptive MTP, absolutely destroys prose performance. With the rise of deep thinking models (like our good friend Qwen3.8 here) there's likely to be significant amounts of time spent generating prose before code gets written.

This is why I've been focusing on preventing/minimising harm to prose performance. We don't want trash that thinking performance just to get some more t/s on code generation and end up slower overall.

@mndodd

mndodd commented Aug 18, 2026

Copy link
Copy Markdown

Overview

Implements adaptive mtp with a new option --spec-type draft-mtp-adaptive

How does this compare with draft-mtp and spec-draft-p-min? I've been playing with pretty deep n-max values (8-16) and p-min>0.5 with good results.

You've provided both a broad range (8-16) and an ambiguous range of p-min > 0.5

I'm guessing you meant --spec-draft-p-min, and not --min-p?

Just to be clear, what's your ask here? For me to test all depths from 8-16 and vaguely a number of --spec-draft-p-min values as a matrix? Wouldn't that be highly dependent on what exactly it is you're doing? It's kind of the point of this PR that you don't need to be fiddling about trying to dial in the perfect depth and p-value each time.

No ask, just curious because I had your exact though this weekend "man, we need an adaptive n-max or something." and then found spec-draft-p-min and it gave me the sort of results I was looking for, with Qwen3.8.

It's also been my experience that raising --spec-draft-p-min, whether it be normal or adaptive MTP, absolutely destroys prose performance. With the rise of deep thinking models (like our good friend Qwen3.8 here) there's likely to be significant amounts of time spent generating prose before code gets written.

This is why I've been focusing on preventing/minimising harm to prose performance. We don't want trash that thinking performance just to get some more t/s on code generation and end up slower overall.

Your PR is on my list to test.

@bucknova

Copy link
Copy Markdown

Tested the fixed-depth equivalent of this on the target hardware/backend this PR doesn't cover yet — Intel Arc Pro B70 (BMG G31, 32GB), llama.cpp SYCL via LocalAI intel-sycl-f16-llama-cpp gallery build 2026-08-03, Qwen3.8-27B UD-Q4_K_XL, 256k ctx, q8_0 KV. Fixed draft-mtp depth sweep, 700-token decode, single stream:

depth t/s
2 ~29
3 32
4 31
6 24.2

Draft acceptance 75–90% (mean accepted length 2.5–4.7) across runs. Two observations that support the adaptive approach directly:

  1. The optimum is sharp and shallow. Peak at 3, and 6 is a 25% loss — deeper drafting actively hurts on this backend. Your default floor of 3 is exactly where I landed by hand.

  2. The penalty is dispatch-bound, so it's worse on SYCL than CUDA/ROCm. Each extra draft step pays the SYCL per-kernel dispatch cost (100–500µs vs ~5µs CUDA), so the "keep it at the floor unless acceptance earns it deeper" logic should pay off proportionally more here than on the platforms already benchmarked.

Happy to run the adaptive build against the same 700-token workload on this B70 once it's testable and post the side-by-side.

@Us5rName

Us5rName commented Aug 19, 2026 •

Copy link
Copy Markdown

@stew675

Do you have any performance comparisons of your implementation and how it affects both prose and code? I tried pretty hard to ensure that prose performance was affected as little as possible, so I'm curious to see results on how you solved that issue.

I ran my heuristic against static length in speedbench with qwen 3.6 35B and mtp

roleplay category was used for prose
coding category was used for coding

*note: on my hardware (rtx 4080 super + rx 7900 xtx, both using vulkan backend), I noticed the maximum draft length that doesn't hurt my performance was 5, and the minimum draft length that didn't hurt it was 2.

draft length 2 was used for prose, and draft length 5 was used for coding.

got very similar results in both the non adaptive case and the adaptive case.

Speedbench, qwen 3.6 35B UD-Q4_K_XL, using mtp:

coding, draft length 5: 157.70 tps
coding, adaptive draft length 2-5: 163.19 tps

roleplay, draft length 2: 147.71 tps
roleplay, adaptive draft length 2-5: 149.08 tps

In my personal experience with my fork, the draft length of my heuristic usually stabilizes at 2 tokens for prose,
3-4 tokens in math,
and 4-5 tokens in code.

Tell me if there are additional files/logs you would like to see.

Your personal branch seems to target DFlash too, right?

Yes. By targeting Dflash I meant I copy pasted the code from my mtp implementation into Dflash - the heuristic works exactly the same in both cases.

In the code, Because the draft length update is checked on every accept(), which every draft spec implementation has, it can absolutely be ported to draft-simple and draft-eagle3, I don't use them so I didn't apply the heuristic to them.

I now also deduplicated code in my fork by using your approach of putting the heuristic in a header, and added a short explanation on the algorithm I used, so it should be easier to read and trivial to port to other draft implementations.

I looked at your code, and it seems like adding the same heuristic you implemented in mtp to Dflash (and other spec types) should be simple, and I think adding your heuristic to Dflash as well is a good experiment because even with Dflash generating all tokens at once, the target model can still try to verify "useless tokens" (In my experiments, my heuristic worked well on Dflash)

I'm fine with us combining efforts, but we'd need to settle on what the UX approach should be. I'm a big fan of KISS. Years ago I would've had knobs for everything, but nowadays I'm a firm believer of use as few knobs as possible.

I agree I that have too many knobs, and when I use my fork I always use --spec-adaptive-length-default (sets my knobs to params that worked well for me)

However, I still think that 1-3 knobs of configuration is still good to have, to let people experiment.

I think a good approach would be like with n-gram speculative decoding - configurable but includes a parameter that sets sane defaults (--spec-default).
What do you think?

Comment thread common/speculative.cpp Resolved
@ghost

This comment was marked as low quality.

@stew675

stew675 commented Aug 19, 2026

Copy link
Copy Markdown
Author

@stew675 , small enhancement from my side:

diff --git a/common/speculative.cpp b/common/speculative.cpp
index 0c7fb38d9..459eea494 100644
--- a/common/speculative.cpp
+++ b/common/speculative.cpp
@@ -1457,6 +1457,12 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl {
             return;
         }

+        // new generation: the depth learned for the previous content is stale,
+        // so the controller starts from the floor again
+        if (adaptive) {
+            adaptive_ctrl[seq_id].reset(params.n_max, params.n_min_adaptive);
+        }
+
         auto * ctx_dft = this->params.ctx_dft;
         const llama_pos pos_max = llama_memory_seq_pos_max(llama_get_memory(ctx_dft), seq_id);

Its a fix for issue with adaptive which has depth from previous state... If you want just pick it up.... however, if you intend to use previous state and let adaptive decrease/increase N this will create unnecessary work

Ooh, good catch! Thank you for that. I see that another work-flow hasn't been approved yet, so now's a good time to merge that in.

@ghost

This comment was marked as low quality.

@stew675

stew675 commented Oct 17, 2026

Copy link
Copy Markdown
Author

Closing this PR. It's been made plainly obvious by now that the team isn't interested.

My apologies to all who were hoping for this one to go in. I'm not going to waste any more of my time on this.

@theIvanR

Copy link
Copy Markdown

@stew675 Team not being arsed to implement PR's is unfortunately a recurrent theme in llama cpp and a real shame. I wish you the best of luck in your future endeavors.

@ahbnr

ahbnr commented Oct 18, 2026

Copy link
Copy Markdown

Closing this PR. It's been made plainly obvious by now that the team isn't interested.

My apologies to all who were hoping for this one to go in. I'm not going to waste any more of my time on this.

Your PR has been quite useful to me, and I am going to continue using it for a while. Please don't apologize, thank you for your hard work on this!

@mirek190

Copy link
Copy Markdown

That's literally bullshit they closed it !

@pwilkin

pwilkin commented Oct 18, 2026

Copy link
Copy Markdown
Member

I'm sorry, forgot about this one, you need to ping the team sometimes since there's a slew of PRs and we're getting overwhelmed - I recently had to ping about my own PR from like 3 months ago.

@pwilkin

pwilkin commented Oct 18, 2026

Copy link
Copy Markdown
Member

/bot review

@ggml-gh-bot

ggml-gh-bot Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Automated code review

Review of PR #27210 (spec: add adaptive MTP draft depth). I traced the wiring end to end: the arg plumbing, the draft-mtp-adaptive enum and init paths, the per-seq controller feedback (draft() -> accept()/accept_partial()), the server/example checkpoint-restore paths, and the delta-net conv-state change against the recurrent-memory rollback machinery.

Verified as correct (no action needed): the non-adaptive draft-mtp path is behavior-preserving (n_cap == params.n_max, n_min cutoff still applied, dp.n_max clamping only avoids drafting tokens that were previously discarded by the wrapper truncation); the replayed-round double-feedback hazard is handled via the n_last reset; the adaptive range validation and the draft-mtp + draft-mtp-adaptive mutual exclusion are sound.

Blocking

(point 1) Missed has_mtp() update in the -fit path: common/common.cpp:1301 still computes spec_mtp with a raw std::find for COMMON_SPECULATIVE_TYPE_DRAFT_MTP only. The PR updated the sibling call sites (arg.cpp, common.cpp:1711, speculative.cpp:2639, server-context.cpp), but this one was missed. With --spec-type draft-mtp-adaptive and the default -fit on (no separate draft model, so has_dft() is false): cparams_dft.ctx_type is not set to LLAMA_CONTEXT_TYPE_MTP for the fit estimation, and has_draft || spec_mtp at line 1325 is false, so common_fit_params gets extra == nullptr and reserves no device memory for the MTP draft context that common_speculative_init will later create. Adaptive MTP can then OOM at draft-context creation or get a smaller fitted n_ctx than plain draft-mtp on the same setup. Fix: const bool spec_mtp = params.speculative.has_mtp();.

Will slow the review

(point 2) The src/models/delta-net-base.cpp change is a standalone delta-net optimization riding along in an MTP feature PR. I checked the invariant and it holds for the in-tree rollback producers (server and speculative-simple verify batches are [last committed token + draft], so rollback <= n_seq_tokens - 1, and split_equal(n_keep_tail = n_rs_seq + 1) guarantees the removed tokens share the ubatch; the new t_min bound writes exactly the slots the fused GDN op already writes, so conv and ssm snapshots stay consistent). But it is a cross-module behavioral contract on shared model code that other reviewers must sign off on independently - if maintainers want it, it would be cleaner as its own small PR with its own perf data. At minimum, link the prior discussion you mentioned in the description.

(point 3) The bound in point 2 relies on split_equal's GGML_ASSERT(n_ubatch > n_keep_tail) (src/llama-batch.cpp:602). With the suggested --spec-draft-n-max 12 this means n_rs_seq = 12 and any user with -ub <= 13 hits a hard abort. That failure mode is pre-existing for deep fixed MTP, but this PR actively steers users toward n_max 12, so consider clamping n_rs_seq against the batch size (or failing with a clear error) rather than leaving an assert.

(point 4) tests/test-speculative-adaptive.cpp is a new file under tests/, which per the contributing guidelines needs explicit maintainer approval. The PR description references earlier review rounds - please confirm that approval is on record. The test itself is fine: cheap, model-free, and it covers the climb/drop/floor/clamp behavior well.

Nits

(point 5) docs/speculative.md: the N in the new --spec-draft-n-min-adaptive block is not aligned with the column used by the surrounding options; add/remove padding to match.

(point 6) common/speculative.cpp:1400: the construction trace still prints 'draft-mtp' when the adaptive variant is built; print the actual type (common_speculative_type_to_str(type)) or mention adaptive.

(point 7) Minor follow-up worth keeping in mind (not for this PR): rounds where p_min truncates the draft produce no controller feedback at all (n_last can end up 0 on early cutoff), which is the "short drafts counted as success" limitation you already discussed in the comments.

This review was generated automatically by pi coding agent using zai-org/GLM-5.3. It may contain mistakes. Maintainers make the final call.

@pwilkin

pwilkin commented Oct 18, 2026

Copy link
Copy Markdown
Member

Can you please rebase on current master?

@stew675

stew675 commented Oct 18, 2026

Copy link
Copy Markdown
Author

I'm sorry, forgot about this one, you need to ping the team sometimes since there's a slew of PRs and we're getting overwhelmed - I recently had to ping about my own PR from like 3 months ago.

Thank you @pwilkin

I will admit that I was quite concerned over prompting again. I'd already done so three times, and there is a number of stories/experiences floating around of people getting banned over nagging. At my end it felt like I was faced with the choice of "nag and risk getting banned", or just close it and move on.

I'll see about rebasing it in a few hours.

Hysteresis state machine with a climb counter and a weighted drop-pressure
accumulator. The depth climbs one step after 5 consecutive verifies that
accepted every drafted token; any miss adds (N - acceptance) to the drop
pressure and the depth drops one step once it exceeds 30. High depths fall
quickly (a total miss adds N), low depths hold, and at the floor no pressure
accumulates at all. The floor is max(1, n_min) and the ceiling is n_max, so
--spec-draft-n-min/--spec-draft-n-max bound the adaptive range and the
cold-start depth is 3.

Assisted-by: pi
Adaptive MTP starts at the floor of --spec-draft-n-min-adaptive (default
3) and adjusts its own depth: consecutive full accepts climb one step,
with a cost table that rises fast to depth 3, blocks 3->4 (where
marginal content collapses), and climbs fast at depth; a drop-pressure
accumulator of n_draft - n_accepted, with a budget of max(depth * 5,
20), lowers it.  Fully accepted but truncated drafts count as full
accepts, and only drafts this implementation actually produced update
the controller.

The depth is independent of --spec-draft-n-min, which keeps its usual
meaning of a minimum draft length to verify for the non-adaptive spec
types.  Extracted the controller into a standalone struct and added unit
test cases for adaptive MTP.

Assisted-by: pi
n_min_adaptive only applies to draft-mtp-adaptive, but the range check
ran unconditionally in the shared MTP ctor, so plain draft-mtp aborted
whenever the effective n_max was below the default floor of 3 (e.g.
--spec-draft-n-max 2). Gate the check on adaptive mode, and when the
chain_heads clamp capped n_max at the model MTP layer count, say so in
the abort message.

Assisted-by: pi
climb_threshold: the 3->4 barrier is hardened to 10 consecutive full
accepts so prose/reasoning stay pinned at the floor; 4->5 raised to 6;
5->6 and 6->7 lowered to 3 and 2 so code accelerates to the deep hold
without over-drafting into the marginal depths.

recurrent snapshot fix: the conv-state loop wrote n_rs_seq + 1 copies per
layer per round, but a rollback can only reach n_seq_tokens - 1 slots back,
so copies beyond the batch were dead work (~2.6% per-round overhead at
n_rs_seq=10 on shallow verifies). Start the loop at
max(1, K - n_seq_tokens + 1).

tests: move the #undef NDEBUG before <cassert> so the asserts actually
run in Release builds (they were silent no-ops), and re-derive the climb
expectations for the new table.

Assisted-by: Pi
I rebased the code against the latest master tip and corrected a handful of outdated comments
Addressed all nits and items marked as review slowers, except the new test
file (tests/test-speculative-adaptive.cpp), which needs maintainer sign-off.

For point 1 (delta-net): the change only skips conv-state snapshot writes that no legal rewind can reach. Short verify batches are already routine upstream - for example `--spec-draft-p-min` truncation, a small `--spec-draft-n-max`, and the server's context clamp can all produce them. The fused GDN path has written only the last min(n_seq_tokens, K) recurrent-state snapshots (leaving the rest stale) since before this PR, and that path is the default for the qwen35 family - it already depends on rewinds never leaving the seq's last ubatch. Verify batches always begin with the seq's last committed token, so a rewind can only remove drafted tokens that sit inside that batch. This change makes the conv-state writer consistent with that existing convention. It is therefore my position that this PR builds upon established behaviour, and there is no known code path or scenario where the invariant is broken, even on the delta-net (GDN) models this change affects.

Implemented a mechanism to prevent stale accept depth feedback reaching the
adaptive controller (point 2): a draft round whose partial acceptance cannot
be applied to the context is reported once with the true accept count via
common_speculative_accept_partial, and the checkpoint-replay round that
follows no longer feeds the controller with the previous round's draft count.
The mechanism is scoped so the non-adaptive MTP accept path behaves exactly
as before.

The controller was re-tested on delta-net hardware after the change
(C3/C6 on Qwen3.8-27B, one repeat): throughput and acceptance match the
previous measurements within run-to-run noise.

Assisted-by: pi
Addressed bot code-review comments from here: ggml-org#27210 (comment)

Assisted-by: pi
@stew675

stew675 commented Oct 18, 2026 •

Copy link
Copy Markdown
Author

Rebase is complete. Regarding point 7 of the bot review. The climb-cost table is already tuned with that behavior in mind. I can change the accept behavior, but then I'd also need to spend an afternoon retuning the table. It's a correct call that this should be a followup.

@am17an

am17an commented Oct 18, 2026

Copy link
Copy Markdown
Contributor

can you try is this diff provides most of the benefit?

diff --git a/common/arg.cpp b/common/arg.cpp
index 8b302d5d7..59d340c9a 100644
--- a/common/arg.cpp
+++ b/common/arg.cpp
@@ -4255,6 +4255,16 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
             }
         }
     ).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_DRAFT_SAMPLING"));
+    add_opt(common_arg(
+        {"--spec-draft-adaptive"},
+        {"--no-spec-draft-adaptive"},
+        string_format("adapt the MTP draft length between --spec-draft-n-min and --spec-draft-n-max: "
+                      "+1 after a fully accepted draft, -1 otherwise (default: %s)",
+                      params.speculative.draft.adaptive ? "enabled" : "disabled"),
+        [](common_params & params, bool value) {
+            params.speculative.draft.adaptive = value;
+        }
+    ).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_DRAFT_ADAPTIVE"));
     add_opt(common_arg(
         {"--spec-draft-device", "-devd", "--device-draft"}, "<dev1,dev2,..>",
         "comma-separated list of devices to use for offloading the draft model (none = don't offload, default: follows --device)\n"
diff --git a/common/common.h b/common/common.h
index 0c2d5e46f..be167f7f3 100644
--- a/common/common.h
+++ b/common/common.h
@@ -336,6 +336,8 @@ struct common_params_speculative_draft {
 
     bool probabilistic = false; // sample the draft and verify by rejection, instead of argmax and match
 
+    bool adaptive = false; // adapt the draft length in [max(1, n_min), n_max] to the acceptance (MTP only)
+
     common_params_model mparams;
 
     llama_context * ctx_tgt = nullptr;
diff --git a/common/speculative.cpp b/common/speculative.cpp
index d8afd4095..64a56e1d9 100644
--- a/common/speculative.cpp
+++ b/common/speculative.cpp
@@ -1466,6 +1466,10 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl {
     std::vector<int>                i_last;
     std::vector<std::vector<float>> chain_h;
 
+    // per-seq draft length, moves within [n_lo, n_max] when params.adaptive is set
+    int32_t              n_lo = 1;
+    std::vector<int32_t> n_cur;
+
     common_speculative_impl_draft_mtp(const common_params_speculative & params, uint32_t n_seq)
         : common_speculative_impl(COMMON_SPECULATIVE_TYPE_DRAFT_MTP, n_seq, params.draft.n_max)
         , params(params.draft)
@@ -1532,6 +1536,9 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl {
         }
         this->n_max = this->params.n_max;
 
+        n_lo = this->params.adaptive ? std::max(1, std::min(this->params.n_min, this->params.n_max)) : this->params.n_max;
+        n_cur.assign(n_seq, n_lo);
+
         pending_h.assign(n_seq, std::vector<float>(n_embd, 0.0f));
 
         i_last.assign(n_seq, -1);
@@ -1560,6 +1567,8 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl {
         // reset here rather than per round, or two identical requests differ
         common_sampler_reset(smpls[seq_id].get());
 
+        n_cur[seq_id] = n_lo;
+
         const int32_t N = (int32_t) prompt.size();
         if (N <= 0) {
             return;
@@ -1803,7 +1812,7 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl {
                     dp.result_q->emplace_back(cur_p->data, cur_p->data + cur_p->size);
                 }
 
-                if (params.n_max <= (int) result.size()) {
+                if (n_cur[seq_id] <= (int) result.size()) {
                     drafting[seq_id] = false;
                     n_drafting--;
                     continue;
@@ -1856,7 +1865,7 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl {
         }
     }
 
-    void accept(llama_seq_id seq_id, uint16_t n_accepted, bool /*is_other*/) override {
+    void accept(llama_seq_id seq_id, uint16_t n_accepted, bool is_other) override {
         if (seq_id < 0 || seq_id >= (llama_seq_id) n_seq) {
             return;
         }
@@ -1866,6 +1875,12 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl {
             return;
         }
 
+        // the verify batch is the sampled token + the draft: +1 if the whole draft was accepted, -1 otherwise
+        if (params.adaptive && !is_other) {
+            n_cur[seq_id] = n_accepted >= n_rows - 1 ? std::min(n_cur[seq_id] + 1, params.n_max)
+                                                     : std::max(n_cur[seq_id] - 1, n_lo);
+        }
+
         const int32_t i_h = std::min<int32_t>(n_accepted, n_rows - 1);
         const size_t row_bytes = (size_t) n_embd * sizeof(float);
         std::memcpy(pending_h[seq_id].data(), verify_h[seq_id].data() + (size_t) i_h * n_embd, row_bytes);

@am17an

am17an commented Oct 18, 2026

Copy link
Copy Markdown
Contributor

please test on tools/server/bench/speed-bench/

@hermeticvm

Copy link
Copy Markdown

Data point from a consumer RDNA2 box, in case it helps the review: adaptive depth clearly helps on its own, but combined with ngram-mod the gain disappears.

Setup. b11804 (c7fc509) with this PR's diff at c1c2b286f9 applied (clean), built with .devops/rocm.Dockerfile for gfx1030. RX 6700 XT 12 GB, Qwen3.6-35B-A3B IQ4_XS with its MTP head, experts of 24 of 40 layers in system RAM (--n-cpu-moe 24), -c 131072 -ub 1024 -np 1 -ctxcp 0, draft KV q8_0. Single stream. "Fresh" writes new code; "rewrite" returns a 5k-token file with one identifier renamed (copy-heavy). Pairs are temperature 0 / 0.6; acceptance is accepted/drafted.

--spec-type fresh tok/s fresh acceptance rewrite tok/s
draft-mtp,ngram-mod, n-max 256, b11804 without the PR 43.0 / 41.3 54 % / 45 % 167 / 183
same, PR build 44.3 / 41.1 62 % / 40 % 173 / 181
draft-mtp-adaptive 45.7 / 45.5 81 % / 81 % 48 / 48
draft-mtp-adaptive,ngram-mod, n-max 256 42.5 / 42.2 51 % / 59 % 171 / 185
draft-mtp-adaptive,ngram-mod, n-max 64 * 45.4 / 42.8 75 % / 65 % 115 / 117

* Separate session; its own baseline was 42.1 / 42.8 fresh and 174 / 183 rewrite. Run-to-run noise is about ±5 %. Prompt processing was unchanged in every variant.

  • With the PR built in but adaptive not selected, results match the unpatched build.
  • draft-mtp-adaptive alone does what it says: acceptance on fresh code rises to 81 % and decode gains 6–10 %. Without ngram-mod, copy-heavy output drops to MTP speed.
  • With ngram-mod added, acceptance and speed fall back to the fixed-depth baseline. With a shorter n-gram cap (64), adaptive behaviour partly returns, at the cost of copy speed.

My guess, unverified: when both are enabled, the adaptive controller's statistics include or are displaced by n-gram drafts, so it never settles on the depth it finds alone. If that is the case, tracking acceptance per drafter, or only for MTP drafts, would let the two combine. Happy to rerun a revision on this box.

@juraj-jumic

Copy link
Copy Markdown

This is draft-dspark, not MTP, but it might be relevant to how the depth gets picked. I benchmarked DSpark on one consumer card with two backends, and the best depth was different on each, even though the acceptance rate was the same.

Setup: b11865 (9a0fde9), RX 7900 GRE 16 GB, Windows 11, Qwen3-8B Q8_0 with the ggml-org DSpark Q8_0 draft, -np 1, --spec-draft-p-min 0. speed-bench qualitative (coding, math, writing, qa, 8 prompts each, osl 512), temperature 0. Baseline is 61.7 t/s on Vulkan and 59.1 t/s on ROCm.

--spec-draft-n-max Vulkan ROCm acceptance (Vulkan / ROCm)
3 115.0 t/s (1.86×) 109.7 t/s (1.85×) 63% / 64%
5 109.1 t/s (1.77×) 127.2 t/s (2.15×) 52% / 52%
7 100.4 t/s (1.63×) 133.0 t/s (2.25×) 43% / 44%

The drafts are accepted at the same rate on both backends, so the difference has to come from the cost of verifying a longer draft. My guess is that cost grows faster on Vulkan than on ROCm. Whichever fixed depth you pick, you lose 13-18% on one of the two.

So a controller that only looks at acceptance would choose the same depth on both backends and be slower on one of them. Taking the measured time per verify step into account might catch this.

Scripts and full results: https://github.com/juraj-jumic/dspark-local-bench

@jukofyork

jukofyork commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

can you try is this diff provides most of the benefit?

diff --git a/common/arg.cpp b/common/arg.cpp
index 8b302d5d7..59d340c9a 100644
--- a/common/arg.cpp
+++ b/common/arg.cpp
@@ -4255,6 +4255,16 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
             }
         }
     ).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_DRAFT_SAMPLING"));
+    add_opt(common_arg(
+        {"--spec-draft-adaptive"},
+        {"--no-spec-draft-adaptive"},
+        string_format("adapt the MTP draft length between --spec-draft-n-min and --spec-draft-n-max: "
+                      "+1 after a fully accepted draft, -1 otherwise (default: %s)",
+                      params.speculative.draft.adaptive ? "enabled" : "disabled"),
+        [](common_params & params, bool value) {
+            params.speculative.draft.adaptive = value;
+        }
+    ).set_spec().set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_CLI}).set_env("LLAMA_ARG_SPEC_DRAFT_ADAPTIVE"));
     add_opt(common_arg(
         {"--spec-draft-device", "-devd", "--device-draft"}, "<dev1,dev2,..>",
         "comma-separated list of devices to use for offloading the draft model (none = don't offload, default: follows --device)\n"
diff --git a/common/common.h b/common/common.h
index 0c2d5e46f..be167f7f3 100644
--- a/common/common.h
+++ b/common/common.h
@@ -336,6 +336,8 @@ struct common_params_speculative_draft {
 
     bool probabilistic = false; // sample the draft and verify by rejection, instead of argmax and match
 
+    bool adaptive = false; // adapt the draft length in [max(1, n_min), n_max] to the acceptance (MTP only)
+
     common_params_model mparams;
 
     llama_context * ctx_tgt = nullptr;
diff --git a/common/speculative.cpp b/common/speculative.cpp
index d8afd4095..64a56e1d9 100644
--- a/common/speculative.cpp
+++ b/common/speculative.cpp
@@ -1466,6 +1466,10 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl {
     std::vector<int>                i_last;
     std::vector<std::vector<float>> chain_h;
 
+    // per-seq draft length, moves within [n_lo, n_max] when params.adaptive is set
+    int32_t              n_lo = 1;
+    std::vector<int32_t> n_cur;
+
     common_speculative_impl_draft_mtp(const common_params_speculative & params, uint32_t n_seq)
         : common_speculative_impl(COMMON_SPECULATIVE_TYPE_DRAFT_MTP, n_seq, params.draft.n_max)
         , params(params.draft)
@@ -1532,6 +1536,9 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl {
         }
         this->n_max = this->params.n_max;
 
+        n_lo = this->params.adaptive ? std::max(1, std::min(this->params.n_min, this->params.n_max)) : this->params.n_max;
+        n_cur.assign(n_seq, n_lo);
+
         pending_h.assign(n_seq, std::vector<float>(n_embd, 0.0f));
 
         i_last.assign(n_seq, -1);
@@ -1560,6 +1567,8 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl {
         // reset here rather than per round, or two identical requests differ
         common_sampler_reset(smpls[seq_id].get());
 
+        n_cur[seq_id] = n_lo;
+
         const int32_t N = (int32_t) prompt.size();
         if (N <= 0) {
             return;
@@ -1803,7 +1812,7 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl {
                     dp.result_q->emplace_back(cur_p->data, cur_p->data + cur_p->size);
                 }
 
-                if (params.n_max <= (int) result.size()) {
+                if (n_cur[seq_id] <= (int) result.size()) {
                     drafting[seq_id] = false;
                     n_drafting--;
                     continue;
@@ -1856,7 +1865,7 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl {
         }
     }
 
-    void accept(llama_seq_id seq_id, uint16_t n_accepted, bool /*is_other*/) override {
+    void accept(llama_seq_id seq_id, uint16_t n_accepted, bool is_other) override {
         if (seq_id < 0 || seq_id >= (llama_seq_id) n_seq) {
             return;
         }
@@ -1866,6 +1875,12 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl {
             return;
         }
 
+        // the verify batch is the sampled token + the draft: +1 if the whole draft was accepted, -1 otherwise
+        if (params.adaptive && !is_other) {
+            n_cur[seq_id] = n_accepted >= n_rows - 1 ? std::min(n_cur[seq_id] + 1, params.n_max)
+                                                     : std::max(n_cur[seq_id] - 1, n_lo);
+        }
+
         const int32_t i_h = std::min<int32_t>(n_accepted, n_rows - 1);
         const size_t row_bytes = (size_t) n_embd * sizeof(float);
         std::memcpy(pending_h[seq_id].data(), verify_h[seq_id].data() + (size_t) i_h * n_embd, row_bytes);

I tested a variation of this and it actually works quite well! I had to reduce the adjustment factor to around ~0.2 and then use floor(x+epilon) (or equivalently/better: use 5 integer bins per draft length and integer division).

  • Anything between 0.1-0.2 works quite well, but 0.25+ jumps about too much to be useful.
  • I found that it helps to set the initial value to what generally works well without this (for my dual RTX 5000 Ada and tensor parallel; this is 3.0).

I tried a few variations on this, but other than the fractional adjustment factor; nothing was obviously better.

It's approximately seeking a draft length that has a median acceptance rate (of the full sequence) of 50% (the floor(x) and other constraints complicate things a bit though...).

I tried a few variations like seeking a mean acceptance rate of 50% (via a proportional correction), but this is hard as the "what if I drafted larger?" side is censured and there's no obvious way to account for this...

You can use a different fixed correction for reward/penalty (and thus seek an arbitration percentile), but not sure it's worth the hassle of another parameter to tune...

I'll tidy up what I have and post it tomorrow, but overall this seems quite a useful addition IMO.

@juraj-jumic

Copy link
Copy Markdown

@jukofyork Rough check of a "seek ~50% acceptance" rule against my DSpark numbers from above (RX 7900 GRE, Qwen3-8B Q8_0):

n-max acceptance Vulkan ROCm
3 63-64% 1.86× 1.85×
5 52% 1.77× 2.15×
7 43-44% 1.63× 2.25×

The ~50% point is n=5 on both backends, which is 4-5% below the best on each. That's a lot better than a wrong fixed value (13-18%), so the simple rule looks good to me. It just can't pick up the backend difference, since acceptance is the same on both. Happy to test your version on this card once you post it, if it applies to draft-dspark too.

This branch has not been deployed

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

Labels

documentation Improvements or additions to documentation model Model specific server testing Everything test related

Projects

None yet

Development

Successfully merging this pull request may close these issues.