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 (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 : a set of rule names (nonterminals), an alphabet of terminals, a set of rules, each of which rewrites a name as a sequence over , and a start name . A name may have several rules, its alternatives. The language is the set of terminal strings that can be derived from by rewriting names with rules until none is left. Here is the Unicode code points, the integers from 0 to that chapter 17’s UTF-8 section encoded, and 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 ), {m,} (at least ) or {m,n} (between and ). 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.
is zero or more copies of . A string of copies is either empty or one followed by a string of copies, which is a rule that refers to itself at its right end:
Unfolding it times and then taking gives exactly copies, for every , and nothing else. is one copy followed by , so it is with the same . For a bounded repetition , write copies and then at most more. “At most more” is either nothing or one copy followed by at most more: , with matching only the empty string. For that is
and parse_gbnf('root ::= "x"{1,3}') produces exactly these, under the names root-3, root-2 and root-1. The strings are (take in ), ( then in ) and . ? is .
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 says “inside alternative , element 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 ( 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 , the frame is advanced past the reference, and for each alternative of a new stack is formed with 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 be what a stack still has to match: the remaining elements of its top frame, then those of the frame below, down to the bottom. For a frame the remaining elements are alts[a][i:], and for a stack , top last,
a sequence of elements, read left to right. Write when the sequence derives the terminal string . Let be the state after the prefix . The claim is: for every prefix and every string ,
The proof uses a lemma about expand: for every stack and string , holds if and only if some in expand(σ) has . Each case of expand preserves the claim. Popping a finished frame removes nothing from , 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 at the front of gives one stack per alternative , with rest . Any derivation of from 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 exactly when some . 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 . For empty, is the expansion of the one-frame stacks for root’s alternatives , whose rests are the alternatives themselves. means , which means some alternative derives , and by the lemma that holds exactly when some stack in has a rest that derives .
For the step, suppose the claim holds for , and consider for a code point . Apply the hypothesis to the string : exactly when some has . Every stack in came out of expand, so it is either (), whose rest is empty and derives only the empty string, never , or its top element is a character class , with where is with its top frame advanced by one. A class derives exactly one character, so holds exactly when accepts and . By the lemma, that holds exactly when some in expand(σ') has , and advance puts precisely those into . So exactly when some has , which is the claim for .
Two consequences are what a decoder uses. Taking empty: exactly when some stack in 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 , so is non-empty exactly when 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 be the length in UTF-8 bytes of the shortest string rule derives, 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 : no text can ever match it. A reference costs the of its rule. An alternative costs the sum of its elements, and a rule its cheapest alternative:
where is the set of ’s alternatives. The equation refers to on both sides, and _min_rule_bytes solves it by iteration: start every rule at , 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 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 . Conversely, if ’s shortest string has a derivation tree of height , then after passes ’s value is at most that length: by induction on , 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 reads them. So the iteration ends at the true , and exactly when 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 , 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 that completes the text to a string of the language. With nothing pending, pick any stack: its rest derives some string , because every element in it can generate one (the previous paragraph), and is ’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 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 is in the language. If is empty, the state accepts with nothing pending, and the end token is allowed. Otherwise the first byte of 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- 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 bytes and carries payload bits (for : the lead is one bits, a zero, then the payload); each continuation byte carries 6. Suppose of the bytes have arrived, , and let be the payload bits seen so far, read as a binary number. The bytes still to come carry more bits, appended below . The finished code point is for some -bit number , and ranges over to , so the code points the partial sequence can still become are the interval
intersected with the code points UTF-8 allows at bytes: for , without the surrogates for , and for . 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: , , , . The interval is , 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, with payload ; A0 is 10 100000, payload ; , , , and the interval is , 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 lies below : 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 is a vector of shape (V,), added to the logits before sampling. For an ordinary token it is 0 if feeding ’s bytes to leaves a non-empty state and otherwise. For the end token it is 0 exactly when accepts with nothing pending. Every other marker is : 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 of the allowed set.
Computing it token by token costs 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.
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 . Over a whole sequence the steps multiply. Write for a complete output (its last token the end marker), for the allowed set at step , which depends on , and
for the probability the model puts on it. Each step samples with probability , so the masked sampler produces with probability
using , 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,
Both are divided by something, but divides by a product that depends on ’s path, and the conditional divides by one constant. They agree for every only if 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 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 and the masked sampler picks a with probability 0.9. After a, only b is allowed: , and b gets probability . After b, only a: , and a gets 1. So and . The conditional is different: , , , so and . The masked sampler produces ab almost ten times as often as the model, conditioned on the language, would (); 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 , and let be the allowed set with probability . A token is returned either because the first draw was , probability , or because the first draw failed, probability , and the masked second draw was , probability :
and a token outside is never returned. That is the masked distribution exactly. A temperature changes nothing in the argument, since it replaces by a tempered 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 , 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 , let suffix[a][i] be the fewest bytes its elements from 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:
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:
which is 0 exactly when some stack is empty (the state accepts) and 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 tokens left, an ordinary token is allowed only if, after it, the state can be finished in at most 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 bytes can always be written in 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 tokens are left, . At the start it is the condition on the budget. Suppose it holds at some step. If , the state accepts and the end token is allowed; and if , no ordinary token is allowed (it would need its completion to fit in bytes), so the end token is the only choice and generation ends. If , then . The first byte of a shortest completion is a token, and after it the rest of that completion, 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 bytes, which is the invariant with tokens left. drops by one each step, and at 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* "\"", wherecharis any character except",\and the control characters below U+0020, or an escape other than a\uescape of a surrogate (see below).integerandnumber: RFC 8259’s number syntax, the integer part limited to 16 digits.booleanandnull: 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 asJSON_GBNF) added to the grammar once. An array withoutitemsis an array of any values.enumandconst: the literals of the compact JSON texts of the allowed values, as alternatives. A siblingtypefilters them:{"type": "string", "enum": ["a", 1]}compiles to"a"alone. Any other restricting keyword beside them, amaxLengthsay, 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 anenumof the values that satisfy it.anyOfand a list of types: alternatives.anyOftakes no restricting sibling at all, for the same reason asoneOfbelow: a grammar can offer the branches but not intersect each with the siblings.- An empty
enum,anyOfortypelist, or anenumthat thetypefilter 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 =minItemsand =maxItems, the items areitem space ( "," space item space ){m-1,n-1}: one item, then between and more, which is to in all. If the whole sequence is optional, which adds the empty array; if the array is"[" space "]".stringwithminLengthandmaxLength:"\"" 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 and optional ones , 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 , possibly empty. A non-empty ordered subset has a first element , after which each later is present or not. So the body is
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 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, for a prompt of 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 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 .
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 of them the stack waiting for c would be frames deep, and the one waiting for the next b .
(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 , , , and one byte of bits is missing. The interval is , 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 . Derive a per-step distribution that is. Let be the probability that the model, continuing from the prefix , produces a complete output in . Show that sampling each token from gives exactly, compute on the Mechanism’s two-step example, and say when the plain mask already equals .
Answer
First, is a distribution. A complete output from must pass through some next token , so , and dividing by shows the sum to 1. Tokens with , the dead ones, get probability 0, so is a mask too, with different weights.
For a complete output in (its last token the end marker), the product over steps telescopes:
, since is already a complete output in , and , the probability of the language from the start. So the product is .
In the example, , , and . So and , and the second step is forced as before: with probability , with , the conditional.
The plain mask samples over the live tokens. It equals exactly when is the same for every live at every step, for instance when every live prefix is completed within 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 in general is 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 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 , the first forbidden and the other two allowed, and top-k with . Grammar first: top-2 of the allowed tokens keeps both, and renormalising gives . llama.cpp’s order: the first draw’s top-2 over all tokens keeps the forbidden token and the first allowed one, renormalised to . 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 . So the first allowed token comes out with probability and the second with , 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 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 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 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
- Brandon T. Willard and Rémi Louf, “Efficient Guided Generation for Large Language Models” (arXiv, 2023). Guided generation as transitions of a finite-state machine, with an index over the vocabulary computed ahead of time; the approach behind the Outlines library, and a different trade from this chapter’s per-step trie walk.
- Saibo Geng, Martin Josifoski, Maxime Peyrard and Robert West, “Grammar-Constrained Decoding for Structured NLP Tasks without Finetuning” (EMNLP, 2023). Grammars as a general interface for structured output, including grammars that depend on the input.
- Kanghee Park, Jiayu Wang, Taylor Berg-Kirkpatrick, Nadia Polikarpova and Loris D’Antoni, “Grammar-Aligned Decoding” (NeurIPS, 2024). The distortion of the Mechanism’s two-step example, and a sampler that converges to the model’s conditional distribution.
- Jay Earley, “An Efficient Context-Free Parsing Algorithm”, Communications of the ACM 13(2), 94–102 (1970). The general parser for any context-free grammar, left recursion included, by sets of partial parses per position; this chapter’s stack sets are the top-down half of the idea.
- Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers: Principles, Techniques, and Tools, 2nd edition (Addison-Wesley, 2006). §2.4 for top-down parsing and left recursion, and §4.3.3 for eliminating left recursion through other rules.
- A. Wright, H. Andrews, B. Hutton and G. Dennis, “JSON Schema: A Media Type for Describing JSON Documents” (draft 2020-12). §10.2.1 for
allOf,anyOfandoneOf. - A. Wright, H. Andrews and B. Hutton (editors), “JSON Schema Validation: A Vocabulary for Structural Validation of JSON” (draft 2020-12).
type,enum,const, the length and item bounds,required, andpattern(§6.3.3). - T. Bray (editor), “The JavaScript Object Notation (JSON) Data Interchange Format”, RFC 8259 (2017). The grammar
JSON_GBNFtranscribes, and the definition of a string’s characters, surrogate pairs included. - llama.cpp (commit
da89bb3):grammars/README.mdfor GBNF and the JSON Schema converter’s stated limits;src/llama-grammar.cppfor the stack recognizer, partial characters and the dead-end exception;common/json-schema-to-grammar.cppandcommon/json-schema.cppfor the converter;common/sampling.cppfor the sample-then-check order and lazy grammars.