mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 19:03:30 +07:00
[PR #3800] [Engine] Token mask for JSON response formats: MTP drafts survive constrained decoding #4787
Labels
No labels
needs-format
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Niko1221/Strata#4787
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 Pull Request Information
Original PR: https://github.com/Niko1221/Strata/pull/3800
Author: @ncphri
Created: 10/23/2026
Status: 🔄 Open
Base:
main← Head:f-json-mask📝 Commits (10+)
6cb9538serve + engine: constrained decoding for JSON response formats: a token mask per window (mask=1, MQ/MF/MK) on the chat routed851324Merge branch 'main' into f-json-mask52922efserve + engine: MTP drafts under the token mask: multi-row MKN windows, MQ/MF/MK round-trip, consume-based lookahead on the server (no validate_tokens); mask stats behind STRATA_MASK_STATS=1a79dd4dMerge remote-tracking branch 'origin/main' into json_mtp8fc68d7Merge branch 'main' into f-json-maskeb4e23cMerge remote-tracking branch 'origin/main' into f-json-maskc4c8323Merge origin/main (0.1.48.x) into f-json-mask: keep both sides — token_mask INFO beside the new prefill keys, mask=1 key parser beside pipe=, mk_take inside the !merged draft gate, sycl mask-cut before the follow-logprobs dump, include union, PY_PACKAGES keeps llguidance3766738Merge remote-tracking branch 'origin/main' into f-json-mask-merged8979f87Merge origin/main (0.2.3) into f-json-mask: keep-both on the draft-window head - the mask-exchange comments ride above main's spec_cost chain_rows clamp6668b9dMerge origin/main (0.2.6) into f-json-mask: keep-both - the mask request key rides beside main's --pipe key and the token-mask INFO literal above main's prefill fields, main's streaming bullet carries the grammar branch (the structured-output paragraphs keep their place at the section's end), and set_family/force_text stay beside _with_constraint📊 Changes
14 files changed (+1342 additions, -16 deletions)
View changed files
📝
docs/DETAILS.md(+19 -2)➕
include/strata/core/token_mask.hpp(+162 -0)📝
include/strata/core/verify.hpp(+18 -0)📝
requirements.txt(+1 -0)➕
serve/constrain.py(+334 -0)➕
serve/fake_mask_engine.py(+89 -0)📝
serve/server.py(+68 -2)➕
serve/test_constrain.py(+430 -0)📝
setup.py(+2 -1)📝
src/core/verify.cpp(+64 -0)📝
src/program/generate.cpp(+91 -6)📝
sycl/include/strata/core/verify.hpp(+11 -0)📝
sycl/src/core/verify.cpp(+24 -0)📝
sycl/src/program/generate.cpp(+29 -5)📄 Description
Problem and result
Structured JSON replies (
response_format: json_schema) were served by prompt instruction + server-side validation only: the model could sample a token that makes the required schema keys unreachable, the reply finished, validation failed, and the client got502 structured_output_failedand retried the whole request. In a production multi-turn agentic pipeline on a quantized model (one deployment run, ~75 report requests), 50 schema-failure events were logged across 10 samples (~13% of samples affected, up to 5 client reconnects each); ~92% were one missing required top-level key, the rest additional-property violations. An agentic CLI client that re-validates the schema client-side over the Responses route failed 3/20 real report prompts (15%) end-over-end on the unmasked build.With this change the engine cuts grammar-illegal tokens before sampling, so constrained replies are valid by construction. Same 20 real prompts, same machine, same day, on the masked build: 20/20 first-pass valid, zero client retries. Per-run decode on the masked arm was steady at 65-81 tok/s (median 73) across all 20 runs; the unmasked arm's effective throughput was far more variable (median 21, range 11-65 tok/s) because failed generations burn whole windows before the client retries. Failures are not fully deterministic - the 15% rate reproduces intermittently, matching the original field logs.
Related discussion
PR #1328 (closed by the tracker reset, not declined; the maintainer asked for a rebase onto main and a fresh PR, which this is).
Approach
The server (
serve/constrain.py) compiles the schema to a token mask with llguidance and answers a per-window mask exchange: MQ (window candidates + drafts) -> MF (free) or MK/MKN (masked rows). Masking happens between logits and sampling, so MTP drafts ride along inside masked multi-row windows instead of dying at the first rejected draft. Opt-in: active only when the request declares a JSON schema AND the engine advertisestoken_mask=1/2in its startup INFO; the default path is byte-identical./v1/statusreportsconstrained_decoding: trueonly when the gate passes. The chat route keeps rejecting tools+schema (400);/v1/responsessupports both.token_mask=2also lets a whole MTP window be masked; row-count shrink trims drafts server-side.Validation
Passed:
origin/maintwice on 2026-10-28 (0.2.7.x ->266ad181) and 2026-11-04 (0.2.10 ->merge head
fc2c1ebb). The first round: keep-both inserve/server.py(main'sprefill_onlyhead rewrite beside the mask block; main's LP-line capture beside
c.feed(t)) and main's window-Trefactor in
generate.cppat the mask-comment hunks. The second round:serve/server.pytakesmain's
rid/pen_frommachinery beside the mask gate (themask=1append rides after main's ridhead),
verify.cpptakes main'sSTRATA_VERIFY_HGLguard beside the token_mask include,generate.cpptakes main's DFlash2/window-rule restructure with the MQ exchange beside main'skeep_sync(window filled -> mask cut -> MQ/MK/MKN rows -> adoption; the HIP stop-bound blockfollows the mask cut), and SYCL keeps its bare-MQ mask block beside the window rule — its result is
one row under the mask (
if (gm_on) T = 1, the deferred lookup gated off). The filed diff againstmainat the merged head is the mask machinery and its serve half only (14 files, +1342/−16,engine files 7 files, +399/−11).
266ad181and 467 testsOK (~150 s, miniforge python 3.12, llguidance 1.9.1, WSL Ubuntu, no GPU) at
fc2c1ebb, zero skips.ed7f0d1e):git diff fc2c1ebb ed7f0d1e -- src include sycl= 0, so the CUDA build and hardware verification run there on2026-11-04 (170/170 steps, 0 errors, engine 0.1.56,
STRATA_TOOL_MASK=1, 15/15 first-pass probes,/v1/statusconstrained_decoding: true) covers this PR's merged engine files byte-identically;the serve-side delta is that PR's lark chain, covered by its own mock suite.
python -m unittest serve.test_constrain serve.test_structured serve.test_responses serve.test_server serve.test_mcp-> 450 tests OK @8979f87f(WSL, CPython 3.12).8979f87f(RTX 4090 Laptop, Windows, CUDA 13.0), and the resulting binary serves the hardware round-trip above (production model, IQ3_S quant; the A/B arms ran on the3766738dbuild, the same C++ mask code through this merge commit - the 0.2.3 merge is comment-only on the C++ side).cmake -S metal -B build-metal -G Ninja -DCMAKE_BUILD_TYPE=Release -DMETAL_CPP_DIR=<metal-cpp> -DSTRATA_GGML_DIR=<llama.cpp @3cf03257>+cmake --build-> 139/139 steps, zero errors @8979f87f(macOS 27 arm64, Apple clang 21); the binary carries the mask code paths. Compilation only - the Metal runtime was not exercised.sycl/tools/build.shin thestrata-sycl-devimage (oneAPI 2026.1, icpx) -> 232/232 steps, zero errors @8979f87f; the binary carries the mask code paths. Compilation only - see Not run.constrained_decoding: false): 17/20 valid, 3 terminal failures (all one missing required key after 5 client reconnects, ~11 min wasted each with zero usable output). Masked build (this branch): 20/20 valid, 0 retries. Same host, same model (IQ3_S quant), same prompts, same day.json_schemarequests: 3/3 first-pass valid, up to 15k-token structured outputs,finish_reason=stop.8979f87f) serving the same prompt plain vsjson_schema(masked), interleaved single-shots, max_tokens 6000, 3 pairs: masked 74.6 / 79.7 / 79.2 tok/s, plain 76.5 / 97.5 / 74.3 (wall-time rates, prefill included; the plain 97.5 is a warm-cache run). Medians 79.2 vs 76.5 - no measurable mask cost; the delta is inside the run-to-run spread./v1/statusgate:constrained_decoding: truewith the masked engine,falsewith the main-branch engine, as designed.Failed:
Not run:
fc2c1ebb= main 0.2.10 + this mask machinery): not attempted here(no oneAPI toolchain); the same engine state's CUDA build is covered by the bullet above
(170/170, 0 errors, at #4222's head
ed7f0d1e).token_mask=1equivalent), untested.Limits
502 structured_output_failedwithfinish_reason=lengthis orthogonal (output budget, not grammar) and still returns 502 by design; the two cases are distinguishable in the error body.🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.