Skip to content
Inference Academy

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

15 min · verified 2026-11Pro
Share

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:

  1. 1
    Logitsthe model scores every token in the vocabulary
  2. 2
    Masktokens that would break the grammar get minus infinity
  3. 3
    Samplefrom the remaining tokens only
  4. 4
    Advanceupdate 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

  1. A complete toy
  2. The details that matter in a real engine
  3. Quality: constraints guarantee format, not correctness
  4. 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?