Skip to content

Support integer minimum, maximium in JSON schemas - #2475

Open
yezhengli-Mr9 wants to merge 2 commits into
abetlen:mainfrom
yezhengli-Mr9:feat/integer-schema-bounds-20261203
Open

yezhengli-Mr9 wants to merge 2 commits into
abetlen:mainfrom
yezhengli-Mr9:feat/integer-schema-bounds-20261203

Conversation

@yezhengli-Mr9

@yezhengli-Mr9 yezhengli-Mr9 commented Dec 3, 2026 •

Copy link
Copy Markdown

Reference PRs

Project Reference PR Status Relevant implementation
llama.cpp #7797 - Support integer minimum, maximum, exclusiveMinimum, exclusiveMaximum Merged Closest upstream reference and selected compatibility target: includes a Python implementation that generates bounded-integer GBNF using decimal digit ranges, rather than enumerating every value.
XGrammar #106 - Simple pattern support + integer ranges Merged Implements integer-range constraints in grammar generation; a counterpart, not an identical implementation.
llguidance #61 - Add tests for numeric regular expressions; some bug fixes Merged Tests and fixes numeric-range regular expressions; reference coverage for a related implementation.
llguidance #372 - Report empty integer intervals as unsatisfiable Merged Reports integer intervals containing no admissible integer as unsatisfiable.

Compatibility status: llama.cpp #7797's Python implementation is the selected exact-match target, including its limitations. The current code in this PR is not yet an exact port: it separately normalizes fractional bounds, intersects simultaneous inclusive/exclusive bounds, supports long one-sided integers without the reference's default digit cap, and explicitly admits -0 whenever zero is allowed. The implementation and validation results below describe the current code, not verified equivalence with #7797.

Summary and logic

Enforce JSON Schema integer bounds during grammar-constrained generation instead of silently ignoring them, for tool arguments such as retry counts, line numbers and edit offsets.

  1. Normalize inclusive bounds with ceil(minimum) / floor(maximum), and exclusive bounds with floor(exclusiveMinimum) + 1 / ceil(exclusiveMaximum) - 1. Intersect simultaneous bounds.
  2. Split the admissible range into negative and nonnegative magnitudes, then decimal digit lengths. Factor shared digit prefixes and interior digit classes rather than enumerating every value; use a repeated-digit tail for one-sided ranges.
  3. Allow -0 exactly when zero is admissible. Preserve JSON integer syntax and allow valid long integers in bounded schemas.
  4. Raise ValueError if the intersection contains no integer; never fall back to an unrestricted integer.

Only explicitly typed integer schemas take the new path, including those reached recursively by the existing visitor. Unbounded schemas and existing union/type-list handling are unchanged. Real-number bounds, multipleOf and general schema satisfiability remain out of scope.

Concrete API example

import json
from llama_cpp import LlamaGrammar

grammar = LlamaGrammar.from_json_schema(json.dumps({
    "type": "integer", "minimum": 8, "maximum": 12,
}))

Generated grammar:

root ::= (([8-9] | "1" [0-2])) space
space ::= " "?

This admits complete values 8, 9, 10, 11, 12, but rejects 7, 13, 999, and the incomplete prefix 1 at EOS. For example, minimum=0, exclusiveMinimum=1, maximum=5, exclusiveMaximum=4 admits only 2 and 3.

Measured comparison

Re-executed against base 77fbb5d7190149d20870cd8d73646a5df3e72b05, with the actual native grammar sampler and EOS checks: 25 schemas x 290 candidate strings = 7,250 decisions per converter.

Correctness / inference measure Original converter This change
Out-of-range / malformed candidates accepted 6,265 0
Valid candidates rejected 4 0
Valid outputs in the paired local-model experiment below 0/6 6/6
Prompt tokens, completed paired experiment 114 114
Completion tokens, completed paired experiment 18 8
Total tokens, completed paired experiment 132 122

The four original false rejections are valid 21-digit integers excluded by the existing unrestricted integer primitive's digit limit. That primitive is unchanged; bounded schemas no longer inherit the unrelated limit.

Representation optimization: prefix rules instead of value enumeration

Inclusive interval Number of admissible integer values Generated GBNF bytes, including root and space rules
0 through 999 1,000 144
0 through 999,999 1,000,000 426
0 through 999,999,999 1,000,000,000 870

These are measured representation sizes, not a throughput benchmark. The original converter's smaller unrestricted grammar is not a correct implementation of the bounded schema. No general inference-speed or AI-coding token-saving claim is made.

Real local coding-model sample

Re-executed with the existing local qwen2.5-coder:1.5b GGUF; no model download. Prompt:

