Repository navigation
fix(hf): enforce llguidance whitespace_pattern bound via >=1.8.0 floor - #1807
Conversation
The {0,20} whitespace_pattern cap in _LLGUIDANCE_GRAMMAR_DEFAULTS was
not actually enforced on the pinned llguidance 1.7.3: the JSON grammar's
skip lexeme could re-match at a single position, so bounded patterns
silently permitted unlimited whitespace (root cause of the failed {1,8}
experiments in the issue). llguidance generative-computing#370 ("Add single-match skip
lexemes", first released in 1.8.0) fixed this upstream.
- Bump llguidance to >=1.8.0 (locked to 1.9.1)
- Document the enforcement requirement in the grammar defaults comment
- Add real-llguidance enforcement regression tests (byte-level matcher,
no model needed); the existing generative-computing#1510 tests only assert the pattern is
passed, via mocks
Issue generative-computing#1515 status: action item 1 (root cause) fully resolved. Item 2
(benchmark against PR generative-computing#1513's 250-trial dataset) cannot be run as
specified because that dataset was never published (item 3); the
enforcement tests here verify the bound directly instead. Item 3
(publishing the raw dataset) remains with the PR generative-computing#1513 author.
Refs generative-computing#1515
Signed-off-by: Mark Sturdevant <[email protected]>
Assisted-by: Claude Code
Signed-off-by: Mark Sturdevant <[email protected]>
|
Need to make sure @planetf1 isn't working on this. I may have stepped on toes. |
ajbozarth
left a comment
There was a problem hiding this comment.
Some feedback from Claude: verified the enforcement tests fail on 1.7.3 (200 == 20) and pass on 1.9.1, so they genuinely catch the regression. Two small nits inline.
| # Guard the constant itself: an unbounded pattern (e.g. `*`/`+` or no upper | ||
| # bound) would make the enforcement tests above vacuous. | ||
| pattern = _LLGUIDANCE_GRAMMAR_DEFAULTS["whitespace_pattern"] | ||
| assert pattern == r"[\x20\x0A\x0D\x09]{0,20}" |
There was a problem hiding this comment.
nit: this guard doesn't do what its comment says. If the pattern became unbounded (or any bound other than 20), test_space_run_capped / test_newline_run_capped would fail (e.g. 200 != 20) rather than pass vacuously. It also duplicates _assert_whitespace_pattern_set in test/backends/test_huggingface_unit.py. I'd drop it, or if you want a single source of truth, derive _WS_BOUND from the pattern instead of hardcoding 20 in two places.
There was a problem hiding this comment.
+1 to this. It also makes the 20 → 64 change from my review easier. With _WS_BOUND derived from the pattern, the limit only lives in util.py. One catch if you do that: the probe loop's hard-coded 200 should become a multiple of the bound, otherwise a larger limit would make the test fail for the wrong reason.
I tried the combined change locally (64, both of Alex's nits, guard test dropped). The tests pass on llguidance 1.9.1 and fail on 1.7.6, so they still catch the original bug. These are test-only changes, so they don't affect the model results I posted.
I missed a few places in my review that also hard-code 20: the two whitespace_pattern checks in test/backends/test_huggingface_unit.py (lines 3792 and 4078), and docs/docs/integrations/huggingface.md line 98, which says 20 and "up to 4 levels". With 64 that becomes "about 15 levels".
| _ARRAY_SCHEMA, overrides=_LLGUIDANCE_GRAMMAR_DEFAULTS | ||
| ) | ||
| matcher = LLMatcher(ll_tokenizer, grammar) | ||
| matcher.try_consume_tokens([*text.encode("utf-8"), 256]) |
There was a problem hiding this comment.
nit: use _ByteTokenizer.eos_token_id instead of the bare 256 so the EOS id lives in one place.
planetf1
left a comment
There was a problem hiding this comment.
Thanks for picking this up, @markstur, and no toes trodden on. You found the real cause, and with llguidance 1.8.0 or later the whitespace limit now works for the first time.
I'd like one change before this merges: raise the limit from 20 to 64.
Some background. When we ask a local Hugging Face model for structured JSON, llguidance controls which characters the model is allowed to write. The whitespace setting decides how many spaces and newlines it may put between JSON items. There are two ways this can go wrong:
- No whitespace allowed: the model gets confused and returns an empty or short list. That was #1510.
- Unlimited whitespace: the model occasionally gets stuck writing spaces until it runs out of tokens. That was Jake's earlier incident.
A limit sits between the two. The question is how big it should be.
What I tested. I rebuilt the #1510 test (the original data wasn't available) and then extended it. I used granite-4.1-3b and 8b, asked for lists of varying length, used both simple and deeply nested JSON layouts, and asked for both compact and nicely indented output. Every limit was compared against unlimited whitespace on exactly the same requests.
What I found. A limit is worth having: unlimited whitespace got stuck in about 1 in 200 requests (6 out of about 1,100), and every limit prevented that. For simple layouts a limit of 20 works perfectly. The problem is nested layouts on the smaller 3b model. Indented JSON five or more levels deep needs more than 20 spaces at the start of a line. When the limit cuts the indentation short, the model switches styles partway through and ends its lists early, which is the #1510 bug again. main doesn't enforce the limit at the moment, so this would be a new problem.
Here's how many requests came back wrong compared with unlimited whitespace, on the 3b model:
| Test | Limit 20 | Limit 64 |
|---|---|---|
| Deeply nested JSON (36 requests) | 12 more wrong | same |
| Random sampling, temperature 0.8 (144 requests) | 11 more wrong | 2 more wrong |
| Mixed layouts (216 requests) | 6 more wrong | same |
The 8b model was fine with either limit, and neither limit made responses any longer.
The change: use [\x20\x0A\x0D\x09]{0,64} as the pattern, set _WS_BOUND = 64 in the new test, and update the comment in util.py. 64 allows about 15 levels of 4-space indentation. The longest whitespace run in a correct answer was 41 characters, so 64 leaves comfortable room.
I also tried a limit of 8 and fixed separators (", " and ": "). Both were worse than 20.
I can share the test script and results if they're useful.
|
Side note on scope: this change only affects the Hugging Face backend, because that's the only place mellea sets llguidance's whitespace rules itself. For vLLM, llama.cpp and Ollama, mellea sends just the JSON schema and the server applies its own rules. While validating the HF change, I ran the same tests against those servers as well, using vLLM 0.31.0, llama.cpp and Ollama. What I found:
None of this needs action here. It depends on each server's implementation, and I've noted it in case it comes up later. |
Limit 20 truncates indentation in deeply nested JSON on smaller models, bringing back the empty-list collapse once the bound is enforced. Derive the test bound from the pattern, drop the redundant guard test, and use the tokenizer's eos_token_id. Refs generative-computing#1515 Assisted-by: Claude Code Signed-off-by: Mark Sturdevant <[email protected]>
|
@planetf1 thanks for the thorough review and the benchmarking. I've pushed 77bae95 with your requested changes:
I also changed the PR to |
planetf1
left a comment
There was a problem hiding this comment.
Thanks @markstur. Checked 77bae95: the limit is 64 in util.py, the comment and huggingface.md match, and the two hard-coded 20s in test_huggingface_unit.py are updated. _WS_BOUND is derived from the pattern and the probe cap scales with it. The whitespace tests pass on llguidance 1.9.1 and fail on 1.7.6, so they still catch the original bug.
8689045
Pull Request
Issue
Closes #1515
Follow-up for the benchmark/dataset items: #1820
Description
The
whitespace_patterncap in_LLGUIDANCE_GRAMMAR_DEFAULTS(added in #1513 as an intermediate fix) was not actually enforced on the pinned llguidance 1.7.3.Root cause (issue #1515, action item 1): in llguidance ≤ 1.7.6, the JSON grammar compiles the whitespace pattern into a grammar-level skip lexeme that can re-match repeatedly at a single position. So a bounded pattern like
[\x20\x0A\x0D\x09]{1,8}(or our default) compiles and partially applies — character classes and lower bounds work within a single match — but once a match completes, the skip lexeme re-opens and matches again: 8+8+8… unbounded. This is exactly why the{1,8}experiments on llguidance 1.7.3 reported in the issue accepted 200 consecutive space tokens.Upstream fix: llguidance #370 "Add single-match skip lexemes" (commit
5d4ba26b, 2026-08-06), first released in v1.8.0. Verified empirically with a byte-level tokenizer/LLMatcher: on 1.9.1 the repo's default caps at exactly its bound (now 64) for consecutive whitespace tokens (space and newline, including multi-char whitespace tokens); on 1.7.3 whitespace is unbounded.Changes:
pyproject.toml:hfextra now requiresllguidance>=1.8.0(lockfile updated to 1.9.1, minimal diff regenerated with current uv to match CI's lockfile serialization)mellea/formatters/granite/base/util.py: comment on_LLGUIDANCE_GRAMMAR_DEFAULTSnow records that the upper bound is only enforced on llguidance ≥ 1.8.0. Since the bound is now really enforced, it is raised from 20 to 64: a limit of 20 truncates indentation in deeply nested JSON on smaller models (granite-4.1-3b) and brings back the llguidance whitespace_flexible=False can silently collapse constrained JSON arrays to empty (LocalHFBackend) #1510 collapse; 64 allows about 15 levels of 4-space indentation (see review discussion)docs/docs/integrations/huggingface.mdand the pattern assertions intest/backends/test_huggingface_unit.py: updated for the new boundtest/formatters/granite/base/test_grammar_whitespace_bound.py(new): enforcement regression tests running against real llguidance with a byte-level tokenizer (no model, no Ollama):util.py)These complement the existing llguidance whitespace_flexible=False can silently collapse constrained JSON arrays to empty (LocalHFBackend) #1510 regression tests in
test_huggingface_unit.py, which mock llguidance and therefore only assert the pattern is passed, never that it is enforced — the gap this bug slipped through.Issue #1515 action-item status:
Residual risk: the fast suite covers the changed mask-level semantics via the new byte-level tests; qualitative/e2e tests against real HF models were not run. The one behavioral trade-off is that the 64-char whitespace ceiling is now real — output wanting deeper indentation (> ~15 levels of 4-space) is forced to a compact continuation, which always exists since the pattern allows zero whitespace.
Testing
uv run pytest test/ -m "not qualitative": 5475 passed, 1 failed —test_adapter_versions_unchanged, which fails identically onmain(pre-existing, unrelated). ruff format/check and mypy clean.Attribution
Adding a new component, requirement, sampling strategy, or tool?
If your PR adds or modifies one of the types below, check the matching box. A checklist of type-specific review items will be posted as a comment.
NOTE: Please ensure you have an issue that has been acknowledged by a core contributor and routed you to open a pull request against this repository. Otherwise, please open an issue before continuing with this pull request.
🤖 Generated with Claude Code