Skip to content

Native structured output: libtfgrammar (xgrammar, loaded at runtime), masks in the lane core, enforced by Qwen3.5-2B on Metal - #596

Merged
ashhart merged 2 commits into
ashhart:mainfrom
BobClawblaw:structured-output
Oct 11, 2026
Merged

ashhart merged 2 commits into
ashhart:mainfrom
BobClawblaw:structured-output

Conversation

@BobClawblaw

Copy link
Copy Markdown
Contributor

Closes #564. This is structured output landed with the first family that enforces it, per your answers there: an optional xgrammar library loaded at runtime, masking in the lane core, and the gate you set.

What changes

libtfgrammar (zig/src/grammar/tf_grammar.cc, about 200 lines): a C ABI over xgrammar's C++ library, driven the way tensorfold/engine/grammar.py drove the Python package.

  • The compiler is built from the tokenizer.json vocabulary, the logits' width and the eos ids.
  • It compiles json and json_schema (with 32 blanks), regex, choice and EBNF.
  • Matchers accept, roll back, report termination and fill next-token bitmasks.
  • Errors come back as xgrammar's text without its timestamp and source path.

Build. zig build grammar -Dxgrammar=DIR builds it from an xgrammar v0.2.8 checkout (pinned in zig/build/grammar.zig) into zig-out/native/lib; it took about 10 s on an M5 Ultra. Nothing from xgrammar is vendored. The server loads the library on the first structured request, looking beside its bin first. It builds and serves text without it, and a structured request then gets a 400 that names the library.

Server.

  • One compiler per model, opened on first use from tokenizer.json, config.json's vocab_size and the eos ids.
  • Each request's grammar is compiled before admission. A grammar xgrammar can't compile gets a 400 with xgrammar's reason.
  • The engine receives the compiler; its own compile is a cache hit.

Lane core (lanes/grammar.zig, Python's Constraint). The core owns each stream's grammar:

  • It follows every committed token.
  • Before each verify, it keeps only the rows an accepted path can use. A draft the grammar rejects goes with its descendants, and nothing is verified after the stop token. Held chains are read back through the head's ranks (alternatives); a held tree verifies no drafts.
  • It hands the backend one allowed-token bitmask per kept row (Window.masks). The first token's mask goes through Backend.first_masked. Forced rows stay in the window.
  • A grammar stream takes verify windows, never pipelined steps.
  • With thinking on, the grammar starts after the think end. Under a grammar, a thinking budget's close ends at that token, as Python's did.
  • The grammar's stop token ends a reply that ignores eos.
  • A token the grammar rejects ends that reply alone (error, with a message); the round goes on.

First family: Qwen3.5-2B on Metal sets Info.structures. Its draws consider only a row's allowed tokens. That is the draw Python's -inf logits give: a -inf candidate never wins the keyed draw and doesn't move top-p or min-p. A host test checks this against the full-vocabulary draw at several top-k, top-p and min-p settings.

Gate

M5 Ultra, macOS 27.0.1, mlx-community/Qwen3.5-2B-MLX-4bit @ 93760be4, xgrammar 0.2.8.

  • Masks equal to xgrammar's own matcher (tools/zig/grammar_masks.py). It drives libtfgrammar through the C ABI the server loads, side by side with the Python package's GrammarMatcher, on a fixed set of 11 grammars: json object, three schemas (flat, nested with arrays/enums/limits, anyOf), three regexes (date, email, unicode), two choices (one with quotes, backslash and tab) and two EBNF grammars. The walks accept random allowed tokens, try disallowed ones and roll back. 855 steps, 0 mismatches in bitmask, accept and termination. Three malformed grammars are refused by both.
  • Served (tools/zig/structured_served.py, --parallel 4). Every field and kind (response_format json_object and json_schema, guided_json, guided_regex, guided_choice, guided_grammar, structured_outputs, plus a plain request), each greedy and seeded-sampled, thinking off and on. The thinking runs carry a 256-token thinking budget, so a forced close comes before the grammar.
    • 32 of 32 runs are valid against their grammar, drafted equal to "draft": false.
    • All 32 at once, 4 at a time with grammar and plain requests mixed: 32 of 32 equal their run alone.
  • Refusals (400 before any token): malformed regex, undefined EBNF rule, schema that isn't JSON, unknown response_format type, a grammar with tool_choice: "required", and a server that can't load libtfgrammar.
  • Engine tests on the fake backend with a test grammar that rejects drafts often:
    • drafted equals one-token decode, greedy and sampled, with held chains read back and dropped;
    • shared rounds of grammar and plain streams equal each stream alone;
    • the thinking start and the forced close;
    • the stop token ending a reply that ignores eos.
  • zig build test passes. One step (run test w) fails intermittently on main as well, 1 in 5 runs on an unmodified checkout.

Not covered here

  • The 2B has no draft head, so its drafts are copies. The held-chain read-back is covered only by the fake's ranked head; the first family with a head that holds drafts will exercise it on real weights.
  • zig build grammar on Linux/CUDA isn't built yet. The step and the loader (libtfgrammar.so) are written for it, and the CUDA families' mask step would follow as its own PR.

…itmask a verify row

libtfgrammar (zig/src/grammar/tf_grammar.cc): a C ABI over xgrammar's C++
library, as tensorfold/engine/grammar.py drove the Python package: the
tokenizer.json vocabulary, the logits' width and the eos ids; json and
json_schema with 32 blanks, regex, choice, EBNF; matchers that accept, roll
back, report termination and fill next-token bitmasks; xgrammar's errors
without their timestamp and source location. `zig build grammar
-Dxgrammar=DIR` builds it from an xgrammar v0.2.8 checkout into
zig-out/native/lib; nothing from xgrammar is in the tree, and the server builds
and serves text without it.

The server opens one compiler per model on the first structured request, compiles
each request's grammar before admission (a 400 with xgrammar's reason when it
cannot, or naming the library when it cannot load) and hands the engine the
compiler, whose compile is then a cache hit.

