Skip to content

npu: response_format json_schema compiled to GBNF (#652 item 1) - #735

Merged
bong-water-water-bong merged 1 commit into
mainfrom
1bit/npu-json-schema
Nov 1, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
1bit/npu-json-schema

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

What

response_format: {"type": "json_schema", …} compiled to GBNF before generation. Implements #652 item 1, which the issue scopes as "the smallest slice": it replaces the refusal that was at app/npu_sampling.h:257-259.

How

New app/npu_json_schema.h: json_schema_to_gbnf(schema) emits a complete GBNF document in the dialect app/npu_grammar.h already parses, so the answer is constrained during generation by the grammar engine this route has — no xgrammar, no second constraint runtime, no new dependency. The refusal is replaced by the conversion; a schema it cannot honour is a 400 that names the keyword, per this route's rule that an unhonourable field is never silently ignored.

Covered (item 1's list): objects (properties / required / additionalProperties: false), arrays (items / minItems / maxItems), string, number, integer, boolean, null, a type list such as ["string","null"], enum, const, oneOf/anyOf as alternation. Empty schema = any JSON.

Refused by name: pattern, format, minLength/maxLength, minimum/maximum, multipleOf, uniqueItems, contains, prefixItems, $ref, allOf, not, if/then/else, propertyNames, patternProperties, dependent*, and additionalProperties given as a schema. A constraint quietly dropped from a schema is worse than one refused: the caller would believe the answer was validated.

Property order is the converter's choice, not the client's: required properties first, then the optional ones nested inside the previous slot's presence, so no alternative can generate a comma straight after {. JSON key order is irrelevant to whoever parses the answer, and this keeps the grammar linear in the number of properties instead of 2^optional.

To keep the two JSON grammars from drifting, the rules they share (any/object/array/string/number/integer/boolean/null/ws) now live in one place — json_shared_rules() in app/npu_grammar.h — and json_grammar() is that block rooted at an object. json_grammar() returns std::string instead of const char* because it now composes.

Measured

strixhalo, Qwen3-0.6B, NPU_INFER_HOST_GEMM=1 (host GEMM: the API layer is exercised, the array is never opened):

request result
schema {name: string, age: integer, tags: [string] min 1 max 2}, required name, closed; prompt asks for "a JSON object wrapped in a ```json markdown fence" 200, {"name": "John Doe", "age": 30, "tags": ["technology", "coding"]} — parses, no fence, no undeclared property, tags = 2 = maxItems
enum {red, green} for a colour field 200, {"colour": "red"}
"pattern": "^a$" 400 json_schema: pattern is not supported by this route's schema-to-GBNF converter
"$ref": "#/definitions/a" 400 json_schema: $ref is not supported …
response_format: json_object (regression) 200, {} — unchanged

ctest -R npu_sampling: PASS, 44 new assertions (test_json_schema, test_json_schema_refusals) plus the rewritten row that used to assert the old refusal — accept/reject for every covered keyword, the fence case, minItems/maxItems bounds, nested containers, enum/const, nullable type list, and the refusal messages. tools/copyright.py --check: rc 0.

Not in this PR

  • Item 2 (tool calling as grammar) and item 3 (the shared reasoning_content/content/tool_calls parser): a tool-call-shaped answer still has to be requested as json_schema.
  • No device row: this box has no current 0.6B full_i8 kernel set (the package ships the sealed layer-kernel sets, not this one). Nothing here claims a device measurement.
  • Independent of npu: logprobs / top_logprobs on /v1/chat/completions (#651 items 2+4) #733 (logprobs): this branch is based on main, and it touches the same functions at a different spot. Whichever of the two merges second is a trivial rebase.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Merge order note for whoever lands #733 first: the two PRs conflict in exactly one file, tests/npu_sampling_test.cpp (both add test functions next to each other and both extend main()). Resolved and verified here — merge both, then:

  1. keep both sides' new functions (test_logprobs, test_logprob_options from npu: logprobs / top_logprobs on /v1/chat/completions (#651 items 2+4) #733; test_json_schema, test_json_schema_refusals from npu: response_format json_schema compiled to GBNF (#652 item 1) #735),
  2. main() calls them in that order: test_logprobs(); test_logprob_options(); test_json_schema(); test_json_schema_refusals(); test_request_parsing();,
  3. keep #include <cmath> (npu: logprobs / top_logprobs on /v1/chat/completions (#651 items 2+4) #733) and the using lines for logprobs_of (npu: logprobs / top_logprobs on /v1/chat/completions (#651 items 2+4) #733) and json_schema_to_gbnf (npu: response_format json_schema compiled to GBNF (#652 item 1) #735).

Measured on that resolution: the merged .cpp compiles with g++-16 -std=c++26 and prints npu_sampling: ok, 152 assertion sites, all passing. No conflict in app/ — #733 touches forward_serve.cpp and #735 does not.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

At d98ffd13 (+452 −22: app/npu_json_schema.h +280, app/npu_grammar.h, app/npu_sampling.h, docs/npu.md, tests/npu_sampling_test.cpp +125).

Ran the tests — same device-free harness:

$ g++-16 -std=c++17 -O1 -I app -I<json-src> tests/npu_sampling_test.cpp -o /tmp/nst735
$ /tmp/nst735        ->  npu_sampling: ok      (exit 0)
$ grep test_json_schema  ->  defined at 324, called from main()

The coverage is the part I would have asked for. test_json_schema does not just check that a schema compiles; it checks the compiled grammar's semantics on both sides:

  • accepted: required property alone, optional integer, optional bounded array, all at once, and a half-written object staying alive but not can_stop (precisely the streaming contract — a prefix must keep the answer open without letting it end);
  • refused: a string slot given an integer, an integer slot given a string, a missing required property, an undeclared property under additionalProperties: false, minItems: 1 against [], maxItems: 2 against three items, and a Markdown-fenced ```json wrapper (outside the grammar by construction, which is the right call for response_format: json_schema).

That is the subset from #652 item 1 exercised where it matters, including the two failure modes that make structured output feel broken in practice (type mismatch and a stray property).

bash/compile clean; the converter lives in one header (app/npu_json_schema.h) with the grammar change confined to app/npu_grammar.h, so the blast radius is the sampler and nothing on the model path.

Not verified: the HTTP surface — response_format: {"type": "json_schema", …} reaching json_schema_to_gbnf and the constraint holding over a real generation — plus whatever keywords the converter refuses (oneOf, $ref, pattern, …). The refusal tests above use schema_error for that, so I expect them to be covered, but I read only the accepted-subset block in detail. That end-to-end check needs a built forward-serve and a model.

tprs-ready applied.

@github-actions

github-actions Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 2ba8421)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

652 - Partially compliant

Compliant requirements:

Non-compliant requirements:

  • None

Requires further human verification:

  • None
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Performance Bottleneck in Rule Generation

The json_schema_to_gbnf function generates GBNF rules dynamically using a recursive approach with new_rule and alternation functions. For complex schemas with deeply nested structures or many optional fields, this could lead to a large number of intermediate rules being generated, potentially impacting performance during the initial grammar compilation phase. While not a correctness issue, it's worth noting for potential optimization.

auto new_rule = [&](const std::string& body) {
    rules.push_back("s" + std::to_string(next) + " ::= " + body);
    return "s" + std::to_string(next++);
};
auto alternation = [&](const std::vector<std::string>& parts) {
    std::string body = "( ";
    for (size_t i = 0; i < parts.size(); i++) body += (i ? " | " : "") + parts[i];
    body += " ) ws";
    return new_rule(body);
};
Error Message Clarity

The error messages thrown by json_schema_to_gbnf are informative but could be more specific in some cases. For example, when a schema contains an unsupported keyword, the error message simply states the keyword is not supported. It might be beneficial to provide a suggestion or a link to documentation for users who encounter such errors.

throw std::runtime_error(std::string("json_schema: ") + key +
                         " is not supported by this route's schema-to-GBNF converter");

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

At 5c44f95, rebased after the merges ahead of it. The author patch is byte-identical to the head I reviewed (d98ffd13) — patch-id from the merge base is the same before and after — so my review stands without re-reading: only main arrived in the rebase.

Nothing new to verify. Everything in my earlier verdict on this PR applies at this head unchanged, including what I noted as not-verified-by-me there.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

At 1d6846ea, rebased as the merges ahead of it landed. The author patch is byte-identical to the head I reviewed (patch-id from the merge base unchanged before and after), so only main arrived in the rebase and my review stands without re-reading.

Nothing new to verify; everything in my earlier verdict on this PR — including what I recorded there as not-verified-by-me — applies at this head unchanged.

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 1d6846e

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 52308d5

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

At 52308d51, rebased as the merges ahead of it landed. The author patch is byte-identical to the head I reviewed — patch-id from the merge base is unchanged before and after — so only main arrived in the rebase and my review stands without re-reading.

Nothing new to verify; everything in my earlier verdict on this PR, including what I recorded as not-verified-by-me, applies unchanged at this head.

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit d862515

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

At d862515d, rebased as the merges ahead of it landed. The author patch is byte-identical to the head I reviewed (patch-id from the merge base unchanged), so only main arrived and my review stands without re-reading. Nothing new to verify; everything in my earlier verdict, including what I recorded as not-verified-by-me, applies at this head unchanged.

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 86b1c5e

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

At 86b1c5ef, clean rebase (identical patch-id). My review stands: tests/npu_sampling_test.cpp compiled and run (npu_sampling: ok), and test_json_schema really tests semantics — type mismatch, missing required, undeclared property under additionalProperties: false, minItems/maxItems, and a Markdown fence all refused; the half-written object stays alive but cannot can_stop.

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 657b60a

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

At 657b60ab, rebased as the merges ahead of it landed. Author patch byte-identical to the head I reviewed (patch-id from merge base unchanged), so only main arrived and my review stands without re-reading. Nothing new to verify; everything in my earlier verdict, including what I recorded as not-verified-by-me, applies at this head unchanged.

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit e1c99ca

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Correction to an assertion count (measured-numbers rule): this PR adds 35 assertions to tests/npu_sampling_test.cpp, not 44. My earlier number came from counting added diff lines containing check(, which counts a two-line check(cond,\n "message") twice. Recounted per test function in the file itself: grep over each new function's body for check( call sites.

bong-water-water-bong pushed a commit that referenced this pull request Nov 1, 2026
…ot misspell a tool or misuse an argument (#652 item 2)

A request that carries `tools` now gets a grammar for the call itself. The name is an alternation
over the DECLARED names and the arguments are that function's own `parameters` schema, compiled by
app/npu_json_schema.h (item 1), so a misspelt tool, an argument of the wrong type, a missing required
field, an undeclared field or a Markdown fence around the call cannot be generated at all:

  tool_choice "required"                 at least one call, any declared tool
  tool_choice {"type":"function",...}    that function only
  parallel_tool_calls false              exactly one call;  true  one or more

The markup is Qwen3's, which is what this route's ChatML models emit:
  <tool_call>{"name": "get_weather", "arguments": {"city": "Paris"}}</tool_call>

What a context-free grammar cannot express is stated instead of faked (header note):
  "none"  forbidding a literal inside free text needs negative lookahead, which GBNF lacks, so no
          grammar is installed and the caller validates the answer (that is #652 item 3's parser).
  "auto"  means "a call, or a plain answer"; that alternation cannot be written without also
          licensing arbitrary text, so "auto" installs no grammar either.  An "auto" request must
          not silently become "required".
  "auto"/"none" also skip argument-schema validation, because with no grammar there is nothing to
          enforce and refusing a serviceable request over one function's `pattern` would be worse
          than not constraining it.  "required" compiles every schema, so there an unsupported
          keyword is a 400 that names it.

json_schema_to_gbnf() is now a wrapper over a new json_schema_rule(schema, prefix, sink), which
emits its rules under a caller-chosen prefix so several argument schemas can share one document
without colliding on `s0`/`s1` or duplicating the shared rules.  The prefix is validated: GBNF rule
names are [A-Za-z0-9-] only, and a bad prefix used to produce a grammar nothing could parse.

Two bugs found while testing this, both mine:
  1. the <tool_call> / </tool_call> literals were built with json_literal(), which JSON-encodes a
     string and so kept its quotes: the grammar demanded the text "\"<tool_call>\"" and refused
     every well-formed call.  Raw markup now goes through schema_detail::literal().
  2. the argument-rule prefix used "_", which app/npu_grammar.h's rule-name lexer does not accept,
     so the document failed to parse with "expecting '::=' at line 2".

Measured on strixhalo, Qwen3-0.6B, NPU_INFER_HOST_GEMM=1 (array never opened), 2 tools declared
(get_weather{city}, get_time{zone}):
  tool_choice required, parallel true   -> 200, valid <tool_call> blocks, "name": "get_weather",
                                           "arguments": {"city": "Paris"}; a second call follows
  tool_choice {"function":{"name":"get_time"}} -> 200, "name": "get_time", "arguments": {"zone": "Rome"}
                                           -- it emitted get_time's argument, never get_weather's
  parallel_tool_calls false             -> exactly 1 <tool_call> in the answer
  no tool_choice (auto)                 -> free prose ("<think>Okay, the user wants..."), as designed
  tools + grammar, tools + response_format -> 400 naming the conflict
ctest -R npu_sampling: PASS, 41 new assertions (test_tool_grammar, test_tool_request_parsing).
tools/copyright.py --check: rc 0.

Stacked on #735 (it compiles the argument schemas with that PR's converter); base branch is
1bit/npu-json-schema, so retarget to main when #735 lands.  Not here: #652 item 3's shared answer
parser, which is what turns this markup into OpenAI's tool_calls and is what makes tool_choice
"none"/"auto" enforceable after the fact.  No device row: no current 0.6B full_i8 kernel set.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

pi-prs: re-verdict at head e1c99ca (branch force-pushed from the stale 657b60a; that head was 6 pre-#733 Merge branch 'main' commits, which is why it went DIRTY — nothing was lost in it, I checked: it simply predated #733's merge).

What this head is: a single commit rebased onto current main (33775af, which contains #733). Conflicts resolved in tests/npu_sampling_test.cpp (union: #733's test_logprobs/test_logprob_options once, then this PR's test_json_schema/test_json_schema_refusals, main() calling both, and the schema_error helper) and docs/npu.md (keep #733's logprobs paragraph, then this PR's json_schema paragraph and its reworded refusal example).

Verified at this head, not argued: tests/npu_sampling_test.cpp compiles with g++-16 -std=c++26 and prints npu_sampling: ok (152 assertion sites, incl. main's 22 from #733); app/forward_serve.cpp is byte-identical to main (this PR does not touch it — diff vs main is 5 files: app/npu_grammar.h, app/npu_json_schema.h, app/npu_sampling.h, docs/npu.md, the test file); tools/copyright.py --check rc 0. CI at this head: build pass, CodeQL pass, pr_agent pass.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

At e1c99ca3, after the conflict resolution (mergeable: true). The author patch changed — both this branch and its sibling picked up #733's logprobs code (Emitted, the chat-shape refusal comment) in the resolution — so I re-ran rather than merely confirming:

g++-16 -std=c++17 -O1 -I app -I<json-src> tests/npu_sampling_test.cpp -o … && ./…
npu_sampling: ok        (exit 0)

So the whole header set compiles and the device-free suite passes with the absorbed code in place. My review of this PR's own content stands unchanged: everything I verified at the previous head (for this PR, its own converter/test rows) still holds at this tree, and #733's additions are the ones I verdicted in #733.

Not verified: unchanged from my earlier verdict — the HTTP surface and the per-shape device behaviour that need a built forward-serve and a model.

Note on merge order: this branch now carries #733's commit, so #733 should land first or the diff will look larger than it is.

tprs-ready stands.

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 4d4db86

…ot leave the schema (#652 item 1)

The route refused json_schema with "needs a schema-to-GBNF converter this route does not
have". This is that converter: app/npu_json_schema.h compiles OpenAI's structured-outputs
subset into GBNF in the dialect app/npu_grammar.h already parses, so the constraint is
enforced while the answer is generated and no second constraint runtime is added. The
refusal at app/npu_sampling.h is replaced by the conversion; a schema it cannot honour is a
400 that names the keyword, never a constraint silently dropped from the schema.

Covered (item 1's list): objects (properties / required / additionalProperties: false),
arrays (items / minItems / maxItems), string, number, integer, boolean, null, a type list
such as ["string","null"], enum, const, and oneOf/anyOf as alternation. Empty schema = any
JSON. Refused by name: pattern, format, minLength/maxLength, minimum/maximum, multipleOf,
uniqueItems, contains, prefixItems, $ref, allOf, not, if/then/else, propertyNames,
patternProperties, dependent*, additionalProperties-as-a-schema.

Property order is the converter's choice, not the client's: required first, then the optional
ones nested inside the previous slot's presence, so no alternative can generate a stray comma
after "{" and the grammar stays linear in the number of properties instead of 2^optional.

To keep the two grammars from drifting, the rules they share (any/object/array/string/number/
integer/boolean/null/ws) now live in one place, json_shared_rules() in app/npu_grammar.h;
json_grammar() is that block rooted at an object, and the converter appends it to its own
schema rules. json_grammar() returns std::string rather than const char* because it composes.

Measured on strixhalo, Qwen3-0.6B, NPU_INFER_HOST_GEMM=1 (API layer, array never opened):
  schema {name:string, age:integer, tags:[string] min 1 max 2, required name, closed}
    asked for "a JSON object wrapped in a ```json markdown fence" ->
    {"name": "John Doe", "age": 30, "tags": ["technology", "coding"]}  (200, parses, 2 tags
    = maxItems 2, no fence, no extra property)
  enum {red,green} -> {"colour": "red"} (200)
  pattern  -> 400 "json_schema: pattern is not supported by this route's schema-to-GBNF converter"
  $ref     -> 400 "json_schema: $ref is not supported ..."
  response_format json_object -> 200 "{}" (unchanged)
ctest -R npu_sampling: PASS, 44 new assertions (test_json_schema, test_json_schema_refusals)
plus the rewritten row that used to assert the old refusal.
tools/copyright.py --check: rc 0.

Not here: item 2 (tool calling as grammar) and item 3 (the shared answer parser), so a
tool-call-shaped schema still has to be sent as response_format json_schema by the client.
No device row: this box has no current 0.6B full_i8 kernel set.
bong-water-water-bong pushed a commit that referenced this pull request Nov 1, 2026
…ot misspell a tool or misuse an argument (#652 item 2)

A request that carries `tools` now gets a grammar for the call itself. The name is an alternation
over the DECLARED names and the arguments are that function's own `parameters` schema, compiled by
app/npu_json_schema.h (item 1), so a misspelt tool, an argument of the wrong type, a missing required
field, an undeclared field or a Markdown fence around the call cannot be generated at all:

  tool_choice "required"                 at least one call, any declared tool
  tool_choice {"type":"function",...}    that function only
  parallel_tool_calls false              exactly one call;  true  one or more

The markup is Qwen3's, which is what this route's ChatML models emit:
  <tool_call>{"name": "get_weather", "arguments": {"city": "Paris"}}</tool_call>

What a context-free grammar cannot express is stated instead of faked (header note):
  "none"  forbidding a literal inside free text needs negative lookahead, which GBNF lacks, so no
          grammar is installed and the caller validates the answer (that is #652 item 3's parser).
  "auto"  means "a call, or a plain answer"; that alternation cannot be written without also
          licensing arbitrary text, so "auto" installs no grammar either.  An "auto" request must
          not silently become "required".
  "auto"/"none" also skip argument-schema validation, because with no grammar there is nothing to
          enforce and refusing a serviceable request over one function's `pattern` would be worse
          than not constraining it.  "required" compiles every schema, so there an unsupported
          keyword is a 400 that names it.

json_schema_to_gbnf() is now a wrapper over a new json_schema_rule(schema, prefix, sink), which
emits its rules under a caller-chosen prefix so several argument schemas can share one document
without colliding on `s0`/`s1` or duplicating the shared rules.  The prefix is validated: GBNF rule
names are [A-Za-z0-9-] only, and a bad prefix used to produce a grammar nothing could parse.

Two bugs found while testing this, both mine:
  1. the <tool_call> / </tool_call> literals were built with json_literal(), which JSON-encodes a
     string and so kept its quotes: the grammar demanded the text "\"<tool_call>\"" and refused
     every well-formed call.  Raw markup now goes through schema_detail::literal().
  2. the argument-rule prefix used "_", which app/npu_grammar.h's rule-name lexer does not accept,
     so the document failed to parse with "expecting '::=' at line 2".

Measured on strixhalo, Qwen3-0.6B, NPU_INFER_HOST_GEMM=1 (array never opened), 2 tools declared
(get_weather{city}, get_time{zone}):
  tool_choice required, parallel true   -> 200, valid <tool_call> blocks, "name": "get_weather",
                                           "arguments": {"city": "Paris"}; a second call follows
  tool_choice {"function":{"name":"get_time"}} -> 200, "name": "get_time", "arguments": {"zone": "Rome"}
                                           -- it emitted get_time's argument, never get_weather's
  parallel_tool_calls false             -> exactly 1 <tool_call> in the answer
  no tool_choice (auto)                 -> free prose ("<think>Okay, the user wants..."), as designed
  tools + grammar, tools + response_format -> 400 naming the conflict
ctest -R npu_sampling: PASS, 41 new assertions (test_tool_grammar, test_tool_request_parsing).
tools/copyright.py --check: rc 0.

Stacked on #735 (it compiles the argument schemas with that PR's converter); base branch is
1bit/npu-json-schema, so retarget to main when #735 lands.  Not here: #652 item 3's shared answer
parser, which is what turns this markup into OpenAI's tool_calls and is what makes tool_choice
"none"/"auto" enforceable after the fact.  No device row: no current 0.6B full_i8 kernel set.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

pi-prs: re-verdict at head 2bc1b55 — again a single json_schema commit, 5 files, 449+/20−, rebased onto current main (91eadcd, which now really contains #650 via #745).

The 2ba8421 head was an automatic Merge branch 'main' into 1bit/npu-json-schema commit that arrived with conflicts (it merged an older main, and main has since gained #650's test_prefix_cache). Rebuilt rather than merged: git reset --hard <my commit> + git rebase --onto origin/main 3722aa7, one conflict in tests/npu_sampling_test.cpp resolved as main's file + this PR's two functions (test_json_schema, test_json_schema_refusals), the schema_error helper, the using, and both main() calls.

Verified at this head: npu_sampling_test (CMake target) builds and prints npu_sampling: ok — 11 test functions, 179 assertion sites; tools/copyright.py --check rc 0; diff vs main is exactly the five expected files and app/forward_serve.cpp is untouched.

Note for whoever runs the waiter: the auto-Merge branch 'main' update is what keeps turning this PR DIRTY. A rebase-first update (or no auto-update) avoids the round trip.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

At 2bc1b555. This one is not a patch-id carry: the author diff changed since my last verdict, so I re-read and re-ran. What changed is a refactor, not a fix —

app/npu_grammar.h splits the JSON grammar into json_shared_rules() (value/string/number/boolean/null/ws in one place) and keeps json_grammar() as root ::= object + those rules, so the schema-constrained grammar in app/npu_json_schema.h cannot drift from the unconstrained one in what it accepts. The object body now uses any ::= object | array | string | number | boolean | null where it used value, which is the same language, spelled once.

Checked both ends of that:

  • callers unaffected — json_grammar() still exists (app/npu_grammar.h:671) and app/forward_serve.cpp:177 still calls npu::json_grammar() for response_format: {"type":"json_object"};
  • the suite passes at this head:
    g++-16 -std=c++17 -O1 -I app -I<json-src> tests/npu_sampling_test.cpp -o … && ./…
    npu_sampling: ok        (exit 0)
    
    which includes test_json_grammar (the unconstrained grammar) and test_json_schema (the converter this PR adds) — so the shared-rules split is exercised from both sides.

Everything else from my earlier review stands: the schema subset is enforced by construction (type mismatch, missing required, undeclared property under additionalProperties: false, minItems/maxItems, Markdown fence all refused; a half-written object stays alive but cannot end the answer).

Build at post time was still in progress on this head; the suite above is the gate I can run without it.

tprs-ready stands.

@bong-water-water-bong
bong-water-water-bong merged commit 026604b into main Nov 1, 2026
7 of 8 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/npu-json-schema branch November 1, 2026 09:20
bong-water-water-bong pushed a commit that referenced this pull request Nov 1, 2026
…ot misspell a tool or misuse an argument (#652 item 2)

A request that carries `tools` now gets a grammar for the call itself. The name is an alternation
over the DECLARED names and the arguments are that function's own `parameters` schema, compiled by
app/npu_json_schema.h (item 1), so a misspelt tool, an argument of the wrong type, a missing required
field, an undeclared field or a Markdown fence around the call cannot be generated at all:

  tool_choice "required"                 at least one call, any declared tool
  tool_choice {"type":"function",...}    that function only
  parallel_tool_calls false              exactly one call;  true  one or more

The markup is Qwen3's, which is what this route's ChatML models emit:
  <tool_call>{"name": "get_weather", "arguments": {"city": "Paris"}}</tool_call>

What a context-free grammar cannot express is stated instead of faked (header note):
  "none"  forbidding a literal inside free text needs negative lookahead, which GBNF lacks, so no
          grammar is installed and the caller validates the answer (that is #652 item 3's parser).
  "auto"  means "a call, or a plain answer"; that alternation cannot be written without also
          licensing arbitrary text, so "auto" installs no grammar either.  An "auto" request must
          not silently become "required".
  "auto"/"none" also skip argument-schema validation, because with no grammar there is nothing to
          enforce and refusing a serviceable request over one function's `pattern` would be worse
          than not constraining it.  "required" compiles every schema, so there an unsupported
          keyword is a 400 that names it.

json_schema_to_gbnf() is now a wrapper over a new json_schema_rule(schema, prefix, sink), which
emits its rules under a caller-chosen prefix so several argument schemas can share one document
without colliding on `s0`/`s1` or duplicating the shared rules.  The prefix is validated: GBNF rule
names are [A-Za-z0-9-] only, and a bad prefix used to produce a grammar nothing could parse.

Two bugs found while testing this, both mine:
  1. the <tool_call> / </tool_call> literals were built with json_literal(), which JSON-encodes a
     string and so kept its quotes: the grammar demanded the text "\"<tool_call>\"" and refused
     every well-formed call.  Raw markup now goes through schema_detail::literal().
  2. the argument-rule prefix used "_", which app/npu_grammar.h's rule-name lexer does not accept,
     so the document failed to parse with "expecting '::=' at line 2".

Measured on strixhalo, Qwen3-0.6B, NPU_INFER_HOST_GEMM=1 (array never opened), 2 tools declared
(get_weather{city}, get_time{zone}):
  tool_choice required, parallel true   -> 200, valid <tool_call> blocks, "name": "get_weather",
                                           "arguments": {"city": "Paris"}; a second call follows
  tool_choice {"function":{"name":"get_time"}} -> 200, "name": "get_time", "arguments": {"zone": "Rome"}
                                           -- it emitted get_time's argument, never get_weather's
  parallel_tool_calls false             -> exactly 1 <tool_call> in the answer
  no tool_choice (auto)                 -> free prose ("<think>Okay, the user wants..."), as designed
  tools + grammar, tools + response_format -> 400 naming the conflict
ctest -R npu_sampling: PASS, 41 new assertions (test_tool_grammar, test_tool_request_parsing).
tools/copyright.py --check: rc 0.

Stacked on #735 (it compiles the argument schemas with that PR's converter); base branch is
1bit/npu-json-schema, so retarget to main when #735 lands.  Not here: #652 item 3's shared answer
parser, which is what turns this markup into OpenAI's tool_calls and is what makes tool_choice
"none"/"auto" enforceable after the fact.  No device row: no current 0.6B full_i8 kernel set.
@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit e705bc3

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

pi-prs: re-verdict at head e705bc3 — this is now only the json_schema commit: 1 commit, 5 files, 449+/20− against main.

The 2-commit/9-file head you saw was #738's squashed commit sitting on top of this branch, because #738 had been merged into this branch (its base) instead of into main. I have:

  1. rebased this branch onto main so npu: multi-prompt prefix cache, resumes from the longest saved prompt (#650) #738's commit is gone from it (it is preserved and re-landed in npu: multi-prompt prefix cache (#650) — re-landing #738, which merged into its base branch and never reached main #745, which is the same npu: no multi-prompt prefix cache — every request prefills from scratch (FLM v1.0.11 has 8 slots) #650 change cherry-picked onto main — main never had app/npu_prefix_cache.h, so npu: multi-prompt prefix cache, resumes from the longest saved prompt (#650) #738's merge had reached no path to main);
  2. dropped the stacking that caused it: this PR's base is main, and npu: tool_choice / parallel_tool_calls as a grammar (#652 item 2, stacked on #735) #741's base has been retargeted to main too, so no PR of mine can merge into a feature branch again.

Verified at this head: npu_sampling_test builds and prints npu_sampling: ok (152 assertion sites); tools/copyright.py --check rc 0; diff vs main is exactly app/npu_grammar.h, app/npu_json_schema.h, app/npu_sampling.h, docs/npu.md, tests/npu_sampling_test.cpp; app/forward_serve.cpp untouched.

bong-water-water-bong pushed a commit that referenced this pull request Nov 1, 2026
…ot misspell a tool or misuse an argument (#652 item 2)

A request that carries `tools` now gets a grammar for the call itself. The name is an alternation
over the DECLARED names and the arguments are that function's own `parameters` schema, compiled by
app/npu_json_schema.h (item 1), so a misspelt tool, an argument of the wrong type, a missing required
field, an undeclared field or a Markdown fence around the call cannot be generated at all:

  tool_choice "required"                 at least one call, any declared tool
  tool_choice {"type":"function",...}    that function only
  parallel_tool_calls false              exactly one call;  true  one or more

The markup is Qwen3's, which is what this route's ChatML models emit:
  <tool_call>{"name": "get_weather", "arguments": {"city": "Paris"}}</tool_call>

What a context-free grammar cannot express is stated instead of faked (header note):
  "none"  forbidding a literal inside free text needs negative lookahead, which GBNF lacks, so no
          grammar is installed and the caller validates the answer (that is #652 item 3's parser).
  "auto"  means "a call, or a plain answer"; that alternation cannot be written without also
          licensing arbitrary text, so "auto" installs no grammar either.  An "auto" request must
          not silently become "required".
  "auto"/"none" also skip argument-schema validation, because with no grammar there is nothing to
          enforce and refusing a serviceable request over one function's `pattern` would be worse
          than not constraining it.  "required" compiles every schema, so there an unsupported
          keyword is a 400 that names it.

json_schema_to_gbnf() is now a wrapper over a new json_schema_rule(schema, prefix, sink), which
emits its rules under a caller-chosen prefix so several argument schemas can share one document
without colliding on `s0`/`s1` or duplicating the shared rules.  The prefix is validated: GBNF rule
names are [A-Za-z0-9-] only, and a bad prefix used to produce a grammar nothing could parse.

Two bugs found while testing this, both mine:
  1. the <tool_call> / </tool_call> literals were built with json_literal(), which JSON-encodes a
     string and so kept its quotes: the grammar demanded the text "\"<tool_call>\"" and refused
     every well-formed call.  Raw markup now goes through schema_detail::literal().
  2. the argument-rule prefix used "_", which app/npu_grammar.h's rule-name lexer does not accept,
     so the document failed to parse with "expecting '::=' at line 2".

Measured on strixhalo, Qwen3-0.6B, NPU_INFER_HOST_GEMM=1 (array never opened), 2 tools declared
(get_weather{city}, get_time{zone}):
  tool_choice required, parallel true   -> 200, valid <tool_call> blocks, "name": "get_weather",
                                           "arguments": {"city": "Paris"}; a second call follows
  tool_choice {"function":{"name":"get_time"}} -> 200, "name": "get_time", "arguments": {"zone": "Rome"}
                                           -- it emitted get_time's argument, never get_weather's
  parallel_tool_calls false             -> exactly 1 <tool_call> in the answer
  no tool_choice (auto)                 -> free prose ("<think>Okay, the user wants..."), as designed
  tools + grammar, tools + response_format -> 400 naming the conflict
ctest -R npu_sampling: PASS, 41 new assertions (test_tool_grammar, test_tool_request_parsing).
tools/copyright.py --check: rc 0.

Stacked on #735 (it compiles the argument schemas with that PR's converter); base branch is
1bit/npu-json-schema, so retarget to main when #735 lands.  Not here: #652 item 3's shared answer
parser, which is what turns this markup into OpenAI's tool_calls and is what makes tool_choice
"none"/"auto" enforceable after the fact.  No device row: no current 0.6B full_i8 kernel set.
bong-water-water-bong pushed a commit that referenced this pull request Nov 1, 2026
…ot misspell a tool or misuse an argument (#652 item 2)

A request that carries `tools` now gets a grammar for the call itself. The name is an alternation
over the DECLARED names and the arguments are that function's own `parameters` schema, compiled by
app/npu_json_schema.h (item 1), so a misspelt tool, an argument of the wrong type, a missing required
field, an undeclared field or a Markdown fence around the call cannot be generated at all:

  tool_choice "required"                 at least one call, any declared tool
  tool_choice {"type":"function",...}    that function only
  parallel_tool_calls false              exactly one call;  true  one or more

The markup is Qwen3's, which is what this route's ChatML models emit:
  <tool_call>{"name": "get_weather", "arguments": {"city": "Paris"}}</tool_call>

What a context-free grammar cannot express is stated instead of faked (header note):
  "none"  forbidding a literal inside free text needs negative lookahead, which GBNF lacks, so no
          grammar is installed and the caller validates the answer (that is #652 item 3's parser).
  "auto"  means "a call, or a plain answer"; that alternation cannot be written without also
          licensing arbitrary text, so "auto" installs no grammar either.  An "auto" request must
          not silently become "required".
  "auto"/"none" also skip argument-schema validation, because with no grammar there is nothing to
          enforce and refusing a serviceable request over one function's `pattern` would be worse
          than not constraining it.  "required" compiles every schema, so there an unsupported
          keyword is a 400 that names it.

json_schema_to_gbnf() is now a wrapper over a new json_schema_rule(schema, prefix, sink), which
emits its rules under a caller-chosen prefix so several argument schemas can share one document
without colliding on `s0`/`s1` or duplicating the shared rules.  The prefix is validated: GBNF rule
names are [A-Za-z0-9-] only, and a bad prefix used to produce a grammar nothing could parse.

Two bugs found while testing this, both mine:
  1. the <tool_call> / </tool_call> literals were built with json_literal(), which JSON-encodes a
     string and so kept its quotes: the grammar demanded the text "\"<tool_call>\"" and refused
     every well-formed call.  Raw markup now goes through schema_detail::literal().
  2. the argument-rule prefix used "_", which app/npu_grammar.h's rule-name lexer does not accept,
     so the document failed to parse with "expecting '::=' at line 2".

Measured on strixhalo, Qwen3-0.6B, NPU_INFER_HOST_GEMM=1 (array never opened), 2 tools declared
(get_weather{city}, get_time{zone}):
  tool_choice required, parallel true   -> 200, valid <tool_call> blocks, "name": "get_weather",
                                           "arguments": {"city": "Paris"}; a second call follows
  tool_choice {"function":{"name":"get_time"}} -> 200, "name": "get_time", "arguments": {"zone": "Rome"}
                                           -- it emitted get_time's argument, never get_weather's
  parallel_tool_calls false             -> exactly 1 <tool_call> in the answer
  no tool_choice (auto)                 -> free prose ("<think>Okay, the user wants..."), as designed
  tools + grammar, tools + response_format -> 400 naming the conflict
ctest -R npu_sampling: PASS, 41 new assertions (test_tool_grammar, test_tool_request_parsing).
tools/copyright.py --check: rc 0.

Stacked on #735 (it compiles the argument schemas with that PR's converter); base branch is
1bit/npu-json-schema, so retarget to main when #735 lands.  Not here: #652 item 3's shared answer
parser, which is what turns this markup into OpenAI's tool_calls and is what makes tool_choice
"none"/"auto" enforceable after the fact.  No device row: no current 0.6B full_i8 kernel set.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY

At e705bc32f, clean (mergeable: true, state clean). Author patch byte-identical to the head I verified after the conflict resolution (patch-id 658293e64655 unchanged), so this is a clean rebase: my review stands, including the part I re-ran — the device-free suite compiled and npu_sampling: ok at that head, with #733's logprobs code absorbed.

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 2ba8421

bong-water-water-bong added a commit that referenced this pull request Nov 1, 2026
…ot misspell a tool or misuse an argument (#652 item 2) (#741)

A request that carries `tools` now gets a grammar for the call itself. The name is an alternation
over the DECLARED names and the arguments are that function's own `parameters` schema, compiled by
app/npu_json_schema.h (item 1), so a misspelt tool, an argument of the wrong type, a missing required
field, an undeclared field or a Markdown fence around the call cannot be generated at all:

  tool_choice "required"                 at least one call, any declared tool
  tool_choice {"type":"function",...}    that function only
  parallel_tool_calls false              exactly one call;  true  one or more

The markup is Qwen3's, which is what this route's ChatML models emit:
  <tool_call>{"name": "get_weather", "arguments": {"city": "Paris"}}</tool_call>

What a context-free grammar cannot express is stated instead of faked (header note):
  "none"  forbidding a literal inside free text needs negative lookahead, which GBNF lacks, so no
          grammar is installed and the caller validates the answer (that is #652 item 3's parser).
  "auto"  means "a call, or a plain answer"; that alternation cannot be written without also
          licensing arbitrary text, so "auto" installs no grammar either.  An "auto" request must
          not silently become "required".
  "auto"/"none" also skip argument-schema validation, because with no grammar there is nothing to
          enforce and refusing a serviceable request over one function's `pattern` would be worse
          than not constraining it.  "required" compiles every schema, so there an unsupported
          keyword is a 400 that names it.

json_schema_to_gbnf() is now a wrapper over a new json_schema_rule(schema, prefix, sink), which
emits its rules under a caller-chosen prefix so several argument schemas can share one document
without colliding on `s0`/`s1` or duplicating the shared rules.  The prefix is validated: GBNF rule
names are [A-Za-z0-9-] only, and a bad prefix used to produce a grammar nothing could parse.

Two bugs found while testing this, both mine:
  1. the <tool_call> / </tool_call> literals were built with json_literal(), which JSON-encodes a
     string and so kept its quotes: the grammar demanded the text "\"<tool_call>\"" and refused
     every well-formed call.  Raw markup now goes through schema_detail::literal().
  2. the argument-rule prefix used "_", which app/npu_grammar.h's rule-name lexer does not accept,
     so the document failed to parse with "expecting '::=' at line 2".

Measured on strixhalo, Qwen3-0.6B, NPU_INFER_HOST_GEMM=1 (array never opened), 2 tools declared
(get_weather{city}, get_time{zone}):
  tool_choice required, parallel true   -> 200, valid <tool_call> blocks, "name": "get_weather",
                                           "arguments": {"city": "Paris"}; a second call follows
  tool_choice {"function":{"name":"get_time"}} -> 200, "name": "get_time", "arguments": {"zone": "Rome"}
                                           -- it emitted get_time's argument, never get_weather's
  parallel_tool_calls false             -> exactly 1 <tool_call> in the answer
  no tool_choice (auto)                 -> free prose ("<think>Okay, the user wants..."), as designed
  tools + grammar, tools + response_format -> 400 naming the conflict
ctest -R npu_sampling: PASS, 41 new assertions (test_tool_grammar, test_tool_request_parsing).
tools/copyright.py --check: rc 0.

Stacked on #735 (it compiles the argument schemas with that PR's converter); base branch is
1bit/npu-json-schema, so retarget to main when #735 lands.  Not here: #652 item 3's shared answer
parser, which is what turns this markup into OpenAI's tool_calls and is what makes tool_choice
"none"/"auto" enforceable after the fact.  No device row: no current 0.6B full_i8 kernel set.

Co-authored-by: bong-water-water-bong <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Review effort 4/5 tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant