Repository navigation
Make the drafter probabilistic and the target verify by rejection sampling for simple draft and MTP - #27694
Conversation
|
@gaugarg-nv |
d30f4a5 to
73986ec
Compare
|
Thanks for the PR. However, this doesn’t appear to implement rejection sampling in the GPU backend, so I wouldn’t expect the implementation to yield a decent performance improvement. Could we instead follow vLLM’s rejection-sampling approach? e.g. https://github.com/vllm-project/vllm/blob/1f1f628859dd0dc2a3b7f43810254884799619e6/vllm/v1/sample/rejection_sampler.py#L715 and https://github.com/vllm-project/vllm/blob/1f1f628859dd0dc2a3b7f43810254884799619e6/vllm/v1/sample/rejection_sampler.py#L774 |
Hi @ruixiang63 The rejection sampling (accept/reject step) runs on the host and not in the GPU backend with this PR. The gain here does not come from sampling being faster though. Argmax-and-match accepts a draft token only when the target's top pick happens to equal the draft's, while min(1, p/q) accepts it with probability p/q, so more tokens survive per verification step and the target runs fewer forward passes. This leads to increased acceptance length: it improves by +2.7% to +13.4% depending on the model, drafter and temperature. I have run sweeps with -bs enabled and disabled along with the changes in this PR. Based on the logs obtained, this PR does not affect the functionality of backend sampling, which ensures that the target sampling chain already happens on the GPU. With -bs on, I see the same accepted length and 1-2% change in throughput, which is consistent with what is observed on the master branch with -bs enabled. On the GPU kernels, I agree it is worth doing. However, I would prefer to take that up as a separate PR so the two changes can be reviewed and measured separately. Note the residual is built over the target's post-chain candidates, which in llama.cpp default to top_k 40 trimmed by top_p, against the draft's top_k 10 — so only a few hundred comparisons per position. This is different from vLLM where vocab_size options are present per token at both draft and target, resulting in many more comparisons. Given the lower number of comparisons per token in llama.cpp I would need to experimentally verify if implementing the rejection sampling in the GPU sampling would result in a considerable throughput gain, which I prefer to do as a separate PR. |
48c375c to
88e706e
Compare
|
@ruixiang63 , @gaugarg-nv , @ORippler can you please review this PR? Thanks. FYI, I have started the GPU kernel for rejection sampling-based experimentation locally and will file a new PR for any corresponding changes. The scope of this PR is limited to rejection sampling (accept/reject step) happening on the CPU. For flexibility, I have also added a flag (defaults to greedy - same as vLLM behavior), when set to probabilistic, enables rejection sampling. |
88e706e to
b11dae7
Compare
|
Could you share some data comparing DFlash/MTP with and without rejection sampling? I’d like to see the differences in acceptance rate and speedup. |
draft_simple and draft_mtp data over different models and HW with percentage increase in acceptance length and throughput is already present in PR description under the performance tab. Also pasting them below in this comment. The PR does not apply to and does not affect DFlash, so its perf numbers and unchanged and not mentioned. Performance
Two machines, eight model configurations each, 11 temperatures from 0.0 to 1.0. Every run is 12 prompts of 256 tokens at --spec-draft-n-max 3, the shipped default. RTX 5090Llama-3.1-8B + 3B-Q8_0 -
Llama-3.1-8B + 3B-Q4_K_M -
Llama-3.1-8B + 3B-IQ2_XS -
Qwen3.5-4B -
Qwen3.5-9B -
Ornith-1.5-9B -
Qwen3.6-27B -
Qwen3.6-35B-A3B -
DGX SparkLlama-3.1-8B + 3B-Q8_0 -
Llama-3.1-8B + 3B-Q4_K_M -
Llama-3.1-8B + 3B-IQ2_XS -
Qwen3.5-4B -
Qwen3.5-9B -
Ornith-1.5-9B -
Qwen3.6-27B -
Qwen3.6-35B-A3B -
|
I didn't get this. What will happen if both draft and target use greedy sampling? and if only draft uses greedy sampling? |
There was a problem hiding this comment.
| dst->cur_p = src->cur_p; | |
| dst->rng = src->rng; |
Need to copy new field here.
There was a problem hiding this comment.
Added this field here in the latest commit.
| slot.spec_draft_q.clear(); | ||
|
|
||
| if (!slot.spec_draft.empty()) { |
There was a problem hiding this comment.
spec_draft_q should not be cleared for replay case when spec_draft is non-empty.
There was a problem hiding this comment.
Fixed in the latest commit.
| if (masked) { | ||
| cand.assign(cur_p->data, cur_p->data + cur_p->size); | ||
| llama_token_data_array arr = { cand.data(), cand.size(), -1, false }; | ||
| llama_sampler_apply(gsmpl->grmr, &arr); | ||
| } | ||
|
|
||
| // a candidate the grammar rejects carries no probability, whatever the target thinks | ||
| auto p_of = [&](size_t k) { | ||
| return masked && cand[k].logit == -INFINITY ? 0.0f : cur_p->data[k].p; | ||
| }; | ||
|
|
||
| // q_x is never 0 for a token the draft produced, but guard the divide | ||
| const float q_x = prob_of(q.data(), q.size(), draft[i]); | ||
|
|
||
| float p_x = 0.0f; | ||
| for (size_t k = 0; k < cur_p->size; ++k) { | ||
| if (cur_p->data[k].id == draft[i]) { | ||
| p_x = p_of(k); |
There was a problem hiding this comment.
Do we not need to renormalize distribution after masking?
There was a problem hiding this comment.
Good catch. Fixed this in the latest commit.
| } | ||
|
|
||
| cur.temp = dp.sampling->temp; | ||
| cur.seed = dp.sampling->seed; |
There was a problem hiding this comment.
Is this same seed as target? Can you check if using the same seed as target expected in rejection sampling?
There was a problem hiding this comment.
Good catch @gaugarg-nv. It was using the same seed as the target, which it should not. This is fixed in the latest commit. The draft's seed and the verifier's rng are now derived from the request seed with distinct constants, so every stream starts differently.
|
@ggerganov @danbev Could you please review this PR when you get some cycles? This implements probabilistic sampling for draft as proposed by SpecDec paper and also implemented by vLLM. |
|
Latest commit addresses @gaugarg-nv's seed question and @danbev's rng-state finding. The verifier's rng and the draft sampler were both seeded from the request seed, and both are now mixed - LLAMA_DEFAULT_SEED is passed through to reseed randomly. This is experimentally confirmed, across 8 seeds the verifier and the draft no longer share a first uniform in any of them, and over 20 requests the draft no longer matches the target chain's stream. That also surfaced another case. The perf tables are re-measured after making these changes, hence some differences from the previous tables may be expected. Updated Performance
Two machines, 11 temperatures from 0.0 to 1.0, 12 prompts, each generating output up to 256 tokens at --spec-draft-n-max 3. RTX 5090Llama-3.1-8B + 3B-Q4_K_M -
Llama-3.1-8B + 3B-Q8_0 -
Llama-3.1-8B + 3B-IQ2_XS -
Qwen3.5-4B -
Qwen3.5-9B -
Ornith-1.5-9B -
Qwen3.6-27B -
Qwen3.6-35B-A3B -
DGX SparkLlama-3.1-8B + 3B-Q8_0 -
Llama-3.1-8B + 3B-Q4_K_M -
Llama-3.1-8B + 3B-IQ2_XS -
Qwen3.5-4B -
Qwen3.5-9B -
Ornith-1.5-9B -
Qwen3.6-27B -
|
|
Ran AIME 2026 (
The target samples stochastically in both arms; the flag selects the draft sampler and the matching verification rule only.
RTX 5090, Qwen3.6-27B-Q4_K_M
DGX Spark GB10, Qwen3.6-35B-A3B-UD-Q4_K_M
|
| // drafters that fill no distribution fall back here, as does a chained draft | ||
| const bool use_rejection = slot.use_spec_rejection() && | ||
| !slot.spec_draft.empty() && | ||
| (slot.spec_is_replay || | ||
| slot.spec_draft_q.size() == slot.spec_draft.size()); |
There was a problem hiding this comment.
This can be simplified because above we assert GGML_ASSERT(n_draft > 0);:
| // drafters that fill no distribution fall back here, as does a chained draft | |
| const bool use_rejection = slot.use_spec_rejection() && | |
| !slot.spec_draft.empty() && | |
| (slot.spec_is_replay || | |
| slot.spec_draft_q.size() == slot.spec_draft.size()); | |
| // drafters that fill no distribution fall back here, as does a chained draft | |
| const bool use_rejection = slot.use_spec_rejection() && | |
| (slot.spec_is_replay || | |
| slot.spec_draft_q.size() == slot.spec_draft.size()); |
Regarding slot.spec_draft_q.size() == slot.spec_draft.size() in which cases this wouldn't be true? If I understand correctly the logic, we probably need the following assert:
GGML_ASSERT(slot.spec_draft_q.empty() || (slot.spec_draft_q.size() == slot.spec_draft.size()));There was a problem hiding this comment.
Good point. Updated as suggested in the latest commit.
| // the target's config; only temp and seed are read, to retune the draft sampler | ||
| const common_params_sampling * sampling = nullptr; |
There was a problem hiding this comment.
Pass only the data that is used (temp + seed) instead of the full sampling object.
There was a problem hiding this comment.
Updated as suggested in the latest commit.
| @@ -294,7 +339,12 @@ struct common_speculative_impl_draft_simple : public common_speculative_impl { | |||
|
|
|||
| n_drafting++; | |||
| drafting[seq_id] = true; | |||
| common_sampler_reset(smpls[seq_id].get()); | |||
| spec_retune(smpls, smpls_cfg, llama_get_model(ctx_dft), seq_id, dp, params.probabilistic); | |||
There was a problem hiding this comment.
Shouldn't we do this in begin() instead of draft()? We don't expect sampling parameters to change in the middle of a generation.
There was a problem hiding this comment.
The draft sampler is rebuilt only on the first draft of a request. For later drafts, spec_retune returns early if temp and seed are unchanged, and on the greedy path it is not called at all, since result_q gates it.
Moving the call into begin() would need the temperature and seed to reach common/ at generation start, since the draft params are filled per round afterwards. This involves function signature rewrites across multiple places for a relatively small change. The gate would also have to change: result_q is what currently tells the drafter that the caller wants rejection, and it is not set yet when begin() runs, so the temp > 0 check would have to be repeated there.
If we prefer that it be done in begin() despite the above, please let me know and I will make the change.
| @@ -85,6 +85,9 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co | |||
| // | |||
| std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sampler * gsmpl, struct llama_context * ctx, const std::vector<int> & idxs, const llama_tokens & draft, bool grammar_first = false); | |||
|
|
|||
| // as above, but verifies by rejection sampling; draft_q holds the draft's candidates per token | |||
| std::vector<llama_token> common_sampler_sample_and_accept_n_rejection(struct common_sampler * gsmpl, struct llama_context * ctx, const std::vector<int> & idxs, const llama_tokens & draft, const std::vector<std::vector<llama_token_data>> & draft_q, bool is_replay = false, bool grammar_first = false); | |||
There was a problem hiding this comment.
Not sure if the is_replay logic needs to be introduced in this API.
I think we should just have an is_replay == true branch in the server-context.cpp logic and handle it there.
There was a problem hiding this comment.
Good point. Updated as suggested in the latest commit.
…aft-simple, MTP) Cherry-pick of ggml-org/llama.cpp PR ggml-org#27694 (ggml-org#27694) Author: Pranesh Gonegandla (@praneshgo) Reason for our setup: our live server runs MTP speculative decoding; at temperature>0 exact-match draft verification loses acceptance. Adds --spec-draft-sampling (greedy|probabilistic, default greedy = current behavior). Flag-gated, no default change. Conflicts resolved manually against PR ggml-org#27210 (adaptive MTP depth): kept both the adaptive controller reset and the sampler reset in begin(); kept result_q recording with the adaptive n_cap check instead of fixed params.n_max.
Cherry-pick of ggml-org/llama.cpp PR ggml-org#27692 (ggml-org#27692) Author: Felix Kranich (@kilofox) Reason for our setup: cuts long-prompt TTFT by having a small draft model estimate which prompt tokens matter before target prefill (ICML 2025 speculative prefill). Opt-in feature; no default behavior change. Conflicts resolved manually against PRs ggml-org#27694 and ggml-org#27210: kept both use_spec_rejection() and prompt_src()/n_prompt_src() in server slot; kept the adaptive-draft arg-parser tests.
…#27694) Cherry-pick of the 7 commits of the open upstream PR ggml-org#27694 onto b11095. Opt-in via --spec-draft-sampling probabilistic; default greedy keeps the old path. Assisted-by: Claude Opus 5.5
|
@ggerganov I have updated the PR and addressed your previous comments. |
ggerganov
left a comment
There was a problem hiding this comment.
Please rebase one more time on latest master.
…27694) * Make the drafter probabilistic and the target verify by rejection sampling * Drop stale spec_draft_q before drafting * Fallback to argmax sampling for grammar-constrained requests and adding flag for enabling probabilistic draft sampling. Default flag value is greedy. * Support grammar-constrained requests in rejection sampling * Fix - renormalize distribution after masking * copy rng on sampler copy and re-accept drafted tokens on replay * Fix draft sampler sharing the target's rng stream * Simplify the rejection sampler's inputs and move replay to the server * Truncate the draft candidates along with the draft --------- Co-authored-by: praneshgo <[email protected]> Co-authored-by: Pranesh Gonegandla <[email protected]> (cherry picked from commit 1fb7ef3)
…bed0a85) Resolution choices: - DSpark --spec-draft-sampling (ours) and upstream ggml-org#27694 probabilistic draft sampling shared one CLI flag/env (--spec-draft-sampling, LLAMA_ARG_SPEC_DRAFT_SAMPLING), draft_params.temp and slot.spec_draft_q. One flag now: greedy | probabilistic (both implementations) | stochastic (DSpark only, back-compat). Ours renamed to dspark_temp/dspark_q and slot.spec_dspark_q; upstream keeps result_q/temp/seed and spec_draft_q. - Verification order: synth > DSpark stochastic > upstream replay (only if the replayed round used rejection) > upstream rejection > sample-and-match, so default behaviour (no flags) is identical to master. - sampling.cpp: keep <functional>. server.cpp: keep router-node early return, keep the "initializing ..." log before llama_backend_init. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Two tailors in Lyon had been making the same coat for a year without meeting. One of them had sewn a hidden pocket for dice, because the customer gambled and liked to have them on him, and had sized it, lined it and tested it on his own hip. The other, who sold more coats, mailed over a pattern that spring with the same pocket drawn in, in the same place, in the same cloth, with a note that said the house of Vernet now considered the dice pocket standard. The first tailor laid the two patterns on the table and found that the seams crossed at fifteen points and that there was no honest way to have both pockets in one coat. He cut his out. He kept the stitch he'd invented for the lining, because the other pattern's lining tore on the Rhone wind and his didn't, and nobody from Vernet had ever stood on that quay. The customer asked which pocket he'd got. The tailor said: theirs, with my thread, and the dice fit the same, and you will not find the seam because I moved it under the arm. --- 607 upstream commits (6d9c82e..06cad0b, b11480). Dropped the fork's --spec-accept stochastic (f8a6903 / e9c788d / 60bc680) for upstream ggml-org#27694 --spec-draft-sampling probabilistic: same rejection sampling, same three hook points, plus spec_retune() so the draft samples at the target temperature. Running both side by side meant fifteen conflicting hunks in common/speculative.cpp for one switch. test-spec-accept, the stochastic/exact/fallback counters in server-common.h and llama_sampler_grammar_is_active go with it. Server verify order is now synth, replay, rejection, exact; the draft params block carries result_q/temp/seed next to the tuner's n_draft_cur. Kept: the keep vector on common_speculative_process, --spec-draft-auto, --spec-draft-ctx-step, -lcd write-back, disk cache v4/v5 and checkpoint spill, perf instrumentation, idempotent synchronize. server-http registers upstream's callback lambda under path_prefix + path. Upstream ggml-org#28498 writes n_rot_k/n_rot_v into the KV state blob, so disk-cache files from the old binary fail with "incompatible key rotation" once, get reprocessed and rewritten. Not a bug. test-recurrent-state-rollback: upstream's dummy models (ggml-org#29133) are noisier and Vulkan drifts ~1e-8 nmse between two contexts even without a restore, so the composed/partial rollback tests bound nmse at 1e-4 and test_rollback at 1e-7 instead of asking for bit-exact logits. CPU stays bit-exact. 130/130 models pass on Vulkan. Server pytests: 24 pass with the uncached upstream presets (tinylaya, tinyopenjev) skipped; they cannot be fetched behind the proxy.
…27694) * Make the drafter probabilistic and the target verify by rejection sampling * Drop stale spec_draft_q before drafting * Fallback to argmax sampling for grammar-constrained requests and adding flag for enabling probabilistic draft sampling. Default flag value is greedy. * Support grammar-constrained requests in rejection sampling * Fix - renormalize distribution after masking * copy rng on sampler copy and re-accept drafted tokens on replay * Fix draft sampler sharing the target's rng stream * Simplify the rejection sampler's inputs and move replay to the server * Truncate the draft candidates along with the draft --------- Co-authored-by: praneshgo <[email protected]> Co-authored-by: Pranesh Gonegandla <[email protected]> (cherry picked from commit 1fb7ef3)
…micro-batch (--spec-draft-n-ubatch) (#281) --spec-draft-sampling (b11368, ggml-org/llama.cpp#27694) samples the draft and verifies it by rejection, for a draft model and MTP. --spec-draft-n-ubatch (b11630, #30459) gives the drafter's context a micro-batch of its own, shrinking its compute buffer. Both are model settings written only for builds that have them, spec-value settings for benchmark sweeps, and counted where they matter: the estimate uses the draft micro-batch for the draft compute buffer, and Autotune's draft-settings stage measures probabilistic drafting on each draft or MTP finalist when the profile samples above temperature 0.
…7694) [TAG_UP27694] Manual port of upstream 1fb7ef3 ("spec : add probabilistic sampling for simple draft and MTP", ggml-org/llama.cpp#27694); cherry-pick conflicted in common/speculative.{h,cpp} and tools/server/server-context.cpp. Release train 63.5 (U7, R127), v63 candidate. What it does (flag on, request temp > 0): draft-simple / draft-mtp sample the draft from a draft sampler retuned to the request's temp/seed (top_k 10 + temp) and keep the candidate set per drafted token; the server verifies by rejection sampling (common_sampler_sample_and_accept_n_rejection: accept with min(1, p/q), else draw from norm(max(0, p - q)); grammar-aware; the uniform draws come from a separate per-sampler mt19937 so the target's dist RNG stream is untouched). Distribution-exact for the target. Default = greedy. With the flag off the behaviour is byte-identical to the base: - the drafters drop result_q -> argmax draft + per-round reset exactly as before; - upstream's new reset in begin() is gated on the flag (fork deviation); - common_sampler gains an rng member seeded from llama_sampler_get_seed (read-only), used only by the rejection path; - server: the rejection branch needs non-empty spec_draft_q of the draft's size, which only a probabilistic drafter fills. Fork adaptations: - replay: upstream's server_accept_replay is NOT ported; the fork's server_sample_and_accept_replay already re-emits committed tokens without re-sampling, which is what the rejection round needs too (its committed tokens include the residual draw). The trace-only re-sample probe is off for rejection rounds (a kept token is not the target's own sample, it would count as a flip). - the upstream GGML_ASSERT on spec_draft_q/spec_draft sizes became a fall-back to sample-and-match; the n_min rule clears result_q together with result in both drafters. - [TAG_UP29638] EOG rule mirrored in the rejection verifier (no draft token after an accepted EOG). - spec_untune(): a T = 0 request after a probabilistic one gets the default draft sampler back (top_k 10 {TOP_K}, MTP fast path), so p_min reads the same draft probabilities. - draft params result_q/temp/seed are set after the fork's aggregate init (the fork struct has n_attempted/n_kept/keep_short in between). Disk-cache key: unchanged. server_cache_param_canon lists draft fields explicitly and does not include `probabilistic`; cache_compat_measure only runs process() on a temporary speculative object (no draft() call), so the knob enters neither the parameter digest nor the measured payload. Tests (balkon CPU, stories15M MoE + stories15M-q4_0 draft-simple): new pytest test_draft_sampling_probabilistic (T = 0 flag on == greedy, T 0.7 accepts drafts and a fixed seed reproduces, T = 0 after T > 0 greedy again); unit/test_speculative.py 11/11; flag off vs the base build: identical ids, draft counts and [spec-ids] rounds on 3 prompts at T 0 and T 0.7 (seed 4242). The draft-mtp path has no CPU-sized test model: it is exercised by the s1 pair gate. EXACT with the flag off (default); behavioural (distribution-exact) with it on. Review fixes (review-u7: M1, m1, m3; m2/m4 left as is): - M1: flag off was not byte-identical for drafters that fill no candidates (ngram-*, eagle3, dflash) at T > 0 when the draft was truncated to n_max: the truncation grew the empty q to n_max empty sets, the size check passed and the rejection verifier ran with q = 0. Now (a) the server asks for candidates and picks the rejection verifier only when --spec-draft-sampling probabilistic is set, and (b) common_speculative_draft cuts q only when it exists and is longer than n_max (so flag on + ngram stays on sample-and-match). Upstream has the same latent bug. Prod (draft-mtp, capped at n_max) never truncated. - m1: no rejection verifier with stateful samplers (mirostat v1/v2, adaptive-p): their state would be updated with the chain's own sample instead of the emitted token. - m3: the trace-only replay re-sample probe is off only for replays of rounds that were actually verified by rejection (per-round slot.spec_round_rejection), not for every T > 0 replay under the flag. - m2 (documented, not changed): with a grammar and grammar_first = false the flag-on verifier preserves norm(mask * chain(p)), while flag off resamples from chain(mask(logits)) on a grammar miss - upstream semantics; the pair gate G4 requires valid JSON, not the same distribution. Re-tested on balkon CPU: test-arg-parser, test-sampling, unit/test_speculative.py 11/11; ids A/B vs the base build: draft-simple flag off == pkg1 (6/6, [spec-ids] identical), ngram-simple (size_m 16, truncations at T 0 and T 0.7) flag off == flag on == pkg1 (6/6, [spec-ids] identical), flag on + mirostat 1/2 == pkg1. (manual port of upstream commit 1fb7ef3)
…7694) [TAG_UP27694] Manual port of upstream 1fb7ef3 ("spec : add probabilistic sampling for simple draft and MTP", ggml-org/llama.cpp#27694); cherry-pick conflicted in common/speculative.{h,cpp} and tools/server/server-context.cpp. Release train 63.5 (U7, R127), v63 candidate. What it does (flag on, request temp > 0): draft-simple / draft-mtp sample the draft from a draft sampler retuned to the request's temp/seed (top_k 10 + temp) and keep the candidate set per drafted token; the server verifies by rejection sampling (common_sampler_sample_and_accept_n_rejection: accept with min(1, p/q), else draw from norm(max(0, p - q)); grammar-aware; the uniform draws come from a separate per-sampler mt19937 so the target's dist RNG stream is untouched). Distribution-exact for the target. Default = greedy. With the flag off the behaviour is byte-identical to the base: - the drafters drop result_q -> argmax draft + per-round reset exactly as before; - upstream's new reset in begin() is gated on the flag (fork deviation); - common_sampler gains an rng member seeded from llama_sampler_get_seed (read-only), used only by the rejection path; - server: the rejection branch needs non-empty spec_draft_q of the draft's size, which only a probabilistic drafter fills. Fork adaptations: - replay: upstream's server_accept_replay is NOT ported; the fork's server_sample_and_accept_replay already re-emits committed tokens without re-sampling, which is what the rejection round needs too (its committed tokens include the residual draw). The trace-only re-sample probe is off for rejection rounds (a kept token is not the target's own sample, it would count as a flip). - the upstream GGML_ASSERT on spec_draft_q/spec_draft sizes became a fall-back to sample-and-match; the n_min rule clears result_q together with result in both drafters. - [TAG_UP29638] EOG rule mirrored in the rejection verifier (no draft token after an accepted EOG). - spec_untune(): a T = 0 request after a probabilistic one gets the default draft sampler back (top_k 10 {TOP_K}, MTP fast path), so p_min reads the same draft probabilities. - draft params result_q/temp/seed are set after the fork's aggregate init (the fork struct has n_attempted/n_kept/keep_short in between). Disk-cache key: unchanged. server_cache_param_canon lists draft fields explicitly and does not include `probabilistic`; cache_compat_measure only runs process() on a temporary speculative object (no draft() call), so the knob enters neither the parameter digest nor the measured payload. Tests (balkon CPU, stories15M MoE + stories15M-q4_0 draft-simple): new pytest test_draft_sampling_probabilistic (T = 0 flag on == greedy, T 0.7 accepts drafts and a fixed seed reproduces, T = 0 after T > 0 greedy again); unit/test_speculative.py 11/11; flag off vs the base build: identical ids, draft counts and [spec-ids] rounds on 3 prompts at T 0 and T 0.7 (seed 4242). The draft-mtp path has no CPU-sized test model: it is exercised by the s1 pair gate. EXACT with the flag off (default); behavioural (distribution-exact) with it on. Review fixes (review-u7: M1, m1, m3; m2/m4 left as is): - M1: flag off was not byte-identical for drafters that fill no candidates (ngram-*, eagle3, dflash) at T > 0 when the draft was truncated to n_max: the truncation grew the empty q to n_max empty sets, the size check passed and the rejection verifier ran with q = 0. Now (a) the server asks for candidates and picks the rejection verifier only when --spec-draft-sampling probabilistic is set, and (b) common_speculative_draft cuts q only when it exists and is longer than n_max (so flag on + ngram stays on sample-and-match). Upstream has the same latent bug. Prod (draft-mtp, capped at n_max) never truncated. - m1: no rejection verifier with stateful samplers (mirostat v1/v2, adaptive-p): their state would be updated with the chain's own sample instead of the emitted token. - m3: the trace-only replay re-sample probe is off only for replays of rounds that were actually verified by rejection (per-round slot.spec_round_rejection), not for every T > 0 replay under the flag. - m2 (documented, not changed): with a grammar and grammar_first = false the flag-on verifier preserves norm(mask * chain(p)), while flag off resamples from chain(mask(logits)) on a grammar miss - upstream semantics; the pair gate G4 requires valid JSON, not the same distribution. Re-tested on balkon CPU: test-arg-parser, test-sampling, unit/test_speculative.py 11/11; ids A/B vs the base build: draft-simple flag off == pkg1 (6/6, [spec-ids] identical), ngram-simple (size_m 16, truncations at T 0 and T 0.7) flag off == flag on == pkg1 (6/6, [spec-ids] identical), flag on + mirostat 1/2 == pkg1. (manual port of upstream commit 1fb7ef3) (cherry picked from commit 116d2a2)
…7694) [TAG_UP27694] Manual port of upstream 1fb7ef3 ("spec : add probabilistic sampling for simple draft and MTP", ggml-org/llama.cpp#27694); cherry-pick conflicted in common/speculative.{h,cpp} and tools/server/server-context.cpp. Release train 63.5 (U7, R127), v63 candidate. What it does (flag on, request temp > 0): draft-simple / draft-mtp sample the draft from a draft sampler retuned to the request's temp/seed (top_k 10 + temp) and keep the candidate set per drafted token; the server verifies by rejection sampling (common_sampler_sample_and_accept_n_rejection: accept with min(1, p/q), else draw from norm(max(0, p - q)); grammar-aware; the uniform draws come from a separate per-sampler mt19937 so the target's dist RNG stream is untouched). Distribution-exact for the target. Default = greedy. With the flag off the behaviour is byte-identical to the base: - the drafters drop result_q -> argmax draft + per-round reset exactly as before; - upstream's new reset in begin() is gated on the flag (fork deviation); - common_sampler gains an rng member seeded from llama_sampler_get_seed (read-only), used only by the rejection path; - server: the rejection branch needs non-empty spec_draft_q of the draft's size, which only a probabilistic drafter fills. Fork adaptations: - replay: upstream's server_accept_replay is NOT ported; the fork's server_sample_and_accept_replay already re-emits committed tokens without re-sampling, which is what the rejection round needs too (its committed tokens include the residual draw). The trace-only re-sample probe is off for rejection rounds (a kept token is not the target's own sample, it would count as a flip). - the upstream GGML_ASSERT on spec_draft_q/spec_draft sizes became a fall-back to sample-and-match; the n_min rule clears result_q together with result in both drafters. - [TAG_UP29638] EOG rule mirrored in the rejection verifier (no draft token after an accepted EOG). - spec_untune(): a T = 0 request after a probabilistic one gets the default draft sampler back (top_k 10 {TOP_K}, MTP fast path), so p_min reads the same draft probabilities. - draft params result_q/temp/seed are set after the fork's aggregate init (the fork struct has n_attempted/n_kept/keep_short in between). Disk-cache key: unchanged. server_cache_param_canon lists draft fields explicitly and does not include `probabilistic`; cache_compat_measure only runs process() on a temporary speculative object (no draft() call), so the knob enters neither the parameter digest nor the measured payload. Tests (balkon CPU, stories15M MoE + stories15M-q4_0 draft-simple): new pytest test_draft_sampling_probabilistic (T = 0 flag on == greedy, T 0.7 accepts drafts and a fixed seed reproduces, T = 0 after T > 0 greedy again); unit/test_speculative.py 11/11; flag off vs the base build: identical ids, draft counts and [spec-ids] rounds on 3 prompts at T 0 and T 0.7 (seed 4242). The draft-mtp path has no CPU-sized test model: it is exercised by the s1 pair gate. EXACT with the flag off (default); behavioural (distribution-exact) with it on. Review fixes (review-u7: M1, m1, m3; m2/m4 left as is): - M1: flag off was not byte-identical for drafters that fill no candidates (ngram-*, eagle3, dflash) at T > 0 when the draft was truncated to n_max: the truncation grew the empty q to n_max empty sets, the size check passed and the rejection verifier ran with q = 0. Now (a) the server asks for candidates and picks the rejection verifier only when --spec-draft-sampling probabilistic is set, and (b) common_speculative_draft cuts q only when it exists and is longer than n_max (so flag on + ngram stays on sample-and-match). Upstream has the same latent bug. Prod (draft-mtp, capped at n_max) never truncated. - m1: no rejection verifier with stateful samplers (mirostat v1/v2, adaptive-p): their state would be updated with the chain's own sample instead of the emitted token. - m3: the trace-only replay re-sample probe is off only for replays of rounds that were actually verified by rejection (per-round slot.spec_round_rejection), not for every T > 0 replay under the flag. - m2 (documented, not changed): with a grammar and grammar_first = false the flag-on verifier preserves norm(mask * chain(p)), while flag off resamples from chain(mask(logits)) on a grammar miss - upstream semantics; the pair gate G4 requires valid JSON, not the same distribution. Re-tested on balkon CPU: test-arg-parser, test-sampling, unit/test_speculative.py 11/11; ids A/B vs the base build: draft-simple flag off == pkg1 (6/6, [spec-ids] identical), ngram-simple (size_m 16, truncations at T 0 and T 0.7) flag off == flag on == pkg1 (6/6, [spec-ids] identical), flag on + mirostat 1/2 == pkg1. (manual port of upstream commit 1fb7ef3) (cherry picked from commit 116d2a2)
…27694) * Make the drafter probabilistic and the target verify by rejection sampling * Drop stale spec_draft_q before drafting * Fallback to argmax sampling for grammar-constrained requests and adding flag for enabling probabilistic draft sampling. Default flag value is greedy. * Support grammar-constrained requests in rejection sampling * Fix - renormalize distribution after masking * copy rng on sampler copy and re-accept drafted tokens on replay * Fix draft sampler sharing the target's rng stream * Simplify the rejection sampler's inputs and move replay to the server * Truncate the draft candidates along with the draft --------- Co-authored-by: praneshgo <[email protected]> Co-authored-by: Pranesh Gonegandla <[email protected]> (cherry picked from commit 1fb7ef3)
Overview
Today the model-based drafters throw away most of what the draft model knows. They run the sampler, discard its result, and take the top candidate, and the target then accepts that token only when its own draw lands on the same one. At temperature 0 that is the best available, since the target also always takes its top token. Above 0, they differ - the target samples while the draft still offers its single safest guess - and acceptance falls away as temperature rises.
This PR adds two things to make this better.
The output distribution is preserved exactly. Accepting with
min(1, p/q)and drawing the remainder fromnorm(max(0, p - q))is the standard construction; the residual cancels the over-delivery on tokens where the draft is more generous than the target. This is same as the mechanism in Leviathan et al.This PR applies to draft_simple and MTP only. Eagle3 is yet to be evaluated and DFlash is experimentally seen not to benefit with these changes. The likely reason for this is structural. DFlash reads every position of its block out of a single forward pass with no re-decode between them, so the positions are predicted jointly rather than conditioned on one another. Substituting a sampled token at one position leaves the rest of the block continuing from a token that was never drafted. The gain at that position is cancelled by the positions after it, which no longer follow from what was drafted — unlike draft-simple and draft-mtp, where each token is re-decoded and the substitution carries forward.
A flag --spec-draft-sampling is added, controlling how the draft is sampled. It takes greedy or probabilistic, defaulting to greedy. This matches vLLM's convention, where draft_sample_method takes the same two values and also defaults to greedy.
I have run sweeps with -bs enabled and disabled along with the changes in this PR. Based on the logs obtained, this PR does not affect the functionality of backend sampling, which ensures that the target sampling chain already happens on the GPU. With -bs on, I see the same accepted length and 1-2% change in throughput, which is consistent with what is observed on the master branch with -bs enabled.
Performance
Two machines, eight model configurations each, 11 temperatures from 0.0 to 1.0. Every run is 12 prompts of 256 tokens at --spec-draft-n-max 3, the shipped default.
Temperature 0.0 is the control. Both arms emit identical tokens there, so accepted length reads exactly +0.00% - the throughput figure on that row is the timing noise floor for that model.
RTX 5090
Llama-3.1-8B + 3B-Q8_0 -
draft-simpleLlama-3.1-8B + 3B-Q4_K_M -
draft-simpleLlama-3.1-8B + 3B-IQ2_XS -
draft-simpleQwen3.5-4B -
draft-mtpQwen3.5-9B -
draft-mtpOrnith-1.5-9B -
draft-mtpQwen3.6-27B -
draft-mtpQwen3.6-35B-A3B -
draft-mtpDGX Spark
Llama-3.1-8B + 3B-Q8_0 -
draft-simpleLlama-3.1-8B + 3B-Q4_K_M -
draft-simpleLlama-3.1-8B + 3B-IQ2_XS -
draft-simpleQwen3.5-4B -
draft-mtpQwen3.5-9B -
draft-mtpOrnith-1.5-9B -
draft-mtpQwen3.6-27B -
draft-mtpQwen3.6-35B-A3B -
draft-mtpRequirements