Grammar-constrained decoding inside an engine
How an engine guarantees output that matches a JSON schema or grammar: compiling the grammar to an automaton, computing a token mask each step, applying it to the logits, handling tokens that span grammar boundaries, and keeping it fast with precomputed masks. With a runnable engine that goes from 0 to 100% valid output.
By Sandip Maity, Applied AI Engineer
Structured output explains why constrained decoding matters for serving. This lesson builds it into the engine: the grammar, the mask and the sampling loop, small enough to read in one sitting.
#The idea
At each step the engine knows the text generated so far. A grammar says which continuations are allowed. So:
- 1Logitsthe model scores every token in the vocabulary
- 2Masktokens that would break the grammar get minus infinity
- 3Samplefrom the remaining tokens only
- 4Advanceupdate the grammar state with the chosen token
If every step keeps the output a valid prefix, and end-of-sequence is allowed only when the output is complete, the result always parses.
Pro content
Keep reading with Inference Academy Pro
Unlock the rest of this lesson, plus every advanced lesson, hands-on lab, the larger playground models and completion certificates.
Still to come in this lesson
- A complete toy
- The details that matter in a real engine
- Quality: constraints guarantee format, not correctness
- Exercises
You will be able to answer
- What does a grammar-constrained decoder do at each step?
- Why is the mask computed over tokens rather than characters?
- Can constraints lower answer quality?
- What makes production constrained decoding fast?
- When must the end-of-sequence token be allowed?
Preparing for an interview?
- Structured output interview questions (constrained decoding) (6 questions with model answers)