[GH-ISSUE #3758] [Engine] Grammar-constrained decoding for json_schema, so an agent's answers always fit its schema #1581

Open
opened 2026-11-04 01:52:23 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @qiuzan2001 on GitHub (Oct 22, 2026).
Original GitHub issue: https://github.com/Niko1221/Strata/issues/3758

Area

[Engine] (speed, kernels, models, the server and API)

What do you want to do?

I want to implement grammar-constrained decoding for response_format: json_schema myself, if you agree with the scope. This issue asks whether you want it in Strata and how it should be built. I will not send a large pull request before you answer.

Why: I run a browser agent (browser_use) on Strata. It sends a JSON schema with every request and needs the model's answer to fit that schema every time.

Today Strata asks for the schema in the prompt and checks the answer afterwards. The engine has no grammar decoder (serve/structured.py, docs/DETAILS.md "schema prompting followed by server validation"). So a low-bit model sometimes writes JSON of the wrong shape, and the agent has to retry.

What happened on my PC (counted from the agent's own log, one run of about 90 agent steps):

  • 14 steps logged a validation error, in 7 separate failures.
  • 5 failures needed 1 retry and 2 needed 2 retries. The agent gives up a job after 6 tries.
  • Two kinds of wrong output. The action has the wrong shape ({"keys":"Escape"} where {"send_keys":{"keys":"Escape"}} is correct). Or thinking comes back as an object instead of a string and the action field is missing.
  • Each failed try costs one more full model call, so the jobs are slower.

I want an answer that fits the schema by construction: while the model writes the answer, only tokens that keep it valid are allowed. Speed should stay close to today's, so the MTP and suffix drafts should still work under the constraint.

Setup: Strata 0.2.2 (engine 0.1.47), Swift 1.5 IQ3_S, RTX 5070 Ti 16 GB, 76 GB RAM, Ubuntu, CUDA 13.1.

Side note: on my install the Python package jsonschema is not installed (it is not in requirements.txt or setup.py), so the server only checks that the answer is one JSON object. Wrong-shape answers pass the server and fail in the client. Installing it makes the server catch them, but it does not make the model write the right shape, so it does not remove the retries.

What do you do today instead?

Nothing that removes the failures. The agent retries. Lower temperature and a smaller action schema should help, but they cannot guarantee a valid answer.

Earlier work and questions

This was asked before. Those threads were closed in the 0.2.0-beta tracker reset (closed, not rejected): #2368 (tracking issue), #334, #1328 (ncphri's token masks that keep the MTP drafts under the mask), #1431, #976. I also saw that someone is working on llguidance support in a fork. I am not asking you to reopen a declined proposal. I would like to continue this work, with new evidence from a real agent workload.

Questions, so that I do not build the wrong thing:

  1. Do you want this in Strata, as an opt-in? If you prefer not to take it, please say so, so I do not spend the time.
  2. Which grammar library: llguidance (better JSON schema support, brings Rust) or XGrammar (faster, weaker schema support)?
  3. First version CUDA only. The engine says in its INFO line whether it can mask, and without that the server keeps today's prompt-and-validate path. I cannot build or run HIP or SYCL here.
  4. Should I start from #1328 (rebased on 0.2.2, with ncphri's credit), or write it fresh?

If you agree, I will keep this thread updated and open a draft pull request for the CUDA version first. Before it is ready for review I will measure: how many answers fit the schema with and without the mask on a set of agent-style requests, decode speed with and without drafts under the mask, and that greedy output is identical when the unmasked answer was already valid.

Originally created by @qiuzan2001 on GitHub (Oct 22, 2026). Original GitHub issue: https://github.com/Niko1221/Strata/issues/3758 ### Area [Engine] (speed, kernels, models, the server and API) ### What do you want to do? I want to implement grammar-constrained decoding for `response_format: json_schema` myself, if you agree with the scope. This issue asks whether you want it in Strata and how it should be built. I will not send a large pull request before you answer. Why: I run a browser agent (browser_use) on Strata. It sends a JSON schema with every request and needs the model's answer to fit that schema every time. Today Strata asks for the schema in the prompt and checks the answer afterwards. The engine has no grammar decoder (`serve/structured.py`, docs/DETAILS.md "schema prompting followed by server validation"). So a low-bit model sometimes writes JSON of the wrong shape, and the agent has to retry. What happened on my PC (counted from the agent's own log, one run of about 90 agent steps): - 14 steps logged a validation error, in 7 separate failures. - 5 failures needed 1 retry and 2 needed 2 retries. The agent gives up a job after 6 tries. - Two kinds of wrong output. The action has the wrong shape (`{"keys":"Escape"}` where `{"send_keys":{"keys":"Escape"}}` is correct). Or `thinking` comes back as an object instead of a string and the action field is missing. - Each failed try costs one more full model call, so the jobs are slower. I want an answer that fits the schema by construction: while the model writes the answer, only tokens that keep it valid are allowed. Speed should stay close to today's, so the MTP and suffix drafts should still work under the constraint. Setup: Strata 0.2.2 (engine 0.1.47), Swift 1.5 IQ3_S, RTX 5070 Ti 16 GB, 76 GB RAM, Ubuntu, CUDA 13.1. Side note: on my install the Python package `jsonschema` is not installed (it is not in requirements.txt or setup.py), so the server only checks that the answer is one JSON object. Wrong-shape answers pass the server and fail in the client. Installing it makes the server catch them, but it does not make the model write the right shape, so it does not remove the retries. ### What do you do today instead? Nothing that removes the failures. The agent retries. Lower temperature and a smaller action schema should help, but they cannot guarantee a valid answer. ### Earlier work and questions This was asked before. Those threads were closed in the 0.2.0-beta tracker reset (closed, not rejected): #2368 (tracking issue), #334, #1328 (ncphri's token masks that keep the MTP drafts under the mask), #1431, #976. I also saw that someone is working on llguidance support in a fork. I am not asking you to reopen a declined proposal. I would like to continue this work, with new evidence from a real agent workload. Questions, so that I do not build the wrong thing: 1. Do you want this in Strata, as an opt-in? If you prefer not to take it, please say so, so I do not spend the time. 2. Which grammar library: llguidance (better JSON schema support, brings Rust) or XGrammar (faster, weaker schema support)? 3. First version CUDA only. The engine says in its INFO line whether it can mask, and without that the server keeps today's prompt-and-validate path. I cannot build or run HIP or SYCL here. 4. Should I start from #1328 (rebased on 0.2.2, with ncphri's credit), or write it fresh? If you agree, I will keep this thread updated and open a draft pull request for the CUDA version first. Before it is ready for review I will measure: how many answers fit the schema with and without the mask on a set of agent-style requests, decode speed with and without drafts under the mask, and that greedy output is identical when the unmasked answer was already valid.
Author
Owner

@Cal1sto commented on GitHub (Oct 31, 2026):

Second data point + implementation-level findings from another box (Strata 0.1.45, RTX 5090, Qwen3.8-Flash-Next IQ3_S, 512K context). Happy to see this being picked up — here is what our code reading and an outside-the-engine prototype established, which I think changes the shape of the answer:

The engine is closer than the docstring suggests — no new GPU kernel needed.

  • Final sampling is host side ("run()'s host-side sampling, Philox(seed, pos0 + t)", src/core/verify.cpp:5005) over candidate lists capped at kSelMax = 64 (include/strata/core/spec_prob.hpp). A grammar mask at that point is a host-side set intersection on <= 64 entries — no device traffic per step.
  • The mask semantics already exist end to end: Verifier::set_logit_bias (verify.cpp:759), and include/strata/core/logit_bias.hpp treats -100 as a hard exclusion (tested there to 103k bans).
  • MTP drafts are a chain, not a tree: advance the automaton along the draft prefix, invalidate verify rows at the first grammar-invalid draft, commit at the divergence point.

What we measured today over the HTTP surface (automaton compiled from JSON-schema, full real vocabulary of 248,320 tokens, per-token byte-level validation, 13/13 automaton unit tests):

  • Exhaustive per-step mask through logit_bias: semantically correct, but 39.1 s per token (3.7 MB payload, 248k banned ids). A dead end outside the engine — and exactly the argument for doing it inside, where the mask is free at the sampling site.
  • Partial assistant prefill through /v1/chat/completions is impossible (the chat template closes the assistant turn: prefilling {"ville": makes the model restart from scratch). So token-level constraint cannot be bolted on client-side at all today; it has to live server-side.
  • Turn-level lazy rejection works with zero engine changes: generate the whole JSON, replay the automaton, ban the first invalid token id (pair-list form, cached), regenerate. Battery on a strict schema (enum + required + types): 3/3 schema-valid vs 3/6 unconstrained, converging with 0 regenerations needed.

Demand nuance, counted honestly: on this box, 0 of 3,091 logged requests used response_format — our agents go through native tool calls. The win materializes once clients adopt the guarantee; the guarantee requires this issue's work.

Side note, cheap fix for anyone validating schemas server-side: jsonschema was missing from the server venv and the validation silently degraded to "is a JSON object" (warning logged once). Worth listing as an actual dependency of structured.py.

@OP if you're still planning this: the host-side sampling site is where I'd put the automaton — same point logit_bias already reaches, behind Verifier::set_logit_bias. That keeps the PR small and kernel-free, which seems like the kind of patch this repo would merge.

<!-- gh-comment-id:6541948765 --> @Cal1sto commented on GitHub (Oct 31, 2026): Second data point + implementation-level findings from another box (Strata 0.1.45, RTX 5090, Qwen3.8-Flash-Next IQ3_S, 512K context). Happy to see this being picked up — here is what our code reading and an outside-the-engine prototype established, which I think changes the shape of the answer: **The engine is closer than the docstring suggests — no new GPU kernel needed.** - Final sampling is host side ("run()'s host-side sampling, Philox(seed, pos0 + t)", `src/core/verify.cpp:5005`) over candidate lists capped at `kSelMax` = 64 (`include/strata/core/spec_prob.hpp`). A grammar mask at that point is a host-side set intersection on <= 64 entries — no device traffic per step. - The mask semantics already exist end to end: `Verifier::set_logit_bias` (`verify.cpp:759`), and `include/strata/core/logit_bias.hpp` treats `-100` as a hard exclusion (tested there to 103k bans). - MTP drafts are a chain, not a tree: advance the automaton along the draft prefix, invalidate verify rows at the first grammar-invalid draft, commit at the divergence point. **What we measured today over the HTTP surface** (automaton compiled from JSON-schema, full real vocabulary of 248,320 tokens, per-token byte-level validation, 13/13 automaton unit tests): - Exhaustive per-step mask through `logit_bias`: semantically correct, but **39.1 s per token** (3.7 MB payload, 248k banned ids). A dead end outside the engine — and exactly the argument for doing it inside, where the mask is free at the sampling site. - Partial assistant prefill through `/v1/chat/completions` is impossible (the chat template closes the assistant turn: prefilling `{"ville":` makes the model restart from scratch). So token-level constraint cannot be bolted on client-side at all today; it has to live server-side. - Turn-level lazy rejection works with zero engine changes: generate the whole JSON, replay the automaton, ban the first invalid token id (pair-list form, cached), regenerate. Battery on a strict schema (enum + required + types): **3/3 schema-valid vs 3/6 unconstrained**, converging with 0 regenerations needed. **Demand nuance, counted honestly:** on this box, 0 of 3,091 logged requests used `response_format` — our agents go through native tool calls. The win materializes once clients adopt the guarantee; the guarantee requires this issue's work. Side note, cheap fix for anyone validating schemas server-side: `jsonschema` was missing from the server venv and the validation silently degraded to "is a JSON object" (warning logged once). Worth listing as an actual dependency of `structured.py`. @OP if you're still planning this: the host-side sampling site is where I'd put the automaton — same point `logit_bias` already reaches, behind `Verifier::set_logit_bias`. That keeps the PR small and kernel-free, which seems like the kind of patch this repo would merge.
Author
Owner

@Have-Purple commented on GitHub (Nov 4, 2026):

Measured cost on a 45-run agent suite (15 tasks × 3 reps) at 128K, two packs, temperature 0:

  • One run in 45 ended on malformed JSON (three invalid replies, then the turn limit) rather than on
    the task. Malformed replies also occurred at 64K, so context length is not the cause.
  • The failures were in ambiguous and budget, both tasks where the reply is prose plus a tool call
    rather than a short answer.

That is the practical argument for this: the model can complete the task, but the harness cannot
parse the answer. A grammar would remove the class rather than penalise it.

<!-- gh-comment-id:6635217300 --> @Have-Purple commented on GitHub (Nov 4, 2026): Measured cost on a 45-run agent suite (15 tasks × 3 reps) at 128K, two packs, temperature 0: - One run in 45 ended on malformed JSON (three invalid replies, then the turn limit) rather than on the task. Malformed replies also occurred at 64K, so context length is not the cause. - The failures were in `ambiguous` and `budget`, both tasks where the reply is prose plus a tool call rather than a short answer. That is the practical argument for this: the model can complete the task, but the harness cannot parse the answer. A grammar would remove the class rather than penalise it.
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#1581
No description provided.