[PR #3800] [Engine] Token mask for JSON response formats: MTP drafts survive constrained decoding #4787

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

📋 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+)

  • 6cb9538 serve + engine: constrained decoding for JSON response formats: a token mask per window (mask=1, MQ/MF/MK) on the chat route
  • d851324 Merge branch 'main' into f-json-mask
  • 52922ef serve + 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=1
  • a79dd4d Merge remote-tracking branch 'origin/main' into json_mtp
  • 8fc68d7 Merge branch 'main' into f-json-mask
  • eb4e23c Merge remote-tracking branch 'origin/main' into f-json-mask
  • c4c8323 Merge 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 llguidance
  • 3766738 Merge remote-tracking branch 'origin/main' into f-json-mask-merged
  • 8979f87 Merge 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 clamp
  • 6668b9d Merge 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 got 502 structured_output_failed and 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.

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 advertises token_mask=1/2 in its startup INFO; the default path is byte-identical. /v1/status reports constrained_decoding: true only when the gate passes. The chat route keeps rejecting tools+schema (400); /v1/responses supports both. token_mask=2 also lets a whole MTP window be masked; row-count shrink trims drafts server-side.

Validation

Passed:

  • Merged with origin/main twice on 2026-10-28 (0.2.7.x -> 266ad181) and 2026-11-04 (0.2.10 ->
    merge head fc2c1ebb). The first round: keep-both in serve/server.py (main's prefill_only
    head rewrite beside the mask block; main's LP-line capture beside c.feed(t)) and main's window-T
    refactor in generate.cpp at the mask-comment hunks. The second round: serve/server.py takes
    main's rid/pen_from machinery beside the mask gate (the mask=1 append rides after main's rid
    head), verify.cpp takes main's STRATA_VERIFY_HGL guard beside the token_mask include,
    generate.cpp takes main's DFlash2/window-rule restructure with the MQ exchange beside main's
    keep_sync (window filled -> mask cut -> MQ/MK/MKN rows -> adoption; the HIP stop-bound block
    follows 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 against
    main at the merged head is the mask machinery and its serve half only (14 files, +1342/−16,
    engine files 7 files, +399/−11).
  • Re-validated at the merged heads: the same suite -> 465 tests OK at 266ad181 and 467 tests
    OK
    (~150 s, miniforge python 3.12, llguidance 1.9.1, WSL Ubuntu, no GPU) at fc2c1ebb, zero skips.
  • Engine identity with the stacked serve PR's merged head (#4222, ed7f0d1e): git diff fc2c1ebb ed7f0d1e -- src include sycl = 0, so the CUDA build and hardware verification run there on
    2026-11-04 (170/170 steps, 0 errors, engine 0.1.56, STRATA_TOOL_MASK=1, 15/15 first-pass probes,
    /v1/status constrained_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.
  • Serve 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).
  • CUDA build: full engine build 165/165 steps, zero errors @ 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 the 3766738d build, the same C++ mask code through this merge commit - the 0.2.3 merge is comment-only on the C++ side).
  • Metal build: 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 build: sycl/tools/build.sh in the strata-sycl-dev image (oneAPI 2026.1, icpx) -> 232/232 steps, zero errors @ 8979f87f; the binary carries the mask code paths. Compilation only - see Not run.
  • Hardware mask round-trip, production workload: 20 real multi-turn report prompts (sanitized copies attached on request) through an agentic CLI client with client-side schema validation. Unmasked build (0.1.44.1, 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.
  • Single-shot json_schema requests: 3/3 first-pass valid, up to 15k-token structured outputs, finish_reason=stop.
  • Mask decode-cost isolation, same revision: the same build (8979f87f) serving the same prompt plain vs json_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/status gate: constrained_decoding: true with the masked engine, false with the main-branch engine, as designed.

Failed:

  • None observed on the masked build. (The 3 failures above are the unmasked control arm demonstrating the problem.)

Not run:

  • HIP build - no toolchain here.
  • SYCL build at the merged head (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).
  • SYCL runtime: the build is SPIR-V JIT for Intel devices; the mask round-trip was not rerun on the SYCL backend (verification was on CUDA).
  • Metal runtime: single-row windows only (token_mask=1 equivalent), untested.

Limits

  • 502 structured_output_failed with finish_reason=length is orthogonal (output budget, not grammar) and still returns 502 by design; the two cases are distinguishable in the error body.
  • The A/B arms ran control-first, so the masked arm had a warmer prompt cache; wall-clock totals favor the mask arm beyond the mask effect itself. The failure-rate delta (3/20 vs 0/20) and per-token decode band are not cache-sensitive in the same way.
  • The mask-cost isolation is n=3 pairs on one prompt with wall-time rates (prefill included, cache hits vary); it rules out a large mask cost but cannot resolve a few-percent effect.
  • n=20 per arm: the unmasked failure rate is intermittent (~13-15% per sample in both field logs and repro); a same-size rerun could show 0-4 failures on the control arm.

🔄 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/3800 **Author:** [@ncphri](https://github.com/ncphri) **Created:** 10/23/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `f-json-mask` --- ### 📝 Commits (10+) - [`6cb9538`](https://github.com/Niko1221/Strata/commit/6cb953893ed114cc910b3d9c11bce255259334cc) serve + engine: constrained decoding for JSON response formats: a token mask per window (mask=1, MQ/MF/MK) on the chat route - [`d851324`](https://github.com/Niko1221/Strata/commit/d851324399ca7a3b1607d8694aac5912faa81852) Merge branch 'main' into f-json-mask - [`52922ef`](https://github.com/Niko1221/Strata/commit/52922ef5c4e0fdf66d238bc4f3403e955010c04b) serve + 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=1 - [`a79dd4d`](https://github.com/Niko1221/Strata/commit/a79dd4d1610a172511f31b9a5a8266a05be89b79) Merge remote-tracking branch 'origin/main' into json_mtp - [`8fc68d7`](https://github.com/Niko1221/Strata/commit/8fc68d7ee2978b538a6d8fd78d70e96fafa4e84f) Merge branch 'main' into f-json-mask - [`eb4e23c`](https://github.com/Niko1221/Strata/commit/eb4e23c69a6f10ae7a888100a611e8fddd5ed7cb) Merge remote-tracking branch 'origin/main' into f-json-mask - [`c4c8323`](https://github.com/Niko1221/Strata/commit/c4c83231b57104533e56f958fa7bad31ea6ba80e) Merge 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 llguidance - [`3766738`](https://github.com/Niko1221/Strata/commit/3766738d62f713c4ccd2eeed6644637cb9620ef1) Merge remote-tracking branch 'origin/main' into f-json-mask-merged - [`8979f87`](https://github.com/Niko1221/Strata/commit/8979f87f582e00ceaa8dbe33fe490c6b6f658095) Merge 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 clamp - [`6668b9d`](https://github.com/Niko1221/Strata/commit/6668b9ddf05abe38c3edf297c6ca180abe383c80) Merge 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) <details> <summary>View changed files</summary> 📝 `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) </details> ### 📄 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 got `502 structured_output_failed` and 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 advertises `token_mask=1/2` in its startup INFO; the default path is byte-identical. `/v1/status` reports `constrained_decoding: true` only when the gate passes. The chat route keeps rejecting tools+schema (400); `/v1/responses` supports both. `token_mask=2` also lets a whole MTP window be masked; row-count shrink trims drafts server-side. ## Validation **Passed:** - Merged with `origin/main` twice on 2026-10-28 (0.2.7.x -> 266ad181) and 2026-11-04 (0.2.10 -> merge head **fc2c1ebb**). The first round: keep-both in `serve/server.py` (main's `prefill_only` head rewrite beside the mask block; main's LP-line capture beside `c.feed(t)`) and main's window-T refactor in `generate.cpp` at the mask-comment hunks. The second round: `serve/server.py` takes main's `rid`/`pen_from` machinery beside the mask gate (the `mask=1` append rides after main's rid head), `verify.cpp` takes main's `STRATA_VERIFY_HGL` guard beside the token_mask include, `generate.cpp` takes main's DFlash2/window-rule restructure with the MQ exchange beside main's `keep_sync` (window filled -> mask cut -> MQ/MK/MKN rows -> adoption; the HIP stop-bound block follows 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 against `main` at the merged head is the mask machinery and its serve half only (14 files, +1342/−16, engine files 7 files, +399/−11). - Re-validated at the merged heads: the same suite -> **465 tests OK** at 266ad181 and **467 tests OK** (~150 s, miniforge python 3.12, llguidance 1.9.1, WSL Ubuntu, no GPU) at fc2c1ebb, zero skips. - Engine identity with the stacked serve PR's merged head (#4222, ed7f0d1e): `git diff fc2c1ebb ed7f0d1e -- src include sycl` = **0**, so the CUDA build and hardware verification run there on 2026-11-04 (170/170 steps, 0 errors, engine 0.1.56, `STRATA_TOOL_MASK=1`, 15/15 first-pass probes, `/v1/status` `constrained_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. - Serve 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). - CUDA build: full engine build 165/165 steps, zero errors @ 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 the 3766738d build, the same C++ mask code through this merge commit - the 0.2.3 merge is comment-only on the C++ side). - Metal build: `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 build: `sycl/tools/build.sh` in the `strata-sycl-dev` image (oneAPI 2026.1, icpx) -> 232/232 steps, zero errors @ 8979f87f; the binary carries the mask code paths. Compilation only - see Not run. - Hardware mask round-trip, production workload: 20 real multi-turn report prompts (sanitized copies attached on request) through an agentic CLI client with client-side schema validation. Unmasked build (0.1.44.1, `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. - Single-shot `json_schema` requests: 3/3 first-pass valid, up to 15k-token structured outputs, `finish_reason=stop`. - Mask decode-cost isolation, same revision: the same build (8979f87f) serving the same prompt plain vs `json_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/status` gate: `constrained_decoding: true` with the masked engine, `false` with the main-branch engine, as designed. **Failed:** - None observed on the masked build. (The 3 failures above are the unmasked control arm demonstrating the problem.) **Not run:** - HIP build - no toolchain here. - SYCL build at the merged head (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). - SYCL runtime: the build is SPIR-V JIT for Intel devices; the mask round-trip was not rerun on the SYCL backend (verification was on CUDA). - Metal runtime: single-row windows only (`token_mask=1` equivalent), untested. ## Limits - `502 structured_output_failed` with `finish_reason=length` is orthogonal (output budget, not grammar) and still returns 502 by design; the two cases are distinguishable in the error body. - The A/B arms ran control-first, so the masked arm had a warmer prompt cache; wall-clock totals favor the mask arm beyond the mask effect itself. The failure-rate delta (3/20 vs 0/20) and per-token decode band are not cache-sensitive in the same way. - The mask-cost isolation is n=3 pairs on one prompt with wall-time rates (prefill included, cache hits vary); it rules out a large mask cost but cannot resolve a few-percent effect. - n=20 per arm: the unmasked failure rate is intermittent (~13-15% per sample in both field logs and repro); a same-size rerun could show 0-4 failures on the control arm. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
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#4787
No description provided.