Repository navigation
sampling : stop accepting draft tokens after an EOG in the rejection verifier - #292
Conversation
Thank you for the reproduction and for the patch. This diff is the fix proposed in #290. I read it against
This is from code reading only. I did not build or run the patch. Your result (9 of 40 follow-up turns re-read, 0 with Whether this goes in here first or upstream first is for the maintainers to decide. |
…verifier common_sampler_sample_and_accept_n stops at an end-of-generation token when more draft follows, so no drafted token after it stays in the context. The rejection verifier common_sampler_sample_and_accept_n_rejection had no such stop: with --spec-draft-sampling probabilistic the drafted tokens after an EOG were accepted and kept in the slot, and the next turn of the conversation re-read the previous answer (halo-box#290, reported with the fix by cellardoorio). Assisted-by: Claude Fable 5.1 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
dzannotti
left a comment
There was a problem hiding this comment.
Verdict
The fix is correct, and it removes the re-reads from #290 on both backends. It now needs one maintainer approval, because it changes the speculative verifier.
Direction
Accept. The change copies the stop that the greedy verifier already has, and it costs 5 lines in an upstream function. The same gap exists on upstream master, so please also open it against halo-box/llama.cpp, where upstream changes are staged. We can carry it here until it comes back through a sync.
Asks
- Should fix:
tests/test-speculative-rejection-sampling.cppcan test this change. The test already loads a generated model with a context and callscommon_sampler_sample_and_accept_n_rejectiondirectly. A kv override oftokenizer.ggml.eos_token_idmakes any token an EOG. The patch in the details block adds such a case. It fails on master (all 3 drafted tokens and a bonus token come back) and passes with this PR. Please add it, or an equivalent test, to this PR. - Should fix: open the same commit against halo-box/llama.cpp (see Direction), and link it here.
Correctness
PASS on Vulkan and ROCm. The spec unit tests (test-spec-mtp-pcum, test-draft-vocab, test-speculative-rejection-sampling, test-mtp-draft-vocab) pass on both sides. The new EOG case fails on master and passes with the PR. At temperature 0 the rejection verifier does not run, and the output is byte-identical to master. With --spec-draft-sampling greedy, all 60 answers of the multi-turn workload are byte-identical to master. The issue reproduces on master and is gone with the PR (table below).
Performance
| backend | master: re-read turns / 40 | PR: re-read turns / 40 | stray tokens per request, master | stray tokens per request, PR |
|---|---|---|---|---|
| Vulkan | 7 (prompt_n 45 to 185) | 0 | -1:13, 0:15, +1:20, +2:12 | -1:45, 0:15 |
| ROCm | 8 (prompt_n 41 to 193) | 0 | -1:20, 0:11, +1:16, +2:13 | -1:44, 0:16 |
A normal follow-up turn reads 18 to 23 prompt tokens. With the draft at temperature 0 (807 to 62145 prompt tokens, 2 rounds per side), TTFT and decode tok/s differ from master by 0.7% or less on both backends, inside the run-to-run spread, and acceptance is the same. At temperature 0 the changed code does not run, so we expect no difference. The full numbers are in the details block.
Verification
Strix Halo (gfx1151), Vulkan (RADV) and ROCm. We tested the PR merged into master f2230a8 (the PR was 5 commits behind, and the merge is clean) against master f2230a8. Master has since moved to 4032d8f. The PR still merges clean there, and the new commits do not touch the files of this PR or the code it calls. Model: Qwen3.8-Flash-Next (qwen4exp, TQ2_0) with the shared Q4_K_M MTP draft, --spec-type draft-mtp --spec-draft-n-max 3.
Not tested
Other models, --spec-draft-n-max above 3, -np above 1, NVIDIA, and the server pytest suite (not available here).
Thanks for the careful reproduction.
Review made with AI on behalf of the strix-llama.cpp maintainers.
Full verification (for reproduction and agents)
Environment
- Ubuntu 26.04.1, kernel 7.0.0-43, AMD Ryzen AI Max+ 395 (gfx1151), 128 GB.
- ROCm 10.1.0 (hipconfig 7.16.26385), AMD clang 24.0.0git d6f6cb69.
- Mesa 26.0.8 (RADV STRIX_HALO).
- cmake 4.2.3, gcc 15.2.0, Ninja.
Compared
- master tip: f2230a8
- PR head: 4b43cfb
- merge base: f5e7a5d (5 commits behind master)
- local merge (PR into master, not pushed): 1aedd14fcd184b08586f0e38aebcfe2771fdbcfc, clean, the same +7 lines as the PR diff.
- master later moved to 4032d8f (#291 CUDA concat, #298 CI fixes, a Vulkan graph_optimize change). The PR merges clean into it, and none of those commits touch
common/sampling.cpp, the server, or the speculative tests. - Both trees had the EOG test patch below applied locally, so that the same test ran on both sides.
Build
cmake -G Ninja -S <tree> -B <tree>/build-hip -DCMAKE_BUILD_TYPE=Release -DGGML_HIP=ON -DGGML_VULKAN=OFF -DGPU_TARGETS=gfx1151 -DCMAKE_HIP_COMPILER=$(hipconfig -l)/clang -DCMAKE_PREFIX_PATH=$(hipconfig -R)
cmake -G Ninja -S <tree> -B <tree>/build-vk -DCMAKE_BUILD_TYPE=Release -DGGML_VULKAN=ON -DGGML_HIP=OFF
cmake --build <build> -j --target llama-server test-speculative-rejection-sampling test-spec-mtp-pcum test-draft-vocab test-mtp-draft-vocab test-llama-archs
Models
- Target: agentionai/Qwen3.8-Flash-Next-Gyro-GGUF,
Qwen3.8-Flash-Next-Gyro-M-TQ2_0.gguf, sha256 7aa36d15131d255179ab6c87fa9c9f81a0b541fc9e81e959d4c3e29eb20feb5f. Loaded with-lm none -lzm on-direct. - Draft: unsloth/Qwen3.8-Flash-Next-GGUF,
MTP/mtp-Qwen3.8-Flash-Next-shared-Q4_K_M.gguf, sha256 f521868a9e143718bef513772f6e04d9642551e362cf2439636d2abdbd149dfc. test-mtp-draft-vocabonly:Qwen3.8-27B-UD-Q4_K_XL.gguf(qwen35 with an MTP head), sha256 3f227079003add2511437e5b1e94812e363385225bf6a9b47b0054a72bc8b01e.test-speculative-rejection-sampling: the generated llama test model (ctest fixture).
Commands
Unit tests, per side and backend:
ctest --test-dir <build> -R 'spec-mtp-pcum|draft-vocab|speculative' --output-on-failure
<build>/bin/test-mtp-draft-vocab -m <27B model>
Server, per side and backend (one fresh server per arm, arms in the order master/PR/PR/master):
llama-server --jinja -m <target> -ngl 99 -fa on -ctk f16 -ctv f16 -lm none -lzm on-direct -np 1 -c 32768 -b 2048 -ub 1024 \
-md <draft> -ngld 99 --spec-type draft-mtp --spec-draft-n-max 3 --spec-draft-sampling probabilistic|greedy
Multi-turn workload: 20 conversations of 3 turns each on /v1/chat/completions, 10 short questions (thinking off for conversations 0-9, on for 10-19), follow-ups "Can you say that in one short sentence?" and "Thanks. Now give me one related fact.", each turn sends back the previous answer with its reasoning_content, temperature 1.0, top_p 0.95, top_k 20, seed 1000+conversation, max_tokens 600. A re-read is a follow-up turn whose timings.prompt_n is above the normal 18 to 23. Stray tokens per request are n_tokens from the server's stop processing line minus cache_n + prompt_n + predicted_n.
Temperature-0 check, on the probabilistic servers: two /completion requests, the first 6000 bytes of the four tests/corpus/correctness-*.txt files joined, n_predict 256, temperature 0, cache_prompt false.
Draft prefill and decode: scripts/bench-spec-prefill.sh from master, with --spec-draft-sampling probabilistic -c 69632, prompts cut from the four corpora joined (repeated for the longest), 807 / 13946 / 39624 / 62145 tokens. The script on master passes the request as a curl -d argument, which fails above about 128 KB, so we changed it to post the same JSON from a file (--data-binary @file). Rounds alternate master and PR.
Results
Vulkan, multi-turn workload (60 requests per arm, all finish_reason: stop):
| arm | re-read turns / 40 | re-read prompt_n | stray tokens per request | draft accepted |
|---|---|---|---|---|
| master, probabilistic | 7 | 45, 69, 71, 73, 105, 161, 185 | -1:13, 0:15, +1:20, +2:12 | 2226/3039 (73.2%) |
| PR, probabilistic | 0 | - (max 23) | -1:45, 0:15 | 2143/3006 (71.3%) |
| master, greedy | 0 | - | -1:40, 0:20 | 2072/3396 (61.0%) |
| PR, greedy | 0 | - | -1:40, 0:20 | 2072/3396 (61.0%) |
ROCm, multi-turn workload:
| arm | re-read turns / 40 | re-read prompt_n | stray tokens per request | draft accepted |
|---|---|---|---|---|
| master, probabilistic | 8 | 41, 45, 68, 74, 91, 106, 165, 193 | -1:20, 0:11, +1:16, +2:13 | 2099/2889 (72.7%) |
| PR, probabilistic | 0 | - (max 23) | -1:44, 0:16 | 2061/2952 (69.8%) |
| master, greedy | 0 | - | -1:40, 0:20 | 1845/2862 (64.5%) |
| PR, greedy | 0 | - | -1:40, 0:20 | 1845/2862 (64.5%) |
Temperature 0: master and PR output identical on both requests and both backends; draft 207, accepted 186 on every request.
Greedy arms: all 60 answers (content and reasoning) identical between master and PR on each backend.
bench-spec-prefill (median TTFT of 3 requests, mean tg, acceptance), one entry per round:
Vulkan:
| prompt tokens | master TTFT ms | PR TTFT ms | master tg tok/s | PR tg tok/s | master accept | PR accept |
|---|---|---|---|---|---|---|
| 807 | 1208, 1205 | 1204, 1200 | 52.14, 52.52 | 52.68, 52.64 | 83, 83% | 83, 83% |
| 13946 | 19146, 19130 | 19113, 19147 | 43.86, 43.93 | 43.93, 43.97 | 73, 73% | 73, 73% |
| 39624 | 53150, 53316 | 53170, 53351 | 45.36, 45.37 | 45.34, 45.37 | 77, 77% | 77, 77% |
| 62145 | 85609, 85657 | 85720, 85650 | 46.72, 46.85 | 46.67, 46.77 | 82, 82% | 82, 82% |
ROCm:
| prompt tokens | master TTFT ms | PR TTFT ms | master tg tok/s | PR tg tok/s | master accept | PR accept |
|---|---|---|---|---|---|---|
| 807 | 1352, 1363 | 1363, 1358 | 40.58, 40.42 | 40.51, 40.48 | 68, 68% | 68, 68% |
| 13946 | 20005, 20072 | 20025, 20063 | 38.87, 38.69 | 38.86, 38.83 | 72, 72% | 72, 72% |
| 39624 | 55015, 55111 | 55182, 55153 | 33.45, 33.44 | 33.34, 33.41 | 58, 58% | 58, 58% |
| 62145 | 88544, 88751 | 88673, 88708 | 41.7, 41.62 | 41.56, 41.65 | 82, 82% | 82, 82% |
Correctness
| check | method | result |
|---|---|---|
| spec unit tests | ctest spec-mtp-pcum, draft-vocab, speculative; test-mtp-draft-vocab |
pass on both sides, both backends, except the new EOG case on master (expected) |
| regression test for the fix | EOG case below | master FAIL (4 tokens returned: 0 1 2 115), PR PASS, both backends |
| target output at temp 0, same draft settings | 2 requests, 256 tokens | byte-identical, both backends |
| greedy draft path unchanged | 60-request workload, --spec-draft-sampling greedy |
byte-identical, same acceptance, both backends |
| claim: no re-read with probabilistic drafts | 60-request workload | reproduced, both backends |
| acceptance, tok/s, TTFT at depth | bench-spec-prefill, 4 depths | within spread, see Results |
| logits / KLD / PPL | not run | the change only affects which drafted tokens are kept after an accepted EOG; no logits change |
Findings in full
common/sampling.cpp:831: the stop matches the greedy verifier (common/sampling.cpp:728). When it fires,i < draft.size(), so no bonus token is sampled after the EOG. The server sees the same[d0 .. EOG]shape that the greedy stop already gives, so rollback,common_speculative_acceptand the stats work as for greedy.- A trailing drafted EOG (last draft position) is still accepted with a bonus token, as in the greedy verifier. The server stops at the EOG and drops the bonus token.
- The rejected path already ends the loop after its resampled token, so a resampled EOG is already last.
- With
ignore_eosthe EOG has probability 0 and is never accepted, so the stop never fires. - The PR description says the sampler tests have no vocab with EOG tokens and no context.
test-speculative-rejection-samplinghas both: the patch below sets the EOS id with a kv override.
EOG test patch (applies to master f2230a8 and to the PR head):
--- a/tests/test-speculative-rejection-sampling.cpp
+++ b/tests/test-speculative-rejection-sampling.cpp
@@ -6,6 +6,7 @@
#include <cmath>
+#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <optional>
#include <random>
@@ -163,6 +164,79 @@
return 0;
}
+// A drafted EOG that is accepted ends the verification: the draft tokens after it are never
+// output, so they must not be accepted into the context either.
+static int test_speculative_rejection_stops_at_eog(common_params params) {
+ const llama_token eog = 0;
+
+ llama_model_kv_override kvo = {};
+ std::snprintf(kvo.key, sizeof(kvo.key), "%s", "tokenizer.ggml.eos_token_id");
+ kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
+ kvo.val_i64 = eog;
+ params.kv_overrides = { kvo, {} };
+ params.sampling.backend_sampling = false;
+
+ auto llama_init = common_init_from_params(params);
+
+ auto * model_tgt = llama_init->model();
+ auto * ctx_tgt = llama_init->context();
+ if (!model_tgt || !ctx_tgt) {
+ LOG_ERR("failed to initialize target model and context\n");
+ return 1;
+ }
+
+ const llama_vocab * vocab = llama_model_get_vocab(model_tgt);
+ if (!llama_vocab_is_eog(vocab, eog)) {
+ LOG_ERR("token %d is not an EOG token after the override\n", eog);
+ return 1;
+ }
+
+ const llama_tokens prompt = { 1, 2, 3, 1, 2 };
+ common_batch batch = common_batch_get_one(ctx_tgt, prompt);
+ if (llama_process(ctx_tgt, LLAMA_PROCESS_TYPE_DECODE, batch.get()) != 0) {
+ LOG_ERR("failed to decode the test prompt\n");
+ return 1;
+ }
+
+ common_params_sampling sampling;
+ sampling.seed = 18;
+ sampling.samplers = { COMMON_SAMPLER_TYPE_TEMPERATURE };
+ sampling.temp = 1.0f;
+
+ common_sampler_ptr smpl(common_sampler_init(model_tgt, sampling));
+ if (!smpl) {
+ LOG_ERR("failed to initialize target sampler\n");
+ return 1;
+ }
+
+ // q gives the EOG almost no mass, so p >= q and the drafted EOG is always accepted
+ const int n_vocab = llama_vocab_n_tokens(vocab);
+ std::vector<llama_token_data> q(n_vocab);
+ for (int i = 0; i < n_vocab; ++i) {
+ q[i] = { i, 0.0f, i == eog ? 1e-9f : 1.0f/(n_vocab - 1) };
+ }
+
+ const llama_tokens draft = { eog, 1, 2 };
+ const std::vector<std::vector<llama_token_data>> draft_q = { q, q, q };
+ const std::vector<int> idxs = { -1, -1, -1, -1 };
+
+ const std::vector<llama_token> result =
+ common_sampler_sample_and_accept_n_rejection(smpl.get(), ctx_tgt, idxs, draft, draft_q, false);
+
+ if (result.size() != 1 || result[0] != eog) {
+ LOG_ERR("expected only the drafted EOG to be accepted, got %zu tokens:", result.size());
+ for (const auto id : result) {
+ LOG_ERR(" %d", id);
+ }
+ LOG_ERR("\n");
+ return 1;
+ }
+
+ LOG("drafted EOG accepted and verification stopped there\n");
+
+ return 0;
+}
+
struct parsed_args {
int n_trials;
std::vector<char *> argv;
@@ -217,7 +291,10 @@
llama_backend_init();
- const int result = test_speculative_rejection_sampling(params, parsed->n_trials);
+ int result = test_speculative_rejection_sampling(params, parsed->n_trials);
+ if (result == 0) {
+ result = test_speculative_rejection_stops_at_eog(params);
+ }
if (result == 0) {
LOG("\nAll tests passed.\n");
} else {Claims
- "Drafted tokens after an EOG stay in the slot with probabilistic drafts, and the next turn re-reads the previous answer": reproduced on master (7/40 re-reads on Vulkan, 8/40 on ROCm, stray +1/+2 tokens), gone with the PR.
- "With the change the histogram has greedy's shape": reproduced (-1/0 only on both backends).
- "The greedy verifier and the greedy default are untouched": confirmed, byte-identical output.
Not tested
- Other target models and drafts (the author's UD-IQ4_XS files),
--spec-draft-n-maxabove 3, adaptive draft length,-npabove 1. - NVIDIA and other non-gfx1151 hardware.
- The server pytest suite (not available on our machine).
- Logits, KLD and PPL (not affected by this change).
dzannotti
left a comment
There was a problem hiding this comment.
Approving, as discussed in the review above. The regression test and an upstream PR to halo-box/llama.cpp are still welcome as follow-ups, but they do not block this merge. Thank you.
Review made with AI on behalf of the strix-llama.cpp maintainers.
Overview
Fixes #290. With
--spec-draft-sampling probabilistic, drafted tokens that follow an end-of-generation token were accepted by the rejection verifiercommon_sampler_sample_and_accept_n_rejectionand stayed in the slot. They are never sent to the client, but on the next turn of the conversation they do not match the new prompt, so the server rolls back and reads the previous answer again. The greedy verifiercommon_sampler_sample_and_accept_nalready stops at an EOG when more draft follows; this adds the same stop to the rejection verifier, as proposed by @cellardoorio in the issue. 8 lines incommon/sampling.cpp.The function is upstream code (ggml-org/llama.cpp PR 27694) and the gap exists on upstream master too, so by CONTRIBUTING.md this is a general fix. It is opened here because the fork's MTP users with probabilistic drafts are the ones hit, the diff is small enough to carry until the next upstream merge, and the issue is here. If you would rather see it go upstream first, say so and I will close this and open it there under upstream's rules.
Measurements
This is a correctness fix, not a throughput change, so
llama-benchcannot show it. The evidence is token counts from the server's owntimingsand itsstop processing: n_tokens = Nlog line.Workload: 20 three-turn conversations per server (10 short questions x 2, thinking on for half, seeds 1000 + conversation, server sampling defaults, 400-token cap),
/v1/chat/completionswith each turn sending back the previous answer and itsreasoning_content. Server:-ngl 999 -fa on --load-mode none --lazy-mode on-direct -np 1 -c 32768 -b 2048 -ub 1024 -ctk f16 -ctv f16 --jinja --spec-type draft-mtp --spec-draft-n-max 3, each arm on a freshly loaded server, one session. A re-read is a follow-up turn whosetimings.prompt_nis more than the new user message plus template tokens (10 to 20 here); stray tokens aren_tokensfrom the stop line minuscache_n + prompt_n + predicted_n.--spec-draft-sampling probabilisticgreedy(control)probabilisticEvery one of the 9 re-reads followed a request that left +2 stray tokens (10 such requests, 9 re-read); none of the +1 cases re-read, matching the issue's observation. With the change the histogram has greedy's shape.
Correctness: the change only removes the acceptance of draft tokens after an EOG, which are never output; the greedy verifier and the
--spec-draft-sampling greedydefault are untouched. All 120 answers in the three arms ended withfinish_reason: stop.Not run:
llama-perplexity(probabilistic drafts change the sampled tokens by construction and the greedy path is untouched),llama-bench,llama-benchy, Vulkan, other models. No regression test added: the sampler tests have no vocab with EOG tokens and no context; the reproduction above is the test, and I can share the client script on request.Additional information
Reported with the diagnosis and the fix by @cellardoorio in #290; this PR builds and measures it. The commit message credits the report.
AI usage: the patch, the reproduction and this text were produced by an AI agent (Claude Fable 5.1) under my direction, on my box; I reviewed them and own the result.
🤖 Generated with Claude Code