diff --git a/llama_cpp/llama_grammar.py b/llama_cpp/llama_grammar.py index ba34dda83..30365cc1f 100644 --- a/llama_cpp/llama_grammar.py +++ b/llama_cpp/llama_grammar.py @@ -234,6 +234,7 @@ def from_json_schema(cls, json_schema: str, verbose: bool = True) -> "LlamaGramm """llama.cpp json-schema to grammar converter from vendor/llama.cpp/examples/json-schema-to-grammar.py""" import json +import math import re from typing import List, Optional @@ -307,6 +308,62 @@ def opt_repetitions(up_to_n, prefix_with_sep=False): return result +def _build_integer_range(minimum: Optional[int], maximum: Optional[int]) -> str: + if minimum is not None and maximum is not None and minimum > maximum: + raise ValueError(f"Schema has an empty integer range: {minimum} > {maximum}") + + def digits(lower: str, upper: str) -> str: + if lower == upper: + return f'"{lower}"' + if lower == "0" * len(lower) and upper == "9" * len(upper): + return _build_repetition("[0-9]", len(lower), len(lower)) + if len(lower) == 1: + return f"[{lower}-{upper}]" + prefix_length = 0 + while lower[prefix_length] == upper[prefix_length]: + prefix_length += 1 + if prefix_length: + return f'"{lower[:prefix_length]}" ' + digits( + lower[prefix_length:], upper[prefix_length:] + ) + low_digit, high_digit = int(lower[0]), int(upper[0]) + remaining = len(lower) - 1 + alternatives = [f'"{low_digit}" ' + digits(lower[1:], "9" * remaining)] + if high_digit > low_digit + 1: + alternatives.append( + f"[{low_digit + 1}-{high_digit - 1}] " + + _build_repetition("[0-9]", remaining, remaining) + ) + alternatives.append(f'"{high_digit}" ' + digits("0" * remaining, upper[1:])) + return "(" + " | ".join(alternatives) + ")" + + def unsigned(lower: int, upper: Optional[int]) -> str: + first_length = len(str(lower)) + last_length = len(str(upper)) if upper is not None else first_length + alternatives = [] + for length in range(first_length, last_length + 1): + low = max(lower, 10 ** (length - 1) if length > 1 else 0) + high = min(upper, 10**length - 1) if upper is not None else 10**length - 1 + alternatives.append(digits(str(low), str(high))) + if upper is None: + alternatives.append( + "[1-9] " + _build_repetition("[0-9]", first_length, None) + ) + return "(" + " | ".join(alternatives) + ")" + + alternatives = [] + if minimum is None or minimum < 0: + lower = max(1, -maximum) if maximum is not None else 1 + upper = -minimum if minimum is not None else None + alternatives.append('"-" ' + unsigned(lower, upper)) + if maximum is None or maximum >= 0: + lower = max(0, minimum) if minimum is not None else 0 + alternatives.append(unsigned(lower, maximum)) + if lower == 0: + alternatives.append('"-0"') + return "(" + " | ".join(alternatives) + ") space" + + class BuiltinRule: def __init__(self, content: str, deps: list = None): self.content = content @@ -830,6 +887,27 @@ def add_component(comp_schema, is_required): + r' "\"" space', ) + elif schema_type == "integer" and any( + key in schema + for key in ("minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum") + ): + lower_bounds = [] + upper_bounds = [] + if "minimum" in schema: + lower_bounds.append(math.ceil(schema["minimum"])) + if "exclusiveMinimum" in schema: + lower_bounds.append(math.floor(schema["exclusiveMinimum"]) + 1) + if "maximum" in schema: + upper_bounds.append(math.floor(schema["maximum"])) + if "exclusiveMaximum" in schema: + upper_bounds.append(math.ceil(schema["exclusiveMaximum"]) - 1) + return self._add_rule( + rule_name, + _build_integer_range( + max(lower_bounds, default=None), min(upper_bounds, default=None) + ), + ) + elif (schema_type == "object") or (len(schema) == 0): return self._add_rule( rule_name, self._add_primitive("object", PRIMITIVE_RULES["object"]) @@ -837,7 +915,7 @@ def add_component(comp_schema, is_required): else: assert schema_type in PRIMITIVE_RULES, f"Unrecognized schema: {schema}" - # TODO: support minimum, maximum, exclusiveMinimum, exclusiveMaximum at least for zero + # TODO: support numeric bounds for "number" schemas. return self._add_primitive( "root" if rule_name == "root" else schema_type, PRIMITIVE_RULES[schema_type], @@ -942,6 +1020,10 @@ def format_grammar(self): def json_schema_to_gbnf(schema: str, prop_order: Optional[List[str]] = None): + """Convert a JSON schema to GBNF, including inclusive/exclusive integer bounds. + + Integer bounds containing no integer raise ValueError. + """ prop_order = prop_order or [] schema = json.loads(schema) prop_order = {name: idx for idx, name in enumerate(prop_order)} diff --git a/tests/test_llama_grammar.py b/tests/test_llama_grammar.py index 34ef2874d..49673cfa9 100644 --- a/tests/test_llama_grammar.py +++ b/tests/test_llama_grammar.py @@ -1,5 +1,9 @@ import llama_cpp +import ctypes import json +import math + +import pytest tree = """ leaf ::= "." @@ -76,3 +80,119 @@ 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(): + model = llama_cpp.Llama( + model_path="./vendor/llama.cpp/models/ggml-vocab-llama-spm.gguf", + vocab_only=True, + verbose=False, + ) + vocab = model._model.vocab + characters = b"-+0123456789.eE" + tokens = { + piece.decode(): token + for token in range(model.n_vocab()) + if (piece := llama_cpp.llama_vocab_get_text(vocab, token)) + and len(piece) == 1 + and piece[0] in characters + } + + samplers = {} + + def accepts(grammar, text): + if grammar._grammar not in samplers: + sampler = llama_cpp.llama_sampler_init_grammar( + vocab, grammar._grammar.encode(), b"root" + ) + assert sampler, grammar._grammar + samplers[grammar._grammar] = sampler + sampler = samplers[grammar._grammar] + llama_cpp.llama_sampler_reset(sampler) + for token in [tokens[c] for c in text] + [model.token_eos()]: + data = (llama_cpp.llama_token_data * 1)( + llama_cpp.llama_token_data(token, 0.0, 0.0) + ) + candidates = llama_cpp.llama_token_data_array(data, 1, -1, False) + llama_cpp.llama_sampler_apply(sampler, ctypes.byref(candidates)) + if not math.isfinite(data[0].logit): + return False + llama_cpp.llama_sampler_accept(sampler, token) + return True + + try: + yield accepts + finally: + for sampler in samplers.values(): + llama_cpp.llama_sampler_free(sampler) + model.close() + + +@pytest.mark.parametrize( + "bounds,valid,invalid", + [ + ({"minimum": 8, "maximum": 12}, ["8", "9", "10", "12"], ["7", "13", "99"]), + ({"minimum": -12, "maximum": -8}, ["-12", "-10", "-8"], ["-13", "-7", "0"]), + ({"minimum": -2, "maximum": 2}, ["-2", "-0", "0", "2"], ["-3", "3", "01"]), + ( + {"exclusiveMinimum": -1.5, "exclusiveMaximum": 2.5}, + ["-1", "0", "2"], + ["-2", "3", "1.5"], + ), + ( + {"minimum": 1.5, "maximum": 4.5}, + ["2", "4"], + ["1", "5"], + ), + ( + {"minimum": 0, "exclusiveMinimum": 1, "maximum": 5, "exclusiveMaximum": 4}, + ["2", "3"], + ["0", "1", "4", "5"], + ), + ( + {"minimum": 98}, + ["98", "99", "100", "123456789012345678901"], + ["97", "-98"], + ), + ( + {"maximum": -98}, + ["-98", "-100", "-123456789012345678901"], + ["-97", "0"], + ), + ( + {"minimum": -2}, + ["-2", "-0", "0", "123456789012345678901"], + ["-3", "01", "1.5"], + ), + ( + {"maximum": 2}, + ["-123456789012345678901", "-0", "0", "2"], + ["3", "00", "--1"], + ), + ({"minimum": 0, "maximum": 0}, ["0", "-0"], ["1", "-1", "00"]), + ], +) +def test_grammar_integer_bounds(grammar_accepts, bounds, valid, invalid): + grammar = llama_cpp.LlamaGrammar.from_json_schema( + json.dumps({"type": "integer", **bounds}) + ) + for text in valid: + assert grammar_accepts(grammar, text), (bounds, text) + for text in invalid: + assert not grammar_accepts(grammar, text), (bounds, text) + + +@pytest.mark.parametrize( + "bounds", + [ + {"minimum": 2, "maximum": 1}, + {"exclusiveMinimum": 1, "exclusiveMaximum": 2}, + {"minimum": 1.2, "maximum": 1.8}, + ], +) +def test_grammar_empty_integer_range(bounds): + with pytest.raises(ValueError, match="empty integer range"): + llama_cpp.LlamaGrammar.from_json_schema( + json.dumps({"type": "integer", **bounds}) + )