The lane core owns each stream's grammar (lanes/grammar.zig, Python's
Constraint): it follows every committed token, and before each verify keeps the
rows an accepted path can use (a draft the grammar rejects goes with its rows,
nothing is verified after the stop token; held chains come back by the head's
ranks) and hands the backend one allowed-token bitmask per kept row
(Window.masks), the first token's through Backend.first_masked. A grammar
stream takes verify windows, never pipelined steps; under a grammar the
thinking budget's close ends at the think end, and the grammar's stop token
ends a reply that ignores eos. A token the grammar rejects ends that reply
alone. Engine tests on the fake: drafted equals one-token decode, shared rounds
of grammar and plain streams equal each alone, greedy and sampled, through a
forced close.
The 2B's draws take only a row's allowed tokens: the draw Python's -inf
logits give, since a -inf candidate never wins the keyed draw nor moves top-p
or min-p (a host test checks it against the full-vocabulary draw).

tools/zig/grammar_masks.py: libtfgrammar's masks, accepts, rollbacks and
termination against xgrammar 0.2.8's own matcher on a fixed grammar set,
through the C ABI the server loads. tools/zig/structured_served.py: every
field and kind, greedy and sampled, thinking off and on, valid and drafted
equal to "draft": false; all at once equal to alone with plain requests mixed;
the 400 refusals.
@ashhart
ashhart merged commit d7d5f6f into ashhart:main Oct 11, 2026
2 checks passed
@ashhart

ashhart commented Oct 11, 2026

Copy link
Copy Markdown
Owner

Thank you, @BobClawblaw. This is in 1.0.6: merge ef6b7a468 brings in your two commits (6bccf6442, 0e0302072) under
your name, with our commits after it, and d7d5f6f12 merges your rebased head 8ced20188, so the PR shows as merged. The shim, the lane core's grammar walk, the build step, the server's compile-once
refusals and the 2B's masked draw are as you wrote them.

