Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- fix(grammar): enforce array length limits without items by @remote-controlled-man in #2463
Reject unsatisfiable repetition bounds instead of producing a grammar that violates the maximum.

- fix: load cached pretrained models in offline mode by @emme1t in #2396
- fix(ci): install matching NVML headers for CUDA wheel builds

Expand Down
20 changes: 17 additions & 3 deletions llama_cpp/llama_grammar.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,9 @@ def from_json_schema(cls, json_schema: str, verbose: bool = True) -> "LlamaGramm
def _build_repetition(
item_rule, min_items, max_items, separator_rule=None, item_rule_is_literal=False
):
if max_items is not None and max_items < min_items:
raise ValueError("maximum repetition count is less than the minimum")

if not separator_rule:
if min_items == 0 and max_items == 1:
return f"{item_rule}?"
Expand Down Expand Up @@ -769,9 +772,16 @@ def add_component(comp_schema, is_required):
)

elif schema_type in (None, "array") and (
"items" in schema or "prefixItems" in schema
"items" in schema
or "prefixItems" in schema
or (
schema_type == "array"
and ("minItems" in schema or "maxItems" in schema)
)
):
items = schema.get("items") or schema["prefixItems"]
items = None
if "items" in schema or "prefixItems" in schema:
items = schema.get("items") or schema["prefixItems"]
if isinstance(items, list):
return self._add_rule(
rule_name,
Expand All @@ -783,7 +793,11 @@ def add_component(comp_schema, is_required):
+ ' "]" space',
)
else:
item_rule_name = self.visit(items, f"{name}{'-' if name else ''}item")
item_rule_name = (
self._add_primitive("value", PRIMITIVE_RULES["value"])
if items is None
else self.visit(items, f"{name}{'-' if name else ''}item")
)
min_items = schema.get("minItems", 0)
max_items = schema.get("maxItems")
return self._add_rule(
Expand Down
200 changes: 200 additions & 0 deletions tests/test_llama_grammar.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import llama_cpp
import json
import ctypes
import math

import pytest

from llama_cpp.llama_grammar import json_schema_to_gbnf

tree = """
leaf ::= "."
Expand Down Expand Up @@ -76,3 +82,197 @@ def test_grammar_anyof():
grammar = llama_cpp.LlamaGrammar.from_json_schema(json.dumps(sch))

# assert grammar.grammar is not None


@pytest.fixture(scope="module")
def grammar_accepts():
"""Check exact UTF-8 bytes and end-of-input with the native grammar sampler."""
params = llama_cpp.llama_model_default_params()
params.vocab_only = True
model = llama_cpp.llama_model_load_from_file(
b"./vendor/llama.cpp/models/ggml-vocab-llama-spm.gguf", params
)
assert model
try:
vocab = llama_cpp.llama_model_get_vocab(model)
byte_tokens = {}
for token in range(llama_cpp.llama_vocab_n_tokens(vocab)):
text = llama_cpp.llama_vocab_get_text(vocab, token)
if text.startswith(b"<0x") and text.endswith(b">"):
byte_tokens[int(text[3:-1], 16)] = token

def accepts(schema, document):
sampler = llama_cpp.llama_sampler_init_grammar(
vocab, json_schema_to_gbnf(json.dumps(schema)).encode(), b"root"
)
assert sampler
try:
tokens = [byte_tokens[b] for b in document.encode()]
tokens.append(llama_cpp.llama_vocab_eos(vocab))
for token in tokens:
candidates = (llama_cpp.llama_token_data * 1)(
llama_cpp.llama_token_data(id=token, logit=0.0, p=0.0)
)
data = llama_cpp.llama_token_data_array(
data=candidates, size=1, selected=-1, sorted=False
)
llama_cpp.llama_sampler_apply(sampler, ctypes.byref(data))
if not math.isfinite(candidates[0].logit):
return False
llama_cpp.llama_sampler_accept(sampler, token)
return True
finally:
llama_cpp.llama_sampler_free(sampler)

yield accepts
finally:
llama_cpp.llama_model_free(model)


@pytest.mark.parametrize(
("limits", "document", "allowed"),
[
({"maxItems": 0}, "[]", True),
({"maxItems": 0}, "[null]", False),
({"minItems": 1}, "[]", False),
({"minItems": 1}, "[1,2,3]", True),
({"maxItems": 2}, "[]", True),
({"maxItems": 2}, "[1,2]", True),
({"maxItems": 2}, "[1,2,3]", False),
({"minItems": 2, "maxItems": 3}, "[1]", False),
({"minItems": 2, "maxItems": 3}, "[1,2]", True),
({"minItems": 2, "maxItems": 3}, "[1,2,3]", True),
({"minItems": 2, "maxItems": 3}, "[1,2,3,4]", False),
({"minItems": 1, "maxItems": 1}, "[]", False),
({"minItems": 1, "maxItems": 1}, "[1,2]", False),
({"minItems": 1, "maxItems": 1}, "1", False),
({"minItems": 1, "maxItems": 1}, "[1,]", False),
({"minItems": 1, "maxItems": 1}, "[", False),
],
)
def test_array_without_items_length_boundaries(
grammar_accepts, limits, document, allowed
):
assert grammar_accepts({"type": "array", **limits}, document) is allowed


@pytest.mark.parametrize(
"value",
[
"42",
"-1.5",
'"text"',
"true",
"false",
"null",
"{}",
"[]",
'"中文"',
'{"nested":[1,null]}',
],
)
def test_array_without_items_keeps_all_json_item_types(grammar_accepts, value):
assert grammar_accepts(
{"type": "array", "minItems": 1, "maxItems": 1}, f"[{value}]"
)


@pytest.mark.parametrize(
("schema", "document", "allowed"),
[
({"type": "array"}, "[]", True),
({"type": "array"}, "[1,true,null,[]]", True),
(
{
"type": "array",
"items": {"type": "integer"},
"minItems": 1,
"maxItems": 2,
},
"[1,2]",
True,
),
(
{
"type": "array",
"items": {"type": "integer"},
"minItems": 1,
"maxItems": 2,
},
'["text"]',
False,
),
(
{
"type": "array",
"prefixItems": [{"type": "integer"}, {"type": "string"}],
"items": False,
},
'[1,"text"]',
True,
),
(
{
"type": "array",
"prefixItems": [{"type": "integer"}, {"type": "string"}],
"items": False,
},
'["text",1]',
False,
),
(
{
"type": "object",
"properties": {
"values": {"type": "array", "minItems": 1, "maxItems": 1}
},
"required": ["values"],
"additionalProperties": False,
},
'{"values":[true]}',
True,
),
(
{
"type": "object",
"properties": {
"values": {"type": "array", "minItems": 1, "maxItems": 1}
},
"required": ["values"],
"additionalProperties": False,
},
'{"values":[]}',
False,
),
],
)
def test_array_length_compatibility(grammar_accepts, schema, document, allowed):
assert grammar_accepts(schema, document) is allowed


@pytest.mark.parametrize(
"schema",
[
{"type": "array", "minItems": 2, "maxItems": 1},
{"type": "array", "items": {"type": "integer"}, "minItems": 2, "maxItems": 1},
{"type": "string", "minLength": 2, "maxLength": 1},
],
)
def test_grammar_rejects_unsatisfiable_length_bounds(schema):
with pytest.raises(ValueError, match="maximum.*minimum"):
llama_cpp.LlamaGrammar.from_json_schema(json.dumps(schema))


@pytest.mark.parametrize(
("schema", "document", "allowed"),
[
({"type": "string", "minLength": 1, "maxLength": 2}, '"a"', True),
({"type": "string", "minLength": 1, "maxLength": 2}, '""', False),
({"type": "string", "minLength": 1, "maxLength": 2}, '"abc"', False),
({"type": "string", "pattern": "^[a-z]{1,2}$"}, '"ab"', True),
({"type": "string", "pattern": "^[a-z]{1,2}$"}, '"abc"', False),
({"type": "string", "pattern": "^a{1,2}$"}, '"aa"', True),
],
)
def test_valid_string_repetition_bounds(grammar_accepts, schema, document, allowed):
assert grammar_accepts(schema, document) is allowed
Loading