Decode under a finite-state grammar
Why it matters JSON mode and tool-call schemas in Outlines, vLLM and llama.cpp grammars work this way.
Structured output libraries turn a grammar into a finite-state machine and mask every token that would leave it.
Write fsm_decode(step_fn, fsm, start, accept, max_new). fsm is a dict {state: {token: next_state}}. At each step take logits = step_fn(tokens), mask every token not allowed from the current state, and pick the arg-max allowed token. Stop when the current state is in accept and has no outgoing tokens, or after max_new tokens. Return the token list. If a state has no allowed tokens and is not accepting, raise ValueError.
def fsm_decode(step_fn, fsm, start, accept, max_new)Example
fsm {0: {7: 1}, 1: {8: 2}, 2: {}}, start 0, accept {2} returns [7, 8] regardless of the logits.
Understand the idea
To force a model to output valid JSON or a fixed format, structured output libraries compile the format into a finite-state machine. Each state lists which tokens are allowed next and which state each one leads to. At every step, all other tokens are masked to -inf, so the model can only choose a valid token. Worked example: fsm {0: {3: 1, 4: 2}, 1: {5: 2}, 2: {}}, start 0, accept {2}, and a model that prefers token 3 over 4. In state 0, tokens 3 and 4 are allowed, and 3 wins, moving to state 1. In state 1 only token 5 is allowed, whatever the logits say, moving to state 2. State 2 is accepting and has no outgoing tokens, so stop with [3, 5]. Rule: state = start; loop up to max_new times: if state is accepting and has no outgoing tokens, stop; if it has no allowed tokens and is not accepting, raise ValueError; mask logits to the allowed tokens, take the argmax, append it and move to fsm[state][token]. Always advance the state after each token. Used in: JSON mode, grammar-constrained decoding and function calling.
Shapes and data flow
state -> allowed {token: next}
logits (V,) -> mask disallowed -> argmax -> token, state = next