← All posts

1,000 Generations, Zero Parse Failures: Guided Decoding in vLLM, Plainly

2026-11-28 · GDE #10 / vLLM serving (structured output — guided decoding, XGrammar, whitespace trap)

Ask a language model for JSON and it will give you JSON — most of the time. The rest of the time it gives you JSON with a trailing comma, a missing quote, a field that wandered off into prose, or a confident apology where the closing brace should be. In a demo, that is a shrug and a retry. In production, where the model's output feeds a parser that feeds a database that feeds a payment, it is a 2 a.m. page. The failure rate is not small, either: in the toy model in this post's notebook, an unguided small model fails to produce parseable JSON 18 times per 1,000 generations on a flat five-field object, 70 times on a nested object, and 144 times on a 50-tool function-calling schema. Guided decoding — vLLM's structured outputs — makes that number exactly zero. Not approximately zero. Zero, by construction, because the model is never allowed to emit a token that would break the schema.

This is GDE post #10 in the vLLM serving series, and it closes Lane A. It is also the post with the most direct production payoff in the lane: every agent, every extraction pipeline, and every tool-calling loop you have built on top of vLLM is one malformed output away from a retry storm, and the fix is a server flag, not a bigger model.

The ELI5 version

Unguided generation is a student writing an essay with no spell-check: they know the subject, and most of the essay is fine, but one typo in the wrong place invalidates the whole thing. Guided decoding is the same student writing on a keyboard where the wrong keys are physically locked. The grammar of the output — the JSON schema, the regex, the list of allowed choices — is compiled into an automaton before generation starts. At every decode step, the engine looks at which tokens would keep the output inside the grammar and sets the logit of every other token to negative infinity. Those tokens get zero probability. They cannot be sampled, at any temperature, by any model, ever.

The invariant is one sentence: the concatenation of emitted tokens is always a prefix of some string in the grammar's language. If the schema says the next character must be a quote, the only tokens the model can emit are tokens that start with a quote. The model still chooses what to say — the value of the field, the name of the tool, the number in the total — but it cannot choose to break the shape of what it says. Shape is the engine's job now; content is still the model's.

How it works: the mask, the automaton, and the backends

The engineering problem is the vocabulary. A modern model has 100,000–256,000 tokens, and the engine has to decide, at every decode step, which of them are legal under the grammar. Doing that naively — checking every token against the automaton every step — would dominate generation time and make structured output unusable. XGrammar, the backend vLLM uses by default, solves it by precomputing per-state token masks and overlapping mask construction with the GPU forward pass, so the mask for the next step is ready before the logits arrive. The paper (arXiv:2411.15100) reports up to 3.5x lower logit-masking overhead for JSON Schema and up to 10x for full context-free grammars versus the engines it replaced, with end-to-end speedups up to 14x and 80x respectively — described as near-zero-overhead structured generation.

Relative masking and end-to-end cost of the engines XGrammar replaced, with XGrammar normalized to 1.0x: prior engines were 3.5x slower on JSON Schema masking, 10x slower on context-free-grammar masking, and 14x to 80x slower end to end. Figures are the XGrammar paper's reported results.

vLLM exposes this as structured outputs, with five constraint types per request:

The backend is set server-side with --structured-outputs-config.backend and defaults to auto, which picks per request from the request's details. You can pin xgrammar or guidance (llguidance) explicitly; outlines is also available. One migration note for 0.33: lm-format-enforcer is deprecated starting in v0.33.0 — it still works with a warning, requires an explicit opt-in in 0.34, and is removed in 0.35. If your deploy still names it, switch to auto now, and re-validate your schemas first: lm-format-enforcer uses Python-style regex while xgrammar and guidance use Rust-style regex, so the same pattern can admit different tokens on the new backend.

The minimal code, offline:

from vllm import LLM, SamplingParams
from vllm.sampling_params import StructuredOutputsParams
from pydantic import BaseModel

class Invoice(BaseModel):
    vendor: str
    total: float
    line_items: list[str]

llm = LLM(model="google/gemma-3-4b-it")
sp = SamplingParams(temperature=0.0, max_tokens=256,
                    structured_outputs=StructuredOutputsParams(json=Invoice.model_json_schema()))
outs = llm.generate(["Extract the invoice fields."], sp)
# json.loads(outs[0].outputs[0].text) parses, always — the grammar guarantees it.

Over the OpenAI-compatible server, the same schema travels in response_format, and the server flag is --structured-outputs-config '{"backend": "xgrammar", "disable_any_whitespace": true}' — that second setting matters, and it is the subject of the trap below.

The numbers: 1,000 generations, zero failures

The notebook runs the toy model: 1,000 generations per schema shape, unguided, with per-generation failure probabilities calibrated to published JSON-mode failure ranges for small models. Flat five-field object: 18 failures. Nested three-level object: 70. Fifty-tool function-calling schema: 144 — nearly one in seven calls. Guided decoding: 0, 0, and 0, because the mask makes a parse failure impossible rather than unlikely.

