Repository navigation
Add grammar-constrained decoding to the GGUF chat path to fix nondeterministic create_schema JSON truncation - #1844
Conversation
apply_chat_template (via llama.cpp's common_chat_templates_apply) already computes a per-turn, per-active-tool-set grammar in ChatTemplateResult, but generate_blocking discarded it and sampled with only a repetition penalty and temperature. Nothing structurally prevented the model from emitting an EOG token mid-tool-call JSON. Mirrors llama.cpp's own common_sampler_init (common/sampling.cpp): selects LlamaSampler::grammar or grammar_lazy_patterns per grammar_lazy, converts Word/Pattern/PatternFull/Token triggers exactly as upstream does (regex- escaping Word triggers, anchoring PatternFull), and runs the grammar first in the chain. A turn with no tools gets grammar: None from llama.cpp itself, so plain chat is unaffected. Co-Authored-By: Claude <[email protected]>
grammar_first=true crashed the daemon: llama.cpp's lazy-grammar trigger-replay path (llama_grammar_accept_impl in llama-grammar.cpp) hits GGML_ASSERT(!stacks.empty()) -- a hard, uncatchable process abort -- once the grammar is applied on every token from the start, confirmed reproducible on a live E4B run right after a lazy trigger fired. Mirrors common_sampler_sample's default (common/sampling.cpp) exactly: sample once with no grammar; only if that pick is grammar-invalid, resample with the grammar applied ahead of the base chain. This is upstream's own default configuration, not a novel mode, and exercises the fragile trigger-replay path far less aggressively. Re-ran the full agent-matrix eval against a real E4B model after this change: no crash, and the exact scenario this issue targets (3, schema creation with several fields) passed with a clean create_schema call. Co-Authored-By: Claude <[email protected]>
Code Review SummaryNet positive change that fixes a real, evidence-backed reliability bug (nondeterministic There is one substantive correctness bug in Trigger conversion ( FindingsCritical IssuesNone that should block merge given the live-model validation already performed, but the double-accept below is a real bug worth fixing (see Improvements). Suggested Improvements🟡
llama_sampler_apply(smpl, &cur_p);
...
auto token = cur_p.data[cur_p.selected].id;
llama_sampler_accept(smpl, token); // <-- implicit accept, inside sample()
return token;For a let token = chain.sample(ctx, idx); // chain.accept(token) already fired here, internally
chain.accept(token); // fires again, explicitlyThis means Compare to the resample path ( Root cause: this codebase's original code ( Fix: drop the explicit 🟢 Test coverage gap for The rejection-sampling function itself has no direct unit test — it needs a loaded model/context ( The 8 new tests for Nitpicks
Requirements Check (issue #1838)
Standard Checks
Recommendation: COMMENTThe implementation is sound in its overall design and the design evolution (grammar-first crash → rejection sampling) reflects real engineering rigor backed by live-model evidence, not just unit tests. The double-accept issue is real but pre-existing (not introduced by this PR) and evidently not severe enough to have shown up in the agent-matrix eval — it inflates the effective repetition penalty rather than causing incorrect grammar/tool-call behavior. Given it predates this PR and this PR's actual target (grammar-constrained decoding to fix truncated JSON) is otherwise correctly and carefully implemented, I'm not blocking merge on it, but recommend either fixing it in this PR (since the function is already being touched and the fix is a one-line deletion on two branches) or filing a fast-follow issue explicitly so it doesn't get lost. |
malibio
left a comment
There was a problem hiding this comment.
Reviewed — see detailed findings in the comment above. One real (pre-existing, not a regression) double-accept bug found in sample_with_grammar_rejection worth a fast-follow; everything else (trigger-conversion fidelity, per-turn grammar scoping, test coverage rationale, CLAUDE.md compliance) checks out. Recommending COMMENT rather than blocking, given live-model validation already performed.
LlamaSampler::sample() wraps llama_sampler_sample(), which already calls llama_sampler_accept() internally before returning (confirmed in the vendored llama-sampler.cpp). The no-grammar and valid-first-pick branches called chain.accept() again explicitly, double-applying penalties' ring buffer and frequency count for every generated token -- inflating the repetition penalty beyond its calibrated strength. Predates this PR (origin/main had the same sample()+accept() pattern); caught during /pragmatic-code-review while sample_with_grammar_rejection was already being rewritten, so fixed here rather than filed as a follow-up. The resample branch was already correct: it uses chain.apply() (pure, no internal accept) followed by exactly one explicit chain.accept(), matching upstream's common_sampler_sample resampling block. Re-ran the full agent-matrix eval against a live E4B model after this change: no crash, same 7/12 pass pattern as before (scenario 3 still clean), confirming the fix doesn't destabilize generation. Co-Authored-By: Claude <[email protected]>
|
Fixed the double-accept bug flagged in review (commit 60f120f): Confirmed this predates the PR ( Re-ran the full agent-matrix eval against a live E4B model after the fix: no crash, same 7/12 pass pattern as the earlier validation run (scenario 3 — this issue's target — still clean). Left the two nitpicks as follow-ups where appropriate: trimmed the duplicated crash-rationale comment at the call site down to a pointer at the function's doc comment (which keeps the full narrative in one place); left the |
Re-review of fix commit 60f120f (double-accept bug)Scope: this is a re-review of the follow-up fix only, per the previous COMMENT-level review at 4c58081 which flagged a double-accept bug in Verdict: the fix is correct and complete. 1. Both flagged branches fixed
2. Resample branch (previously correct) is untouchedConfirmed via 3. No return-semantics change from removing the explicit acceptChecked the vendored 4. No remaining double-accept, no new under-acceptTraced all three branches at HEAD:
Every path accepts 5. Nitpicks (informational, non-blocking, as originally flagged)
Additional verification performed
The fix does exactly what the original diagnosis prescribed, on exactly the two branches it named, without touching the branch that was already correct. Combined with the live E4B re-validation reported in the follow-up comment (no crash, same 7/12 pass pattern, scenario 3 clean), this closes out the one substantive finding from the prior review. |
malibio
left a comment
There was a problem hiding this comment.
Re-review of fix commit 60f120f: VERDICT = APPROVE (submitted as COMMENT review — GitHub blocks self-approval on this PR's own author account). The double-accept bug flagged in the prior review is correctly and completely fixed on both branches, the already-correct resample branch is untouched, and no new double- or under-accept path was introduced. Build clean, 115/115 lib tests pass. Full details in the review comment above. No merge action taken.
Closes #1838