Compiling JSON Schemas or regexes into deterministic finite-state machines (DFAs) and pre-indexed vocabulary bitmasks lets LLM servers mask invalid token logits to -inf before Softmax in < 50 microseconds, guaranteeing 100% schema-valid output in a single pass.
TL;DR30-second simplified summary▾
Production AI agents and tool-calling pipelines require 100% schema-valid JSON at 10,000+ requests per second. Relying on prompt engineering plus json.loads() retry loops suffers roughly 18% structural parse failures on complex nested schemas, wasting up to 3x GPU decode FLOPs and inflating tail latency.
Constrained decoding solves this by compiling a JSON Schema into a regular expression or context-free grammar (CFG), determinizing it into a Finite-State Machine (FSM), and pre-indexing every state against the model's 128K+ token vocabulary into a compact bitmask table.
During autoregressive decoding, each active sequence tracks its current FSM state q_i. Before Softmax sampling, a fused GPU kernel applies the bitmask for q_i to the raw logit vector—setting invalid token logits to -inf so their probability becomes zero—and advances the FSM state upon sampling.
Advanced engines like XGrammar and Outlines further eliminate per-token overhead via CPU-GPU overlapped bitmask lookup, compressed vocabulary tries for multi-byte BPE tokens, and token jump-forward (coalescing) that skips deterministic boilerplate tokens such as {"id": in a single step.
From patterns to decisions.
Compiling JSON Schemas or regexes into deterministic finite-state machines (DFAs) and pre-indexed vocabulary bitmasks lets LLM servers mask invalid token logits to -inf before Softmax in < 50 microseconds, guaranteeing 100% schema-valid output in a single pass.
Stage 1: Why Prompt-and-Retry Fails at 10K+ req/sec.
Unconstrained LLMs treat JSON syntax as soft statistical preferences, leading to trailing commas, unescaped quotes, or truncated braces under temperature > 0. At an 18% parse-failure rate, retrying failed generations consumes up to 3x GPU KV-cache and decode FLOPs while breaking strict SLA budgets.
Prompt-and-Retry Loop vs. Single-Pass Deterministic Validity
1.3x Compute Amplification: Discarding a 500-token generation on a single missing brace wastes the entire prefill + decode budget.
2.First-Pass Guarantee: Logit masking prevents invalid syntax tokens from ever being sampled, eliminating schema retries.
Post-hoc json.loads() retries waste up to 3x GPU compute on ~18% failure rates, whereas logit masking guarantees valid output in one pass.
Stage 2: Compiling JSON Schema & Regex into a DFA.
A JSON Schema defines field names, types, enums, and nesting constraints. An offline compiler translates the schema into a regex (or pushdown CFG for recursive objects), converts it to an NFA via Thompson's construction, and applies subset construction + Hopcroft minimization to produce a compact Deterministic Finite Automaton (DFA) with states q_0...q_k.
Lowering JSON Schema to a Minimized Deterministic Finite Automaton
1.Amortized Compilation: Compiled DFAs are cached by schema hash in shared RAM so repeated API calls skip compilation.
2.Deterministic Transitions: Each character or token maps deterministically from state q_i to exactly one next state q_j.
JSON Schemas compile through regex/CFG lowering and subset construction into a minimized DFA cached by schema hash.
Stage 3: BPE Vocabulary Indexing & Precomputed Bitmask Tables.
LLMs operate over subword BPE vocabularies (V = 128,256+ tokens) where a single token like ": " or 123, spans multiple DFA transitions. During compilation, the engine walks every token in the vocabulary trie from each DFA state q_i to record which token IDs remain valid, packing them into a compact bitmask array of ceil(V / 32) uint32 words per state.
Mapping 128K BPE Tokens onto DFA States as 16 KB Bitmasks
1.16 KB Per State: A 128K-token vocabulary packs into just 4,008 uint32 words (16 KB) per DFA state.
2.Trie Prefix Sharing: Walking a compressed BPE trie avoids re-evaluating shared token prefixes, cutting compile time by 10x.
Precomputing a 16 KB uint32 bitmask per DFA state over the BPE trie turns runtime token validation into an O(1) table lookup.
Stage 4: Element-Wise Logit Masking & Fused Softmax Kernels.
At each decode step, the engine fetches the 16 KB bitmask for sequence i's current FSM state and applies it to the [B, V] raw logit tensor on GPU. Any token whose bit is 0 has its logit overwritten with -inf before Softmax, ensuring zero probability mass without disturbing relative probabilities among valid tokens.
Fused Bitmask + Softmax Kernel Under 50 Microseconds
1.Distribution Preservation: Masking invalid tokens to -inf before Softmax preserves exact relative odds among all schema-valid tokens.
2.Sub-50 us Overhead: Fusing bit-unpacking with Softmax avoids an extra global HBM round-trip on the 128K logit tensor.
A fused CUDA kernel unpacks the uint32 bitmask and sets invalid logits to -inf before Softmax in under 50 microseconds.
Stage 5: CPU-GPU Overlap in Continuous Batching Loops.
If the CPU advances FSM states and copies bitmasks synchronously between decode steps, the GPU stalls waiting on PCIe transfers. Continuous batching engines overlap CPU FSM stepping and pinned-memory async H2D bitmask copies for step t+1 while the GPU executes Transformer layers for step t.
Hiding FSM Transitions & H2D Copies Behind GPU Forward Passes
1.Zero Bubble Overhead: 20 us of CPU FSM work and 16 KB DMA fit completely inside a 10-20 ms Transformer decode step.
2.Pinned Memory Pool: Pre-allocated pinned host buffers prevent page-fault stalls during cudaMemcpyAsync.
Overlapping host FSM transitions and async pinned H2D bitmask copies with GPU Transformer layers eliminates decode bubbles.
Stage 6: Token Jump-Forward (Coalescing) for Boilerplate Keys.
Whenever the FSM enters a state with only one valid outgoing string—such as ","status":" or fixed enum prefixes—the LLM has zero entropy and would waste 3 to 6 forward passes generating known tokens. Jump-forward decoding detects single-path DFA chains, appends those tokens directly into the KV-cache prefill/chunked-prefill batch, and advances the FSM to the next branching state.
Skipping Deterministic JSON Keys via DFA Jump-Forward Decoding
1.2x-3x Decode Speedup: Schema-heavy JSON payloads with fixed keys cut autoregressive decode steps by up to 60%.
2.Exact Logit Equivalence: When out-degree is 1, only one token sequence has non-zero probability, so jumping preserves exact distribution.
Jump-forward decoding injects deterministic single-path JSON keys directly into chunked KV prefill, cutting decode steps by up to 60%.
Stage 7: Context-Free Grammars (CFG) & Adaptive Bitmask Caching.
Pure DFAs cannot express unbounded recursive nesting such as trees or nested comments without state explosion. Engines like XGrammar split vocabulary tokens into context-independent tokens (evaluated once per pushdown CFG state and cached) and context-dependent tokens (evaluated dynamically over the active stack), bounding per-step CPU latency to < 40 microseconds even for arbitrary CFGs.
Splitting Context-Independent & Stack-Dependent Tokens in XGrammar
1.Unbounded Nesting: Pushdown automata handle recursive schemas and DSLs without exponential DFA state blowup.
2.< 1% Dynamic Checks: Pre-caching context-independent tokens leaves only a tiny fraction of tokens needing stack inspection.
Adaptive bitmask caching splits pushdown CFG tokens into 99% static cached masks and < 1% stack-checked tokens for < 40 us steps.
Practice: Make the trade-off yourself.
Why does FSM logit masking set invalid token logits to -inf BEFORE Softmax rather than filtering tokens after Softmax?