Efficient Guided Generation for Large Language Models
Paper · 2023 · Brandon T. Willard and Rémi Louf
Summary
A text generator can produce a plausible answer that a program cannot use. If the program expects a year, a network address, or a fragment of source code, extra prose can make the response unusable even when part of it looks promising. Willard and Louf study how to enforce such requirements while text is being generated by large language models. A decoder can already enforce a format by checking every possible next token and giving incompatible tokens zero probability. The difficulty is that the check repeats after every choice, across a vocabulary that can contain tens of thousands of entries.
The authors use a finite-state machine to represent a regular expression. Its current state records the information about the generated prefix that matters for future matching. During preparation, the algorithm tries each vocabulary string from every relevant state and records where the string can be read. During generation, the decoder uses the current state to look up the permitted tokens and advances the machine when it selects one. The paper gives a cost of O(N) per generated token for checking the whole vocabulary, where N is the vocabulary size. The indexed approach gives an average O(1) lookup for the state’s permitted set. That estimate describes the lookup. The decoder still obtains next-token scores, applies the constraint, and chooses a token.
The authors extend the idea to a context-free grammar. This case has two kinds of progress to track. A generated fragment may be partway through a word or punctuation pattern that the grammar recognizes, while the parser must also remember where that symbol fits into the larger structure. The paper combines finite-state matching for the fragments with the states and stack of an LALR(1) parser. A trie, which shares common beginnings of stored sequences, lets the resulting index match the relevant parts of the parser’s stack. The approach works at the decoder interface, and the authors provide an implementation in Outlines, an open-source Python library.
The Outlines demonstrations use GPT2-medium with 355M parameters. The guided continuations take the form of an answer from a prescribed set, a year with a prescribed digit pattern, and an IP address. The unguided continuations expand into prose. The guided year, 1952, also illustrates the scope of the constraint. It satisfies the pattern, while the pattern itself supplies no evidence about the person’s birth year. In a separate timing comparison for a Python variable-name prompt, Outlines shows more favorable scaling as the generation limit increases than the version of Guidance tested. The paper takes a single timing at each limit. For a slightly extended Python grammar, the authors report an index of around 50 MB even with redundant states and configurations. They also suggest using the masks during training, measuring how much they change a predictor’s scores, and moving them earlier into the network to investigate whether some calculations could be skipped.
Deep dive: Efficient Guided Generation for Large Language Models
Efficient guided generation uses a vocabulary index to enforce regular expressions and grammars without scanning every token at each step. · about 35 minutes to read
The problem and its context
A format requirement changes the next decision
The paper treats text generation as a series of decisions about what to append. At each decision the system has a prefix, meaning all the tokens already present, and a distribution over the tokens it might add. Each vocabulary token represents a string. Once those strings are joined, the result must obey a rule stated over characters or grammatical symbols. The mechanism that selects a token and the mechanism that recognizes a valid string therefore work with different units. That mismatch comes from tokenization.
A regular expression describes acceptable character sequences. It can require particular text, allow alternatives, or permit repetition. A grammar can place rules on how symbols join into larger structures. The paper names formats and languages such as JSON, SQL, and Python as motivations for going beyond the regular-expression case. A consumer that expects any of these structures reads the whole response according to its own rules. The fact that a response contains recognizable code or a plausible data value is of limited help if the rest of the response prevents the consumer from reading it.
A format constraint acts before the complete response exists. Suppose a field requires a fixed beginning followed by a variable number of admissible characters. Part of the fixed beginning can be a useful prefix even if it would fail a test for the full field. A token can finish that beginning and also consume some of the variable part. The decoder needs to allow both kinds of progress. It needs to exclude a token if some character within it makes the required format impossible under the current matching state.
The allowed choices also change over time. As soon as a format has passed a point where some punctuation can occur, the same punctuation may become invalid. Conversely, characters disallowed at the very beginning can be available later. A fixed list of banned tokens cannot express that dependence on its own. A guided decoder needs a way to carry the relevant part of the prefix forward so it can make a different decision when the context changes. The paper’s contribution lies in how it represents that context and retrieves the choices associated with it.
A separate decision concerns when the response may end. A prefix can still lead to a valid answer while being too short to return as one. A prefix can also be a valid answer and still admit further characters. The decoder therefore has to distinguish extension from termination. This distinction matters for a format such as a number, where a shorter prefix may already match and a longer continuation may also match. It matters at the grammar level too, where a word can be finished even though the expression or statement containing it remains incomplete.
Masking had already supplied a way to enforce constraints
The paper situates its problem in earlier work on constrained code generation, incremental parsing, grammar prompting, and prompting interfaces. Its account is that rigid output formats can be difficult or costly to obtain through fine-tuning alone. A decoder that can enforce a separate rule gives the calling program another way to impose a format. One of the cited examples of earlier work on code and structured meaning is Abstract Syntax Networks for Code Generation and Semantic Parsing.
The general enforcement mechanism already existed. The decoder alters the scores used to choose the next token so that incompatible options receive no probability. The allowed options then compete according to the remaining weights. The paper calls the selection of permitted positions a mask. A mask for generating a digit can be simple. A mask for a pattern or grammar changes with each selected token because the last choice can change which part of the rule applies next.
A straightforward implementation tries every token in the vocabulary. It checks whether the current prefix plus that token could still be part of an allowed response. This is sufficient to construct the mask, but it performs a vocabulary-wide check even when few tokens are permitted. The paper describes vocabularies on the order of 10^4 entries or larger. At that scale the mask can be costly even for a short response. The paper cites work on representing text in smaller string units, including Neural Machine Translation of Rare Words with Subword Units.
Partial matching can address the fact that generation produces incomplete strings. The paper points out that one implementation strategy starts that match again at the beginning of the candidate string every time. The cost then has two sources. Every new token requires another pass over the candidate vocabulary, and every trial can include material that was matched in earlier steps. More of the already generated prefix is available to revisit as the output grows. Remembering a match state addresses the repeated processing of old characters. Indexing the match state addresses the repeated search for possible next tokens.
The paper discusses this work against several ways to use next-token probabilities. Greedy decoding repeatedly selects the highest-probability option. Beam search maintains alternatives in a heuristic search for a likely sequence. Ordinary categorical sampling draws a token at random with the given weights. The authors also cite Sequential Monte Carlo Steering of Large Language Models using Probabilistic Programs as prior work on sequence generation. Their own analysis starts from a sampling loop so that it can identify the operation shared by successive draws under a hard format constraint.
A vocabulary-aware automaton was the closest precedent
The authors identify Kuchnik and colleagues’ work on validating language models with relm as the closest precedent for regular expressions. They describe that work as using a transducer formulation to produce state machines defined over the generator’s vocabulary. A transducer relates sequences in different symbol systems. Here the useful relationship is between the character-level description of a format and the tokens available to the decoder. The authors credit that formulation with retaining much of the same information and offering similar scaling advantages.
Willard and Louf organize this information as an index beside the usual regular-expression machine. The machine continues to describe the character transitions. The extra data says which whole vocabulary strings can traverse those transitions from a particular state. Existing matching libraries can consequently supply the underlying automaton, with the index handling the connection to generation. The same design informs the grammar extension. The authors describe augmenting the lexer and parsing operations so that an existing parser can participate in an incremental decoder.
This framing makes the preparation and generation stages distinct. The rule and vocabulary are both known before the next-token loop begins, so questions about whether a vocabulary string fits from a particular state can be answered ahead of time. The actual path followed through the rule is only known as the decoder makes its choices. The index stores the possible transitions. The generated sequence determines which entries the decoder visits.
The method, step by step
From a next-token distribution to an allowed choice
The starting point is a generator trained to continue a token sequence. Its parameters are already available when the constraint is introduced. Each call uses the current token sequence to get weights for the possible next tokens. A categorical draw is a random choice among a finite set of alternatives. In the unguided loop, the decoder appends the result, asks again using the expanded sequence, and ends when it obtains the special end-of-sequence token.
The paper writes the prefix and vocabulary size as follows.
Sₜ = (s₁ … sₜ), sₜ ∈ 𝒱, |𝒱| = N
Sₜ is the prefix after t token positions. Each s with a subscript denotes the token at that position, from s₁ at the beginning to sₜ at the end. The ellipsis stands for the intervening positions. 𝒱 is the vocabulary, and ∈ means that a token is an element of that vocabulary. Vertical bars around 𝒱 mean its size, denoted by N. Parentheses enclose the ordered sequence, and = states an equality or definition.
The vocabulary consists of strings over a fixed character alphabet. The decoder chooses among these strings by token identity. The recognizer reads their characters in order. That distinction explains why a continuation can cross several transitions of a character-level machine in a single draw, or land partway through the spelling of a grammar symbol.
α = LLM(Sₜ, θ)
α is the vector of next-token values. LLM denotes the next-token predictor, Sₜ is its sequence input, and θ stands for the trained parameters. The comma separates the two inputs. The paper places the vector in ℝᴺ, meaning it has N real-valued entries, one for each vocabulary item. The authors describe the predictor in terms of a neural network and allow the method to apply to other next-token predictors with the same distribution interface.
sₜ₊₁ ∼ Categorical(α)
sₜ₊₁ is the next token, with t+1 indicating the position immediately after the current prefix. ∼ means that this token is drawn from the specified distribution. Categorical names the distribution over the vocabulary alternatives, and α supplies the values that determine their probabilities.
The constraint adds a selection between scoring and drawing. The paper uses 𝒫(𝒱) to denote the possible subsets of the vocabulary, with 𝒫 the powerset operator. It also describes the desired samples as sequences ending in EOS, the end-of-sequence token, which belongs to 𝒱. The order of those tokens matters for the string being generated. At each particular position, however, the permitted next choices form a set. The mask turns that set into a vector whose positions line up with the scoring vector.
α = LM(S̃ₜ, θ)
LM is the predictor, using the shorter name the paper adopts in the guided equations. S̃ₜ is the current sequence produced under the guidance rule. The tilde marks a quantity associated with guided generation. θ remains the predictor’s trained parameters, and α is the score vector for this prefix before applying the mask.
α̃ = m(S̃ₜ) ⊙ α
α̃ contains the masked weights. m(S̃ₜ) denotes the mask associated with the guided prefix. It has N positions, with 1 marking an allowed token and 0 marking an excluded one. ⊙ is elementwise multiplication, meaning the mask entry multiplies the score or weight at the corresponding position. In the paper’s distributional description, the result supplies unnormalized weights. The allowed weights must define a usable distribution for the subsequent draw. When a decoder represents its scores as raw logits, the intended effect of the mask is zero probability for the excluded positions after probability conversion.
s̃ₜ₊₁ ∼ Categorical(α̃)
s̃ₜ₊₁ is the next guided token. The sampling symbol ∼ again indicates a draw, and Categorical(α̃) refers to the distribution obtained from the allowed weights. The draw still uses the predictor’s preferences among the admissible tokens. The constraint controls the support, meaning which tokens can occur.
After a choice, the decoder has both an expanded predictor input and a new constraint state. The predictor may respond differently to the full expanded sequence. The constraint can update from the state it already held and the token it just received. Keeping these two updates distinct is what permits the regular-expression index to serve many different prefixes that reach the same state, even if they induce different next-token scores.
Preparing and using the vocabulary index
The steps in order.
Carry a regular-expression match across token boundaries
A finite-state machine represents progress through a regular expression as a position in a network of states. The character being read and the present state determine the next state. Some states indicate that the characters read so far form an acceptable match. Several different prefixes can reach the same state, in which case they have the same future possibilities under the machine. The decoder can carry that state forward as the relevant summary for matching.
M = (Q, Σ, δ, q₀, F)
M names the finite automaton. Q is the finite set of states. Σ is the character alphabet for this machine. δ is its transition function. q₀ is the start state and belongs to Q. F is the set of accepting states, all drawn from Q. The parentheses enclose the components of the automaton. The paper labels states with integers for convenience.
δ: Q × Σ → Q
δ takes a state from Q and a character from Σ and gives the state reached after reading the character. The colon introduces the function’s type. × denotes the Cartesian product, so the input is an ordered pair drawn from the two sets. → points to the set containing the result. When the recognizer cannot continue a match on a character, the token containing that character cannot supply a valid continuation along that path.
To use the machine with a token, the decoder must account for every character in that token. It begins from its saved state, reads the token’s first character, and uses the resulting state for the next character. The end state can then serve as the starting point for whatever token comes next. An allowable token may end while the full regular expression is still incomplete. An accepting end state, by contrast, says that the characters already read can constitute a complete match. Acceptance can coexist with further eligible transitions.
The number-pattern illustration gives a small example of how this bookkeeping affects a mask. At the beginning, in state 0, the sample vocabulary has entries including A, ., 42, .2, and 1. The machine rejects A and allows the numeric fragments and the dot. A draw of .2 takes it to state 3. From that point, when choosing among the illustrated entries, the decoder can add 42 or 1. Those strings keep extending the digits. The alternatives containing a dot would introduce punctuation after the match has already passed that part of the pattern.
Taking 1 first leads to state 1. At that stage the decoder can still choose a dot or a fragment that starts with one. There is a difference between the two prefix states even though both prefixes contain a digit. The feature relevant to the next match is whether the optional decimal point has already been consumed. The state carries that distinction without storing a copy of the previously generated characters for the purpose of matching.
The example also shows why length in tokens has a weak relationship to progress through the recognizer. Both 1 and .2 are single choices in the sample vocabulary. One sets up a position before a possible decimal point. The other both uses the point and adds a following digit. A procedure that advanced the recognizer by one character after each vocabulary choice would lose part of the effect of .2. Treating each token as an entire character path makes the state update correspond to the text actually appended.
Precompute paths from every viable state
Saving the state solves repeated matching of the prefix. It still leaves the question of which vocabulary tokens can extend that state. The authors answer it during preprocessing. They take a vocabulary string and find the paths through the automaton on which the entire string can be consumed. The candidate starting points include the viable internal states, so a string can qualify as the continuation of a pattern even when it would fail at the beginning.
For each valid path, the first state tells the index where that token is an eligible choice. The last state tells the decoder where matching has reached after the token. The intermediate states establish that all of the token’s characters can be read in order. When a token contains several characters, checking only its first character would admit some strings that fail later. Checking only whether the token matches the whole expression in isolation would miss strings that are useful continuations.
The numerical example gives the intuition for indexing interior states. A fragment that contains punctuation can be appropriate early in a match and impossible later. More generally, a token could supply the end of a required literal and the beginning of a following field. Its eligibility is determined by its whole path from the state where it will be used. Running the preprocessing against only the start state would leave the decoder without precisely the information it needs after it has made its initial choice.
σ: Q → 𝒫(𝒱)
σ is the index that associates each finite-state-machine state with a set of tokens. Q is its set of possible keys. 𝒫(𝒱) is the set of all possible subsets of 𝒱, the vocabulary. The arrow gives the direction of the mapping. Looking up a state yields the vocabulary subset eligible from that state. The path information used during preprocessing also determines the end state associated with consuming a chosen token.
The authors propose a hash map for σ. A hash map retrieves a value by its key, in this case the current automaton state. The paper’s O(1) average refers to obtaining the associated set this way. In this notation, O describes the growth of an operation’s cost, and 1 expresses constant growth with respect to the variable in question. The variable here is N, the vocabulary size. The repeated scan has O(N) growth because it examines the vocabulary each time. Obtaining an already computed set avoids that scan.
The size of the retrieved set still matters to operations that consume it. For instance, a decoder that represents its mask as a dense vector still has a vocabulary-sized representation to manage. The index also takes work to construct and memory to retain. The paper distinguishes preparation from repeated sampling, and the constant-average lookup is a claim about the latter. A particular constraint and vocabulary determine what must be precomputed. Each actual generation then determines the order in which the entries are used.
The construction is a preprocessing procedure over the vocabulary and the rule. It adds no parameter-fitting stage and requires no examples of correct responses to infer the constraint. The supplied regular expression defines the allowed structure, the supplied vocabulary defines the strings available to append, and the predictor scores those strings as generation proceeds. The authors implement the regular-expression approach in Outlines.
Preserve an unfinished grammar symbol
Grammars introduce a second distinction between units. A parser uses terminals, the symbols it reads as the leaves of a grammatical structure. A lexer recognizes those terminals in characters. A decoder token may contain part of a terminal, a whole terminal, or text that spans a terminal boundary. Progress in parsing must account for all of these cases.
The paper illustrates the issue with a Python-like function definition. The vocabulary fragments d and ef together spell the keyword def. A fragment containing a space and f follows, so the prefix is def f. A lexer given just this string as its full input could identify the keyword as DEF and the f as a NAME. In the paper’s example, later input supplies oo(. The resulting name is foo, and the opening parenthesis has also arrived inside the same new vocabulary token.
The parser cannot infer from the token boundary after f that the identifier has ended. At that point a matching machine for NAME can be in an accepting state and still allow more identifier characters. One possible continuation stays within the same terminal. Another finishes the identifier and begins the opening parenthesis, which the grammar represents as LPAR. The same prefix therefore supports choices that have different effects on the lexer and parser.
The authors give a small finite-state machine for the identifier. Its start state is 0. State 1 represents having read the initial character of the name. State 2 represents progress through the repeating portion. The paper places both 1 and 2 among the accepting states. It records the paths taken by the character f as follows.
(0, 1), (1, 2), (2, 2)
Each parenthesized pair describes one path for reading f in this illustrative machine. The first entry is the state before reading it, and the second is the state after. 0 is the initial state, while 1 and 2 are the accepting states just described. The commas inside the pairs separate the positions, and those between the pairs separate the possible paths. The character can begin a name, extend a name that has just started, or keep advancing within its repeating portion.
That inventory of paths is useful for lexical questions. It can say whether a piece of a token extends the unfinished name, and whether the machine was in a state where the name could end. The parser supplies a further condition. When the token oo( finishes the name and starts a new terminal, the grammar must allow LPAR at that point. The paper’s example rejects the vocabulary fragment ): after def f. A fragment of that form may appear elsewhere in a function definition. Its eligibility here depends on the current grammatical position.
The authors use small fragments to make the recognition problem visible. The underlying issue persists for the parser whenever input becomes available a little at a time. Committing to a terminal too early can make a valid continuation appear incompatible. Delaying every commitment until the full response is known would withhold the information needed to choose the next token. The proposed configuration records the current progress of recognition and the possible symbols while enough information is still arriving to distinguish them.
Combine lexical progress with parser state
An LALR(1) parser uses a parse state, a stack, and one lookahead terminal to determine its actions. The stack holds information about the parts of a grammatical structure that the parser has processed. When the parser reduces a recognized sequence to a larger grammatical unit, it can remove several stack entries and use the exposed context to continue. That behavior gives the grammar extension more state to account for than the regular-expression case.
The paper uses a pushdown automaton to describe this situation. A pushdown automaton adds a stack to the machinery of a finite-state machine. The stack gives the parser a way to preserve information about surrounding structures while it reads their contents. A query about a vocabulary token can depend on the present parser state, how far the scanner has read into its current terminal, and what the relevant portion of the stack contains.
(Q, Σ, Γ, δ, q₀, F)
This tuple gives the components of the pushdown automaton. Q is the set of parser states. Σ is the automaton’s input alphabet, used here for grammar terminals. The characters in the vocabulary strings are consumed by the separate lexical machines. Γ is the alphabet of symbols that can appear on the stack. δ is the pushdown transition rule, q₀ is the start state, and F is the set of accepting states. Parentheses group the components in order.
δ: Q × Σₑ × Γₑ → 𝒫(Q × Γₑ)
δ takes a current state in Q, an input in Σₑ, and a stack value in Γₑ. The subscript ₑ marks an alphabet extended with ε, the empty symbol. Thus the rule can express steps involving no input symbol or no stack symbol in the corresponding position. × forms the ordered combinations of the indicated sets. 𝒫 is the powerset operator. The result is a set of possible pairs, with a destination in Q and a stack action represented using Γₑ. The arrow separates the input type from the result type.
The authors connect this automaton to the recognizer for individual terminals. In each parser state, the allowed parser actions identify the terminals that may be read. Each terminal has a character-level machine for recognizing its spelling or pattern. The paper combines those machines by union. This gives a scanner for that parser state which can track the possible terminals while reading the characters since the last resolved symbol.
For example, the prefix de is compatible with the beginning of DEF, and the characters can also belong to NAME. The scanner retains both possibilities. Further characters can make the distinction, as in the paper’s contrast between keyword text followed by a space and the identifier default. The scanner’s state therefore conveys both the progress through the available recognition paths and which terminal interpretations remain open.
The paper applies the regular-expression path procedure to the combined machines. For each vocabulary string, it finds the lexical paths that can consume the string from a possible starting position. It then considers parser configurations made up of parser states, lexical states, and candidate terminals. A path within a terminal is part of this calculation. A path can also finish one terminal and require a parser action before the next characters of the same vocabulary string can be read.
Determine which stack contexts admit a token
The next preprocessing question is which contents of the stack make a proposed parser transition usable. The paper approaches this by looking backward through the transition rule. Given a candidate parser state and possible terminal symbols, it collects the stack values from which the required action is available.
δ⁻¹(q, V, ·) ≡ { g : δ(q, v, g) ∈ 𝒫(Q × Γₑ), g ∈ Γₑ, v ∈ V }
δ⁻¹ denotes a preimage query, meaning a search for inputs to the transition rule with the other arguments specified. q is the current parser state, V is the set of possible terminals, and the dot leaves the stack argument open. ≡ introduces the definition. The braces enclose the set of qualifying g values. g is a candidate stack symbol, and v is a terminal drawn from V. The ∈ signs denote membership. 𝒫, Q, ×, and Γₑ have the meanings given for the transition type. In operational terms, the construction keeps a candidate stack value when a required transition is available. A transition set with no actions gives the parser no path to follow.
The test can reach beyond the value on top of the stack. In an LALR(1) REDUCE action, the parser treats material it has already recognized as one grammatical unit. Removing the entries for that material can expose a stack state needed for the next action. A single vocabulary string can require multiple parser steps, so testing whether the parser can consume all its characters can involve a sequence of such stack requirements. The authors describe considering the valid stack prefixes implicated by the reductions for that string.
The resulting entry describes a configuration from which the parser can consume the whole vocabulary string. The whole string in this definition is the proposed next token’s character content. The surrounding generated program or document can still be unfinished. This distinction is important because the index is meant to operate during generation, at positions well before the parser could accept the complete response.
A trie stores sequences by sharing their common beginnings. The paper proposes a trie for the part of the index that must be queried against the stack. A stack query can follow successive values in the relevant order instead of treating every possible stack fragment as an unrelated key. The regular-expression case could use the current lexical state alone as the key. Here the lexer state, the parser state, and the stack context together determine which vocabulary paths are admissible.
The overall decoding procedure remains recognizable across the two cases. The predictor supplies its preferences. The index supplies the allowed choices for the present configuration. The decoder draws from the masked distribution and carries forward the resulting configuration. For a grammar, that update can leave a terminal partially matched, finish a terminal, or take parser actions while consuming one vocabulary string. The authors present these changes as extensions to ordinary lexer and parser operations, so that the underlying machinery can remain available to an existing implementation.
Experiments and results
Paired continuations show what the format controls
The regular-expression examples compare guided and unguided continuations from the same prompts in Outlines. They use GPT2-medium, with 355M parameters, and the examples set a maximum of 30 generated tokens per call. The constraint changes between prompts. The paper uses the resulting strings as demonstrations of form. There is no benchmark split or aggregate accuracy measure associated with the examples.
The arithmetic prompt invites a short judgment. The unguided continuation begins a discussion and carries on into other material. The guided version picks Always from a set of answer forms that also includes yes, no, and never, with capitalization alternatives. This case shows how a format can restrict the answer to a compact set while allowing the predictor to select the actual option. A user who intends to accept only a particular answer would need a rule that expresses that intention or a separate check on the answer’s content.
The birth-year prompt shows a different kind of restriction. The unguided response mentions 1895 in a longer narrative. The guided response is 1952, which has the prescribed year shape. The displayed expression constrains the beginning to 19 and the last digit to 2, with a variable digit in between. The experiment demonstrates that the sampler can stay within this small family of strings. It supplies no factual reference answer, and the regex itself has no way to determine a birth year.
The DNS prompt asks for an IP address. The unguided continuation gives prose about DNS and then drifts away from a usable answer. Guided generation yields 2.2.6.1. Its form makes it usable as a candidate address string, while establishing the address of the requested server would require a separate source of evidence. Across the demonstrations, the observed benefit is a constrained response shape. The examples leave open how the predictor chooses among plausible strings with that shape on a larger set of questions.
Maximum generated tokens by decoding setting in the Outlines prompt demonstrations
The demonstrations use the same token budget for unguided and regular-expression-guided continuations.
The numbers
| System or setting | maximum generated tokens |
|---|---|
| Unguided continuation | 30 |
| Regular-expression-guided continuation (this paper) | 30 |
The chart compares the configured token limits. A lower limit in this setting means a smaller generation budget, and the equal values keep that budget fixed across the paired examples. The limit measures how many tokens a call may generate. The reported continuations show the kind of output produced under each setting, and the paper’s latency comparison uses a separate setup.
Runtime of a guided variable-name continuation
The timing experiment compares Outlines with the Guidance library for a prompt asking for a suitable Python variable name. Both use the gpt2 configuration in the code shown for this comparison, with CUDA as the device and a temperature of 0.1. Temperature is a sampling setting that affects how concentrated the token choices are. Both systems use a regular expression intended to guide the continuation into an identifier-like string. The paper gives 50,257 as the vocabulary size scanned at each Guidance step.
The tested version of Guidance applies a partial regex match from the beginning of the sampled sequence. It tries that check across the vocabulary as generation proceeds. Outlines uses the current state and the precomputed index. The comparison therefore places the two sources of repeated matching work together on the Guidance side, searching through candidates and processing earlier characters. The Outlines side uses a different route to the mask in the normal generation call.
The code disables caching in both setups. It also turns off the Guidance library’s option called token healing. In Outlines the guided continuation is created before the timed call, and the wrapper clears its saved parser states before obtaining a continuation. That reset makes the call start with a fresh generation state. The paper varies max_tokens, the upper limit on the length of the continuation, and takes one timing sample at each limit with timeit.
The measured quantity is runtime for the specified generation call. The paper describes a marked difference in how the compared runtimes grow with the maximum number of generated tokens, favoring Outlines in the reported setup. The timing values are presented graphically in the paper. It gives no numerical minute, second, or speedup values in the text. The stated vocabulary size and temperature describe the setup and should be read independently of the latency result.
The timing boundary matters for interpreting this comparison. Creating the Outlines continuation ahead of the call places setup outside the metric. The experiment addresses what happens once the indexed continuation is ready to use, which is where the authors intended to reduce repeated masking work. It supplies a practical observation for the particular prompt and libraries. The observed growth with the configured cap also concerns that cap. The cap is an upper bound, and the paper gives no separate tally of realized tokens for each timed call.
Memory for the grammar index
The grammar extension has a quantitative observation of a different kind. The authors report an index of around 50 MB for a slightly augmented Python grammar. The figure measures the size of the constructed index. It is independent of the token limit used for the regular-expression demonstrations and the runtime comparison with Guidance.
The reported index contains unused and redundant parser and lexical-machine configurations. Its deterministic finite automata, or DFAs, are unreduced. An unreduced DFA can retain states that could be combined while preserving the decisions the machine makes about which strings it recognizes. The reported memory result therefore comes from a construction with redundant material still present.
This result gives a concrete size for one fairly involved grammar under the authors’ construction. The paper supplies neither a parallel latency run for that grammar nor measurements over several grammars. Its Python-like walkthrough explains how fragment handling and parser transitions can be incorporated into the index. The memory observation indicates the scale of a resulting index in the authors’ tests. These pieces of evidence address different questions about the grammar extension.
What the ablations show
The paper reports no component ablations and instead offers paired guided and unguided examples, a timing comparison between implementations, and an index-size observation for an unoptimized grammar construction.
The paired continuations make one effect easy to see. Holding the prompt and generation cap fixed in the examples, the guided calls return text in the required shape. The unguided calls can continue into prose. The comparison illustrates what the mask changes at the level of output. Any correct implementation of the same allowed choices could impose those shapes, including an implementation that checks the whole vocabulary. The paired examples therefore give evidence about guidance. The separate runtime comparison concerns the way those choices are found.
The timing comparison shows the combined effect of the implementations as configured. There are two conceptual changes in the paper’s design. Saving the state allows partial matching to resume from the current position. Precomputing the set of available tokens avoids discovering that set afresh at every step. The design explains how each saves work. The plotted experiment changes both at once, along with the surrounding library code. It cannot allocate a share of the observed runtime gap to each change. A measurement with retained state and a full vocabulary scan would address a different question from the comparison reported.
The small automaton example helps isolate the reasoning behind the state representation even though it is a walkthrough rather than a measured intervention. After the decimal point has been consumed, tokens containing a decimal point are ruled out. At an earlier position, some of those same tokens can be used. A state-specific mask captures this difference. The effect follows directly from how the paths are recorded. The walkthrough gives a reason to expect these changes in the allowable choices, independent of any next-token preferences.
The identifier example likewise shows why a configuration needs to distinguish an unfinished lexical match from a completed terminal. At def f, the name can extend inside the current terminal or end immediately before an opening parenthesis. A decoder can take oo( because it accounts for both effects in order. This example exposes a case where a check of terminals alone would miss relevant information about the partly consumed characters, and where a check of lexical form alone would lack the parser context for the parenthesis. It motivates the combined configuration without reporting an error rate for simpler alternatives.
The memory observation answers whether an index with redundant states can have the reported size in the tested Python setup. The authors mention reducing deterministic machines or considering other state-machine representations as routes to lower storage use. They do not measure what those changes would save. In particular, the 50 MB figure cannot be used as an estimate of the savings from reducing the machines. It is an observation about the unreduced construction.
Taken together, the analyses give different kinds of support for different parts of the proposal. The examples make specific acceptance decisions intelligible. The timings measure an implementation-level outcome under a particular workload. The memory result provides a size for a grammar index constructed with redundancies. There is no experimentally isolated comparison for the trie, the retention of lexical alternatives, or the way stack prefixes are enumerated.
Limitations
Bounds and qualifications the authors state
The paper presents indexing as a tradeoff between computation during generation and storage. Moving work out of the sampling loop makes the timed call cheaper, while preparation still has to enumerate relevant vocabulary paths and store the result. The authors expect many practical patterns to use a limited portion of the possible state and token combinations. Some combinations can have more complicated or larger indexes. The Python observation is their example of the tradeoff in one setting.
The authors note that their index still contains unnecessary entries and that the deterministic machines used to build it have redundant states. They suggest that standard reductions could lower the storage requirement. They also mention nondeterministic finite automata as another possible representation if memory becomes a concern. Such a machine can represent alternative matching paths for the same input. The paper leaves measurements of these alternatives for future investigation.
The authors qualify the timing comparison by acknowledging that a configuration issue could affect the size of the gap. Their procedure collects one measurement per token limit, which gives no estimate of run-to-run variation at each setting. The statement about scaling is consequently tied to the code and workload they report. The paper introduces the comparison as an illustration of the repeated computation it analyzes.
The discussion proposes several extensions beyond the tested procedure. Masks might assist training or fine-tuning when structured output is required. Comparing raw and masked scores might reveal how much a predictor’s own preferences depart from the allowed set. The authors also consider supplying the mask earlier in the network so that it could influence which computations are performed. The implementation described applies the constraint at the output-scoring stage. The paper gives no measured training benefits or network-level computation savings.
Limits of the design and experiments
The constant-average estimate concerns the hash-map retrieval of a state’s token set. It leaves the cost of producing the next-token distribution, sampling, updating state, and representing the mask to the rest of the implementation. Set size also matters if the contents need to be enumerated or transferred. The estimate should therefore be read as an improvement to a specific operation whose former cost depended on inspecting the entire vocabulary at every step. The grammar extension adds stack queries and parser work, whose cost the regular-expression hash-map estimate does not characterize.
A ready index also presupposes a particular rule and vocabulary. Changing either can change which strings are acceptable from each state. That matters to the practical end-to-end cost if applications need to prepare many distinct constraints or use a constraint only briefly. The timed call leaves preparation outside its boundary. The paper does not measure index-build latency across constraints or how much generation is needed to offset it. The reusable part of the design is clear. The reuse achieved by any particular deployment depends on its workload.
Validity depends on how the constraint is specified and when the decoder stops. A regular expression can require a shape while permitting unsuitable content. A grammar can accept a syntactically well-formed statement with meaning that the user never intended. The demonstrations make the distinction visible. The year pattern says which digit strings may be sampled. The address pattern says how an address-shaped answer may be written. Neither experiment evaluates an external fact. An application with facts or other meaning-level requirements would need to express or check them separately.
There is also a distinction between an allowed prefix and a finished response. Recognition state helps the decoder preserve paths that are still eligible. A complete output requires the decoder to stop at a point the rule accepts. A generation cap can interrupt a prefix whose grammar still expects more material. The examples give a cap and show completed outputs, while the paper leaves the handling of an incompatible stopping limit or an empty set of available tokens mostly outside the evaluation. The presence of an acceptance rule and the behavior of the caller at the stopping boundary both matter to the resulting guarantee.
The masked sampling equations specify how to choose the next token among the presently admissible options. They do not account for the total probability of valid future completions behind each option. For instance, two tokens can both enter legal prefixes while the predictor assigns very different probabilities to their later valid continuations. Applying the mask now preserves both options according to their masked next-token weights. An algorithm sampling from the original distribution conditioned on validity of the entire finished sequence would have to consider the probabilities of those futures. The paper evaluates local guidance for form and efficiency, instead of making claims about that sequence-level distribution.
The timing setup supplies one prompt, one pattern, and one configured predictor. It gives a comparison between two library implementations under those conditions. Actual output lengths, multiple timing runs, and different patterns would be needed to distinguish several potential explanations for the size of the observed gap. The paper’s algorithmic argument supplies the basis for expecting fewer repeated matching operations. Its experiment supplies an observation of runtime in one environment. Keeping those claims at their respective scopes avoids treating the comparison as a general speed estimate.
Finally, the grammar example is a construction based on LALR(1) parsing and terminal recognizers. The paper names several applications for grammar-constrained generation and gives a Python-based memory observation. It does not present a coverage study across those formats, a grammatical validity benchmark, or a measured rate of successful complete generation. The reader can trace why an index entry records a permitted parser path through the characters of a token. Performance and coverage for a particular larger grammar remain questions about that grammar, its lexer, the predictor’s vocabulary, and the way the resulting decoder is configured.
What came after
The subsequent citing work takes up several problems that arise once generation can be made to follow a specified structure. The titles identify work on executing programs that include generation, benchmarking schema-constrained output, training for adherence, and using structured responses in extraction tasks. A citation establishes a connection in the research literature. The particular implementation choices and experimental outcomes of these works are separate questions from the topics identified by their titles.
SGLang studies efficient execution for programs built around structured generation. Willard and Louf locate a specific expense inside the decoding loop, where a system has to translate a format constraint into choices for the next token. The execution problem named by SGLang has a wider unit of work, the program containing the generation calls. Its connection to the earlier paper is the need to make structure affordable as part of execution. The citing title identifies that larger program-level scope without specifying which index or parser it uses. SGLang
JSONSchemaBench makes structured outputs the subject of a benchmark. This brings evaluation to the foreground. The earlier paper illustrates enforcement with particular prompts and a regular expression at a time, plus a grammar construction. A schema benchmark asks how structured-output methods are evaluated when the schema itself is part of the problem being tested. The title identifies that shift towards systematic assessment. It gives no basis for assigning a measured schema coverage rate or runtime to the Willard and Louf method. JSONSchemaBench
Think Inside the JSON studies a reinforcement strategy for strict schema adherence. Its stated approach is relevant to Willard and Louf’s suggestion that guidance and training for structure might interact. Here there are two distinct points of intervention. An indexed mask changes the available choices at decoding time, while an adherence objective concerns the behavior the predictor learns. The later title identifies reinforcement as its direction. It does not establish that its training strategy incorporates the earlier vocabulary index. Think Inside the JSON
The survey on generative information extraction places generation in the service of recovering information from text. This setting has both a structural and a substantive requirement. A consumer may need fields it can read reliably, and the fields have to contain information supported by the input. The earlier paper describes a mechanism for the first requirement. The citing survey’s subject places that mechanism in a broader area where the second requirement is central. The survey title indicates the field it covers, without specifying which extraction systems employ constrained decoding. Large Language Models for Generative Information Extraction
The work on decoding and meta-generation frames inference-time algorithms as an area of study in its own right. Inference time is the stage at which a trained predictor is used to produce an answer. Willard and Louf’s mask is an intervention at that stage. It changes the token choices as the answer is generated and leaves the trained parameters available to score them. The later work names a wider range of inference-time approaches, giving the earlier method a place in a broader discussion of how a generation procedure can affect an answer. From Decoding to Meta-Generation
DeAL focuses on alignment at decoding time. Its relation to the earlier paper is the location of the intervention, the process of choosing an output from a trained predictor. In Willard and Louf’s case, the intended behavior is specified as membership in a formal language. Alignment names a broader objective for the output’s behavior. The title gives the aim and the stage at which DeAL intervenes. It does not describe the criterion as a regular expression or grammar, or establish that the two works implement their controls with the same mechanism. DeAL
DocUA at CRF Filling names schema-guided reasoning condensation and deterministic compilation as parts of its approach. That framing connects a structured-output requirement to an application where generation and the construction of the final form are both part of the job. The earlier paper puts a rule directly into the next-token decision. The later title places schema guidance alongside a deterministic compilation step. This gives the two works a common concern with the path from generated text to a required artifact, while the title alone leaves the connection between their implementations unspecified. DocUA at CRF Filling
Cite
Cite as Brandon T. Willard and Rémi Louf. 2023. Efficient Guided Generation for Large Language Models. arXiv:2307.09702.
@misc{willard2023efficient,
title = {{Efficient Guided Generation for Large Language Models}},
author = {Brandon T. Willard and Rémi Louf},
year = {2023},
doi = {10.48550/arxiv.2307.09702},
eprint = {2307.09702},
archivePrefix = {arXiv},
url = {https://doi.org/10.48550/arxiv.2307.09702}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/willard-2023-efficient-guided-generation-large-language/
References
- Luca Beurer-Kellner, Marc Fischer, and Martin Vechev. Prompting is programming: A query language for large language models. Proceedings of the ACM on Programming Languages, 70 (PLDI):0 1946–1969, 2023. OpenAlex ↗ · Scholar ↗
- Yihong Dong, Ge Li, and Zhi Jin. CODEP: Grammatical Seq2Seq Model for General-Purpose Code Generation. In Proceedings of the 32nd ACM SIGSOFT International Symposium on Software Testing and Analysis, ISSTA 2023, pages 188–198, New York, NY, USA, July 2023. Association for Computing Machinery. ISBN 9798400702211. . OpenAlex ↗ · Scholar ↗
- Saibo Geng, Martin Josifosky, Maxime Peyrard, and Robert West. Flexible Grammar-Based Constrained Decoding for Language Models, May 2023. OpenAlex ↗ · Scholar ↗
- Michael Kuchnik, Virginia Smith, and George Amvrosiadis. Validating large language models with relm. Proceedings of Machine Learning and Systems, 5, 2023. OpenAlex ↗ · Scholar ↗
- Alexander K. Lew, Tan Zhi-Xuan, Gabriel Grand, and Vikash K. Mansinghka. Sequential Monte Carlo Steering of Large Language Models using Probabilistic Programs. arXiv preprint arXiv:2306.03081, 2023. our card
- Rémi Louf and Brandon T. Willard. Outlines: Generative Model Programming. URL https://github.com/normal-computing/outlines. OpenAlex ↗ · Scholar ↗
- Microsoft. Guidance. Microsoft, July 2023. URL https://github.com/microsoft/guidance. OpenAlex ↗ · Scholar ↗
- Gabriel Poesia, Oleksandr Polozov, Vu Le, Ashish Tiwari, Gustavo Soares, Christopher Meek, and Sumit Gulwani. Synchromesh: Reliable code generation from pre-trained language models. arXiv preprint arXiv:2201.11227, 2022a. OpenAlex ↗ · Scholar ↗
- Gabriel Poesia, Oleksandr Polozov, Vu Le, Ashish Tiwari, Gustavo Soares, Christopher Meek, and Sumit Gulwani. Synchromesh: Reliable code generation from pre-trained language models, January 2022b. OpenAlex ↗ · Scholar ↗
- Maxim Rabinovich, Mitchell Stern, and Dan Klein. Abstract syntax networks for code generation and semantic parsing. arXiv preprint arXiv:1704.07535, 2017. our card
- Alec Radford, Jeffrey Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. Language models are unsupervised multitask learners. OpenAI blog, 10 (8):0 9, 2019. OpenAlex ↗ · Scholar ↗
- Matt Rickard. parserLLM, July 2023a. URL https://github.com/r2d4/parserllm. OpenAlex ↗ · Scholar ↗
- Matt Rickard. R2d4/rellm: Exact structure out of any language model completion., 2023b. URL https://github.com/r2d4/rellm. OpenAlex ↗ · Scholar ↗
- Torsten Scholak, Nathan Schucher, and Dzmitry Bahdanau. PICARD: Parsing incrementally for constrained auto-regressive decoding from language models. arXiv preprint arXiv:2109.05093, 2021. OpenAlex ↗ · Scholar ↗
- Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words with subword units. arXiv preprint arXiv:1508.07909, 2015. our card
- Michael Sipser. Introduction to the Theory of Computation. International Thomson Publishing, 1996. OpenAlex ↗ · Scholar ↗
- Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, \Lukasz Kaiser, and Illia Polosukhin. Attention is all you need. Advances in neural information processing systems, 30, 2017. our card
- Bailin Wang, Zi Wang, Xuezhi Wang, Yuan Cao, Rif A. Saurous, and Yoon Kim. Grammar Prompting for Domain-Specific Language Generation with Large Language Models, May 2023. OpenAlex ↗ · Scholar ↗
- Lilian Weng. Controllable Neural Text Generation, January 2021. URL https://lilianweng.github.io/posts/2021-01-02-controllable-text-generation/. OpenAlex ↗ · Scholar ↗