diff --git a/CHANGELOG.md b/CHANGELOG.md index bfa7e917b..0c3f16c66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ 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 + Keep large array bounds enforceable without deeply nested grammar rules. + Reject unsatisfiable repetition bounds for typed and untyped arrays and string lengths. + - fix: load cached pretrained models in offline mode by @emme1t in #2396 - fix(ci): install matching NVML headers for CUDA wheel builds diff --git a/llama_cpp/llama_grammar.py b/llama_cpp/llama_grammar.py index ba34dda83..b546d6793 100644 --- a/llama_cpp/llama_grammar.py +++ b/llama_cpp/llama_grammar.py @@ -251,9 +251,21 @@ def from_json_schema(cls, json_schema: str, verbose: bool = True) -> "LlamaGramm SPACE_RULE = '" "?' +def _normalize_array_bound(bound): + # JSON Schema treats integral numbers such as 2.0 as integers. + if isinstance(bound, float): + if not bound.is_integer(): + raise ValueError("array length bounds must be integers") + return int(bound) + return bound + + 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}?" @@ -769,9 +781,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, @@ -783,16 +802,26 @@ 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( - rule_name, - '"[" space ' - + _build_repetition( + if items is None: + min_items = _normalize_array_bound(min_items) + max_items = _normalize_array_bound(max_items) + if items is None and max_items is not None and max_items > 1: + repetition = self._build_bounded_array_items( + rule_name, item_rule_name, min_items, max_items + ) + else: + repetition = _build_repetition( item_rule_name, min_items, max_items, separator_rule='"," space' ) - + ' "]" space', + return self._add_rule( + rule_name, '"[" space ' + repetition + ' "]" space' ) elif schema_type in (None, "string") and "pattern" in schema: @@ -843,6 +872,47 @@ def add_component(comp_schema, is_required): PRIMITIVE_RULES[schema_type], ) + def _build_bounded_array_items(self, rule_name, item_rule, min_items, max_items): + if max_items < min_items: + raise ValueError("maximum repetition count is less than the minimum") + + # Named rules double the length without deep groups or large GBNF quantifiers. + next_item = self._add_rule( + f"{rule_name}-array-next-item", f'"," space {item_rule}' + ) + powers = [next_item] + for exponent in range(1, (max_items - 1).bit_length()): + previous = powers[-1] + powers.append( + self._add_rule( + f"{rule_name}-array-items-{1 << exponent}", + f"{previous} {previous}", + ) + ) + + def exact(count): + return " ".join( + rule for exponent, rule in enumerate(powers) if count & (1 << exponent) + ) + + required = max(1, min_items) + remaining = max_items - required + sizes = [] + size = 1 + while remaining > 0: + # Previous optional groups cover all lengths through size - 1. + group_size = min(size, remaining) + sizes.append(group_size) + remaining -= group_size + size <<= 1 + + parts = [item_rule] + if required > 1: + parts.append(exact(required - 1)) + parts.extend(f"({exact(size)})?" for size in reversed(sizes)) + result = " ".join(parts) + return f"({result})?" if min_items == 0 else result + def _add_primitive(self, name: str, rule: BuiltinRule): n = self._add_rule(name, rule.content) diff --git a/tests/test_llama_grammar.py b/tests/test_llama_grammar.py index 34ef2874d..49696c85d 100644 --- a/tests/test_llama_grammar.py +++ b/tests/test_llama_grammar.py @@ -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 ::= "." @@ -76,3 +82,229 @@ 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), + ({"maxItems": 2.0}, "[1,2]", True), + ({"maxItems": 2.0}, "[1,2,3]", False), + ({"minItems": 1.0, "maxItems": 2.0}, "[]", False), + ({"minItems": 1.0}, "[1]", True), + ({"minItems": 1.0, "maxItems": 1.0}, "[1]", True), + ({"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( + ("minimum", "maximum", "count", "allowed"), + [ + (0, 257, 257, True), + (0, 257, 258, False), + (0, 1000, 0, True), + (257, 1000, 256, False), + (257, 1000, 257, True), + (0, 2002, 2002, True), + (0, 2002, 2003, False), + ], +) +def test_array_without_items_grammar_loads_for_large_bounds( + grammar_accepts, minimum, maximum, count, allowed +): + schema = {"type": "array", "minItems": minimum, "maxItems": maximum} + document = json.dumps([0] * count, separators=(",", ":")) + assert grammar_accepts(schema, document) is allowed + + +@pytest.mark.parametrize("bound", ["minItems", "maxItems"]) +def test_array_without_items_rejects_fractional_lengths(bound): + schema = {"type": "array", bound: 2.5} + with pytest.raises(ValueError, match="bounds must be integers"): + json_schema_to_gbnf(json.dumps(schema)) + + +@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