18. Constrained decoding

Why this layer exists

Chapter 13 trained a model to write tool calls and checked them with one function. parse_reply is the only thing between a sampled sequence and a call: the network produces a distribution over tokens at every step, and a call is well formed only if the tokens it happens to sample spell one. On chapter 13’s lab model at step 25, none of them did. Chapter 17’s server inherited the problem. It holds a call until <|end|> because only then can it tell whether the tokens form a call at all, and when they do not, it passes them on as text.

Structured output (response_format with a JSON Schema), reliable tool calls, and llama-server’s --grammar and json_schema options all rest on one idea: before sampling each token, remove every token that could not continue a valid output. You have met the idea twice already. Chapter 17’s tool_choice masks remove <|call|> or everything but <|call|> at the first step. llama-server’s reasoning budget, from chapter 13, forces the end of a thinking block by setting every logit except the forced token’s to −∞-\infty (common_reasoning_budget_apply, common/reasoning-budget.cpp:166-186, as of llama.cpp da89bb3 (2026-09-29), the commit every llama.cpp source reference below is to). This chapter builds the general form: a grammar, a recognizer that tracks every way a prefix can still be parsed, a mask computed from it over a vocabulary of byte strings, a length budget the mask can enforce, and a compiler from JSON Schema to grammars, wired into chapter 17’s server. It also says where the idea fails. A mask guarantees the form of the output and nothing about its content, and on the lab’s model it costs content.

Mechanism

Grammars over characters

A context-free grammar is a tuple G=(N,Σ,R,S)G = (N, \Sigma, R, S): a set NN of rule names (nonterminals), an alphabet Σ\Sigma of terminals, a set RR of rules, each of which rewrites a name as a sequence over N∪ΣN \cup \Sigma, and a start name S∈NS \in N. A name may have several rules, its alternatives. The language L(G)L(G) is the set of terminal strings that can be derived from SS by rewriting names with rules until none is left. Here Σ\Sigma is the Unicode code points, the integers from 0 to 0x10FFFF\texttt{0x10FFFF} that chapter 17’s UTF-8 section encoded, and SS is the rule called root.

