Skip to content

Commit 55c6fd9

Browse files
committed
common : stop accepting draft tokens at EOG
1 parent 4364bf7 commit 55c6fd9

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

‎common/sampling.cpp‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,8 @@ std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sample
681681
std::vector<llama_token> result;
682682
result.reserve(idxs.size());
683683

684+
const llama_vocab * vocab = llama_model_get_vocab(llama_get_model(ctx));
685+
684686
size_t i = 0;
685687
for (; i < draft.size(); i++) {
686688
const llama_token id = common_sampler_sample(gsmpl, ctx, idxs[i], grammar_first);
@@ -689,7 +691,9 @@ std::vector<llama_token> common_sampler_sample_and_accept_n(struct common_sample
689691

690692
result.push_back(id);
691693

692-
if (draft[i] != id) {
694+
// the draft tokens after an EOG are never output, do not accept them into the context
695+
// a trailing EOG is accepted, since the draft of a checkpoint replay ends with the last target token
696+
if (draft[i] != id || (llama_vocab_is_eog(vocab, id) && i + 1 < draft.size())) {
693697
break;
694698
}
695699
}

‎tools/server/tests/unit/test_speculative.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,3 +203,25 @@ def test_multi_requests_parallel(n_slots: int, n_requests: int):
203203
for res in results:
204204
assert res.status_code == 200
205205
assert match_regex("(wise|kind|owl|answer)+", res.body["content"])
206+
207+
208+
def test_no_draft_tokens_cached_after_eog():
209+
global server
210+
# ngram-simple drafts what follows the answer in the prompt: EOG tokens
211+
server.model_draft = None
212+
server.spec_type = "ngram-simple"
213+
server.start()
214+
context = server.make_request("POST", "/tokenize", data={"content": "Once upon a time, there was a little girl named Lily. She loved to play in the park with her friends."}).body["tokens"]
215+
answer = server.make_request("POST", "/tokenize", data={"content": " The end."}).body["tokens"]
216+
eog = server.make_request("POST", "/tokenize", data={"content": "</s>", "parse_special": True}).body["tokens"]
217+
# the grammar forces the answer, then only EOG tokens can be sampled
218+
res = server.make_request("POST", "/completion", data={
219+
"prompt": context + answer + eog * 16 + context,
220+
"grammar": "root ::= " + " ".join(f"<[{t}]>" for t in answer),
221+
"n_predict": 64,
222+
})
223+
assert res.status_code == 200
224+
assert res.body["stop_type"] == "eos"
225+
assert res.body["timings"]["draft_n_accepted"] > 0
226+
# neither the EOG token nor the draft tokens after it may stay in the context
227+
assert res.body["tokens_cached"] == res.body["tokens_evaluated"] + res.body["tokens_predicted"] - 1

0 commit comments

Comments
 (0)