Skip to content

Structured output on the Flash Next CUDA engine: response_format and guided_* enforced (patch 0032) - #69

Closed
devopsfortunato wants to merge 1 commit into
MiaAI-Lab:mainfrom
devopsfortunato:structured-output
Closed

devopsfortunato wants to merge 1 commit into
MiaAI-Lab:mainfrom
devopsfortunato:structured-output

Conversation

@devopsfortunato

@devopsfortunato devopsfortunato commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Today the Zig engine answers response_format and the guided_* fields with HTTP 400 ("structured output ... is not supported by this engine yet"). Clients that rely on it (tool-eval-bench, mem0, see #66) then fall back to prompt-only JSON, and the model often answers in prose after a tool call. This PR enforces structured output by constrained decoding.

What changes

  • patches/0032-engine-structured-output.patch (after 0031; on current main the 20 patches apply on a clean db281878 and give exactly the tested engine tree):
    • Grammar layer, ported from TensorFold PR #596 by @BobClawblaw: libtfgrammar (a C ABI over xgrammar v0.2.8, loaded on the first structured request), the lane core's grammar constraint (per-row masks, drafts the grammar rejects are trimmed), and the server's parsing of response_format (json_object, json_schema), structured_outputs, guided_json / guided_regex / guided_choice / guided_grammar, Responses text.format and Anthropic output_config.format.
    • Compiling, bounded:
      • The server compiles a request's grammar once, on its own thread, before the request reaches the engine. The engine thread only builds a matcher from it: it compiles nothing and takes no lock.
      • A compile gets 10 s; past that the request is refused (HTTP 400) and the compile ends on its own.
      • At most 4 compiles run at once, abandoned ones included. A request waits for a free one within the same 10 s, and is refused with "retry shortly" when none frees up.
      • A schema, regex, choice list or grammar over 64 KiB, or nested deeper than 64 levels, is refused with HTTP 400 before it is compiled.
    • Flash Next CUDA:
      • Mask kernel: tf_fn_grammar_mask sets the bf16 logits of disallowed tokens to -inf. The existing greedy, top-k or nucleus draw then runs unchanged. The mask is uploaded on the engine's stream, ahead of the kernel.
      • First token: it is drawn from the prompt's last logits row (kept on the host for grammar streams only) under the same mask.
      • MTP drafts: held drafts are read back (held) and walked through the grammar, and each verify row is masked. A drafted structured reply therefore equals its "draft": false reply.
      • Prompt bursts: a burst with a structured request is filled one prompt at a time.
      • Ranks: structures is on at one rank only.
    • Tests:
      • zig build grammar-test: libtfgrammar's C ABI through the lane core (masks, a drafted window and its rollback, the grammar after </think>, xgrammar's error text for a bad schema, the compile limits including the timeout and the slot wait).
      • zig build flashnext-grammar-mask: the CUDA mask kernel against a host reference on 5 shapes, Flash Next's 248,320-token rows and a padded 16-row drafted window among them, and the shapes it refuses.
      • Lanes engine tests (drafted == plain with and without held drafts, shared rounds == alone, thinking then grammar, the grammar's stop), the Flash Next Toy engine test (grammar streams alone, together, and four at once), and a server test of the depth count.
  • scripts/prepare.sh:
    • clones xgrammar v0.2.8 at depth 1 (commit-checked) and fetches only its 3rdparty/dlpack submodule (googletest and cpptrace are not built);
    • runs zig build grammar to build libtfgrammar.so, then zig build grammar-test on it;
    • links it into /usr/local/lib with ldconfig, and the build fails unless ctypes.CDLL("libtfgrammar.so") loads;
    • ships the xgrammar, dlpack and picojson licenses in /opt/tensorfold/share/doc/xgrammar.
    • The image grows by about 50 MB (libtfgrammar.so is 48 MB); xgrammar's source stays in the build stage. The image hash changes, so start.sh rebuilds once.
  • README (the structured-output bullet), CHANGELOG, CREDITS (#596, xgrammar).

The engine commits behind the patch, for review: https://github.com/devopsfortunato/TensorFold/tree/flashnext-structured-output-v2

  • 7ebf4431 is the pin plus the recipe's patches through 0031.
  • de2ded8a ports #596's lane core and server; 25d48efd names the reply's grammar apart from the constraint method.
  • 55457fdc is the Flash Next CUDA side.
  • 53d7980c moves the compile to the request thread with its limits and adds the tests; d7f30ac3 orders the mask uploads on the engine's stream and makes a request wait for a compile slot.

Evidence (one DGX Spark, NVIDIA FP4 checkpoint, THINKING=0, port 8000)

tool-eval-bench 2.8.1.dev13 (97 scenarios, --hardmode --seed 42 --temperature 0 --timeout 300 --no-think). "Before" is the stock image zig-db28187 in two runs; "after" is this branch.

before (run 1 / run 2) after
Final score 86 / 86 88
Total points 166 / 166 170
Structured Output 6/12 / 6/12 10/12
TC-64 Simple Schema pass / pass pass
TC-65 Tool → Structured partial (not JSON) pass
TC-66 Nested Schema partial (not JSON) pass
TC-67 Enum + Analysis partial (not JSON) pass
TC-68 Schema Violation Resistance fail fail*
TC-69 Multi-Tool → Complex Schema partial (not JSON) pass
response_format fallback in the report TC-64/65/66/67/69 "endpoint rejected it" none

* TC-68 sends no response_format on purpose (the bench's tc68.py: "intentionally NO response_format_override"), so there is nothing for the server to enforce.

Every other scenario scores the same in every run. The rebased branch scores the same 97 results as the first version of this PR.

Plain requests are unchanged, against main e1f564e's image:

  • tools/exact.py: per-prompt text and token hashes are equal to main's; drafted == "draft": false (495 drafts accepted); concurrent == serial. PASS.
  • tools/toolcheck.py: 3/3.
  • tools/bench.py decode (main → this branch): code greedy 69.9 → 70.2 tok/s; chat sampled 42.9 → 43.4 tok/s.

Structured requests (a small client script, temperature 0):

  • Every reply is valid for its constraint:
    • json_schema with a prose-inviting prompt, json_object (the first token is {), guided_choice and guided_regex;
    • a JSON answer after a tool result with the tools still offered;
    • thinking on, where the grammar starts after </think>.
  • Drafted == "draft": false for json_schema and json_object. 60 structured replies (10 rounds, drafted and "draft": false) all succeed, and each equals the first reply of its kind.
  • 4 structured plus 4 plain requests at once give the same replies as each served alone.
  • Refused with HTTP 400: a schema xgrammar cannot compile ("the grammar cannot be enforced: ..."), a schema over 64 KiB, one nested 81 deep, a regex nested 70 deep. Served: a schema nested 21 deep, and 8 distinct schemas sent at once.
  • Speed, 700-token replies, end to end: plain 41.9 tok/s, json_object 40.4, json_schema 40.8 (main plain 41.4).
  • tf-flashnext-grammar-mask passes on the GB10.

Limits

  • One rank only: at TP=2 a structured request is still refused with HTTP 400.
  • Tools plus response_format in one request: the grammar holds from the reply's first token, so the model cannot open a tool call in that turn. vLLM behaves the same way, and tool-eval-bench sends response_format only after the first tool round.
  • max_tokens: a reply cut by max_tokens can end mid-JSON.
  • xgrammar is a new build-time dependency; without libtfgrammar.so only structured requests are refused ("the server cannot load libtfgrammar.so"), plain serving does not load it.

Refs #66.

@plotarmordev

Copy link
Copy Markdown

I tested this on one DGX Spark with the Qwen3.8 Flash Next FP4 weights, current main 656879f against this branch at 06ce0fe, thinking off.
On main, response_format json_schema and json_object both return HTTP 400; on this branch both return HTTP 200 with valid JSON, and the schema reply has exactly a string answer and an integer count.
Drafted and draft:false replies matched for both formats (content, finish reason, token hash), and exact.py passed with all twelve text and token hashes equal to main (495 accepted drafts).
I did not rerun tool-eval-bench (the 97 scenarios), guided regex/choice, thinking-on, tools, the 4+4 concurrency matrix, or the 700-token structured speed numbers.

@MiaAI-Lab

Copy link
Copy Markdown
Owner

Thanks for this, and for the benchmark numbers; a third party reproduced the basic json_schema and json_object cases on a Spark. It stays open and is not merged by the triage because it adds a new build-time dependency (xgrammar v0.2.8 built from source into the image, scripts/prepare.sh), which needs a maintainer decision. Reading the patch: grammar compilation runs under one process-wide lock with no timeout (Compiler.compile), the server compiles on the request thread and LaneHost.startOne compiles again on the engine thread, so a slow or cache-missed compile can stall every stream; there are no size, depth or time limits on user-supplied schemas, regexes and grammars beyond the HTTP body limit; the clone fetches submodules the build does not use (googletest, cpptrace); and none of the new tests exercise tf_grammar.cc, the Zig FFI or the CUDA mask. It also conflicts with #44, #49, #70, #72 and #73 and uses the patch number 0016 that #70 also used. Linked to #66.

(Review notes prepared with Claude Code on behalf of the maintainer.)

Constrained decoding for response_format (json_object, json_schema) and
the guided_* fields, over xgrammar v0.2.8 (libtfgrammar, from TensorFold
PR #596) with a CUDA mask kernel, masked first token and MTP drafts
checked against the grammar.

Rebased on main and renumbered from 0016 to 0032, after 0031. The server
compiles each grammar once, off the engine thread, within 10 s and at
most 4 at a time; grammars over 64 KiB or nested past 64 levels are
refused. prepare.sh fetches only xgrammar's dlpack submodule and runs
the new libtfgrammar tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@devopsfortunato devopsfortunato changed the title Structured output on the Flash Next CUDA engine: response_format and guided_* enforced (patch 0016) Structured output on the Flash Next CUDA engine: response_format and guided_* enforced (patch 0032) Oct 26, 2026
@devopsfortunato

Copy link
Copy Markdown
Contributor Author

Thanks for the review. I pushed a rebased version: one commit on e1f564e. Point by point:

Compile lock and double compile. Both are gone. The server compiles a request's grammar once, on its own thread, before the request reaches the engine. LaneHost.startOne only builds a matcher from that compiled grammar: xgrammar's compiler is thread-safe, and each matcher keeps its own reference to the grammar. The engine thread compiles nothing and takes no lock.

Time, size and depth limits.

  • A compile gets 10 s. Past that the request is refused (400); the compile finishes on its own thread and is then freed.
  • At most 4 compiles run at once, abandoned ones included. A request waits for a free slot within the same 10 s, and gets "retry shortly" when none frees up.
  • A schema, regex, choice list or grammar over 64 KiB, or nested deeper than 64 levels, is refused with 400 before it is compiled. Brackets inside strings and after escapes don't count toward the depth.

Submodules. prepare.sh clones v0.2.8 at depth 1, checks the commit and fetches only 3rdparty/dlpack. googletest and cpptrace are no longer fetched.

Tests.

  • zig build grammar-test: libtfgrammar's C ABI through the lane core. It covers masks, a drafted window and its rollback, the grammar after </think>, xgrammar's error text for a bad schema, and the compile limits, including the timeout and the slot wait. prepare.sh runs it on the library it builds.
  • zig build flashnext-grammar-mask: the CUDA mask kernel against a host reference on 5 shapes, among them Flash Next's 248,320-token rows and a padded 16-row drafted window. It also checks the shapes the kernel refuses.
  • A server test of the depth count.

Patch number. It is now patches/0032, after 0031. On current main the 20 patches apply on db281878 and give exactly the engine tree I tested.

Conflicts with the other PRs.

xgrammar as a dependency. That decision is yours. The facts:

  • It is needed at build time only: pinned to v0.2.8 with a commit check, and built in the build stage. Its source does not ship in the final image; its licenses are in /opt/tensorfold/share/doc/xgrammar.
  • The image grows by about 50 MB (libtfgrammar.so is 48 MB).
  • At run time the server loads the library on the first structured request. Plain requests never touch it. If it is missing, a structured request is refused with "the server cannot load libtfgrammar.so".

A bug I found while re-testing. With "draft": false, a structured reply could fail now and then with a 500, "the reply's grammar rejected a chosen token". The mask and the first token's logits row were copied with cuMemcpyHtoD. That copy runs on the legacy stream, which the engine's non-blocking stream does not wait for, and from pageable memory it can return before the DMA lands. A row could then be masked with the previous token's mask. Both copies are now cuMemcpyHtoDAsync on the engine's stream, ahead of the kernel. The first version of this PR had the same bug.

Validation on a DGX Spark: this branch's image against main e1f564e's.

Check main this PR
tools/exact.py (drafted = "draft": false, concurrent = serial) pass pass, same text and token hashes as main
tools/toolcheck.py 3/3 3/3
Decode, tools/bench.py: code greedy / chat sampled (tok/s) 69.9 / 42.9 70.2 / 43.4
700-token reply: plain / json_object / json_schema (tok/s) 41.4 / – / – 41.9 / 40.4 / 40.8
Structured replies (json_object, json_schema), drafted and "draft": false, 10 rounds – 60/60 succeed, each equal to the first reply of its kind
Drafted = "draft": false; 4 structured beside 4 plain = each served alone; guided_choice, guided_regex, JSON after a tool result, thinking on – pass
Limits: 64 KiB+ schema, 81-deep schema and 70-deep regex refused with 400; 21-deep schema served; 8 distinct schemas at once all served – pass
tool-eval-bench 2.8.1 (97 scenarios, --hardmode, seed 42, temperature 0, thinking off) 86 (stock image, earlier run) 88; Structured Output 6/12 → 10/12, every other scenario as on stock
CUDA mask kernel test (tf-flashnext-grammar-mask) – pass

Before the fix, this repeated test hit that 500 in round 1. After it, 60 of 60 pass.

@MiaAI-Lab

Copy link
Copy Markdown
Owner

Thank you for this work. Structured output and required tool calls now work on main without this patch: the v1.1.4 image copies TensorFold's own prebuilt libtfgrammar.so (xgrammar) from its release archive (scripts/prepare.sh:139, :180; SHA-256 pinned in scripts/config.sh), so the recipe adds no grammar build and no new compile-time dependency. The patch is also written against the retired db281878 tree and would not apply to v1.1.4. Closing as superseded; the credit to you for the approach and the report that led here is kept in the issue history.

(Review notes prepared with Claude Code on behalf of the maintainer.)

@MiaAI-Lab MiaAI-Lab closed this Oct 27, 2026
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.

3 participants