Repository navigation
Conversation
df8a245 to
8ad93c4
Compare
Tool-call schema grammars enforced the declared property order, so a model writing keys in a different order was forced into garbage or dropped keys. Add an opt-in unordered object mode and use it for tool-* schema parsers. Required properties must appear and each key may appear only once. Assisted-by: Claude Opus 5.5
Objects with more than 6 properties fell back to the declared order, which is the case that corrupts column-like tool args. Required keys come first in any order, then optional keys. Up to 6 keys in total are tracked for presence and uniqueness; the remaining properties and additional keys are accepted in any order. Assisted-by: Claude Opus 5.5
Assisted-by: Claude Opus 5.5
…epts Assisted-by: Claude Opus 5.5
Assisted-by: Claude Opus 5.5
Assisted-by: Claude Opus 5.5
8ad93c4 to
9d8ea5e
Compare
…t rules - one $ref memo keyed by (target, mode): two tools with same-named $defs no longer share a rule - reserve the $ref rule name before visiting the target so a nested rule with the same name cannot take it - allOf: a property declared twice is emitted once, a required component's schema wins - more than COMMON_CHAT_MAX_PERMUTE required keys: build the declared-order chain with a loop, not recursion - COMMON_CHAT_MAX_PERMUTE is shared with the <parameter> permute Assisted-by: Claude Fable 5.1
unordered_schema() did nothing when given a parser that was not the schema node. Assisted-by: Claude Fable 5.1
Assisted-by: Claude Fable 5.1
Assisted-by: Claude Opus 5.5
Assisted-by: Claude Opus 5.5
|
@aldehir You've reviewed similar PRs and been opposed, but I think my approach really resolves concerns I've seen on other PRs. It fixes the issue and doesn't impact performance. Could you review this please? |
|
I oppose of those PRs (and this one) because I think it's the wrong direction. Models share syntax but order arguments differently. It's been a losing battle to try to accommodate all permutations. Even the frontier models place certain restrictions on their JSON schemas when grammar constrained decoding is enabled (i.e. passing tools with I believe llama.cpp should drop the grammar sampler except when strict tools are requested, and place schema limitations similar to OpenAI's structured outputs. It will also address a couple of outstanding performance issues caused by the grammar sampler, and allow backend sampling which has been a strong desire from several maintainers. I am actively working towards that goal, and unfortunately it does not align with further complicating grammar generation. That said, I have an open PR #30476 that reorders optionals to match the order in the request. Would that help to address the issues you're facing? |
|
I ran a few tests and I guess we can consider this instead of my PR. I'll do a more thorough review soon. |
| common_peg_parser common_peg_parser_builder::schema(const common_peg_parser & p, const std::string & name, common_chat_schema_document_ptr doc, const common_chat_schema & node, bool raw, bool unordered) { | ||
| return wrap(arena_.add_parser(common_peg_schema_parser{p.id(), name, std::move(doc), &node, raw, unordered})); |
There was a problem hiding this comment.
Let's remove the unordered flag and just apply this to every grammar generated by a JSON schema. Please consolidate the test as a result, since you don't need two unique set of tests for ordered vs. unordered.
There was a problem hiding this comment.
Done, but this exposed a problem in my initial version of unbounded key repeats. Models looped on response_format until they hit max tokens. Objects now track up to 10 keys exactly and cap repeats past that.
But, I experimented with a new GBNF construct that does this without the cap: the grammar engine tracks which keys it has seen, so every key is exact up to 64 and the rule count stays linear. That however seems like another can of worms. I am happy to share it though.
There was a problem hiding this comment.
I took a look, and it's an interesting idea but the added complexity might be a hard sell.
I wonder, if we took an alternate approach and removed the schema grammar from the qwen3-coder parser instead, would that also improve tool calling?
There was a problem hiding this comment.
I actually tried that already. It fixed the corrupted keys, but almost no tool calls matched the tool's schema, 0–2 of 32 on Nemotron 3.5 and Qwen3.5-9B, vs ~30 with the schema grammar.
There was a problem hiding this comment.
Can you give this a shot? aldehir#39
I'm seeing good results for Qwen3.8 27B, Qwen 3.5 4B/9B, and Nemotron Nano 30B. Qwen 3.5 2B struggles a little.
I would think tool calling would be on par with other inference engines, as llama.cpp is unique in grammar sampling by default.
There was a problem hiding this comment.
Ran it through the same gauntlet I've done all my changes.
Corrupt keys gone and completion rate on par, but schema validity drops to 0-2 of 32 on both models vs 26-32 with the schema grammar. Same result I got when I removed the value schema outright. And it doesn't touch response_format, where declared order drops 3 of 10 optional keys per output.
I am going to expand the tests I am running to add a few more scenarios to make sure my scenario just isn't the one black hole.
…udget Drop the unordered flag: every grammar generated from a JSON schema now accepts object properties in any order. Keys are tracked as a set while 2^tracked * (untracked + 1) fits common_grammar_options::max_object_states (1024, so objects with up to 10 properties allow each key once). Keys past that share a counter capped at their number, so they may come in any order but cannot repeat without bound. max_total_states (4096) shrinks the budget of later objects in the same grammar. Too many required keys to track keep the declared order. Tests consolidated into one set; small budgets are pinned through common_grammar_options. Assisted-by: Claude Opus 5.5
|
@marcusds how are you measuring schema validity? I surveyed vLLM, XGrammar, OpenAI, and Anthropic's limitations on tool calling / structured output and they all have limitations that heavily restricts the allowed schemas. vLLM and Anthropic's API does not grammar constrain unless asked explicitly. OpenAI Responses API tries to grammar constrain by default but falls back to unconstrained if it is not supported by their criteria. All of them prescribe an order of some sort, mostly in the schema order, but there is some variation. None of them allow any order, with the exception of XGrammar but vLLM's usage explicitly passes All of that is to say, I'm feeling llama.cpp is being held to a higher standard here. If you could provide some insight into the schemas you are testing, that would be great. |
|
@aldehir Your survey raises an interesting point: the others either constrain in schema order or allow optional properties, never both by default. llama.cpp does both, and that combination is what drops keys. I'm measuring schema validity with Python jsonschema against the tool's parameters, 32 replays per request at temp 1.0 with checks for corrupt key names and that the keys the prompt asked for are present. The scheme I noticed this on came from NVIDIA-NeMo/DataDesigner, it is quite complex (and something I will look at improving at the source). My test harness ran with 12 additional tool schemas with varying levels of success. I think due to how constraints plus optionals means that there is a big area of growth here for llama.cpp. I am currently running my harness against vllm and will post some comparisons with the full test results when done. |
|
Finished my comparison to vLLM. vLLM's auto or just required mode is more successful than llama.cpp, but its required+strict is more or less the same. This PR is more successful at tool calling than vLLM. |
|
What is original vs. natural in this context? |
|
Sorry yeah, natural is just in my test harness pre-sorting the properties. Just a stort of a control. Not honestly the most useful in this context. |
|
Interestingly enough, I also tested sorting the properties and found Nemotron Nano 30B to perform better but no difference with Qwen models. I have some findings of my own, I'll post them shortly. FWIW, I do agree the behavior of master is suboptimal. |
|
I took the schemas from your PR to the helix repo and ran some tests: Each cell is Qwen3.5 9B / Nemotron 3.5 Lightning.
I did update to a newer Nemotron model, but I can't imagine it should perform better than one 4x its size. The What I see here is: tool schema matters. Ideally you want to design it so the model can produce a tool call without constraints. This is shown by your new proposed tool design. I see the value of a little nudge, but I'm currently struggling to follow your implementation. Can you make the following changes:
Big picture, I will refactor llama.cpp's tool calling to remove reliance on grammar sampling. It is hindering progress on other fronts. It will of course be a toggle, but in general trying to keep up with every possible schema thrown at llama.cpp is a losing battle. |
|
I am running my tests now on the suggestions you made. And yes, I agree about the tool design, I've got an open PR in Helix to fix these. This PR goal wasn't to fix that specific problem but hopefully improve tool calling across the board. I'll get back when my tests are done. |
Restore master's $ref resolution and allOf property handling; both fixes and their tests now live in a separate PR. The rule name reservation helper stays, the any-order object rule uses it for its own rules. Assisted-by: Claude Fable 5.1
Per review: objects that allow additional properties keep the declared order (master's rule). Closed objects accept keys in any order; the first 8 keys are tracked exactly and the rest share a counter, which replaces the per-object and grammar-wide state budget. More than 8 required keys keep the declared order. Assisted-by: Claude Fable 5.1
The shared counter let one untracked key be written twice: on a 10-key response_format schema Nemotron repeated a key in 10 of 16 outputs. Track a position instead, so each untracked key appears at most once and in declared order among the untracked keys. Same number of states. Assisted-by: Claude Fable 5.1
The rules were built by recursion, one level per key, so a closed object with about 1000 required keys overflowed a 512 KB thread stack. Reserve every rule name first and fill the bodies in loops instead. Each state also listed every remaining key past the first 8, so the grammar grew quadratically: 100 optional keys produced a 25 MB grammar. Chain those keys instead, one rule per position, which keeps the size linear (4 MB for 100 keys). Same language, no duplicate keys. Assisted-by: Claude Fable 5.1
…rties Assisted-by: Claude Opus 5.5
Overview
Tool-call argument grammars are enforcing the declared property order of JSON arguments, but not all models send arguments in any sort of fixed order resulting in garbage keys, dropped fields, and tool call failures.
This happens in Nemotrons and Qwens.
This change makes every grammar generated from a JSON schema accept object keys in any order. Keys are tracked as a set while the number of grammar states fits a budget of 1024 per object, so objects with up to 10 properties allow each key exactly once. Keys past that still accept any order, with repeats capped. A grammar-wide budget of 4096 keeps schemas with many wide objects bounded, and objects with too many required keys to track keep the declared order. In my repro, run 32 times, master produces 0 to 3 valid tool calls and this PR 25 to 29.
Additional information
Replay of 32 tool-call requests per cell (
tool_choice: required, temperature 1.0,max_tokens4096, 4 slots) and 16response_formatrequests per schema, on a GB300. Tool cells are complete calls out of 32 (corrupt keys in parentheses); "complete" means no corrupt keys and bothexpranddtypepresent. The Nemotron PR cells are three runs.response_format10-property object, master → PREvery remaining PR miss is a generation that hit
max_tokenswhile reasoning or skipped the optionaldtype, which the models do on master too. Generation speed is unchanged (Nemotron 66.1 → 66.6 t/s).Grammar setup grows only for objects with more than 6 properties: about 2 ms per request for each object with 10 or more, capped by the grammar-wide budget.
Requirements