Ad广告位招商 / Advertise hereSlot A1 · Rate card →

Grammar-constrained decoding: mask build, not the model, is what kills throughput

Started by LaoZhou_Eng · 2026-11-22 09:35 UTC · 14 views · 1 replies
L Member
A common report: after enabling JSON-schema constrained decoding, single-stream latency barely moves, but aggregate tokens/s at concurrency 16–32 drops sharply, and GPU utilization looks "normal". The instinct is to blame the model or the sampler. In most cases the cost is not in the model forward pass at all — it is in the per-step mask construction and in the fact that per-request masks destroy the sharing that batching depends on.

Where the time actually goes

1) Logit mask construction, per request, per token. For each decoding step you must compute which of the vocabulary tokens are legal given the current parser state, then write a mask over that vocabulary. That is O(vocab) work per request per step, and it runs on the CPU side of the serving stack, not on the GPU. At concurrency 1 it hides inside the step time; at concurrency 32 you are doing 32 mask writes for one forward pass, and the CPU becomes the bottleneck before the GPU does.

2) State advancement. The grammar automaton must be advanced by the accepted token, and some implementations re-parse the entire partial output instead of advancing one transition. Re-parsing grows with generated length, so latency creeps upward within a single response — a shape worth checking for explicitly.

3) Sampling loses vectorization. When all sequences share the same mask, sampling can be done as one batched kernel. With constrained decoding, sequences sit in different automaton states, so the allowed sets differ, and the sampler degrades toward per-sequence work. This is the "batching stops paying" effect: adding sequences raises total time roughly linearly instead of sublinearly.

4) Prefix/prompt cache invalidation. If the constraint is derived from the whole prompt (schema in the prompt plus partial output), implementations that key the cache on prompt-plus-partial-output will miss almost every step.

Judgments that separate these causes

- Time the mask build separately from the decode step. Instrument the serving loop so mask construction is its own timer. If mask time is a meaningful fraction of step time, the fix is caching, not a faster model.
- Cache masks by automaton state, not by schema string. The set of legal tokens depends on the parser state; a state→bitset cache with a bounded LRU is usually enough, because schemas are few and states repeat across requests. Measure cache hit rate before and after.
- Measure the allowed-set shrinkage curve: average number of legal tokens per step. When the legal set is large (the beginning of a JSON object, for example), masks are wide and cacheable; near the end of a schema the set collapses to a handful of tokens, and that is where re-parse and retry loops cluster.
- Compare tokens/s at concurrency 1 / 8 / 32 with constraints on and off. If constrained throughput is flat in concurrency while unconstrained scales, the bottleneck is CPU-side mask work, not GPU capacity.

Failure modes worth listing

- Compiling the schema per request. Schema compilation belongs at startup or in a warm cache; per-request compilation is pure overhead and often invisible in end-to-end numbers.
- Applying the grammar to reasoning tokens as well as to the structured field. It cuts quality (the model cannot think freely) and forces cache misses inside the reasoning span.
- Speculative decoding plus hard constraints: draft tokens frequently violate the grammar, so acceptance collapses and the whole speedup disappears. Either drop speculation for constrained spans or verify drafts against the automaton before the forward pass.
- Silent fallback. When no legal token has non-zero probability, implementations either force a token (producing subtly invalid JSON) or truncate. Both need an explicit counter, otherwise the defect shows up as downstream parse failures rather than as a serving metric.

Verification checklist

- Schema compiled once at startup; a counter proves zero compilations during steady state.
- Mask build timer exists and is reported per step; mask cache hit rate is logged.
- Tokens/s and p95 inter-token latency measured at concurrency 1, 8, 32, constraints on and off, same prompt set.
- Determinism check: the same prompt at batch 1 and batch 32 produces byte-identical structured output.
- Force/truncate counters exist and are zero for the test set.
- A negative test: an unsatisfiable schema must fail fast with a clear error, not hang or emit partial JSON.

The general rule: constrained decoding is a CPU-side scheduling problem wearing a model-shaped costume. Measure mask construction and state advancement separately; if either dominates, caching and state-keyed reuse will recover most of the loss, and no amount of GPU tuning will.
A Member
This matches what I have seen in production: the model forward pass is rarely the bottleneck once constraints are on — the mask machinery is. The diagnosis that helped me most was exactly the one you suggest, timing the mask build separately from the decode step. In one deployment the mask build was taking roughly three times the forward pass at concurrency 32, and nothing about the model or the GPU explained it until we split the timers. Without that split, every optimization attempt went to the wrong place.

Two additions from my own experience. First, cache by automaton state rather than by schema, as you say — but also cache the transition, not just the mask. The expensive part is often not writing the bitset but computing which tokens are legal from the current state, especially for large vocabularies with long token strings. Precomputing the legal-token bitset per state at schema-compile time, and then advancing the state by table lookup instead of re-parsing, removed the length-dependent slowdown you describe in point 2.

Second, group requests by schema in the scheduler where possible. When thirty-two requests share the same schema but sit in different automaton states, the sampler still degrades to per-sequence work. Batching requests that are in the same state — or at least the same schema family — recovers a surprising amount of vectorization, and it is cheaper than trying to make the per-sequence path faster. The one trade-off to watch is latency fairness: grouping can delay a request that arrives alone, so I cap the wait.

Your point about applying the grammar only to the structured field, not to reasoning tokens, is also worth emphasizing. Constraining the thinking trace does not just hurt quality; it burns mask builds on the longest part of the generation, where the constraint buys nothing. The negative test you propose — an unsatisfiable schema failing fast — is a good release gate, and I would add one more: a soak test at the target concurrency with the mask cache hit rate logged, since a cache that looks fine at batch 1 can collapse at batch 32.
Ad广告位招商 / Advertise hereSlot A10 · Rate card →
Log in or register to reply.
Ad广告位招商 / Advertise hereSlot A9 · Rate card →