llama.cpp writes grammars in a notation it calls GBNF, and this chapter parses the part of it that JSON needs. A rule is name ::= alternatives, with alternatives separated by |. An element is one of:

  • a literal, "abc", which matches exactly that sequence of characters;
  • a character class, [a-z0-9_], which matches one character in any of the listed ranges, or a negated class, [^"\\], which matches one character in none of them; . matches any character;
  • a rule name, which matches whatever that rule matches;
  • a group in parentheses, which matches whatever the alternatives inside it match.

Any element can be followed by * (zero or more), + (one or more), ? (zero or one), {m} (exactly mm), {m,} (at least mm) or {m,n} (between mm and nn). Escapes such as \n, \x1f and \u00e9 name characters inside literals and classes.

The recognizer below understands only two kinds of element: a character class, stored as ("chars", ((lo, hi), ...), negated), and a reference to a rule, ("ref", name). Everything else is rewritten into those by parse_gbnf. A literal of one character is a class with one range; a longer literal becomes a helper rule whose single alternative is its characters in order. A group becomes a helper rule whose alternatives are the group’s. Repetition becomes right-recursive helper rules, and the rewriting can be derived from what each operator means.

x∗x^* is zero or more copies of xx. A string of copies is either empty or one xx followed by a string of copies, which is a rule that refers to itself at its right end:

t::=x t∣ε. t \mathrel{::=} x\ t \mid \varepsilon .

Unfolding it kk times and then taking ε\varepsilon gives exactly kk copies, for every k≥0k \ge 0, and nothing else. x+x^+ is one copy followed by x∗x^*, so it is r::=x tr \mathrel{::=} x\ t with the same tt. For a bounded repetition x{m,n}x\{m, n\}, write mm copies and then at most n−mn - m more. “At most kk more” is either nothing or one copy followed by at most k−1k - 1 more: tk::=x tk−1∣εt_k \mathrel{::=} x\ t_{k-1} \mid \varepsilon, with t0t_0 matching only the empty string. For x{1,3}x\{1,3\} that is

r::=x t2,t2::=x t1∣ε,t1::=x∣ε, r \mathrel{::=} x\ t_2, \qquad t_2 \mathrel{::=} x\ t_1 \mid \varepsilon, \qquad t_1 \mathrel{::=} x \mid \varepsilon ,

and parse_gbnf('root ::= "x"{1,3}') produces exactly these, under the names root-3, root-2 and root-1. The strings are xx (take ε\varepsilon in t2t_2), xxxx (xx then ε\varepsilon in t1t_1) and xxxxxx. ? is {0,1}\{0,1\}.

The nesting is not the only way to write “at most three”, but the obvious alternative, x? x? x?, is ambiguous: a single x can be the first, second or third optional one, and the recognizer below has to carry every such reading. On root ::= "x"? "x"? "x"? "y" it holds 4 partial parses at the start, then 3, 2 and 1 after each x; on root ::= "x"{0,3} "y" it holds 2, 2, 2 and 1 (computed on talos). llama.cpp’s grammars/README.md warns about exactly this (“the syntax x? x? x?.... x? (with N repetitions) may result in extremely slow sampling”) and recommends x{0,N}, which its parser desugars into the same nesting.

One restriction is essential. A rule is left-recursive if it can reach itself again without consuming a character: expr ::= expr "+" term | term rewrites expr into a sequence that starts with expr. A recognizer that works top-down, as this one does, expands the leftmost name first, and would expand expr into expr "+" term, then into expr "+" term "+" term, forever, without looking at the input. Such a grammar can always be rewritten. The language of expr above is a term followed by any number of "+" term, which is expr ::= term ( "+" term )*: the recursion moves to the right end, where it is harmless because something has been consumed before it is reached. (Aho, Lam, Sethi and Ullman give the transformation for a rule that refers to itself first in §2.4.5, and for left recursion through other rules in §4.3.3.) Grammar refuses a left-recursive grammar when it is built. It first computes which rules are nullable, able to derive the empty string, since A ::= B A is left-recursive if B can be empty. Then it collects, for each rule, the rules that can come first in it, skipping past nullable ones, and follows those links from each rule looking for the rule itself. llama.cpp’s llama_grammar_init_impl refuses the same grammars with “unsupported grammar, left recursion detected” (src/llama-grammar.cpp:1162-1173).

Recognition with a set of stacks

A grammar describes a language; a decoder needs to know, after each prefix, whether the prefix can still be completed and in which ways. The machine for that is a pushdown automaton, and since a grammar can be ambiguous, it is nondeterministic. The recognizer simulates it on every branch at once, holding the set of stacks all branches could be in.

Grammar flattens the rules. alts[a] is one alternative’s elements, and by_rule[name] lists the indices of that rule’s alternatives. A frame (a,i)(a, i) says “inside alternative aa, element ii comes next”. A stack is a tuple of frames, top last; the frames below the top are the places each enclosing rule will resume once the rule above it finishes. A state is a set of stacks.

Two operations maintain it.

expand(stack) rewrites a stack until a character element is on top. If the top frame is finished (ii is past the end of its alternative), it is popped. If its next element is a character class, the stack is ready. If its next element is a reference to rule BB, the frame is advanced past the reference, and for each alternative bb of BB a new stack is formed with (b,0)(b, 0) pushed on top, and each is expanded in turn. One detail keeps stacks short: if the reference was the last element of its alternative, the advanced frame would be finished, with nothing left to do but be popped, so it is not kept at all. The empty stack () is a stack with nothing left to match: the input may end there.

advance(stacks, cp) consumes one code point. It keeps each stack whose top element accepts cp, advances that frame by one, and expands the result. The new state is the union. accepts(stacks) is true when () is among them.

Trace root ::= "(" root ")" | "x" on ((x)). The flattening has two alternatives: 0 is "(" root ")" and 1 is "x". The start state expands both of root’s alternatives, {((0,0)), ((1,0))}: one stack waits for (, the other for x. On (, only the first survives; its frame advances to (0,1), a reference to root that is not last, so the frame advances again to (0,2) (waiting for )) and each alternative of root is pushed above it:

start  {((0,0)), ((1,0))}
'('    {((0,2),(0,0)), ((0,2),(1,0))}
'('    {((0,2),(0,2),(0,0)), ((0,2),(0,2),(1,0))}
'x'    {((0,2),(0,2))}
')'    {((0,2))}
')'    {()}                     accepts

(printed by a script on talos). The stack depth is the nesting depth: that is the pushdown part, and no finite automaton could track it.

Now root ::= "a"* "b", which parse_gbnf turns into root ::= root-2 "b", root-2 ::= root-1 and root-1 ::= "a" root-1 | ε, flattened as alternatives 0 ("a" root-1), 1 (empty), 2 (root-1) and 3 (root-2 "b"). The start state is {((3,1)), ((3,1),(0,0))}: the first stack has already taken the empty alternative and waits for b; the second waits for a inside the repetition. After an a, frame (0,0) advances to (0,1), the reference to root-1, which is the last element of alternative 0, so the frame is dropped rather than kept under the new root-1 frames. The state after a, aa or any number of them is the same two stacks. Without the rule about last references, every a would leave a finished (0,2) frame behind and the stack would grow with the input; with it, a repetition runs in constant stack depth, which is tail-call elimination.

Why is this right? Let rest(σ)\mathrm{rest}(\sigma) be what a stack σ\sigma still has to match: the remaining elements of its top frame, then those of the frame below, down to the bottom. For a frame (a,i)(a, i) the remaining elements are alts[a][i:], and for a stack ((a1,i1),…,(ak,ik))((a_1, i_1), \ldots, (a_k, i_k)), top last,

rest(σ)=alts[ak][ik:] alts[ak−1][ik−1:]⋯alts[a1][i1:], \mathrm{rest}(\sigma) = \texttt{alts}[a_k][i_k{:}]\ \texttt{alts}[a_{k-1}][i_{k-1}{:}] \cdots \texttt{alts}[a_1][i_1{:}] ,

a sequence of elements, read left to right. Write α⇒∗v\alpha \Rightarrow^* v when the sequence α\alpha derives the terminal string vv. Let S(w)S(w) be the state after the prefix ww. The claim is: for every prefix ww and every string vv,

wv∈L(G)⇔some σ∈S(w) has rest(σ)⇒∗v. w v \in L(G) \;\Leftrightarrow\; \text{some } \sigma \in S(w) \text{ has } \mathrm{rest}(\sigma) \Rightarrow^* v .

The proof uses a lemma about expand: for every stack σ\sigma and string vv, rest(σ)⇒∗v\mathrm{rest}(\sigma) \Rightarrow^* v holds if and only if some τ\tau in expand(σ) has rest(τ)⇒∗v\mathrm{rest}(\tau) \Rightarrow^* v. Each case of expand preserves the claim. Popping a finished frame removes nothing from rest\mathrm{rest}, since a finished frame contributes no elements; the same holds for not keeping a frame whose only remaining element was the reference being expanded. Expanding a reference to BB at the front of rest(σ)=Bβ\mathrm{rest}(\sigma) = B\beta gives one stack per alternative bb, with rest αbβ\alpha_b \beta. Any derivation of vv from BβB\beta can be reordered to rewrite the leftmost name first (the order of rewrites in a context-free derivation does not matter), and its first step then picks some alternative, so Bβ⇒∗vB\beta \Rightarrow^* v exactly when some αbβ⇒∗v\alpha_b \beta \Rightarrow^* v. The recursion is finite because the grammar has no left recursion: every chain of expansions either pops a frame or reaches a character element before a rule can recur, so the lemma follows by induction on the depth of the recursion.

Now the claim, by induction on the length of ww. For ww empty, S(ε)S(\varepsilon) is the expansion of the one-frame stacks ((a,0))((a, 0)) for root’s alternatives aa, whose rests are the alternatives themselves. v∈L(G)v \in L(G) means root⇒∗v\texttt{root} \Rightarrow^* v, which means some alternative derives vv, and by the lemma that holds exactly when some stack in S(ε)S(\varepsilon) has a rest that derives vv.

For the step, suppose the claim holds for ww, and consider wcwc for a code point cc. Apply the hypothesis to the string cvcv: wcv∈L(G)wcv \in L(G) exactly when some σ∈S(w)\sigma \in S(w) has rest(σ)⇒∗cv\mathrm{rest}(\sigma) \Rightarrow^* cv. Every stack in S(w)S(w) came out of expand, so it is either (), whose rest is empty and derives only the empty string, never cvcv, or its top element is a character class ee, with rest(σ)=erest(σ′)\mathrm{rest}(\sigma) = e\,\mathrm{rest}(\sigma') where σ′\sigma' is σ\sigma with its top frame advanced by one. A class derives exactly one character, so erest(σ′)⇒∗cve\,\mathrm{rest}(\sigma') \Rightarrow^* cv holds exactly when ee accepts cc and rest(σ′)⇒∗v\mathrm{rest}(\sigma') \Rightarrow^* v. By the lemma, that holds exactly when some τ\tau in expand(σ') has rest(τ)⇒∗v\mathrm{rest}(\tau) \Rightarrow^* v, and advance puts precisely those τ\tau into S(wc)S(wc). So wcv∈L(G)wcv \in L(G) exactly when some τ∈S(wc)\tau \in S(wc) has rest(τ)⇒∗v\mathrm{rest}(\tau) \Rightarrow^* v, which is the claim for wcwc.

Two consequences are what a decoder uses. Taking vv empty: w∈L(G)w \in L(G) exactly when some stack in S(w)S(w) has a rest that derives the empty string, and since every non-empty stack has a character class in front, which cannot derive the empty string, that stack must be (). So accepts is membership. And if every rule derives at least one string (the next section makes Grammar check this), every rest derives some vv, so S(w)S(w) is non-empty exactly when ww is a prefix of some string of the language. That is why GBNF works: the state after a prefix is empty exactly when the prefix is dead.

llama.cpp’s recognizer is the same machine. Its stacks are vectors of pointers to grammar elements rather than frames, and llama_grammar_advance_stack (src/llama-grammar.cpp:860-942) expands them, with the same rule for last references: “if this rule ref is followed by another element, add that to stack” (:903-906), and otherwise not. llama_grammar_accept (:1050-1058) is advance.

The cost of a step is proportional to the number of stacks, which is bounded by how many ways the grammar can parse the prefix. JSON is nearly deterministic, and its states stay small; the x? x? x? example above is the kind of grammar that makes them grow. advance memoises its result on the pair (state, code point), so a state met again (the inside of a long string, for instance) costs a dictionary lookup. The memo is bounded at 65,536 entries and cleared when full, as chapter 7’s encoding cache is, because a server sees unbounded text.

Productive rules, and why the mask is never empty

A rule that derives no finite string is a trap. root ::= "a" root accepts a, aa and so on as prefixes, but no string ever completes: every derivation of root contains root again. A decoder following such a grammar can extend a prefix forever and never be allowed to stop. Grammar finds these rules by computing, for each rule, the fewest bytes it can generate.

Let m(A)m(A) be the length in UTF-8 bytes of the shortest string rule AA derives, +∞+\infty if it derives none. A character class costs the UTF-8 length of the smallest character it accepts, where a character means a Unicode scalar value, a code point UTF-8 can encode: not a surrogate (U+D800 to U+DFFF) and not past U+10FFFF (_min_char_bytes: for a plain class, the smallest range start that is a scalar, or U+E000 when a range starts among the surrogates and reaches it; for a negated class, the smallest scalar outside all its ranges). A class that accepts no scalar, such as the empty range [z-a], [\uD800] or [\U00110000], costs +∞+\infty: no text can ever match it. A reference costs the mm of its rule. An alternative costs the sum of its elements, and a rule its cheapest alternative:

m(A)=minα∈R(A)∑X∈αm(X), m(A) = \min_{\alpha \in R(A)} \sum_{X \in \alpha} m(X) ,

where R(A)R(A) is the set of AA’s alternatives. The equation refers to mm on both sides, and _min_rule_bytes solves it by iteration: start every rule at +∞+\infty, and repeatedly recompute each rule’s value from the current values, keeping it when it is smaller, until a full pass changes nothing.

It stops. A value never increases, because each is replaced only by something smaller. A value that is finite is a sum of finitely many element costs, each a positive integer from 1 to 4 or a finite rule value, so it is a non-negative integer; a non-increasing sequence of non-negative integers changes only finitely often, and a value can go from +∞+\infty to finite only once. So after finitely many passes nothing changes.

It stops at the right values. Every finite value it assigns is the length of some string the rule derives: by induction on the updates, the value is a sum of element costs, each of which is the length of some string that element derives. So no value falls below the true mm. Conversely, if AA’s shortest string has a derivation tree of height hh, then after hh passes AA’s value is at most that length: by induction on hh, the children in the tree have trees of smaller height, so their values are already at most their strings’ lengths when the pass that updates AA reads them. So the iteration ends at the true mm, and m(A)=+∞m(A) = +\infty exactly when AA derives no string. Grammar refuses any such rule: parse_gbnf('root ::= "a" root') raises rules ['root'] generate no string. It refuses a class that accepts no character first, wherever it appears, even in one alternative of a rule whose other alternatives are fine: root ::= "a" [z-a] | "b" has m=1m = 1, but after a its only stack waits for a character that cannot come. So in a grammar Grammar accepts, every element of every alternative can generate some string.

With every rule productive, the mask of a live state is never empty, provided the vocabulary can spell every byte. The lab’s tokenizer is a byte-level BPE whose 384 ordinary tokens include all 256 single bytes (checked by a script). Suppose the state after the text so far is non-empty, and build a byte string cc that completes the text to a string of the language. With nothing pending, pick any stack: its rest derives some string vv, because every element in it can generate one (the previous paragraph), and cc is vv’s UTF-8 bytes. With bytes pending, pick a stack that advance_bytes kept: it was kept because its top class accepts some character whose encoding begins with the pending bytes (the interval it checks is intersected with the scalar values), so cc is that code point’s missing bytes, followed by the bytes of some string that the rest of the stack below its top element derives. In both cases the text followed by cc is in the language. If cc is empty, the state accepts with nothing pending, and the end token is allowed. Otherwise the first byte of cc is itself a token, and appending it leaves a prefix of a string of the language, so the state after it is not empty. Either way at least one token is allowed.

So chapter 12’s all-−∞-\infty row, the one sample_token refuses with “no token left to sample”, cannot come from a correct mask over this vocabulary. It can still come from a bug in a constraint, from another filter whose allowed set does not intersect the mask’s, or from a vocabulary without single-byte tokens, in which some characters cannot be spelled at all. What should a server do then? There are three candidates. It could end the reply there, but then it returns text that does not parse, labelled as a complete reply, which is exactly the failure constrained decoding exists to remove. It could backtrack, unsampling tokens until some other choice survives: that is machinery for a case the argument above excludes, and it changes the distribution being sampled in ways that are hard to state. Or it can fail the request. This server fails it: the ValueError from sample_token becomes a 500 with type: "server_error" before any header is sent, and mid-stream an error event with no [DONE] after it, which chapter 17 showed a client must read as incomplete. test_no_surviving_token_is_an_error_to_the_client pins both. llama-server makes the same choice. llama_grammar_accept_token throws “Unexpected empty grammar stack after accepting piece” when no stack survives a token (src/llama-grammar.cpp:1526-1528); the server’s iterate catches the exception around each slot’s sampling and sends an error of type ERROR_TYPE_SERVER (tools/server/server-context.cpp:2711-2720), which becomes a 500 with server_error (tools/server/server-common.cpp:52-55).

Tokens are bytes; the grammar is characters

Chapter 7’s tokens are byte strings, and chapter 17 derived what that does to a stream: a token can end in the middle of a character. A grammar over code points has to decide, for a token that ends that way, whether its partial character could still be one the grammar accepts.

Chapter 17’s table gives the answer. A lead byte announces a length of nn bytes and carries 7−n7 - n payload bits (for n≥2n \ge 2: the lead is nn one bits, a zero, then the payload); each continuation byte carries 6. Suppose kk of the nn bytes have arrived, 1≤k<n1 \le k < n, and let vv be the payload bits seen so far, read as a binary number. The n−kn - k bytes still to come carry r=6(n−k)r = 6(n - k) more bits, appended below vv. The finished code point is v⋅2r+xv \cdot 2^r + x for some rr-bit number xx, and xx ranges over 00 to 2r−12^r - 1, so the code points the partial sequence can still become are the interval

[v⋅2r, v⋅2r+2r−1], \left[\, v \cdot 2^r,\ v \cdot 2^r + 2^r - 1 \,\right] ,

intersected with the code points UTF-8 allows at nn bytes: [0x80,0x7FF][\texttt{0x80}, \texttt{0x7FF}] for n=2n = 2, [0x800,0xFFFF][\texttt{0x800}, \texttt{0xFFFF}] without the surrogates [0xD800,0xDFFF][\texttt{0xD800}, \texttt{0xDFFF}] for n=3n = 3, and [0x10000,0x10FFFF][\texttt{0x10000}, \texttt{0x10FFFF}] for n=4n = 4. The lower bounds exclude overlong encodings, and the surrogates are the UTF-16 halves that are not characters. That is _VALID.

Take é, U+00E9, bytes C3 A9, and suppose a token ends after C3. C3 is 110 00011: n=2n = 2, k=1k = 1, v=000112=3v = \texttt{00011}_2 = 3, r=6r = 6. The interval is [3⋅64,3⋅64+63]=[192,255][3 \cdot 64, 3 \cdot 64 + 63] = [192, 255], U+00C0 to U+00FF, all valid two-byte code points. Against [a-z] (U+0061 to U+007A) the intersection is empty, so a token ending in C3 is cut. Against [^a] some code point in the interval is outside a, so it survives. Now ED A0: ED is 1110 1101, n=3n = 3 with payload 110121101_2; A0 is 10 100000, payload 1000002100000_2; k=2k = 2, v=11011000002=0x360v = 1101\,100000_2 = \texttt{0x360}, r=6r = 6, and the interval is [0xD800,0xD83F][\texttt{0xD800}, \texttt{0xD83F}], entirely surrogates. It intersects nothing, so ED A0 cannot begin any character, whatever the grammar says, and advance_bytes rejects it even against .. So does E0 80, whose interval [0,0x3F][0, \texttt{0x3F}] lies below 0x800\texttt{0x800}: it could only begin an overlong encoding.

So a token is allowed if all its bytes can be consumed. advance_bytes feeds them one at a time. A byte that completes a character hands the code point to advance. A byte that leaves a character unfinished keeps only the stacks whose top class accepts some code point in that character’s interval, and the state carries the unfinished bytes as pending. The filtering is not only an optimisation: a stack whose top cannot accept any completion is already dead, and leaving it in the state would make the shortest-completion count of the budget section below count a parse that cannot happen, so that a budget admits a token it cannot pay for. test_every_budget_from_the_least_up_completes catches that mistake.

llama.cpp computes the same interval in llama_grammar_match_partial_char (src/llama-grammar.cpp:795-841): low = partial_value << (n_remain * 6) and high = low | ((1 << (n_remain * 6)) - 1), raising low when the payload so far is zero (the overlong case). It does not remove the surrogates, so against a class that includes them, as . does, it would let ED A0 through where _VALID does not.

The mask and the trie

The mask for a state ss is a vector of shape (V,), added to the logits before sampling. For an ordinary token tt it is 0 if feeding tt’s bytes to ss leaves a non-empty state and −∞-\infty otherwise. For the end token it is 0 exactly when ss accepts with nothing pending. Every other marker is −∞-\infty: a marker is never text. What the mask does to one step’s distribution chapter 17 already derived: the allowed tokens keep their relative probabilities, renormalised by the probability ZZ of the allowed set.

Computing it token by token costs VV runs of advance_bytes, each as long as its token. But tokens share prefixes: n, ni, no, not and ns all begin with n, and whether n keeps the parse alive is decided once. TokenTrie stores every ordinary token’s bytes in a trie, a node per distinct prefix, with the ids of the tokens that end at each node. allowed_tokens walks it depth first from the root, advancing the state by one byte per edge, and abandons a subtree the moment the state dies: no token below a dead prefix can be allowed. The work is the number of edges tried, one per live prefix and one per child of each live prefix. For the lab’s vocabulary the trie has 484 nodes, against 714 bytes in all 384 tokens. Under the JSON grammar, at four states measured on talos, the walk tries from 264 edges (after [tru, where one token survives) to 483 (inside a string after {"a, where 274 do), and takes 0.19 to 0.82 ms per mask. At 384 tokens the trie saves little; the saving grows with the vocabulary, since one dead prefix removes every token below it in one step. llama.cpp gets the same sharing without a trie: llama_grammar_reject_candidates_for_stack (src/llama-grammar.cpp:1061-1130) advances all candidate tokens by their first code point together, and recurses with the survivors on the next.

The figure shows one step of the lab’s grammar, an object whose one property subject is one of six nouns, after the text {"subject":"pri. The logits are the served model’s, on talos, with that text appended to the prompt the lab uses.

One decoding step under a grammar: the parse state, the token trie walked from it, and the mask it yields The grammar is the one for an object with a subject drawn from six nouns, and the text so far is {"subject":"pri. Top left, the parse state: one stack of two frames, top first. The top frame is inside the literal "prince" at position 4, whose next character is n; below it, the object rule at position 7, whose next element is the optional space before the closing brace. Top right, a fragment of the served model's token trie walked from that state. The edge from the root to n is kept, because the top frame accepts n. The edges from n on to i, o and s are cut, because after n the top frame wants c. The edge to v is cut, because no stack's top accepts v. The edge to the byte e2 is cut although e2 is only part of a character: e2 can only begin a code point from U+2000 to U+2FFF, and no top accepts one. Bottom, the mask as a table of six tokens with the served model's logits on talos: rd 11.27, end 8.59, quote-brace 5.88, n 1.32, ni minus 0.35, v minus 0.74. The mask is 0 for n and minus infinity for the others. The model's probabilities are 0.924, 0.063, 0.0042, 0.000044, 0.000008 and 0.000006; after the mask, n has probability 1 and the others 0. Parse state Token trie "prince" · 4 next: n r2 · 7 next: space "}" One stack, top frame above, after the text {"subject":"pri root kept n v e2 i o s cut: after n, the top wants c cut: no top accepts v cut: e2 begins U+2000–U+2FFF, and no top accepts those Token Logit Mask Before mask After mask rd <|end|> "} ni v 11.27 8.59 5.88 −0.35 −0.74 −∞ −∞ −∞ −∞ −∞ 0.924 0.063 0.0042 0.000008 0.000006 0 0 0 0 0 n 1.32 0 0.000044 1 The served model on talos; the mask removes 0.99996 of its probability.

The model’s favourite, rd, with probability 0.924, would make prird. The mask leaves only n, whose probability was 0.000044, and renormalisation makes it certain. That is the mechanism doing its job, and also the first sign of the cost measured under tokenization boundaries below: here the constraint and the model disagree about almost everything.

What a mask does to the distribution

Chapter 17 showed that one masked step samples from p(t∣t∈A)p(t \mid t \in A). Over a whole sequence the steps multiply. Write x=(x1,…,xT)x = (x_1, \ldots, x_T) for a complete output (its last token the end marker), AtA_t for the allowed set at step tt, which depends on x<tx_{<t}, and

Zt=∑u∈Atp(u∣x<t) Z_t = \sum_{u \in A_t} p(u \mid x_{<t})

for the probability the model puts on it. Each step samples xtx_t with probability p(xt∣x<t)/Ztp(x_t \mid x_{<t}) / Z_t, so the masked sampler produces xx with probability

q(x)=∏t=1Tp(xt∣x<t)Zt=p(x)∏t=1TZt, q(x) = \prod_{t=1}^{T} \frac{p(x_t \mid x_{<t})}{Z_t} = \frac{p(x)}{\prod_{t=1}^{T} Z_t} ,

using p(x)=∏tp(xt∣x<t)p(x) = \prod_t p(x_t \mid x_{<t}), the chain rule of probability that the model’s factorisation rests on. Compare that with what one might want: the model’s distribution conditioned on the output being in the language,

p(x∣x∈L)=p(x)p(L),p(L)=∑y∈Lp(y). p(x \mid x \in L) = \frac{p(x)}{p(L)}, \qquad p(L) = \sum_{y \in L} p(y) .

Both are p(x)p(x) divided by something, but qq divides by a product that depends on xx’s path, and the conditional divides by one constant. They agree for every xx only if ∏tZt\prod_t Z_t takes the same value along every path, and in general it does not.

A two-step example makes the difference concrete. Let the language be {ab,ba}\{ab, ba\} over the tokens a and b (each followed by the end marker, which the model always emits after two tokens). The model puts 0.9 on a first and 0.1 on b. After a it strongly prefers another a (0.99), which the grammar forbids, over b (0.01); after b it prefers a (0.9) over b (0.1). Both first tokens are allowed, so Z1=1Z_1 = 1 and the masked sampler picks a with probability 0.9. After a, only b is allowed: Z2=0.01Z_2 = 0.01, and b gets probability 0.01/0.01=10.01 / 0.01 = 1. After b, only a: Z2=0.9Z_2 = 0.9, and a gets 1. So q(ab)=0.9q(ab) = 0.9 and q(ba)=0.1q(ba) = 0.1. The conditional is different: p(ab)=0.9×0.01=0.009p(ab) = 0.9 \times 0.01 = 0.009, p(ba)=0.1×0.9=0.09p(ba) = 0.1 \times 0.9 = 0.09, p(L)=0.099p(L) = 0.099, so p(ab∣L)=0.009/0.099=1/11≈0.091p(ab \mid L) = 0.009 / 0.099 = 1/11 \approx 0.091 and p(ba∣L)=10/11≈0.909p(ba \mid L) = 10/11 \approx 0.909. The masked sampler produces ab almost ten times as often as the model, conditioned on the language, would (0.9/(1/11)=9.90.9 / (1/11) = 9.9); it commits at the first step to the branch the model liked there, and the model’s low opinion of how that branch continues never gets a say. The same grammar through GrammarConstraint, with this table as the model, sampled 20,000 times from seed 0 on talos: ab 0.89895, ba 0.10105.

Kanghee Park, Jiayu Wang, Taylor Berg-Kirkpatrick, Nadia Polikarpova and Loris D’Antoni name the problem of sampling the conditional grammar-aligned decoding (“Grammar-Aligned Decoding”, NeurIPS 2024), and show that grammar-constrained decoding distorts the model’s distribution in just this way: its outputs are grammatical but appear with probabilities that are not proportional to the model’s. Sampling the conditional exactly needs, at each step, the probability that each continuation can still be completed within the language, which is a sum over all completions; exercise (c) derives the per-step distribution that would do it.

llama.cpp orders the work differently, and the order is worth checking. common_sampler_sample (common/sampling.cpp:594-676) runs the sampler chain on the unmasked logits first and samples a token; then it checks that one token against the grammar (:646-657); only if it fails does it recompute the logits, apply the grammar to all of them, and sample again (:659-676). The check costs one token’s worth of grammar work, where a full mask costs a walk over the vocabulary, and the first draw usually passes. Does it sample the masked distribution? Take a chain that samples straight from pp, and let AA be the allowed set with probability ZZ. A token t∈At \in A is returned either because the first draw was tt, probability p(t)p(t), or because the first draw failed, probability 1−Z1 - Z, and the masked second draw was tt, probability p(t)/Zp(t)/Z:

P(t)=p(t)+(1−Z)p(t)Z=p(t)Z+1−ZZ=p(t)Z, P(t) = p(t) + (1 - Z)\,\frac{p(t)}{Z} = p(t)\,\frac{Z + 1 - Z}{Z} = \frac{p(t)}{Z} ,

and a token outside AA is never returned. That is the masked distribution exactly. A temperature changes nothing in the argument, since it replaces pp by a tempered pTp_T in both draws. Exercise (d) takes up the filters for which it fails.

Where it fails: tokenization boundaries

A mask decides which byte strings may be written. The model decides which tokens to write them with, and it learned that from training text encoded one way, the BPE’s canonical encoding. Chapter 7’s encode turns {"subject":"prince"} into {", subject, ":, ", prince, "}, and a model trained on that text would have seen only that sequence. The mask allows any sequence of tokens whose bytes spell a prefix of the language: s, u, b, j, e, c, t is as allowed as subject. A model on its own distribution rarely wanders there. A model pushed off it by the mask has no learned preferences among such sequences, because it never saw them, and its probabilities for them are whatever the network extrapolates.

The lab measures this on the served model of chapter 17, which was trained to answer subject of: the prince summons a king . with the bare word prince. Constrained to {"subject": <noun>} with greedy decoding over 40 such questions on talos, every reply parses, and 26 of 40 name the right subject, where the same model unconstrained answers all 40 correctly in its own format. Only 12 of the 40 constrained replies are the canonical tokenization of their own text. One spells subject a byte at a time; another ends with " and } as two tokens where the canonical encoding has "} as one. At an average step the mask removed 91.2% of the model’s probability, and at the first step all of it (1.000 to three decimals): unconstrained, the model’s reply is the bare noun, and it puts essentially no probability on a reply that opens with {.

Each number follows from the mechanism. Renormalisation keeps the relative probabilities of what is allowed, and when 91% of the mass is gone, what is left is the part of the distribution the model is least sure of. The first step’s choice is made from the tail of a distribution that put essentially everything elsewhere, and the rest of the reply is conditioned on that choice, as in the two-step example. Content suffers first: the model would have named the subject in its own format, and here it has to name it through a format it never saw.

A second failure sits at the end of the language. A token whose bytes run past the last byte the grammar accepts is cut, even if the model’s most likely continuation is exactly that token: a model that learned to end an object with } and a newline, where the vocabulary has one token for both, cannot write it, and the end token wins by elimination if it is the only other choice. The lab’s vocabulary has no such token (its only tokens containing } are } and "}), but a production vocabulary with merged whitespace does.

Form is guaranteed and content is not, which is the whole contract of constrained decoding: a harness that relies on it still has to check content, which is what chapter 37’s evals are for.

Budgets: forcing, as the reasoning budget does

max_tokens and the context bound every reply. Unconstrained, a reply that reaches the bound is cut and marked finish_reason: "length". A constrained reply cut in the middle is exactly the malformed output the grammar was supposed to prevent. So GrammarConstraint takes a budget BB, the number of tokens generation may still take, the end token included, and uses it to force completion. A client’s stop string would cut the output in the same way, so constraint_for answers 400 to a request that combines stop with response_format or tools; llama-server accepts the combination and erases the constrained text from the first stop string on, as for any other reply (tools/server/server-context.cpp:1835-1839).

The first ingredient is the shortest completion of a state. For an alternative aa, let suffix[a][i] be the fewest bytes its elements from ii on can generate. Since the elements are generated one after another, and each independently of the others, the minimum of the sum is the sum of the minima:

suffix[a][i]=∑j≥im(alts[a][j])=m(alts[a][i])+suffix[a][i+1],suffix[a][∣alts[a]∣]=0, \texttt{suffix}[a][i] = \sum_{j \ge i} m(\texttt{alts}[a][j]) = m(\texttt{alts}[a][i]) + \texttt{suffix}[a][i+1], \qquad \texttt{suffix}[a][\,|\texttt{alts}[a]|\,] = 0 ,

which _suffix fills from the right. A stack’s rest is its frames’ suffixes one after another, so the fewest bytes that finish it are the sum of suffix[a][i] over its frames, and the fewest bytes that finish a state are the minimum over its stacks:

min_bytes(S)=minσ∈S∑(a,i)∈σsuffix[a][i], \texttt{min\_bytes}(S) = \min_{\sigma \in S} \sum_{(a, i) \in \sigma} \texttt{suffix}[a][i] ,

which is 0 exactly when some stack is empty (the state accepts) and +∞+\infty for the empty state. With a character pending, _state_min_bytes counts the bytes that character still needs and then the rest of each surviving stack after its top element.

The rule: with BB tokens left, an ordinary token is allowed only if, after it, the state can be finished in at most B−2B - 2 bytes, two tokens being spent on this token and on the end. The count is in bytes because every byte is a token, so a completion of bb bytes can always be written in bb tokens. That is a conservative bound, since multi-byte tokens could do it in fewer. The end token is allowed, as before, whenever the state accepts. The claim: if the budget is at least the constraint’s least, the shortest completion of the start state plus one for the end, generation always ends with the end token within the budget.

The proof is by induction on the tokens left, with the invariant: whenever B≥1B \ge 1 tokens are left, min_bytes(S)≤B−1\texttt{min\_bytes}(S) \le B - 1. At the start it is the condition on the budget. Suppose it holds at some step. If min_bytes(S)=0\texttt{min\_bytes}(S) = 0, the state accepts and the end token is allowed; and if B=1B = 1, no ordinary token is allowed (it would need its completion to fit in −1-1 bytes), so the end token is the only choice and generation ends. If min_bytes(S)=m≥1\texttt{min\_bytes}(S) = m \ge 1, then B−1≥m≥1B - 1 \ge m \ge 1. The first byte of a shortest completion is a token, and after it the rest of that completion, m−1≤B−2m - 1 \le B - 2 bytes, still finishes the state, so that token is allowed and the mask is not empty. Whatever allowed token is sampled leaves a state that can be finished in at most B−2=(B−1)−1B - 2 = (B - 1) - 1 bytes, which is the invariant with B−1B - 1 tokens left. BB drops by one each step, and at B=1B = 1 the invariant says the state accepts and only the end token remains, so generation ends with the end token no later than the last token of the budget.

The lab’s PERSON schema has least 20: its shortest text, {"name":"","age":0}, is 19 bytes, plus the end token. test_a_budget_forces_the_shortest_completion gives it exactly 20 tokens and a random model at temperature 1, and every sample ends with the end token and validates; with 19 the constraint refuses to be built. A request whose budget is below least is a 400 naming the budget, where the alternative would be to accept it and fail on every run. test_every_budget_from_the_least_up_completes runs each of the seven test schemas at every budget from least to least + 4.

This is chapter 13’s reasoning budget generalised. That sampler is a small state machine (common_reasoning_budget_accept, common/reasoning-budget.cpp:74-164): idle until a start sequence appears, then counting tokens, then, once the count runs out, forcing the end sequence by allowing exactly one token at a time, then done. It has one more state, REASONING_BUDGET_WAITING_UTF8, entered when the count runs out on a token that ends inside a character, which delays the forcing until the character is complete: this chapter’s partial-character problem, met from the other side. Here the state is a grammar’s stack set, the allowed set is whatever keeps it alive and finishable, and the transition is advance_bytes. Any constraint of this kind is a state, an allowed set and a transition, and exercise (f) writes the reasoning budget in that form. llama-server does not budget grammar output: at n_predict a slot stops with STOP_TYPE_LIMIT whatever the grammar’s state (tools/server/server-context.cpp:1876-1882), and the reply’s finish_reason is "length", its JSON unfinished.

JSON Schema to grammar

A JSON Schema describes a set of JSON values, its instances. schema_to_gbnf compiles a schema into a grammar whose language is a set of JSON texts, and the one property it must have is soundness: every text the grammar accepts is an instance of the schema. Soundness is what makes constrained output validate, and it has a direction. The grammar may accept fewer texts than the schema allows, since generating from a subset still produces instances; it may never accept more. So a compiler can ignore any keyword that only widens the set or only annotates it, and must refuse any restriction it cannot express, because ignoring a restriction means generating texts the schema rejects.

The subset this compiler understands is type (one or a list), properties and required, items, minItems and maxItems, enum, const, anyOf, minLength and maxLength. title, description, default, examples, $schema and $comment are annotations and are ignored. additionalProperties is ignored only where the compiler builds an object from its properties: whatever it says, such an object never holds a property that is not listed, which is a subset of what any value of it allows. Everywhere else it would widen the output if ignored, so it counts as a restriction: in a schema with no type ({"additionalProperties": false} alone must not become “any value”, which includes {"a": 1}), and beside const, enum or anyOf, whose values or branches may be objects with other properties. Both are a 400. Every other keyword raises a ValueError that names it, and the server turns that into a 400. pattern, format and minimum are restrictions this compiler does not implement, $ref is a reference it does not resolve, and allOf is an intersection it does not compute. oneOf is refused for a reason of its own: it means “valid against exactly one of these” (JSON Schema Core, §10.2.1.3), and a grammar can say “one of these” but not “not also another”, so compiling it as anyOf would accept texts that match two branches, which the schema rejects.

Each type compiles as follows, with space the optional single space between tokens:

  • string: "\"" char* "\"", where char is any character except ", \ and the control characters below U+0020, or an escape other than a \u escape of a surrogate (see below).
  • integer and number: RFC 8259’s number syntax, the integer part limited to 16 digits.
  • boolean and null: their literals.
  • {}, true, and a schema of annotations alone (title, description, default, examples, $schema, $comment; ANNOTATIONS): any JSON value, by a fixed set of rules (ANY_RULES, the same shape as JSON_GBNF) added to the grammar once. An array without items is an array of any values.
  • enum and const: the literals of the compact JSON texts of the allowed values, as alternatives. A sibling type filters them: {"type": "string", "enum": ["a", 1]} compiles to "a" alone. Any other restricting keyword beside them, a maxLength say, is a 400 naming the combination, since checking each literal against every keyword would mean a validator inside the compiler; the pair is easy to rewrite as an enum of the values that satisfy it.
  • anyOf and a list of types: alternatives. anyOf takes no restricting sibling at all, for the same reason as oneOf below: a grammar can offer the branches but not intersect each with the siblings.
  • An empty enum, anyOf or type list, or an enum that the type filter empties, admits no value, and is a 400 rather than a grammar that matches nothing, or the empty string.
  • array: an opening bracket, then the items separated by commas, then the closing bracket. With bounds mm = minItems and nn = maxItems, the items are item space ( "," space item space ){m-1,n-1}: one item, then between m−1m - 1 and n−1n - 1 more, which is mm to nn in all. If m=0m = 0 the whole sequence is optional, which adds the empty array; if n=0n = 0 the array is "[" space "]".
  • string with minLength mm and maxLength nn: "\"" char{m,n} "\"".
  • object: the properties in the order the schema lists them, the required ones first and then the optional ones, and no others.

Objects are the interesting case, because JSON allows the properties in any order and a grammar that accepted every order would need a rule for every permutation. Fixing the order gives up texts the schema accepts, which soundness allows, and it matches what a model trained on schema-ordered JSON writes. With required properties r1,…,rkr_1, \ldots, r_k and optional ones o1,…,olo_1, \ldots, o_l, the body is the required key-value pairs separated by commas, followed by ( "," space o_j )? for each optional one in order. With no required properties the commas have nothing to attach to, and the rule is harder. The body is some ordered subset of o1,…,olo_1, \ldots, o_l, possibly empty. A non-empty ordered subset has a first element oio_i, after which each later ojo_j is present or not. So the body is

( o1(","o2)?⋯(","ol)? ∣ o2(","o3)?⋯(","ol)? ∣ ⋯ ∣ ol )?, \Big(\ o_1 \,(\text{","}\, o_2)^? \cdots (\text{","}\, o_l)^?\ \Big|\ o_2 \,(\text{","}\, o_3)^? \cdots (\text{","}\, o_l)^?\ \Big|\ \cdots\ \Big|\ o_l\ \Big)^? ,

one alternative per possible first element, and the whole optional for the empty object. Every ordered subset is produced exactly once, by the alternative for its first element, so the grammar is unambiguous; test_objects_put_required_properties_first_in_order checks {}, {"q":null} and {"p":null,"q":null} against a two-property schema, and that {"q":null,"p":null} is refused.

minLength needs one more restriction. JSON Schema counts a string’s length in characters of the decoded string (JSON Schema Validation, §6.3.2, by RFC 8259’s definition), and the grammar counts char elements of the JSON text, where an escape is one element. The two agree except for a character above U+FFFF written as an escaped surrogate pair, \ud83d\ude00: two elements, one character. With a plain \u followed by any four hex digits, {"type": "string", "minLength": 2} would accept "\ud83d\ude00", which decodes to a string of length 1. So STRING_CHAR spells out the hex digits of a \u escape so as to exclude D800 to DFFF: a first digit other than d, or d followed by 0 to 7. A character above U+FFFF can still be written, as itself in UTF-8, which is one element and one character; lone surrogates, which RFC 8259 leaves to the implementation, cannot be written at all. test_string_lengths_count_characters_not_escapes checks both spellings of U+1F600 under minLength: 2. JSON_GBNF, which has no lengths to count, keeps plain \u escapes.

The bounds themselves are the client’s, and parse_gbnf expands char{m,n} into nn helper rules, so an unchecked maxLength of a million would build a million rules. schema_to_gbnf checks each subschema’s own bounds as it reaches it (_check_bounds), where a key is known to be a keyword and not a property name or part of an enum value, and rejects any minLength, maxLength, minItems or maxItems that is not a non-negative integer or is larger than cap, the most characters or items a reply within the budget can hold, which constraint_for computes: the budget in tokens times the longest token in bytes, since every character and every item takes at least a byte. A larger bound could never be reached, and a 400 says so.

llama.cpp’s converter (common/json-schema-to-grammar.cpp and the schema reader in common/json-schema.cpp) makes the same structural choices and different policy ones. It orders properties the same way, required first (_build_object_rule, json-schema-to-grammar.cpp:699-794). It supports more: pattern for anchored regular expressions, format for dates, times and UUIDs, minimum and maximum for integers, $ref, allOf, tuples. Its additionalProperties defaults to false when properties are given (json-schema.cpp:155-169; grammars/README.md says so). Its whitespace rule is wider, a space or up to two newlines and twenty spaces or tabs (SPACE_RULE, json-schema-to-grammar.cpp:229). And where it cannot express a restriction, it widens. An unanchored pattern fails the converter’s check (:406-408) and is replaced by “any string”, with a warning printed to the server’s standard error and nothing sent to the client (_visit_pattern, :390-404, and check_errors, :975-982). oneOf is read as anyOf with no warning at all (json-schema.cpp:234-237). The README states the policy: “Unsupported features are skipped silently.” Both behaviours produce output that violates the schema the client sent, which is what this compiler’s 400 prevents; the lab captures one.

Tool calls at the source

A tool call is JSON too. With tools offered, constraint_for builds a call grammar from the schema

{"anyOf": [{"type": "object", "required": ["name", "arguments"],
            "properties": {"name": {"const": "lookup"}, "arguments": <lookup's parameters>}}, …]}

with one branch per tool, so the name selects the branch and the arguments must satisfy that tool’s parameters. ReplyConstraint puts it together with chapter 17’s template, where a call is <|call|> followed by the call’s JSON and <|end|>. At the first step it offers <|call|>, and under tool_choice: "auto" also whatever text is allowed; under "required" or a named tool (whose call grammar has only that tool’s branch), only <|call|>; under "none", only text. After <|call|> every token is masked by the call grammar with a budget one smaller, the marker having used a token. Under "auto", if the call grammar’s shortest output does not fit the budget, the call is not offered at all, rather than failing a request that can still be answered in text; under "required" that is a 400. test_constrained_tool_calls_always_parse runs a random model at temperature 1 under "required" ten times, and every reply is a call that reply_message, chapter 17’s decoder, accepts, with the argument word present. That is chapter 13’s promise kept: a malformed call cannot be sampled.

A server could now stream a constrained call as it is generated, since every prefix under the mask is a prefix of a valid call; this one still holds calls until <|end|>, as chapter 17 wrote it.

llama.cpp constrains tool calls with the same shape and one refinement. The model’s template decides where a call starts (a marker such as <tool_call>), and until then the model writes free text. Its grammars are lazy: they carry trigger patterns or tokens, and the grammar sampler does nothing until one appears in the output, after which it constrains the rest (common/sampling.cpp:220-270 builds the triggers; llama_grammar_apply_impl returns at once while awaiting_trigger is set, src/llama-grammar.cpp:1362-1364). ReplyConstraint under "auto" is a lazy grammar whose trigger is <|call|>, at the first position.

The server

constraint_for(engine, req) is the constrain hook chapter 17’s handler calls before the first token. It returns None when the request has neither response_format nor tools (with tool_choice other than "none"), so plain requests are unchanged. Otherwise it renders the prompt to find the budget: the smaller of max_tokens and the room left in the context, C−n+1C - n + 1 for a prompt of nn tokens, chapter 17’s bound. It compiles response_format into the text grammar, JSON_GBNF for json_object and the schema’s grammar for json_schema, the tools into the call grammar, and returns a ReplyConstraint. A schema outside the subset, an empty enum, a bound too large for the budget and a budget below the grammar’s shortest output are all ValueErrors, and all become a 400 naming the problem, before any header is sent; so does a stop string. A schema malformed in some other way (properties given as a list, say) raises a TypeError or its like inside the compiler, and is a 400 too; any other failure is a 500. Either way the client gets an OpenAI error object, never a dropped connection. json_object here means any JSON value, as JSON_GBNF defines it; llama-server, when the request gives no schema of its own, reads json_object as the schema {"type": "object"} (tools/server/server-common.cpp:1258-1277), objects only.

tinygpt.server’s main passes constraint_for, so the server of chapter 17’s lab now answers response_format, where it answered 400 before, and constrains every token of a tool call, where chapter 17’s masks constrained only the first.

Walkthrough

The reference module is py/tinygpt/grammar.py. First the grammar: the flattening, and the checks that make a grammar safe to decode with.

class Grammar:
    """A context-free grammar over code points: rules[name] is a list of alternatives, each a list of
    elements, ("chars", ((lo, hi), ...), negated) or ("ref", name). The start rule is "root".

    Flattened for the recognizer: alts[a] is one alternative's elements, and by_rule[name] the
    indices of that rule's alternatives. A parse state is a set of stacks; a stack is a tuple of
    (a, i) frames, "match alts[a][i] next", top last.
    """

    def __init__(self, rules):
        if "root" not in rules:
            raise ValueError("a grammar needs a root rule")
        self.alts, self.by_rule = [], {}
        for name, alternatives in rules.items():
            self.by_rule[name] = []
            for alt in alternatives:
                for el in alt:
                    if el[0] == "ref" and el[1] not in rules:
                        raise ValueError(f"rule {name} refers to undefined rule {el[1]}")
                self.by_rule[name].append(len(self.alts))
                self.alts.append(tuple(el if el[0] == "ref" else ("chars", tuple(el[1]), el[2]) for el in alt))
        self._check_left_recursion()
        empty = sorted({n for n, idx in self.by_rule.items() for a in idx
                        for el in self.alts[a] if el[0] == "chars" and _min_char_bytes(el) == float("inf")})
        if empty:
            raise ValueError(f"rules {empty} have a character class that accepts no character")
        self.min_rule = self._min_rule_bytes()
        bad = sorted(n for n, v in self.min_rule.items() if v == float("inf"))
        if bad:
            raise ValueError(f"rules {bad} generate no string")
        self.suffix = [self._suffix(alt) for alt in self.alts]     # suffix[a][i]: min bytes of alts[a][i:]
        self._memo = {}

    def _el_min(self, el, rule_min):
        return _min_char_bytes(el) if el[0] == "chars" else rule_min[el[1]]

    def _min_rule_bytes(self):
        """Fewest UTF-8 bytes each rule can generate, by fixed-point iteration; inf for a rule that
        generates no finite string (it can never be completed)."""
        best = {n: float("inf") for n in self.by_rule}
        changed = True
        while changed:
            changed = False
            for n, idx in self.by_rule.items():
                v = min(sum(self._el_min(el, best) for el in self.alts[a]) for a in idx) if idx else float("inf")
                if v < best[n]:
                    best[n], changed = v, True
        return best

    def _suffix(self, alt):
        out = [0] * (len(alt) + 1)
        for i in range(len(alt) - 1, -1, -1):
            out[i] = out[i + 1] + self._el_min(alt[i], self.min_rule)
        return out

    def _check_left_recursion(self):
        """A rule that can reach itself without consuming a character would expand forever."""
        nullable = set()
        changed = True
        while changed:
            changed = False
            for n, idx in self.by_rule.items():
                if n not in nullable and any(all(el[0] == "ref" and el[1] in nullable for el in self.alts[a])
                                             for a in idx):
                    nullable.add(n)
                    changed = True
        first = {n: set() for n in self.by_rule}          # rules that can come first in n
        for n, idx in self.by_rule.items():
            for a in idx:
                for el in self.alts[a]:
                    if el[0] != "ref":
                        break
                    first[n].add(el[1])
                    if el[1] not in nullable:
                        break
        for n in self.by_rule:
            seen, todo = set(), list(first[n])
            while todo:
                m = todo.pop()
                if m == n:
                    raise ValueError(f"rule {n} is left-recursive")
                if m not in seen:
                    seen.add(m)
                    todo += first[m]

Every element passes through the constructor once, so a reference to a rule that does not exist is caught here, not in the middle of a generation. The class element’s ranges become a tuple so that alternatives are hashable. The constructor refuses a class that accepts no character before it computes anything else, naming every rule that holds one. _min_rule_bytes treats a rule with no alternatives as unproductive, and the refusal lists every unproductive rule by name, sorted, which makes the message stable. _check_left_recursion builds first[n], the rules that can come first in n, by walking each alternative’s leading references and stopping at the first that is not nullable, then searches from each rule for a path back to it.

The recognizer:

def expand(self, stack):
    """The stacks reachable from stack without consuming a character, each with a character
    element on top, or () when the stack is used up (the input may end here)."""
    if not stack:
        return {()}
    a, i = stack[-1]
    rest = stack[:-1]
    if i == len(self.alts[a]):
        return self.expand(rest)
    el = self.alts[a][i]
    if el[0] == "chars":
        return {stack}
    cont = rest if i + 1 == len(self.alts[a]) else rest + ((a, i + 1),)   # a finished frame is not kept
    out = set()
    for b in self.by_rule[el[1]]:
        out |= self.expand(cont + ((b, 0),))
    return out

def start(self):
    return frozenset(s for a in self.by_rule["root"] for s in self.expand(((a, 0),)))

def advance(self, stacks, cp):
    """The parse state after one more code point; empty when no parse survives."""
    key = (stacks, cp)
    if key not in self._memo:
        if len(self._memo) >= 1 << 16:
            self._memo.clear()                        # bounded, as chapter 7's encode cache is
        out = set()
        for st in stacks:
            if st:
                a, i = st[-1]
                if _matches(self.alts[a][i], cp):
                    out |= self.expand(st[:-1] + ((a, i + 1),))
        self._memo[key] = frozenset(out)
    return self._memo[key]

@staticmethod
def accepts(stacks):
    return () in stacks

def min_bytes(self, stacks):
    """Fewest bytes that complete some parse in stacks: 0 if it accepts, inf if stacks is empty."""
    return min((sum(self.suffix[a][i] for a, i in st) for st in stacks), default=float("inf"))

expand is recursive, and its depth is bounded by the grammar’s size because of the left-recursion check. cont is the frame advanced past the reference, dropped when the reference was last: rest if i + 1 == len(self.alts[a]). advance skips the empty stack, which cannot consume anything, and keys its memo on the frozen state and the code point; the states are frozensets so that they can be keys. min_bytes is the formula above, a sum of suffixes per stack and a minimum over stacks, with default=float("inf") for the empty state.

The bytes-to-characters layer:

class MatchState:
    """Where a parse stands after some bytes: the grammar's stacks, plus the bytes of a character
    begun but not finished (a token may end in the middle of one)."""

    __slots__ = ("stacks", "pending")

    def __init__(self, stacks, pending=b""):
        self.stacks, self.pending = stacks, pending

    def __eq__(self, other):
        return self.stacks == other.stacks and self.pending == other.pending

    def __hash__(self):
        return hash((self.stacks, self.pending))


# The code points each length of UTF-8 encodes; the surrogates D800-DFFF are not characters.
_VALID = {2: ((0x80, 0x7FF),), 3: ((0x800, 0xD7FF), (0xE000, 0xFFFF)), 4: ((0x10000, MAX_CP),)}


def advance_bytes(grammar, state, data):
    """The state after data, or None if no parse survives. A character completed by data advances
    the grammar. An unfinished one keeps only the stacks whose top class accepts some code point
    that begins with those bytes, and survives if any does."""
    stacks, pending = state.stacks, state.pending
    for byte in data:
        buf = pending + bytes([byte])
        lead = buf[0]
        need = 1 if lead < 0x80 else 2 if 0xC2 <= lead < 0xE0 else 3 if 0xE0 <= lead < 0xF0 else \
            4 if 0xF0 <= lead < 0xF5 else 0
        if need == 0 or (len(buf) > 1 and not 0x80 <= byte < 0xC0):
            return None                                   # not UTF-8
        if len(buf) < need:
            rest = 6 * (need - len(buf))                  # payload bits still to come
            v = lead & (0x7F >> need)
            for b in buf[1:]:
                v = (v << 6) | (b & 0x3F)
            spans = [(max(v << rest, a), min((v << rest) | ((1 << rest) - 1), b)) for a, b in _VALID[need]]
            stacks = frozenset(st for st in stacks if st and any(
                lo <= hi and _matches(grammar.alts[st[-1][0]][st[-1][1]], lo, hi) for lo, hi in spans))
            if not stacks:
                return None
            pending = buf
            continue
        try:
            cp = ord(buf.decode("utf-8"))
        except UnicodeDecodeError:
            return None
        stacks, pending = grammar.advance(stacks, cp), b""
        if not stacks:
            return None
    return MatchState(stacks, pending)


def _state_min_bytes(grammar, state):
    """Fewest bytes that complete a parse from state; an unfinished character's missing bytes count."""
    if not state.pending:
        return grammar.min_bytes(state.stacks)
    lead = state.pending[0]
    need = 2 if lead < 0xE0 else 3 if lead < 0xF0 else 4
    return need - len(state.pending) + min(sum(grammar.suffix[a][i] for a, i in st[:-1])
                                           + grammar.suffix[st[-1][0]][st[-1][1] + 1] for st in state.stacks)

need is computed from the lead byte by chapter 17’s table, with C0 and C1 (which could only lead an overlong two-byte encoding) and F5 to FF (beyond U+10FFFF) mapped to 0, not UTF-8. A byte after the first that is not a continuation byte is rejected. For an unfinished character, v accumulates the payload bits and spans is the interval of the Mechanism intersected with each of _VALID[need]’s ranges, lo <= hi discarding the empty intersections. A completed character is decoded with Python’s own strict decoder. That is a backstop: by the time a character completes, the interval checks on its earlier bytes have already rejected surrogates, overlong forms and code points above U+10FFFF. _state_min_bytes handles the pending case: the missing bytes of the character, plus each surviving stack’s frames below the top and its top frame from the element after the pending character.

The mask:

class TokenTrie:
    """Every ordinary token's bytes in a trie, so tokens that share a prefix share its parse."""

    def __init__(self, tok):
        self.root = ({}, [])                               # (children by byte, ids of tokens ending here)
        for i, raw in tok.bpe.vocab.items():
            node = self.root
            for b in raw:
                node = node[0].setdefault(b, ({}, []))
            node[1].append(i)
        self.vocab_size = tok.vocab_size


def allowed_tokens(grammar, trie, state, budget=None):
    """Boolean (V,) mask of the ordinary tokens whose bytes keep a parse of state alive. With a budget
    of B tokens still to generate, one of which must be the end token, a token is allowed only if the
    grammar can still be completed in the B - 2 tokens after it: each byte is a token, so a completion
    of b bytes always fits in b tokens."""
    allowed = np.zeros(trie.vocab_size, dtype=bool)
    todo = [(trie.root, state)]
    while todo:
        (children, _), st = todo.pop()
        for byte, child in children.items():
            nxt = advance_bytes(grammar, st, bytes([byte]))
            if nxt is None:
                continue                                   # no token below this prefix can be allowed
            if child[1] and (budget is None or _state_min_bytes(grammar, nxt) <= budget - 2):
                allowed[child[1]] = True
            todo.append((child, nxt))
    return allowed

A trie node is a pair, a dictionary of children by byte and a list of token ids ending there. Iterating tok.bpe.vocab covers only the ordinary tokens, so markers never enter the trie, and the mask has vocab_size entries with the markers left false. The walk is an explicit stack of (node, state) pairs. The budget test is applied where a token ends, but a node whose own tokens fail it still has its children walked, since a longer token may leave a state that finishes sooner (a token that closes a string, say).

The constraint that stream_generate calls:

class GrammarConstraint:
    """A mask for stream_generate: ordinary tokens that keep the grammar alive, and end_id once the
    grammar accepts. budget is the number of tokens generation may take (end included) or None."""

    def __init__(self, grammar, tok, end_id, budget=None):
        self.grammar, self.tok, self.end_id, self.budget = grammar, tok, end_id, budget
        self.trie = TokenTrie(tok)
        self.state, self.seen = MatchState(grammar.start()), 0
        self.least = _state_min_bytes(grammar, self.state) + 1   # tokens that always suffice, end included
        if budget is not None and self.least > budget:
            raise ValueError(f"the grammar's shortest output may take {self.least} tokens; the budget is {budget}")

    def feed(self, token):
        if token == self.end_id:
            return
        nxt = advance_bytes(self.grammar, self.state, self.tok.bpe.vocab[token])
        if nxt is None:
            raise ValueError(f"token {token} does not continue the grammar")
        self.state = nxt

    def __call__(self, out):
        for t in out[self.seen:]:
            self.feed(t)
        self.seen = len(out)
        left = None if self.budget is None else self.budget - len(out)
        allowed = allowed_tokens(self.grammar, self.trie, self.state, left)
        mask = np.where(allowed, 0.0, -np.inf)
        if not self.state.pending and self.grammar.accepts(self.state.stacks):
            mask[self.end_id] = 0.0
        return mask

__call__(out) receives everything generated so far and feeds only what it has not seen, so each token’s bytes are consumed once. feed refuses a token that does not continue the grammar, which can only happen if something other than this mask chose it. left is the budget minus what has been generated, and allowed_tokens applies the B−2B - 2 rule to it. The end token is added only when the state accepts with nothing pending.

Replies that may be calls:

class ReplyConstraint:
    """A reply that is either a tool call, <|call|> then JSON the call grammar accepts, or text, which
    the text grammar constrains if there is one. choice is tool_choice: "auto" allows both, "required"
    (or a named tool) only the call, "none" only text. Under "auto", a call that cannot fit in the
    budget is not offered; under "required" that is an error, as is a text grammar that cannot fit."""

    def __init__(self, tok, call_grammar, text_grammar, choice, budget=None):
        S = tok.special
        self.tok, self.choice, self.call_id, self.end_id = tok, choice, S["<|call|>"], S["<|end|>"]
        self.call = None
        if call_grammar is not None and choice != "none":
            try:
                self.call = GrammarConstraint(call_grammar, tok, self.end_id, budget - 1 if budget else None)
            except ValueError:
                if choice != "auto":
                    raise
        self.text = GrammarConstraint(text_grammar, tok, self.end_id, budget) if text_grammar is not None else None

    def _free_text(self):
        mask = np.full(self.tok.vocab_size, -np.inf)
        mask[:self.tok.bpe.vocab_size] = 0.0             # any ordinary token, and the end marker
        mask[self.end_id] = 0.0
        return mask

    def __call__(self, out):
        if out and out[0] == self.call_id:
            return self.call(out[1:])
        text = self.text(out) if self.text is not None else self._free_text()
        if out or self.call is None:
            return text
        mask = np.full(self.tok.vocab_size, -np.inf) if self.choice != "auto" else text
        mask[self.call_id] = 0.0
        return mask

_free_text is the mask for text without a grammar: every ordinary token and the end token, and no other marker. Once <|call|> has been sampled, every later step goes to the call constraint with the marker stripped from out. At the first step under "auto" the text mask and <|call|> are both allowed; under "required" everything but <|call|> is −∞-\infty.

The schema compiler:

def schema_to_gbnf(schema, cap=None):
    """GBNF for the JSON texts that satisfy schema, for this subset of JSON Schema: type (one or a
    list), properties and required, items, minItems and maxItems, enum, const, anyOf, minLength and
    maxLength. Objects have their required properties first, then the optional ones, in the order
    given, and no others. Annotations (title, description, ...) are ignored, and so is
    additionalProperties wherever an object is compiled from its properties, since those objects
    never hold another property; any other keyword is a ValueError, since ignoring a restriction
    would generate invalid texts. That includes oneOf: a grammar can say "one of these" but not
    "exactly one of these". For the same reason const, enum and anyOf take no restricting sibling
    but type, which filters the values of const and enum; a schema that restricts without a type or
    other supported keyword is an error; and so is an empty enum, anyOf or type list, which nothing
    satisfies. A length or item bound above cap is an error."""
    rules = {"char": STRING_CHAR, "space": '" "?'}
    count = [0]

    def rule(body):
        count[0] += 1
        name = f"r{count[0]}"
        rules[name] = body
        return name

    def value(s):
        if s is True:
            s = {}
        if not isinstance(s, dict):
            raise ValueError(f"schema must be an object, not {s!r}")
        unknown = set(s) - SUPPORTED - IGNORED
        if unknown:
            raise ValueError(f"unsupported JSON Schema keywords: {sorted(unknown)}")
        _check_bounds(s, cap)
        if set(s) <= ANNOTATIONS:                     # {}, true, or annotations only: any value
            rules.update((k, v) for k, v in ANY_RULES.items() if k not in rules)
            return "any"
        restricting = set(s) & SUPPORTED
        if s.get("additionalProperties", True) not in (True, {}):
            restricting.add("additionalProperties")   # restricts objects; sound to drop only where
        if not set(s) & SUPPORTED:                    # objects are built from declared properties
            raise ValueError(f"{sorted(set(s) - ANNOTATIONS)} without a type or another keyword this compiler "
                             "supports: only annotations alone mean any value")
        if "const" in s or "enum" in s:
            others = restricting - {"type"}
            if others != {"const"} and others != {"enum"}:
                raise ValueError(f"unsupported combination of keywords: {sorted(others)}")
            values = [s["const"]] if "const" in s else list(s["enum"])
            if "type" in s:
                types = s["type"] if isinstance(s["type"], list) else [s["type"]]
                values = [v for v in values if any(_is_type(v, t) for t in types)]
            if not values:
                raise ValueError(f"enum or const leaves no value of type {s.get('type')!r}: no value satisfies the schema")
            return rule(" | ".join(_literal(v) for v in values))
        if "anyOf" in s:
            if restricting != {"anyOf"}:
                raise ValueError(f"unsupported combination of keywords: {sorted(restricting)}")
            if not s["anyOf"]:
                raise ValueError("anyOf is empty: no value satisfies the schema")
            return rule(" | ".join(value(sub) for sub in s["anyOf"]))
        types = s.get("type")
        if isinstance(types, list):
            if not types:
                raise ValueError("type is an empty list: no value satisfies the schema")
            return rule(" | ".join(value({**s, "type": t}) for t in types))
        if types == "object":
            props = s.get("properties", {})
            required = [k for k in props if k in s.get("required", ())]
            missing = set(s.get("required", ())) - set(props)
            if missing:
                raise ValueError(f"required properties {sorted(missing)} have no schema")
            optional = [k for k in props if k not in required]
            kv = {k: f'{_literal(k)} space ":" space {value(props[k])}' for k in props}
            if required:
                body = ' "," space '.join(kv[k] + " space" for k in required)
                body += "".join(f' ( "," space {kv[k]} space )?' for k in optional)
            else:                                     # any ordered subset of the optional properties
                body = " | ".join(kv[k] + " space" + "".join(f' ( "," space {kv[o]} space )?' for o in optional[i + 1:])
                                  for i, k in enumerate(optional))
                body = f"( {body} )?" if body else ""
            return rule(f'"{{" space {body} "}}"')
        if types == "array":
            item = value(s.get("items", {}))
            lo, hi = s.get("minItems", 0), s.get("maxItems")
            more = f'( "," space {item} space )' + ("{%d,%s}" % (max(lo - 1, 0), "" if hi is None else hi - 1))
            if hi == 0:
                return rule('"[" space "]"')
            inner = f"{item} space {more}"
            return rule(f'"[" space {inner if lo else f"( {inner} )?"} "]"')
        if types == "string" and ("minLength" in s or "maxLength" in s):
            lo, hi = s.get("minLength", 0), s.get("maxLength")
            return rule(r'"\"" char{%d,%s} "\""' % (lo, "" if hi is None else hi))
        if types in PRIMITIVES:
            return rule(PRIMITIVES[types])
        raise ValueError(f"unsupported or missing type {types!r}")

    root = value(schema)
    return "\n".join([f"root ::= {root}"] + [f"{k} ::= {v}" for k, v in rules.items()])

value returns the name of a new rule for each subschema, so the output is a flat list of numbered rules, r1, r2 and so on, plus char and space. A schema that is True, {} or annotations alone means “any value” (additionalProperties is not an annotation): ANY_RULES is copied into the rules once and its root, any, returned, so a nested {} or an array without items refers back to the same rules instead of compiling “any value” again, which for an array of any values would recurse without end. const and enum go first, before type, because they fix the value outright. The array’s repetition bound uses Python’s % formatting to write {m-1,n-1}, with an empty upper bound for an unbounded array.

Finally the hook the server calls:

def constraint_for(engine, req):
    """The mask a request's response_format and tools call for, or None. Raises OpenAIError 400
    for a schema outside the subset, a bound or budget the reply cannot meet, and a stop string
    (which would cut constrained output short); any other failure to compile is a 500, never a
    dropped connection."""
    tok = engine.tok
    tools = req.tools if req.tool_choice != "none" else None
    fmt = req.response_format
    if fmt is None and tools is None:
        return None
    param = "response_format" if fmt is not None else "tools"
    if req.stop:
        raise OpenAIError(400, f"stop cannot be combined with {param}: a stop string would cut the "
                               "constrained output before it is complete", param="stop")
    prompt = render_messages(tok, req.messages, req.tools)
    room = engine.context - len(prompt) + 1
    budget = min(req.max_tokens or room, room)
    cap = budget * max(len(b) for b in tok.bpe.vocab.values())    # no reply holds more characters or items
    try:
        text = None
        if fmt is not None and fmt["type"] == "json_object":
            text = parse_gbnf(JSON_GBNF)
        elif fmt is not None:
            schema = (fmt.get("json_schema") or {}).get("schema")
            if schema is None:
                raise ValueError("response_format json_schema needs json_schema.schema")
            text = parse_gbnf(schema_to_gbnf(schema, cap))
        call = None
        if tools is not None:
            named = req.tool_choice["function"]["name"] if isinstance(req.tool_choice, dict) else None
            calls = [{"type": "object", "required": ["name", "arguments"],
                      "properties": {"name": {"const": t["function"]["name"]},
                                     "arguments": t["function"].get("parameters") or {"type": "object"}}}
                     for t in tools if named in (None, t["function"]["name"])]
            call = parse_gbnf(schema_to_gbnf({"anyOf": calls}, cap))
        choice = "required" if isinstance(req.tool_choice, dict) else req.tool_choice if tools else "none"
        return ReplyConstraint(tok, call, text, choice, budget)
    except (ValueError, TypeError, KeyError, AttributeError) as e:
        raise OpenAIError(400, f"{type(e).__name__}: {e}" if not isinstance(e, ValueError) else str(e),
                          param=param) from None
    except RecursionError:
        raise OpenAIError(400, "the schema nests too deeply to compile", param=param) from None
    except Exception as e:
        raise OpenAIError(500, f"could not compile the constraint: {e!r}", type="server_error") from None

A tool without parameters gets {"type": "object"}, which this compiler reads as the empty object: no properties are listed, so none are generated. The param of the 400 names response_format when there is one and tools otherwise, and stop for the stop-string refusal, which comes first. cap is the bound of the JSON Schema section, handed to schema_to_gbnf, which checks it subschema by subschema, so a tool parameter called maxLength is a name and not a bound.

Exercises

(a) Trace the stacks for root ::= "a" b* "c" with b ::= "b" on abbc, and show where dropping a last reference keeps the stack from growing.

Answer

parse_gbnf flattens it into alternatives 0 (b root-1) and 1 (empty) for root-1, 2 (root-1) for root-2, 3 ("a" root-2 "c") for root, and 4 ("b") for b. Printed by a script on talos:

start [((3, 0),)]
'a'   [((3, 2),), ((3, 2), (0, 1), (4, 0))]
'b'   [((3, 2),), ((3, 2), (0, 1), (4, 0))]
'b'   [((3, 2),), ((3, 2), (0, 1), (4, 0))]
'c'   [()]                                   accepts

After a, frame (3,1) refers to root-2 and is not last, so it advances to (3,2), waiting for c. root-2’s only alternative is the reference to root-1, which is last, so no (2,1) frame is kept. root-1 gives two stacks: its empty alternative leaves ((3,2)), and alternative 0 pushes (0,0), a reference to b that is not last, so it becomes (0,1) with (4,0) above it. On b, (4,0) matches and finishes and is popped, leaving (0,1) on top: the reference to root-1, last in its alternative. It is replaced, not kept, and root-1 expands to the same two stacks as before. So the state after any number of bs is the same, three frames deep at most. Without the rule, each b would leave a finished (0,2) frame on the stack, and after kk of them the stack waiting for c would be k+2k + 2 frames deep, and the one waiting for the next b k+4k + 4.

(b) A token ends with the bytes E2 80. Which code points can the character become? Which of [‘-”], [a-z] and [^"] keep it alive?

Answer

E2 is 1110 0010: a three-byte lead with payload 0010. 80 is 10 000000, payload 000000. So n=3n = 3, k=2k = 2, v=00100000002=0x80v = 0010\,000000_2 = \texttt{0x80}, and one byte of r=6r = 6 bits is missing. The interval is [0x80⋅64,0x80⋅64+63]=[0x2000,0x203F][\texttt{0x80} \cdot 64, \texttt{0x80} \cdot 64 + 63] = [\texttt{0x2000}, \texttt{0x203F}], all valid three-byte code points (none is a surrogate). It includes U+2018 ‘ to U+201D ”, so [‘-”] keeps it; it is disjoint from U+0061 to U+007A, so [a-z] cuts it; and [^"] accepts everything but U+0022, so it keeps it. advance_bytes agrees on all three (checked on talos). This is chapter 17’s split of ’, U+2019: a grammar over curly quotes lets the half-character token through, and one over ASCII letters does not.

(c) The Mechanism showed that masked sampling is not p(x∣L)p(x \mid L). Derive a per-step distribution that is. Let E(w)E(w) be the probability that the model, continuing from the prefix ww, produces a complete output in LL. Show that sampling each token from q∗(t∣w)=p(t∣w)E(wt)/E(w)q^*(t \mid w) = p(t \mid w)\,E(wt)/E(w) gives p(x∣L)p(x \mid L) exactly, compute q∗q^* on the Mechanism’s two-step example, and say when the plain mask already equals q∗q^*.

Answer

First, q∗q^* is a distribution. A complete output from ww must pass through some next token tt, so E(w)=∑tp(t∣w)E(wt)E(w) = \sum_t p(t \mid w)\,E(wt), and dividing by E(w)E(w) shows the q∗(t∣w)q^*(t \mid w) sum to 1. Tokens with E(wt)=0E(wt) = 0, the dead ones, get probability 0, so q∗q^* is a mask too, with different weights.

For a complete output x=(x1,…,xT)x = (x_1, \ldots, x_T) in LL (its last token the end marker), the product over steps telescopes:

∏t=1Tp(xt∣x<t)E(x≤t)E(x<t)=p(x)E(x)E(ε). \prod_{t=1}^{T} p(x_t \mid x_{<t})\,\frac{E(x_{\le t})}{E(x_{<t})} = p(x)\,\frac{E(x)}{E(\varepsilon)} .

E(x)=1E(x) = 1, since xx is already a complete output in LL, and E(ε)=p(L)E(\varepsilon) = p(L), the probability of the language from the start. So the product is p(x)/p(L)=p(x∣L)p(x)/p(L) = p(x \mid L).

In the example, E(ab)=E(ba)=1E(ab) = E(ba) = 1, E(a)=p(b∣a)=0.01E(a) = p(b \mid a) = 0.01, E(b)=p(a∣b)=0.9E(b) = p(a \mid b) = 0.9 and E(ε)=0.9×0.01+0.1×0.9=0.099E(\varepsilon) = 0.9 \times 0.01 + 0.1 \times 0.9 = 0.099. So q∗(a)=0.9×0.01/0.099=1/11q^*(a) = 0.9 \times 0.01 / 0.099 = 1/11 and q∗(b)=0.1×0.9/0.099=10/11q^*(b) = 0.1 \times 0.9 / 0.099 = 10/11, and the second step is forced as before: abab with probability 1/111/11, baba with 10/1110/11, the conditional.

The plain mask samples p(t∣w)/Zp(t \mid w)/Z over the live tokens. It equals q∗q^* exactly when E(wt)E(wt) is the same for every live tt at every step, for instance when every live prefix is completed within LL with probability 1. That is the case the mask is built for: a model that already writes the format, which the mask only protects from rare slips. The obstacle to q∗q^* in general is EE itself, a sum over every completion of every candidate; Park et al. approximate it from earlier samples.

(d) The Mechanism showed that llama.cpp’s sample-check-resample order gives the masked distribution when its chain samples from pp with a temperature. Its chain can also include top-k, top-p and min-p, and the first draw runs them over all tokens while the resample runs them over the allowed ones. Does the equivalence survive top-k? Give a proof or a counterexample.

Answer

It does not. Take three tokens with p=(0.5,0.3,0.2)p = (0.5, 0.3, 0.2), the first forbidden and the other two allowed, and top-k with k=2k = 2. Grammar first: top-2 of the allowed tokens keeps both, and renormalising gives (0.6,0.4)(0.6, 0.4). llama.cpp’s order: the first draw’s top-2 over all tokens keeps the forbidden token and the first allowed one, renormalised to (0.625,0.375,0)(0.625, 0.375, 0). The draw is valid with probability 0.375, and then it is the first allowed token. Otherwise, with probability 0.625, the resample runs grammar first and gives (0.6,0.4)(0.6, 0.4). So the first allowed token comes out with probability 0.375+0.625×0.6=0.750.375 + 0.625 \times 0.6 = 0.75 and the second with 0.625×0.4=0.250.625 \times 0.4 = 0.25, against 0.6 and 0.4 with the grammar first (computed on talos). The proof in the Mechanism needed the first draw, restricted to the allowed set, to be proportional to the resample’s distribution. Temperature preserves that, since it rescales each token’s logit on its own. Top-k does not, because which tokens it keeps depends on the whole set it looks at, and the forbidden ones change the set. Top-p and min-p fail the same way. With k=3k = 3 nothing is cut, and the two orders agree.

(e) Write GBNF for ISO dates, YYYY-MM-DD with month 01 to 12 and day 01 to 31. Constrain the served model to it on the lab’s 40 prompts at temperature 1 and count the replies that are the canonical tokenization of their own text. Explain the count.

Answer

The grammar, and a script that runs it (from py/, OPENBLAS_NUM_THREADS=1 PYTHONPATH=. uv run python /tmp/ex_dates.py /tmp/tinygpt-chat):

import sys

import numpy as np

from tinygpt.chat import NOUNS, VERBS
from tinygpt.grammar import GrammarConstraint, parse_gbnf
from tinygpt.sample import KVCache
from tinygpt.serve import render_messages, stream_generate
from tinygpt.server import load_engine

DATE = r'''
root  ::= year "-" month "-" day
year  ::= [0-9]{4}
month ::= "0" [1-9] | "1" [0-2]
day   ::= "0" [1-9] | [12] [0-9] | "3" [01]
'''
engine = load_engine(sys.argv[1] if len(sys.argv) > 1 else "/tmp/tinygpt-chat")
tok, model = engine.tok, engine.model
end = tok.special["<|end|>"]
grammar = parse_gbnf(DATE)
rng = np.random.default_rng(7)
N, canonical = 40, 0
for i in range(N):
    subj, obj = str(rng.choice(NOUNS)), str(rng.choice(NOUNS))
    prompt = render_messages(tok, [{"role": "user", "content": f"subject of: the {subj} {VERBS[subj]} a {obj} ."}])
    c = GrammarConstraint(grammar, tok, end, budget=20)
    ids = [s.token for s in stream_generate(model, prompt, KVCache(model.cfg.n_layers), 20, np.random.default_rng(i),
                                            stop_ids=(end,), mask=c, temperature=1.0)]
    text = tok.bpe.decode(ids[:-1])
    canonical += tok.bpe.encode(text) == ids[:-1]
    if i < 3:
        print(repr(text), [tok.bpe.vocab[t] for t in ids[:-1]], "canonical:", tok.bpe.encode(text) == ids[:-1])
print(f"parsed {N}/{N}, canonical tokenization {canonical}/{N}")

On talos:

'7300-11-29' [b'7', b'3', b'0', b'0', b'-', b'1', b'1', b'-', b'2', b'9'] canonical: True
'6919-08-30' [b'6', b'9', b'1', b'9', b'-', b'0', b'8', b'-', b'3', b'0'] canonical: True
'1381-10-17' [b'1', b'3', b'8', b'1', b'-', b'1', b'0', b'-', b'1', b'7'] canonical: True
parsed 40/40, canonical tokenization 40/40

All 40 are canonical because there is nothing else they could be: the lab’s BPE has no multi-byte token made of digits and - (checked by a script), so every date has exactly one tokenization, a byte per token. The tokenization failure needs a choice between tokenizations, as subject against s, u, … had. The dates themselves are what a model that has never seen a digit writes: uniform-looking digits within the grammar. And the grammar accepts 2026-02-31: a context-free grammar can enumerate month lengths (and, with more rules, leap years), but this one does not, and “valid” means only what the grammar says.

(f) Write chapter 13’s reasoning budget as a constraint for stream_generate(mask=…): pass tokens through until a start sequence appears, count the tokens after it, and once NN have gone by without the end sequence, force the end sequence one token at a time. Check it with a random model and the byte-level tokenizer.

Answer

The state is where the start sequence is, whether the end sequence has followed it, and how many tokens have been spent; the allowed set is everything, or one forced token; the transition is appending a token. None from a mask means “no constraint”, which stream_generate accepts.

import numpy as np

from tinygpt.bpe import BPE
from tinygpt.chat import ChatTokenizer
from tinygpt.sample import KVCache
from tinygpt.serve import SERVE_SPECIALS, stream_generate
from tinygpt.transformer import GPT, GPTConfig


class ReasoningBudget:
    """Pass through until the start sequence appears; after n more tokens without the end sequence,
    force the end sequence one token at a time. start and end are lists of token ids."""

    def __init__(self, vocab_size, start, end, n):
        self.V, self.start, self.end, self.n = vocab_size, list(start), list(end), n

    @staticmethod
    def _find(seq, sub, frm=0):
        for i in range(frm, len(seq) - len(sub) + 1):
            if seq[i:i + len(sub)] == sub:
                return i
        return -1

    def __call__(self, out):
        s = self._find(out, self.start)
        if s < 0:
            return None                                  # not thinking yet: no constraint
        body = s + len(self.start)
        if self._find(out, self.end, body) >= 0:
            return None                                  # the block is closed
        spent = len(out) - body
        if spent < self.n:
            return None
        forced = spent - self.n                          # end tokens already forced
        mask = np.full(self.V, -np.inf)
        mask[self.end[forced]] = 0.0
        return mask


tok = ChatTokenizer(BPE([]), SERVE_SPECIALS)            # byte level: every character is its own token
start, end = tok.bpe.encode("<t>"), tok.bpe.encode("</t>")
model = GPT(GPTConfig(tok.vocab_size, 128, d_model=16, n_heads=2, n_layers=1), np.random.default_rng(0))
prompt = tok.bpe.encode("q?") + start                   # the prompt opens the block, as a template would
for n in (0, 5, 20):
    for seed in range(3):
        # the mask sees only generated tokens, so give it the start sequence as if generated
        rb = ReasoningBudget(tok.vocab_size, start, end, n)
        ids = [s.token for s in stream_generate(model, prompt, KVCache(1), n + len(end) + 5, np.random.default_rng(seed),
                                                 mask=lambda out: rb(start + out), temperature=1.0)]
        closed = ReasoningBudget._find(ids, end)
        assert 0 <= closed <= n, (n, seed, ids)
        if seed == 0:
            print(f"n={n:2d}: block closed after {closed} tokens:", repr(tok.bpe.decode(ids[:closed + len(end)])))
print("every run closed the block within its budget")

On talos:

n= 0: block closed after 0 tokens: '</t>'
n= 5: block closed after 5 tokens: '�C\x0b\x02�</t>'
n=20: block closed after 20 tokens: '�C\x0b\x02�\U000a2fcc��\x01�\x07�,�Fk</t>'
every run closed the block within its budget

A random model never closes the block itself, so each run spends exactly its NN tokens and is then forced. With a byte-level tokenizer the forced sequence </t> is four tokens, forced one per step, which is why the counter keeps forced: the budget’s end is a short grammar, a single string, walked by position. llama.cpp’s version (common/reasoning-budget.cpp) does the same with its force_pos. It also accepts several start and end sequences at once, matched token by token with an Aho–Corasick automaton (token_matcher, :14-49), where this one rescans for a single sequence at every step; and it waits for a character split across tokens to finish before forcing, the WAITING_UTF8 state of the budgets section, where this one can force </t> straight after half a character. The n=5 line shows it: the last byte the model generated was D4, the lead of a two-byte character, and the forcing cut it off (printed as the � before </t>).

Lab

Implement the stubs in py/labs/ch18/starter.py: the recognizer (Grammar.expand, start, advance, accepts, min_bytes), advance_bytes with unfinished characters, TokenTrie and allowed_tokens, GrammarConstraint, ReplyConstraint and schema_to_gbnf. The grammar’s construction and checks (Grammar.__init__ and its helpers), the GBNF parser, JSON_GBNF, MatchState and constraint_for are provided. Run

make lab CH=18 IMPL=mine

until it passes; against the reference it takes about 10 seconds on talos. The tests pin GBNF’s literals, classes, groups and repetition; the grammar errors; the JSON grammar against json.loads on valid and invalid texts; tokens that end inside a character, surrogates, overlong forms and stray continuation bytes; the mask against a brute-force check of every token at six states; the end token; budgets, including every budget from least up for seven schemas; the schema compiler’s object order, its refusals (pattern, minimum, format, $ref, allOf, oneOf, restrictions beside const, enum or anyOf, restrictions without a type, empty alternatives), any-value schemas, the type filter on enum, string lengths against escapes, and its annotations; constrained tool calls; and, over HTTP, response_format, any-value schemas, a named tool_choice, 400s for bad schemas, oversized bounds, a lone surrogate, small budgets and stop, and the dead-end error. The acceptance tests are two. test_sampled_output_always_parses_and_validates runs a random model at temperature 1 under seven schemas, 15 seeds each: the model knows nothing, the mask does all the work, and every output must parse with json.loads and satisfy the schema by validate, a checker written independently of the grammar. test_response_format_json_schema_over_http does the same through the server.

Then measure what the mask costs on the model chapter 17’s lab trained. Save as /tmp/grammar_lab.py:

"""Chapter 18 lab: constrain the served model to a JSON answer, and measure what the mask costs.

    OPENBLAS_NUM_THREADS=1 PYTHONPATH=. uv run python /tmp/grammar_lab.py /tmp/tinygpt-chat
"""
import json
import sys

import numpy as np

from tinygpt.chat import NOUNS, VERBS
from tinygpt.grammar import GrammarConstraint, parse_gbnf, schema_to_gbnf
from tinygpt.sample import KVCache, forward_cached, log_softmax
from tinygpt.serve import render_messages, stream_generate
from tinygpt.server import load_engine

engine = load_engine(sys.argv[1] if len(sys.argv) > 1 else "/tmp/tinygpt-chat")
tok, model = engine.tok, engine.model
end = tok.special["<|end|>"]
schema = {"type": "object", "properties": {"subject": {"enum": NOUNS}}, "required": ["subject"]}
grammar = parse_gbnf(schema_to_gbnf(schema))
print(schema_to_gbnf(schema))

rng = np.random.default_rng(7)
right = canonical = plain = 0
removed, first = [], []
N = 40
for i in range(N):
    subj, obj = str(rng.choice(NOUNS)), str(rng.choice(NOUNS))
    prompt = render_messages(tok, [{"role": "user", "content": f"subject of: the {subj} {VERBS[subj]} a {obj} ."}])
    c = GrammarConstraint(grammar, tok, end, budget=40)
    masks = []

    def mask(out):
        m = c(out)
        masks.append(m)
        return m
    free = [s.token for s in stream_generate(model, prompt, KVCache(model.cfg.n_layers), 40,
                                             np.random.default_rng(i), stop_ids=(end,), temperature=0)]
    plain += tok.bpe.decode(free[:-1]) == subj
    steps = list(stream_generate(model, prompt, KVCache(model.cfg.n_layers), 40, np.random.default_rng(i),
                                 stop_ids=(end,), mask=mask, temperature=0))
    ids = [s.token for s in steps]
    # the probability the unconstrained model put on tokens the mask removed, at each step
    cache = KVCache(model.cfg.n_layers)
    logits = forward_cached(model, prompt + ids[:-1], cache)[len(prompt) - 1:]
    p = np.exp(log_softmax(logits))
    gone = [float(p[t][np.isinf(m)].sum()) for t, m in enumerate(masks)]
    removed += gone
    first.append(gone[0])
    text = tok.bpe.decode(ids[:-1])
    right += json.loads(text)["subject"] == subj
    canonical += tok.bpe.encode(text) == ids[:-1]
    if i < 3:
        print(repr(text), [tok.bpe.vocab[t] for t in ids[:-1]])
print(f"unconstrained replies right {plain}/{N}")
print(f"parsed {N}/{N}, subject right {right}/{N}, canonical tokenization {canonical}/{N}")
print(f"probability mass the mask removed per step: mean {np.mean(removed):.3f}, max {np.max(removed):.3f}, "
      f"first step {np.mean(first):.3f}")

and run it from py/ as its docstring says. On talos:

root ::= r2
char ::= [^"\\\x00-\x1f] | "\\" ( ["\\/bfnrt] | "u" ( [0-9a-cA-C] [0-9a-fA-F]{3} | [dD] [0-7] [0-9a-fA-F]{2} | [eEfF] [0-9a-fA-F]{3} ) )
space ::= " "?
r1 ::= "\"cat\"" | "\"dog\"" | "\"bird\"" | "\"king\"" | "\"queen\"" | "\"prince\""
r2 ::= "{" space "\"subject\"" space ":" space r1 space "}"
'{"subject" :"prince"}' [b'{"', b'subject', b'"', b' ', b':', b'"', b'prince', b'"}']
'{"subject" :"prince"}' [b'{"', b'subject', b'"', b' ', b':', b'"', b'prince', b'"', b'}']
'{"subject" :"king"}' [b'{"', b's', b'u', b'b', b'j', b'e', b'c', b't', b'"', b' ', b':', b'"', b'king', b'"}']
unconstrained replies right 40/40
parsed 40/40, subject right 26/40, canonical tokenization 12/40
probability mass the mask removed per step: mean 0.912, max 1.000, first step 1.000

The compiled grammar comes first: char is STRING_CHAR, unused here, r1 is the enum, six literals, and r2 the object. The three sample replies answer the prince summons a king ., the queen commands a prince . and the king rules a queen ., and show the tokenization section’s effects in miniature. The first is right, and is the canonical encoding of its own text, which has a space before the colon: after subject the model chose " where the compact text’s encoding has ":, then the space the space rule allows, and went on from there. The second names the object, prince, where the subject is the queen, and ends with " and } as two tokens where "} is one, so it is not canonical. The third is right, and spells subject a byte at a time. The last three lines are the numbers the Mechanism explained: every reply parses, 26 of 40 are right against 40 of 40 without the mask, 12 of 40 are canonical, and the mask removed 91.2% of the model’s probability at an average step and all of it at the first.

Finally the fleet, read-only, with the same guard as chapter 17’s script: it reads GET /v1/models, refuses unless the model’s status is "loaded", and sends ?autoload=false, so the router answers 400 rather than load anything. It sends two constrained requests: one with the lab’s schema, and one with a pattern that is not anchored. Save as /tmp/fleet_schema.py:

"""Read-only: one short json_schema-constrained completion from a model a fleet router already has loaded.

    python3 /tmp/fleet_schema.py HOST MODEL        e.g. dixie ornith-1.5-9b-uncensored

Never loads a model: it reads /v1/models first, refuses unless the model's status is "loaded", and
sends ?autoload=false so the router answers 400 rather than load anything."""
import json
import sys
import time
import urllib.error
import urllib.request

host, model = sys.argv[1], sys.argv[2]
base = f"http://{host}:11434"


def get(path):
    with urllib.request.urlopen(base + path, timeout=10) as r:
        return json.loads(r.read())


def post(body):
    req = urllib.request.Request(base + "/v1/chat/completions?autoload=false", json.dumps(body).encode(),
                                 {"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=120) as r:
            return r.status, json.loads(r.read())
    except urllib.error.HTTPError as e:
        return e.code, json.loads(e.read())


status = {m["id"]: (m.get("status") or {}).get("value") for m in get("/v1/models")["data"]}
if status.get(model) != "loaded":
    raise SystemExit(f"{model} is {status.get(model)!r} on {host}, not loaded; nothing sent")
print("date", time.strftime("%Y-%m-%d %H:%M %Z"), "host", host, "build", get("/props")["build_info"], "model", model)
schema = {"type": "object", "properties": {"subject": {"enum": ["cat", "dog", "bird", "king", "queen", "prince"]}},
          "required": ["subject"]}
base_body = {"model": model, "temperature": 0, "max_tokens": 48, "chat_template_kwargs": {"enable_thinking": False},
             "messages": [{"role": "user", "content": "subject of: the prince summons a king ."}]}
for name, fmt in [("json_schema", {"type": "json_schema", "json_schema": {"name": "s", "schema": schema}}),
                  ("pattern", {"type": "json_schema", "json_schema": {"name": "p", "schema": {
                      "type": "object", "properties": {"code": {"type": "string", "pattern": "[A-Z]{3}"}},
                      "required": ["code"]}}})]:
    code, body = post(base_body | {"response_format": fmt})
    if code == 200:
        print(name, code, repr(body["choices"][0]["message"]["content"]), body["choices"][0]["finish_reason"])
    else:
        print(name, code, body["error"]["message"][:200])

Run python3 /tmp/fleet_schema.py dixie ornith-1.5-9b-uncensored. A capture from talos against dixie:

date 2026-09-30 00:32 PDT host dixie build b10964-b29c606 model ornith-1.5-9b-uncensored
json_schema 200 '{"subject": "king"}' stop
pattern 200 '{"code": "}> The subject of "\n\n  }' stop

The build is b10964-b29c606, 300 commits behind the da89bb3 this chapter quotes, as chapter 17’s capture found. A nine-billion-parameter model, constrained to the schema, returned valid JSON with the wrong subject (the prince summons the king, so the subject is prince), and form is not content at any size. The pattern request was answered, not refused. JSON Schema patterns are not anchored (JSON Schema Validation, §6.3.3: “regular expressions are not implicitly anchored”), so [A-Z]{3} means “contains three capital letters in a row”, and llama.cpp’s converter, which handles only anchored patterns, replaced it with “any string”. The model duly wrote a string, "}> The subject of ", with no three capitals in it, followed by blank lines that the converter’s whitespace rule allows. The reply violates the schema it was asked for, and nothing in the response says so. This server answers the same request with a 400 naming pattern.

Last, the live test, which adds a json_schema request to chapter 17’s streaming check and parses the reply. From py/:

AEC_LIVE=dixie uv run pytest -q tests/test_live_serving.py

It passed against dixie on 2026-09-30 (2 passed). Without AEC_LIVE, or with no chat model loaded, both tests skip; they never load one.

Further reading

results matching ""

    No results matching ""