Write exactly 999 as a JSON integer. Do not write anything else.
Answer:
Allowed interval Original output, seeds 0 / 1 Patched output, seeds 0 / 1 Valid original -> patched
8 through 12 999 / 999 9 / 9 0/2 -> 2/2
-12 through -8 999 / 999 -9 / -9 0/2 -> 2/2
-2 through 2 999 / 999 1 / 1 0/2 -> 2/2

Twelve completed calls / six matched pairs, all finishing with finish_reason="stop". This deliberately adversarial range-conformance smoke test is not a representative coding benchmark; the smaller completion-token counts reflect shorter numbers, and repeated seeds are not independent tasks.

Settings: n_ctx=512, n_batch=128, n_threads=2, n_threads_batch=2, max_tokens=12, temperature=0.2, top_p=0.9, repeat_penalty=1.0; seeds 0 and 1, model state reset before each call. Ubuntu 24.04 Docker, Python 3.12, 2 CPUs / 4 GiB limit, networking disabled, capabilities dropped, model volume and source read-only.

Focused test cleanup and validation

  • Keep only feature-specific native acceptance and empty-range regressions. Remove the helper's sampler cache, cache reset/lookup/teardown, unused character allowlist and extra import; each temporary native sampler is freed in finally.
  • Replace the narrow positive interval with 98..321, covering shared prefixes, an interior digit branch and a digit-length transition without another test case. Retain distinct negative, zero-crossing, one-sided, zero-only, inclusive/exclusive fractional, intersected and empty-range cases.
  • All feature regression cases fail against the original converter while existing grammar smoke tests pass. The cleaned suite passes against this change.
  • Branch scope remains two Python files; test additions decrease from 120 to 111 lines versus the base. No committed Markdown, dependencies, public signatures, server or GPU-backend changes.
python -m pytest tests/test_llama_grammar.py -q
python -m ruff check llama_cpp/llama_grammar.py tests/test_llama_grammar.py
python -m ruff format --check llama_cpp/llama_grammar.py tests/test_llama_grammar.py
git diff --check
Latest validation Result / limitation
Ubuntu 24.04 / Python 3.12 focused native suite Pass
Original-converter regression proof Every new regression case fails as expected; existing cases pass
Paired native acceptance matrix Results above reproduced after cleanup
Local-model matched experiment Results above reproduced after cleanup
Ruff, formatting, Python syntax, whitespace Pass
Native runtime Same-version official llama-cpp-python==0.3.38 CPU wheel libraries selected via LLAMA_CPP_LIB_PATH; not rebuilt from source
Windows / full suite Native Windows execution and the full server/multimodal suite were not validated in this cleanup run
Exact matrix inputs and experiment identity

The matrix uses the committed test fixture grammar_accepts for both converter classes, loading the original converter with git show 77fbb5d7190149d20870cd8d73646a5df3e72b05:llama_cpp/llama_grammar.py.

Inclusive (minimum, maximum) intervals:

[
    (-130, -110), (-101, -99), (-100, -1), (-12, -8), (-10, 0),
    (-2, 2), (-1, 0), (0, 0), (0, 1), (0, 9), (0, 10), (1, 1),
    (1, 9), (8, 12), (9, 100), (10, 99), (98, 102), (110, 130),
]

Seven additional type="integer" bound dictionaries:

[
    {"minimum": 98}, {"maximum": -98}, {"minimum": -2}, {"maximum": 2},
    {"minimum": 1.5, "maximum": 4.5},
    {"exclusiveMinimum": -1.5, "exclusiveMaximum": 2.5},
    {"minimum": 0, "exclusiveMinimum": 1, "maximum": 5, "exclusiveMaximum": 4},
]

Candidates:

[str(n) for n in range(-140, 141)] + [
    "-0", "00", "01", "-01", "1.5", "+1", "--1",
    "123456789012345678901", "-123456789012345678901",
]

The oracle requires re.fullmatch(r"-?(0|[1-9][0-9]*)", text), then compares int(text) with every applicable inclusive/exclusive bound. Grammar-size measurements use len(grammar._grammar.encode()).

Existing model GGUF SHA-256: 29d8c98fa6b098e200069bfb88b9508dc3e85586d20cba59f8dda9a808165104.

For inference, instantiate Llama with the recorded settings and pass each converter class's from_json_schema result as grammar to create_completion, resetting state before each interval/seed/converter call.

@yezhengli-Mr9
yezhengli-Mr9 marked this pull request as ready for review December 4, 2026 03:54
@yezhengli-Mr9 yezhengli-Mr9 changed the title fix(grammar): enforce integer bounds in JSON schemas Support integer minimum, maximium integer bounds in JSON schemas Dec 4, 2026
@yezhengli-Mr9 yezhengli-Mr9 changed the title Support integer minimum, maximium integer bounds in JSON schemas Support integer minimum, maximium in JSON schemas Dec 4, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant