Skip to content

Commit 9217721

Browse files
authored
speculative : add grammar support (ggml-org#2991)
* speculative : add grammar support * grammars : add json_arr.gbnf * grammar : add comments to new grammar file * grammar : remove one nested level * common : warm-up with 2 tokens - seems to work better * speculative : print draft token pieces * speculative : reuse grammar parser + better logs and comments * speculative : avoid grammar_mem * make : fix speculative build
1 parent 2ba85c8 commit 9217721

File tree

6 files changed

+126
-13
lines changed

6 files changed

+126
-13
lines changed

Makefile

+1-1
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,7 @@ baby-llama: examples/baby-llama/baby-llama.cpp ggml.o llama.o common.o $(OBJS)
495495
beam-search: examples/beam-search/beam-search.cpp build-info.h ggml.o llama.o common.o $(OBJS)
496496
$(CXX) $(CXXFLAGS) $(filter-out %.h,$^) -o $@ $(LDFLAGS)
497497

498-
speculative: examples/speculative/speculative.cpp build-info.h ggml.o llama.o common.o $(OBJS)
498+
speculative: examples/speculative/speculative.cpp build-info.h ggml.o llama.o common.o grammar-parser.o $(OBJS)
499499
$(CXX) $(CXXFLAGS) $(filter-out %.h,$^) -o $@ $(LDFLAGS)
500500

501501
ifdef LLAMA_METAL

common/common.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -772,7 +772,7 @@ std::tuple<struct llama_model *, struct llama_context *> llama_init_from_gpt_par
772772
{
773773
LOG("warming up the model with an empty run\n");
774774

775-
const std::vector<llama_token> tmp = { llama_token_bos(lctx), };
775+
const std::vector<llama_token> tmp = { llama_token_bos(lctx), llama_token_eos(lctx), };
776776
llama_eval(lctx, tmp.data(), tmp.size(), 0, params.n_threads);
777777
llama_reset_timings(lctx);
778778
}

examples/speculative/speculative.cpp

+69-11
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
#include "common.h"
88
#include "llama.h"
9+
#include "grammar-parser.h"
910

1011
#include <cmath>
1112
#include <cstdio>
@@ -109,16 +110,35 @@ int main(int argc, char ** argv) {
109110
// used to determine end of generation
110111
bool has_eos = false;
111112

113+
// grammar stuff
114+
struct llama_grammar * grammar_dft = NULL;
115+
struct llama_grammar * grammar_tgt = NULL;
116+
117+
grammar_parser::parse_state parsed_grammar;
118+
119+
// if requested - load the grammar, error checking is omitted for brevity
120+
if (!params.grammar.empty()) {
121+
parsed_grammar = grammar_parser::parse(params.grammar.c_str());
122+
// will be empty (default) if there are parse errors
123+
if (parsed_grammar.rules.empty()) {
124+
return 1;
125+
}
126+
127+
std::vector<const llama_grammar_element *> grammar_rules(parsed_grammar.c_rules());
128+
grammar_tgt = llama_grammar_init(grammar_rules.data(), grammar_rules.size(), parsed_grammar.symbol_ids.at("root"));
129+
}
130+
112131
const auto t_dec_start = ggml_time_us();
113132

114133
while (true) {
115134
LOG("drafted: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx_dft, drafted));
116135

117-
// sample from the drafted tokens if any
118136
int i_dft = 0;
119137
while (true) {
120-
const llama_token id = llama_sample_token(ctx_tgt, NULL, NULL, params, last_tokens, candidates, i_dft);
138+
// sample from the target model
139+
const llama_token id = llama_sample_token(ctx_tgt, NULL, grammar_tgt, params, last_tokens, candidates, i_dft);
121140

141+
// remember which tokens were sampled - used for repetition penalties during sampling
122142
last_tokens.erase(last_tokens.begin());
123143
last_tokens.push_back(id);
124144

@@ -134,8 +154,9 @@ int main(int argc, char ** argv) {
134154

135155
++n_predict;
136156

157+
// check if the draft matches the target
137158
if (i_dft < (int) drafted.size() && id == drafted[i_dft]) {
138-
LOG("drafted token %d accepted\n", id);
159+
LOG("the sampled target token matches the %dth drafted token (%d, '%s') - accepted\n", i_dft, id, token_str.c_str());
139160
++n_accept;
140161
++n_past_tgt;
141162
++n_past_dft;
@@ -145,6 +166,14 @@ int main(int argc, char ** argv) {
145166
}
146167

147168
// the drafted token was rejected or we are out of drafted tokens
169+
170+
if (i_dft < (int) drafted.size()) {
171+
LOG("the %dth drafted token (%d, '%s') does not match the sampled target token (%d, '%s') - rejected\n",
172+
i_dft, drafted[i_dft], llama_token_to_piece(ctx_dft, drafted[i_dft]).c_str(), id, token_str.c_str());
173+
} else {
174+
LOG("out of drafted tokens\n");
175+
}
176+
148177
llama_eval(ctx_dft, &id, 1, n_past_dft, params.n_threads);
149178
++n_past_dft;
150179

@@ -158,7 +187,16 @@ int main(int argc, char ** argv) {
158187
break;
159188
}
160189

161-
// sample n_draft tokens from the draft model picking the best token
190+
if (grammar_tgt) {
191+
if (grammar_dft) {
192+
llama_grammar_free(grammar_dft);
193+
}
194+
grammar_dft = llama_grammar_copy(grammar_tgt);
195+
196+
LOG("copied target grammar to draft grammar\n");
197+
}
198+
199+
// sample n_draft tokens from the draft model using greedy decoding
162200
int n_past_cur = n_past_dft;
163201
for (int i = 0; i < n_draft; ++i) {
164202
float * logits = llama_get_logits(ctx_dft);
@@ -170,32 +208,48 @@ int main(int argc, char ** argv) {
170208

171209
llama_token_data_array cur_p = { candidates.data(), candidates.size(), false };
172210

211+
if (grammar_dft != NULL) {
212+
llama_sample_grammar(ctx_dft, &cur_p, grammar_dft);
213+
}
214+
173215
// computes softmax and sorts the candidates
174216
llama_sample_softmax(ctx_dft, &cur_p);
175217

176218
for (int i = 0; i < 3; ++i) {
177-
LOG(" - draft candidate %d: %d (%.3f)\n", i, cur_p.data[i].id, cur_p.data[i].p);
219+
LOG(" - draft candidate %3d: %6d (%8.3f) '%s'\n", i, cur_p.data[i].id, cur_p.data[i].p, llama_token_to_piece(ctx_dft, cur_p.data[i].id).c_str());
178220
}
179221

180-
// too low probability, stop drafting
222+
// TODO: better logic?
181223
if (cur_p.data[0].p < 2*cur_p.data[1].p) {
224+
LOG("stopping drafting, probability too low: %.3f < 2*%.3f\n", cur_p.data[0].p, cur_p.data[1].p);
182225
break;
183226
}
184227

185-
drafted.push_back(cur_p.data[0].id);
228+
// drafted token
229+
const llama_token id = cur_p.data[0].id;
230+
231+
drafted.push_back(id);
186232
++n_drafted;
187233

188-
if (i < n_draft - 1) {
189-
// evaluate the drafted token on the draft model
190-
llama_eval(ctx_dft, &drafted.back(), 1, n_past_cur, params.n_threads);
191-
++n_past_cur;
234+
// no need to evaluate the last drafted token, since we won't use the result
235+
if (i == n_draft - 1) {
236+
break;
237+
}
238+
239+
// evaluate the drafted token on the draft model
240+
llama_eval(ctx_dft, &drafted.back(), 1, n_past_cur, params.n_threads);
241+
++n_past_cur;
242+
243+
if (grammar_dft != NULL) {
244+
llama_grammar_accept_token(ctx_dft, grammar_dft, id);
192245
}
193246
}
194247

195248
// evaluate the target model on the drafted tokens
196249
llama_eval(ctx_tgt, drafted.data(), drafted.size(), n_past_tgt, params.n_threads);
197250
++n_past_tgt;
198251

252+
// the first token is always proposed by the traget model before the speculation loop
199253
drafted.erase(drafted.begin());
200254
}
201255

@@ -226,6 +280,10 @@ int main(int argc, char ** argv) {
226280
llama_free(ctx_dft);
227281
llama_free_model(model_dft);
228282

283+
if (grammar_dft != NULL) {
284+
llama_grammar_free(grammar_dft);
285+
llama_grammar_free(grammar_tgt);
286+
}
229287
llama_backend_free();
230288

231289
fprintf(stderr, "\n\n");

grammars/json_arr.gbnf

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# This is the same as json.gbnf but we restrict whitespaces at the end of the root array
2+
# Useful for generating JSON arrays
3+
4+
root ::= arr
5+
value ::= object | array | string | number | ("true" | "false" | "null") ws
6+
7+
arr ::=
8+
"[\n" ws (
9+
value
10+
(",\n" ws value)*
11+
)? "]"
12+
13+
object ::=
14+
"{" ws (
15+
string ":" ws value
16+
("," ws string ":" ws value)*
17+
)? "}" ws
18+
19+
array ::=
20+
"[" ws (
21+
value
22+
("," ws value)*
23+
)? "]" ws
24+
25+
string ::=
26+
"\"" (
27+
[^"\\] |
28+
"\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes
29+
)* "\"" ws
30+
31+
number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws
32+
33+
# Optional space: by convention, applied in this grammar after literal chars when allowed
34+
ws ::= ([ \t\n] ws)?

llama.cpp

+19
Original file line numberDiff line numberDiff line change
@@ -3850,6 +3850,25 @@ void llama_grammar_free(struct llama_grammar * grammar) {
38503850
delete grammar;
38513851
}
38523852

3853+
struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
3854+
llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
3855+
3856+
// redirect elements in stacks to point to new rules
3857+
for (size_t is = 0; is < result->stacks.size(); is++) {
3858+
for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
3859+
for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
3860+
for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
3861+
if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
3862+
result->stacks[is][ie] = &result->rules[ir0][ir1];
3863+
}
3864+
}
3865+
}
3866+
}
3867+
}
3868+
3869+
return result;
3870+
}
3871+
38533872
//
38543873
// sampling
38553874
//

llama.h

+2
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,8 @@ extern "C" {
410410

411411
LLAMA_API void llama_grammar_free(struct llama_grammar * grammar);
412412

413+
LLAMA_API struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar);
414+
413415
//
414416
// Sampling functions
415417
//

0 commit comments

Comments
 (0)