Optimization & decoding4 min read

Structured outputs and constrained decoding in LLM serving

Prompting a model to “reply only with valid JSON” still fails at scale when a single stray markdown fence, trailing comma, or hallucinated field breaks downstream parsers. Constrained decoding compiles your JSON Schema, regex, or context-free grammar into an automaton that masks invalid vocabulary tokens before sampling—eliminating syntax retries and even skipping deterministic boilerplate tokens.

Conceptual illustration of token cubes passing through precision state-machine gates that filter invalid branches.
Finite-state and grammar masks block invalid vocabulary tokens before sampling so outputs match the target schema.

How grammar-guided logit masking guarantees valid syntax

At every decode step, a language model outputs a vector of raw scores (logits) over its entire vocabulary V. Unconstrained sampling converts all V logits into probabilities, giving nonzero mass to tokens that violate your target schema. Constrained decoding tracks parser state alongside sequence generation and sets disallowed token logits to -∞ before softmax.

Comparing structured-output enforcement strategies in production.
ApproachSyntax guaranteeLatency and token cost
Prompt instructions + parser retryNone on first pass; retries multiply tail latencyWastes prefill and decode tokens whenever validation fails
Regex / FSM constrained decodingExact match for regular languages and flat/bounded JSON schemasNear-zero per-step overhead with precomputed token bitmasks; supports jump-forward
Pushdown / CFG decoding (XGrammar, llguidance)Exact match for recursive schemas, SQL, and DSLsSub-millisecond CPU stack + bitmask generation overlapped with GPU execution

Naively testing 128,000 BPE strings against a regex on every decode step would bottleneck the CPU. Outlines solved this for regular expressions and JSON schemas by indexing the tokenizer vocabulary against deterministic finite-state machine (FSM) states offline, storing a compact allowed-token bitmask per state. XGrammar extended low-overhead masking to full context-free grammars by separating context-independent token masks from tiny dynamic stack checks.

Trace FSM logit masking and jump-forward in Python

Notice two wins when a schema compiles into a token-level FSM: first, chatty preambles (" sure") receive -inf and can never be sampled; second, whenever an FSM state allows only one valid token (such as "{" or '"status":'), the engine can append those deterministic tokens without running a full GPU decode step per character—a technique SGLang calls compressed finite-state jump-forward decoding.

Run with Python 3; no GPU or packages required
vocab = ["{", '"status":', ' "ok"', ' "error"', "}", " sure", " ```"]
# FSM transitions for {"status": "ok"|"error"}: state -> {token_id: next_state}
fsm = {
    0: {0: 1},             # deterministic: must emit "{"
    1: {1: 2},             # deterministic: must emit '"status":'
    2: {2: 3, 3: 3},       # model chooses between ' "ok"' and ' "error"'
    3: {4: 4},             # deterministic: must emit "}"
}
raw_logits_at_choice = [0.4, 0.2, 2.1, 1.3, 0.1, 4.8, 3.9]  # model prefers " sure"!

state, output, model_calls = 0, [], 0
while state != 4:
    allowed = fsm[state]
    if len(allowed) == 1:  # jump-forward deterministic boilerplate
        tok_id, state = next(iter(allowed.items()))
        output.append(vocab[tok_id])
    else:
        model_calls += 1
        masked = [score if i in allowed else float("-inf")
                  for i, score in enumerate(raw_logits_at_choice)]
        tok_id = max(range(len(vocab)), key=masked.__getitem__)
        output.append(vocab[tok_id])
        state = allowed[tok_id]

print("Generated:", "".join(output))
print(f"Decision steps requiring model logits: {model_calls} (out of {len(output)} tokens)")
Calculated output
Generated: {"status": "ok"}
Decision steps requiring model logits: 1 (out of 4 tokens)

Even though " sure" (4.8) and " `" (3.9) had higher raw logits than valid JSON values, masking guaranteed {"status": "ok"} on the first pass. When compressed tokens are appended via jump-forward, the engine runs a single multi-token prefill/extension pass over the inserted boilerplate so the KV cache stays exact before the next branching decision. Implement full FSM masking yourself in Finite-State Constrained Decoding.

Visual explanation

Jump-forward boilerplate, then mask invalid logits at branch points

Candidate tokens at state 2FSM bitmask applied before softmax
  1. "ok" ✓
  2. "error" ✓
  3. sure ×
  4. ``` ×

Disallowed tokens receive −∞ so chatty prose or markdown fences cannot be sampled.

Generated JSON tokens3 deterministic jumps + 1 model choice
  1. {
  2. "status":
  3. "ok"
  4. }

Single-transition states insert deterministic syntax directly; the model chooses among valid schema branches.

Illustrative trace from the Python example in this section. When jump-forward inserts multiple tokens at once, the serving engine still updates KV state for those tokens before the next decision.

Four failure modes to guard against in production

  1. Syntax validity is not semantic accuracy. Forcing JSON without mentioning the schema in the system prompt makes the model discover field names blindly via logit masks, degrading answer quality. Always include concise field descriptions in the prompt AND attach response_format or tools.
  2. Unbounded whitespace or optional loops. Loose regexes or schemas that permit infinite spaces/newlines allow a confused model to spin until max_tokens truncates the JSON mid-object. Bound array lengths (maxItems) and string patterns where practical.
  3. First-schema compilation cold start. Compiling a large recursive JSON Schema for the first time can take tens or hundreds of milliseconds on CPU. Reuse canonical schema definitions across requests so vLLM structured outputs and SGLang structured outputs hit their in-memory grammar caches.
  4. Reasoning traces plus JSON. Reasoning models need unconstrained <think>...</think> tokens before schema enforcement begins; configure reasoning parsers alongside tool-call parsers in our vLLM & SGLang command builder.

Structured outputs and constrained decoding FAQ

Does constrained decoding slow down every decode step?

Modern backends such as XGrammar and compressed FSMs compute bitmasks on the CPU in microseconds and overlap mask transfer with GPU execution, often matching—or with jump-forward, beating—unconstrained latency.

Why did my constrained JSON response still fail json.loads()?

Almost always because generation hit max_tokens before reaching a terminal FSM state; check finish_reason == "length" before parsing.

What is the difference between response_format (json_schema) and tools function calling?

json_schema constrains the entire assistant message to one schema, whereas tools lets the model choose whether to reply in natural language or emit one or more structured tool calls parsed via --tool-call-parser.

Sources and further reading

Primary documentation and research behind this guide.

  1. Efficient Guided Generation for Large Language Models (Outlines, 2023)
  2. XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models (2024)
  3. LMSYS Org: Fast JSON Decoding for Local LLMs with Compressed Finite State Machine
  4. vLLM v0.30.0: Structured outputs
  5. SGLang: Structured outputs and jump-forward decoding

Keep learning

Related guide · 7 min readLLM inference explained: from prompt to generated tokensRelated guide · 7 min readSpeculative decoding explained: faster LLM inferenceRelated guide · 6 min readLLM inference metrics: TTFT, TPOT, ITL, and throughputRelated guide · 7 min readvLLM vs SGLang: measured comparison and benchmark planAcademy course · 9 unitsInference Engineering FoundationsAcademy course · 13 unitsvLLMAcademy course · 13 unitsSGLangAcademy course · 20 unitsHugging Face Transformers
Back to all articles