[PR #3922] [CLOSED] [Engine] GBNF constrained decoding: stable tool calls + JSON schema #4837

Closed
opened 2026-11-07 15:39:23 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Niko1221/Strata/pull/3922
Author: @sd133cn
Created: 10/24/2026
Status: ❌ Closed

Base: main ← Head: feature/gbnf-constrained-decoding


📝 Commits (10+)

  • 3429acb Source probe: --source auto measures Hugging Face and ModelScope per repository (a 2 MB Range read of each, the MB/s printed) and downloads from the faster host; the file is checked against ModelScope's published SHA-256 (#908's never-switch rule relaxed for the measured winner; explicit --source skips the probe).
  • 50813a0 Merge origin/main (v0.1.42-0.2.2): keep the source probe (model_source(url) + probe_source against upstream's fetch_mtp, which honors an explicit STRATA_SOURCE); docs' ModelScope notes sit in upstream's strata launch structure; Swift IQ3_S converges on upstream's wording (swift Q2_0 stays qwen-only, #171).
  • db1549e tests: regenerate the setup golden file after the merge (upstream's launch plans record 'exe'; the source-probe announcement words ride along)
  • a9cc2c2 chore: 添加 .zcodeignore 配置及引擎更新状态文件
  • f796d48 docs: GBNF constrained-decoding spec (reviewed) and 13-task implementation plan
  • 677efdc Grammar: port the llama.cpp GBNF core into strata::grammar (parser, stacks, accept; MIT attribution kept)
  • 34d8145 Grammar: GGUF vocab (full token arrays, control/eog flags) and the bitmask builder with a stack-key LRU cache
  • 0a9ffa0 Grammar: per-row bitmask in the sampler kernels at the logit_bias site (null default = byte-identical path); parity pins bans, order, and immutability
  • 51c8643 fix: MSVC full-build blockers on Windows: gdn_chunk_parity/gdn_chunk_bench/hc_persist_parity env setters (decode_cluster_parity pattern), native_hadamard_test std::popcount, ggml_tq_overlay_test.cmake CMP0057 NEW
  • dc16a10 Grammar: GRAMMAR registration line + grammar= request key + hard grammar+spec rejection; per-slot state stacks with per-step advance at the token readback and a mask ring H2D into the sampler; mask cache keyed against the owning grammar's rules (clone stacks); closed-loop GPU decode test

📊 Changes

74 files changed (+35708 additions, -93 deletions)

View changed files

➕ .zcodeignore (+84 -0)
📝 CMakeLists.txt (+43 -1)
📝 bench/gdn_chunk_bench.cpp (+10 -2)
➕ bench/results/2026-10-24-1332-grammar-4090/grammar-acceptance.json (+123 -0)
➕ bench/results/2026-10-24-1332-grammar-4090/json-items.jsonl (+50 -0)
➕ bench/results/2026-10-24-1332-grammar-4090/serve.cfg.json (+1 -0)
➕ bench/results/2026-10-24-1332-grammar-4090/tool-items.jsonl (+30 -0)
📝 cmake/ggml_tq_overlay_test.cmake (+4 -0)
📝 data/gguf_fingerprints.json (+20 -0)
📝 docs/AI_SETUP.md (+12 -3)
📝 docs/DETAILS.md (+61 -9)
📝 docs/INSTALL.md (+10 -7)
📝 docs/TERMINAL_LAUNCH.md (+3 -0)
➕ docs/superpowers/plans/2026-10-24-gbnf-constrained-decoding.md (+471 -0)
➕ docs/superpowers/specs/2026-10-23-gbnf-constrained-decoding-design.md (+121 -0)
➕ engine-feed-new/.updates/state.json (+11 -0)
➕ engine-feed/.updates/state.json (+29 -0)
📝 include/strata/artifact/gguf_reader.hpp (+9 -6)
➕ include/strata/grammar/compat.hpp (+10 -0)
➕ include/strata/grammar/grammar.hpp (+208 -0)

...and 54 more files

📄 Description

The problem

Strata's JSON and tool-call outputs are prompt-and-validate today: the server appends an output-format
directive, the model improvises the shape, and the server validates (and on failure, the whole request
fails with 502). Long tool calls and deeply nested schemas are exactly where prompting runs out:
ZCode's and Claude Code's tool grammars (ZCode's own tool calls run through GBNF), and the agent harnesses
most of our users plug in, need decoding that cannot leave the shape.

The result

Constrained decoding is now real: every token is sampled from the set the grammar allows.

  • response_format (json_object, json_schema) decodes schema-valid output directly. On a
    grammar-capable engine the server registers the converted grammar, drops the prompt directive, streams
    unbuffered, and keeps the validation as a canary (502 only on an engine bug).
  • Tool calls (OpenAI chat, /v1/responses, Anthropic) are grammar-constrained from the template
    serialization: required/named/auto (with prose), parallel calls, the </think> prologue. No more
    calls that fail to parse.
  • A raw grammar parameter (GBNF text) rides the same path for agents that write their own grammars.
  • /v1/status reports method: "grammar", constrained_decoding: true.

Measured on the RTX 4090 rig (Swift IQ3_S, engine 0.1.47 build, 2026-10-24, results in
bench/results/2026-10-24-1332-grammar-4090/): the JSON suite answers 50/50 inside its schemas
(5 schemas × 10 prompts, effort low, temperature 0.6), the tool suite parses 30/30 calls with 0
failures
and 0 rescued from the reasoning stream, protocol smoke 6/6. Cost: a 400-token answer at
effort none ran at a median of 84.8 tok/s plain vs 82.6 tok/s constrained (−2.6%), with a one-time
mask-kernel warm-up on a session's first constrained request (26.9 tok/s once); with 6 concurrent slots
the aggregate fell 172.1 → 140.1 tok/s (−18.6%) — the per-slot mask upload rides every generated token.

The approach

  • The llama.cpp GBNF core (parser, stacks, accept) is ported into src/grammar/ (MIT kept, per-file
    attribution). The GGUF vocab is loaded from the model's tokenizer.ggml.tokens + token_type.
  • The per-step mask (LRU cache over whole-stack states) is built on the CPU side and uploaded as a
    per-row bitmask; the CUDA/HIP sampler applies it at the logit-bias read site (bit=1 bans → -inf),
    before bias and penalties. grammar_mask = nullptr keeps the default path byte-identical.
  • The engine speaks GRAMMAR <sha16> <byte_len> <text> (register once per grammar; parsed, cached),
    and grammar=<sha16> rides the GEN line per request. Slots advance their state stacks at the token
    readback; the per-slot mask ring is one H2D per token — free next to decode.
  • A continuation pass (a thinking wrap-up, a close retry, a forced call, a batch slot handed back to
    solo) resends the prompt with what it generated and names the tail with gseed=<n>: the engine
    replays those tokens through the grammar so the state and mask continue where the last pass left
    off. A tail that does not fit the grammar is refused (400), never silently unconstrained.
  • The JSON Schema converter is vendored from llama.cpp (vendor/json_schema_to_grammar/) and built as
    the grammar_schema CLI; the server shells out to it (zero new dependencies).
  • SentencePiece piece decoding (Ċ→\n, Ġ→ , 0xA1-0xFF byte tokens) is applied at vocab load —
    Qwen's GGUF tokens are symbols, and GBNF literals are text. (Found on the rig: without it every
    whitespace token is banned.)
  • Grammar + speculative decoding (MTP, --spec, spec_min_p) is refused at the request boundary;
    suffix/n-gram drafting is silently off for grammar requests (drafted windows sample masks built for
    the wrong prefix).

Validation

  • Passed: grammar unit tests, registry tests (including the seed-replay state test), sampler parity
    (grammar mask, 3 kernel paths), GPU accept→mask→sample closed loop (grammar_decode_test, 100
    rounds, all legal), grammar_schema 77 golden cases from the vendored llama.cpp converter suite, serve
    grammar suite (24), builder suite (12), full ctest on this rig (156/157 passed, 7 skipped; the one
    failure is ple_parity, which needs Q2_0 model fixtures this rig does not have), full serve suite
    (953 tests; the one error is test_winjob's tasklist read, which fails the same way with this
    branch's changes stashed), tools suite (1142; the failures are the setup/MCP download and process
    tests that fail on this box regardless of branch), acceptance on the 4090 rig (above).
  • Protocol smoke (rig, IQ3_S): GRAMMAR OK/ERR/len-validation, GEN grammar key, not-registered,
    spec refusal — all green.
  • Not run: HIP gfx906 build (no AMD card on this rig), SYCL build (no oneAPI) — the fields are
    mirrored in the SYCL tree; recorded in the Task-7 commit.
  • Apps/host npm test: 4 failures are Windows symlink-permission (EPERM) on fixtures this rig's git
    checkout does not create; they fail the same way without this branch.
  • tests/terminal: main tree on the same rig fails 59/28 (failures/errors, 86 skipped); this branch
    fails 54/30 — the same environmental class (download pins, MCP process tests, Windows fixtures),
    no grammar-related failure.

Limits

  • CUDA/HIP kernels + the SYCL mirror; Metal and the CPU path do not advertise the capability, so
    those engines keep the prompt path (the server detects grammar=1 in INFO).
  • Constrained requests pay decoding without drafters (suffix/n-gram) — the speed cost is measured
    in the acceptance numbers; the model's thinking budget is untouched.
  • grammar + tools/MCP on one request: tool grammars take the tools route; bare grammar + tools
    is a 400.
  • GBNF surface = the vendored converter's (llama.cpp 3cf03257); the %llguidance branch is bypassed.
  • The per-token host CPU milliseconds of the mask build were not captured by this run's probe (its
    process-time read returned 0); the 6-slot aggregate throughput stands in as the measured proxy.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Niko1221/Strata/pull/3922 **Author:** [@sd133cn](https://github.com/sd133cn) **Created:** 10/24/2026 **Status:** ❌ Closed **Base:** `main` ← **Head:** `feature/gbnf-constrained-decoding` --- ### 📝 Commits (10+) - [`3429acb`](https://github.com/Niko1221/Strata/commit/3429acb586538a6b6893f85fab0f264a424ad560) Source probe: --source auto measures Hugging Face and ModelScope per repository (a 2 MB Range read of each, the MB/s printed) and downloads from the faster host; the file is checked against ModelScope's published SHA-256 (#908's never-switch rule relaxed for the measured winner; explicit --source skips the probe). - [`50813a0`](https://github.com/Niko1221/Strata/commit/50813a0603ebeb34c785d378fd6b8bed277a27f3) Merge origin/main (v0.1.42-0.2.2): keep the source probe (model_source(url) + probe_source against upstream's fetch_mtp, which honors an explicit STRATA_SOURCE); docs' ModelScope notes sit in upstream's strata launch structure; Swift IQ3_S converges on upstream's wording (swift Q2_0 stays qwen-only, #171). - [`db1549e`](https://github.com/Niko1221/Strata/commit/db1549e4094832ec96aefc631d3c1ced1328e380) tests: regenerate the setup golden file after the merge (upstream's launch plans record 'exe'; the source-probe announcement words ride along) - [`a9cc2c2`](https://github.com/Niko1221/Strata/commit/a9cc2c201b42823d5120a1613d88a7633adea7cf) chore: 添加 .zcodeignore 配置及引擎更新状态文件 - [`f796d48`](https://github.com/Niko1221/Strata/commit/f796d48e81bcd42194cc859157d8349f2bf98561) docs: GBNF constrained-decoding spec (reviewed) and 13-task implementation plan - [`677efdc`](https://github.com/Niko1221/Strata/commit/677efdcf5af8ecdab351a2fbc55cd198f141b91f) Grammar: port the llama.cpp GBNF core into strata::grammar (parser, stacks, accept; MIT attribution kept) - [`34d8145`](https://github.com/Niko1221/Strata/commit/34d8145640ace3dc7af1722c04d2c8932aae7552) Grammar: GGUF vocab (full token arrays, control/eog flags) and the bitmask builder with a stack-key LRU cache - [`0a9ffa0`](https://github.com/Niko1221/Strata/commit/0a9ffa0fdfe003028bd75621c4eb1328e1f13974) Grammar: per-row bitmask in the sampler kernels at the logit_bias site (null default = byte-identical path); parity pins bans, order, and immutability - [`51c8643`](https://github.com/Niko1221/Strata/commit/51c8643b0b39f1115417634b5f6033c96c3a3acf) fix: MSVC full-build blockers on Windows: gdn_chunk_parity/gdn_chunk_bench/hc_persist_parity env setters (decode_cluster_parity pattern), native_hadamard_test std::popcount, ggml_tq_overlay_test.cmake CMP0057 NEW - [`dc16a10`](https://github.com/Niko1221/Strata/commit/dc16a10f2e1abc342dfa5a0aee6dfffef6918982) Grammar: GRAMMAR registration line + grammar= request key + hard grammar+spec rejection; per-slot state stacks with per-step advance at the token readback and a mask ring H2D into the sampler; mask cache keyed against the owning grammar's rules (clone stacks); closed-loop GPU decode test ### 📊 Changes **74 files changed** (+35708 additions, -93 deletions) <details> <summary>View changed files</summary> ➕ `.zcodeignore` (+84 -0) 📝 `CMakeLists.txt` (+43 -1) 📝 `bench/gdn_chunk_bench.cpp` (+10 -2) ➕ `bench/results/2026-10-24-1332-grammar-4090/grammar-acceptance.json` (+123 -0) ➕ `bench/results/2026-10-24-1332-grammar-4090/json-items.jsonl` (+50 -0) ➕ `bench/results/2026-10-24-1332-grammar-4090/serve.cfg.json` (+1 -0) ➕ `bench/results/2026-10-24-1332-grammar-4090/tool-items.jsonl` (+30 -0) 📝 `cmake/ggml_tq_overlay_test.cmake` (+4 -0) 📝 `data/gguf_fingerprints.json` (+20 -0) 📝 `docs/AI_SETUP.md` (+12 -3) 📝 `docs/DETAILS.md` (+61 -9) 📝 `docs/INSTALL.md` (+10 -7) 📝 `docs/TERMINAL_LAUNCH.md` (+3 -0) ➕ `docs/superpowers/plans/2026-10-24-gbnf-constrained-decoding.md` (+471 -0) ➕ `docs/superpowers/specs/2026-10-23-gbnf-constrained-decoding-design.md` (+121 -0) ➕ `engine-feed-new/.updates/state.json` (+11 -0) ➕ `engine-feed/.updates/state.json` (+29 -0) 📝 `include/strata/artifact/gguf_reader.hpp` (+9 -6) ➕ `include/strata/grammar/compat.hpp` (+10 -0) ➕ `include/strata/grammar/grammar.hpp` (+208 -0) _...and 54 more files_ </details> ### 📄 Description ## The problem Strata's JSON and tool-call outputs are prompt-and-validate today: the server appends an output-format directive, the model improvises the shape, and the server validates (and on failure, the whole request fails with 502). Long tool calls and deeply nested schemas are exactly where prompting runs out: ZCode's and Claude Code's tool grammars (ZCode's own tool calls run through GBNF), and the agent harnesses most of our users plug in, need decoding that cannot leave the shape. ## The result Constrained decoding is now real: every token is sampled from the set the grammar allows. - `response_format` (`json_object`, `json_schema`) decodes schema-valid output directly. On a grammar-capable engine the server registers the converted grammar, drops the prompt directive, streams unbuffered, and keeps the validation as a canary (502 only on an engine bug). - Tool calls (OpenAI chat, `/v1/responses`, Anthropic) are grammar-constrained from the template serialization: required/named/auto (with prose), parallel calls, the `</think>` prologue. No more calls that fail to parse. - A raw `grammar` parameter (GBNF text) rides the same path for agents that write their own grammars. - `/v1/status` reports `method: "grammar"`, `constrained_decoding: true`. Measured on the RTX 4090 rig (Swift IQ3_S, engine 0.1.47 build, 2026-10-24, results in `bench/results/2026-10-24-1332-grammar-4090/`): the JSON suite answers **50/50 inside its schemas** (5 schemas × 10 prompts, effort low, temperature 0.6), the tool suite parses **30/30 calls with 0 failures** and 0 rescued from the reasoning stream, protocol smoke 6/6. Cost: a 400-token answer at effort none ran at a median of 84.8 tok/s plain vs 82.6 tok/s constrained (**−2.6%**), with a one-time mask-kernel warm-up on a session's first constrained request (26.9 tok/s once); with 6 concurrent slots the aggregate fell 172.1 → 140.1 tok/s (−18.6%) — the per-slot mask upload rides every generated token. ## The approach - The llama.cpp GBNF core (parser, stacks, accept) is ported into `src/grammar/` (MIT kept, per-file attribution). The GGUF vocab is loaded from the model's `tokenizer.ggml.tokens` + token_type. - The per-step mask (LRU cache over whole-stack states) is built on the CPU side and uploaded as a per-row bitmask; the CUDA/HIP sampler applies it at the logit-bias read site (bit=1 bans → -inf), before bias and penalties. `grammar_mask = nullptr` keeps the default path byte-identical. - The engine speaks `GRAMMAR <sha16> <byte_len> <text>` (register once per grammar; parsed, cached), and `grammar=<sha16>` rides the GEN line per request. Slots advance their state stacks at the token readback; the per-slot mask ring is one H2D per token — free next to decode. - A continuation pass (a thinking wrap-up, a close retry, a forced call, a batch slot handed back to solo) resends the prompt with what it generated and names the tail with `gseed=<n>`: the engine replays those tokens through the grammar so the state and mask continue where the last pass left off. A tail that does not fit the grammar is refused (400), never silently unconstrained. - The JSON Schema converter is vendored from llama.cpp (`vendor/json_schema_to_grammar/`) and built as the `grammar_schema` CLI; the server shells out to it (zero new dependencies). - SentencePiece piece decoding (`Ċ`→`\n`, `Ġ`→` `, 0xA1-0xFF byte tokens) is applied at vocab load — Qwen's GGUF tokens are symbols, and GBNF literals are text. (Found on the rig: without it every whitespace token is banned.) - Grammar + speculative decoding (MTP, `--spec`, `spec_min_p`) is refused at the request boundary; suffix/n-gram drafting is silently off for grammar requests (drafted windows sample masks built for the wrong prefix). ## Validation - Passed: grammar unit tests, registry tests (including the seed-replay state test), sampler parity (grammar mask, 3 kernel paths), GPU accept→mask→sample closed loop (`grammar_decode_test`, 100 rounds, all legal), grammar_schema 77 golden cases from the vendored llama.cpp converter suite, serve grammar suite (24), builder suite (12), full ctest on this rig (156/157 passed, 7 skipped; the one failure is `ple_parity`, which needs Q2_0 model fixtures this rig does not have), full serve suite (953 tests; the one error is `test_winjob`'s tasklist read, which fails the same way with this branch's changes stashed), tools suite (1142; the failures are the setup/MCP download and process tests that fail on this box regardless of branch), acceptance on the 4090 rig (above). - Protocol smoke (rig, IQ3_S): GRAMMAR OK/ERR/len-validation, GEN grammar key, not-registered, spec refusal — all green. - Not run: HIP gfx906 build (no AMD card on this rig), SYCL build (no oneAPI) — the fields are mirrored in the SYCL tree; recorded in the Task-7 commit. - Apps/host `npm test`: 4 failures are Windows symlink-permission (EPERM) on fixtures this rig's git checkout does not create; they fail the same way without this branch. - `tests/terminal`: main tree on the same rig fails 59/28 (failures/errors, 86 skipped); this branch fails 54/30 — the same environmental class (download pins, MCP process tests, Windows fixtures), no grammar-related failure. ## Limits - CUDA/HIP kernels + the SYCL mirror; Metal and the CPU path do not advertise the capability, so those engines keep the prompt path (the server detects `grammar=1` in INFO). - Constrained requests pay decoding without drafters (suffix/n-gram) — the speed cost is measured in the acceptance numbers; the model's thinking budget is untouched. - `grammar` + tools/MCP on one request: tool grammars take the tools route; bare `grammar` + tools is a 400. - GBNF surface = the vendored converter's (llama.cpp 3cf03257); the `%llguidance` branch is bypassed. - The per-token host CPU milliseconds of the mask build were not captured by this run's probe (its process-time read returned 0); the 6-slot aggregate throughput stands in as the measured proxy. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-07 15:39:23 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#4837
No description provided.