Skip to content

Commit dd373dd

Browse files
llama: fix error on bad grammar (#12628)
1 parent 5d01670 commit dd373dd

File tree

3 files changed

+12
-0
lines changed

3 files changed

+12
-0
lines changed

Diff for: common/sampling.cpp

+3
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,9 @@ struct common_sampler * common_sampler_init(const struct llama_model * model, co
208208
trigger_patterns_c.data(), trigger_patterns_c.size(),
209209
trigger_tokens.data(), trigger_tokens.size())
210210
: llama_sampler_init_grammar(vocab, params.grammar.c_str(), "root");
211+
if (!grmr) {
212+
return nullptr;
213+
}
211214
}
212215

213216
auto * result = new common_sampler {

Diff for: include/llama.h

+4
Original file line numberDiff line numberDiff line change
@@ -1265,6 +1265,10 @@ extern "C" {
12651265
float tau,
12661266
float eta);
12671267

1268+
/// @details Intializes a GBNF grammar, see grammars/README.md for details.
1269+
/// @param vocab The vocabulary that this grammar will be used with.
1270+
/// @param grammar_str The production rules for the grammar, encoded as a string. Returns an empty grammar if empty. Returns NULL if parsing of grammar_str fails.
1271+
/// @param grammar_root The name of the start symbol for the grammar.
12681272
LLAMA_API struct llama_sampler * llama_sampler_init_grammar(
12691273
const struct llama_vocab * vocab,
12701274
const char * grammar_str,

Diff for: src/llama-sampling.cpp

+5
Original file line numberDiff line numberDiff line change
@@ -1477,6 +1477,7 @@ static struct llama_sampler * llama_sampler_grammar_clone(const struct llama_sam
14771477
const auto * ctx = (const llama_sampler_grammar *) smpl->ctx;
14781478

14791479
auto * result = llama_sampler_init_grammar_impl(ctx->vocab, nullptr, nullptr, false, nullptr, 0, nullptr, 0, nullptr, 0);
1480+
GGML_ASSERT(result);
14801481

14811482
// copy the state
14821483
{
@@ -1548,6 +1549,10 @@ static struct llama_sampler * llama_sampler_init_grammar_impl(
15481549
/* .grammar_root = */ grammar_root,
15491550
/* .grammar = */ llama_grammar_init_impl(vocab, grammar_str, grammar_root, lazy, trigger_patterns, num_trigger_patterns, trigger_tokens, num_trigger_tokens),
15501551
};
1552+
if (!ctx->grammar) {
1553+
delete ctx;
1554+
return nullptr;
1555+
}
15511556
} else {
15521557
*ctx = {
15531558
/* .vocab = */ vocab,

0 commit comments

Comments
 (0)