What we added on top, and why:

  • Nemotron drafts under a grammar. Its served chains don't keep the head's ranked alternatives, so constrain() got
    none back and dropped every held draft: a grammar stream decoded one token a round. A new Backend.held reads the
    drafts the head wrote into the stream's next window, chains and trees alike, and the grammar walks those.
  • Nemotron enforces grammars on Metal and on CUDA: a kernel turns each verify row's disallowed logits to -inf before
    its draw, and the first token is drawn among the grammar's tokens.
  • tool_choice: "required" and a named function are a grammar now: calls in the template's own markup, each with its
    arguments inside the tool's schema (an xgrammar structural tag, the shim's kind 5). parallel_tool_calls: false
    allows one call.
  • libtfgrammar ships in each release archive's lib/ (macOS arm64, Linux x86_64 and aarch64), and the server finds
    it there.
  • The grammar drafts the text it forces (xgrammar's jump-forward string, spelled as tokens) after the head's drafts.
    On Nemotron that is +4% decode on average over 20 structured cells on CUDA and +0.7% on Metal; JSON schemas gain
    most, up to 10-20%.

Checks on this tree: your mask oracle, extended with the two tool grammars, finds 0 mismatches in 1,134 steps against
xgrammar 0.2.8's Python package, and the library gives the same masks on all three platforms. Served Nemotron on CUDA:
22 of 22 cells valid (JSON schemas, regex, choice, required and named tool calls, greedy and sampled), each equal to
its "draft": false reply token for token, and replies without a grammar equal to main's. On an M3 Ultra, 26 of 26 cells
pass the same way, and your served harness gives 32 of 32 concurrent replies equal to their runs alone.

One thing we saw on the 2B in the release gate: on an integer field it wants to write as a decimal (an invoice's
unit_price_cents), it keeps adding digits until max_tokens, since the grammar allows no decimal point there. Drafted
and "draft": false give the same tokens, and Nemotron writes the same schema correctly, so it's the small model under
that constraint rather than the mask.

jschmied pushed a commit to jschmied/TensorFold that referenced this pull request Oct 11, 2026
lane_host.zig was at 596 lines with ashhart#578 and ashhart#596 still to add; the lesson queue and its idle-only step are their own job. A move, with words() made public and the two lock wrappers inlined.
jschmied pushed a commit to jschmied/TensorFold that referenced this pull request Oct 11, 2026
…loaded at runtime), masks in the lane core, enforced by Qwen3.5-2B on Metal

Thanks @BobClawblaw. Conflicts with ashhart#623 kept both (lane_host.zig's fillOne/unfill beside the constraint; addStream's two changes ported into lanes/open.zig: drawFirst for the first token, no pipelined first step under a grammar; both engine tests kept).
jschmied pushed a commit to jschmied/TensorFold that referenced this pull request Oct 11, 2026
The API page says which native engines enforce structured output and required tool calls, where libtfgrammar comes
from and what is refused. The 2B's masked-draw comment and the served harness's docstring are one line each.
jschmied pushed a commit to jschmied/TensorFold that referenced this pull request Oct 11, 2026
…nds across runner slots, DFlash2 for one stream, and tf-qwen27-bench

On the 1.0.6 candidate: the stream spec and the fake backend carry ashhart#596's grammar beside ashhart#578's decode spans and memory
lanes, and the lane host gives a stream both. ashhart#596 gave the 2B's draw a grammar mask; the 27B's lane backend passes none,
as it serves no structured output.

Thanks @BobClawblaw.
@BobClawblaw
BobClawblaw deleted the structured-output branch October 11, 2026 20:35
BlivionIaG pushed a commit to BlivionIaG/TensorFold that referenced this pull request Oct 20, 2026
lane_host.zig was at 596 lines with ashhart#578 and ashhart#596 still to add; the lesson queue and its idle-only step are their own job. A move, with words() made public and the two lock wrappers inlined.
BlivionIaG pushed a commit to BlivionIaG/TensorFold that referenced this pull request Oct 20, 2026
…loaded at runtime), masks in the lane core, enforced by Qwen3.5-2B on Metal

Thanks @BobClawblaw. Conflicts with ashhart#623 kept both (lane_host.zig's fillOne/unfill beside the constraint; addStream's two changes ported into lanes/open.zig: drawFirst for the first token, no pipelined first step under a grammar; both engine tests kept).
BlivionIaG pushed a commit to BlivionIaG/TensorFold that referenced this pull request Oct 20, 2026
The API page says which native engines enforce structured output and required tool calls, where libtfgrammar comes
from and what is refused. The 2B's masked-draw comment and the served harness's docstring are one line each.
BlivionIaG pushed a commit to BlivionIaG/TensorFold that referenced this pull request Oct 20, 2026
The author rebased ashhart#596 onto main after our merge; this keeps the PR's current head in the history with no change to the tree.
BlivionIaG pushed a commit to BlivionIaG/TensorFold that referenced this pull request Oct 20, 2026
…nds across runner slots, DFlash2 for one stream, and tf-qwen27-bench

On the 1.0.6 candidate: the stream spec and the fake backend carry ashhart#596's grammar beside ashhart#578's decode spans and memory
lanes, and the lane host gives a stream both. ashhart#596 gave the 2B's draw a grammar mask; the 27B's lane backend passes none,
as it serves no structured output.

Thanks @BobClawblaw.
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.

Native structured output: an xgrammar shim and lane grammar types, before any family enforces it

2 participants