Parse failures per 1,000 generations in the notebook's toy model: unguided generation fails 18 times on a flat object, 70 on a nested object, and 144 on a 50-tool schema; guided decoding fails zero times on all three, by construction.

Every unguided failure also costs a full regeneration. At ~180 tokens per output, the nested-schema job wastes ~14,940 tokens per 1,000 generations on outputs it throws away — 8.3% of its token budget, before the retry even succeeds — and the retry itself can fail again. The guided job pays a mask instead, and the mask is the near-zero-overhead part: the XGrammar numbers above are the reason the throughput cost of turning structured output on is measured in single-digit percent on JSON schemas, not in multiples.

XGrammar-2: the compile-time fix

XGrammar's first version made the decode step cheap. XGrammar-2 (May 2026) attacks the other end: grammar compilation. Compiling a schema into an automaton is a one-time cost per schema, but with 50 tools in a function-calling set it used to be a real one — 534 ms for a single complex JSON Schema, and hundreds of milliseconds across a tool set, paid on every server start and every new schema. XGrammar-2 reports up to 80x faster compilation as the tool count scales from 10 to 500, a repetition compression that takes one complex schema from 534 ms to 5.37 ms, and cross-grammar caching that reuses close to 50% of structure when compiling a 50-tool set.

Grammar compile time against tool count: XGrammar v1 climbs from 41 ms at 10 tools to 812 ms at 500, while XGrammar-2 stays near flat, 3.4 ms to 10.2 ms — up to 80x faster. The single-schema headline is 534 ms down to 5.37 ms.

For an agent server that registers dozens of tools, this is the difference between structured output being a startup tax and being free. It is also the reason the structural_tag constraint exists: tool-calling schemas are the biggest, most compilation-expensive grammars in production, and the tag format lets one grammar cover a whole tool protocol instead of compiling one per tool.

The whitespace trap: the grammar cannot stop a legal loop

There is one failure mode guided decoding does not prevent, and it is the most instructive one in this post. JSON allows any amount of whitespace between fields, so every tab and space is a legal next token — and a grammar can only forbid illegal tokens. A model that starts emitting whitespace can emit it forever, and the grammar cannot stop it, because nothing about the whitespace violates the schema. A real document-AI deployment on vLLM-TorchTPU 0.33 hit exactly this: Gemma 4 on a TPU v6e chip, extracting invoice fields into a Pydantic schema, got stuck in a whitespace loop mid-extraction.

The fix is one server setting, disable_any_whitespace: true on the xgrammar backend, which forces compact JSON. Extraction got faster too, from 5.1 s to 4.4 s — and the token math explains why: the toy invoice JSON in the notebook is 182 tokens with whitespace allowed and 141 compact, 22.5% fewer tokens for the same fields.

Tokens per invoice JSON and wall time per extraction, whitespace allowed versus compact: 182 tokens down to 141 (22.5% fewer) and 5.1 seconds down to 4.4 (13.7% faster) with disable_any_whitespace set. The timing is the cited deployment's measured result.

The rule that falls out of it: if you constrain generation, cap or remove the whitespace. A second line of defense — one retry, then a plain-text fallback — is still worth having, because the model can still produce a valid JSON object with wrong values. Guided decoding guarantees shape, never truth. A schema-valid invoice with the wrong total is still a wrong invoice; validate the values after parsing, the way the deployment above checks quantity × price against the subtotal.

When guided decoding loses

Structured output is the wrong tool in three situations. First, free-form generation: if the output is prose, a summary, or a chat reply, a schema adds cost and buys nothing — the constraint only pays when a parser consumes the output. Second, schemas the model cannot fill: if the model does not know the answer, the grammar forces it to emit something schema-valid, which is a confident hallucination in a well-formed envelope. A schema makes wrong answers look right. Third, very large or deeply recursive schemas on the decode path: compile time is now cheap, but a grammar with thousands of states still costs mask memory per request — measure it before putting a 500-tool schema on a latency SLO.

The decision rule is one sentence: if a parser, a database, or another agent consumes the output, constrain it; if a human reads it, do not.

Takeaways

Honesty note: parse-failure rates and token counts are this notebook's toy model, calibrated to published JSON-mode failure ranges — not a measured vLLM run; the real vLLM calls are in the notebook's last cell and need a GPU box. XGrammar/XGrammar-2 figures are the papers' and project's reported results. The 5.1→4.4 s whitespace fix is one deployment's measured result (Nov 2026, Gemma 4 on TPU v6e via vLLM-TorchTPU 0.33). vLLM 0.33 structured-outputs behavior verified against docs.vllm.ai (stable) on Nov 28, 2026. No Meta content per the standing exclusion.

Companion notebook: guided_decoding_vllm.ipynb — parse-failure simulation, retry cost, XGrammar-2 compile scaling, whitespace math, and the 0.33 config guard, all exec-tested.

Companion notebook

guided_decoding_vllm.ipynb — the runnable tutorial for this post (download, or open it in Colab/Jupyter).

← All posts