Grammar-Aligned Decoding

Authors: kanghee  park
jiayu  wang
taylor  berg-kirkpatrick
nadia  polikarpova
loris d ' antoni
-  madison
Venue: NeurIPS_cc_2024_Conference
Published: 2024-05-14 22:02:11

Abstract: Large Language Models (LLMs) struggle with reliably generating highly structured outputs, such as program code, mathematical formulas, or well-formed markup. Constrained decoding approaches mitigate this problem by greedily restricting what tokens an LLM can output at each step to guarantee that the output matches a given constraint. Specifically, in grammar-constrained decoding (GCD), the LLM's output must follow a given grammar. In this paper we demonstrate that GCD techniques (and in general constrained decoding techniques) can distort the LLM's distribution, leading to outputs that are grammatical but appear with likelihoods that are not proportional to the ones given by the LLM, and so ultimately are low-quality. We call the problem of aligning sampling with a grammar constraint, grammar-aligned decoding (GAD), and propose adaptive sampling with approximate expected futures (ASAp), a decoding algorithm that guarantees the output to be grammatical while provably producing outputs that match the conditional probability of the LLM's distribution conditioned on the given grammar constraint. Our algorithm uses prior sample outputs to soundly overapproximate the future grammaticality of different output prefixes. Our evaluation on code generation and structured NLP tasks shows how ASAp often produces outputs with higher likelihood (according to the LLM's distribution) than existing GCD techniques, while still enforcing the desired grammatical constraints.

Main paper: 
 introduction: 
 Despite their remarkable success, pre-trained Large Language Models (LLMs) often struggle with generating highly structured outputs, such as program code, configuration files, or mathematical formulas. A naïve approach to enforcing structure is rejection sampling, which repeatedly samples strings from the LLM and checks them against a validity oracle, typically in the form of a contextfree grammar (CFG). Rejection sampling is highly inefficient or simply intractable for restrictive grammars and long output sequences-i.e., most generated strings will not be in the target grammar.Constrained decoding addresses the inefficiency of rejection sampling by greedily "forcing" the LLM output to satisfy the given constraint. Specifically, when the constraint is given as a grammar, grammar-constrained decoding (GCD) [7, 27, 28] , can build automata that allow for on-the-fly masking of tokens that will provably lead to outputs outside of the grammar during decoding.While GCD does not incur the overhead of rejection sampling-i.e., the generated output is always in the language of the grammar-we show that GCD and in general all forms of structured decoding introduce a new problem: structured decoding distorts the LLM's learned language distribution, effectively hindering the LLM's capabilities. This paper introduces and formalizes grammar-aligned decoding (GAD), the problem of sampling from an LLM so that the outputs (1) are guaranteed to adhere to a given grammar, and (2) are unbiased wrt. the LLM's distribution. Although exact GAD is intractable in general (similar to rejection sampling), we propose a new adaptive decoding algorithm for approximate GAD, which starts off as GCD and gradually converges to the LLM's distribution, and thus allows trading off between efficiency and accuracy. The algorithm, which we dub Adaptive Sampling with Approximate Expected Futures (ASAp), is built "on top" of existing constrained decoding algorithms. Whereas GCD approaches simply mask out tokens that lead to non-grammatical sequences for a given prefix, ASAp remembers for all sampled prefixes the probability associated with masked-out tokens and uses it to upper bound the probability of grammaticality. By updating this bound when more samples are observed, the decoding algorithm converges to the desired probability distribution-i.e., it samples outputs from the LLM-induced probability conditioned on the outputs being accepted by the grammar. The idea works for any structured decoding approach and not just for GCD, but in this paper we focus our evaluation on constraints expressed via grammars.We evaluate ASAp on two structured prediction tasks: formal program synthesis and constituency parsing. Our experiments on program synthesis and NLP tasks show that GCD techniques generate outputs that are grammatical but unlikely according to the LLM, while with ASAp, the likelihood of the generated outputs improves over time, converging to the target constrained LLM-i.e., GAD better respects the LLM while still enforcing the constraints. 
grammar-aligned decoding: 
 In this section, we formalize the problem of grammar-aligned decoding (GAD) as decoding from an autoregressive language model while enforcing the output sequence to be accepted by a given context-free grammar. We also demonstrate the limitations of existing approaches to this problem.Language Models An (autoregressive) language model defines a probability distribution P on the set of all strings w ∈ Σ * over a vocabulary of tokens Σ via a product of left-to-right next-token conditional distributions P (w 1 . . . w n ) = Π n i=1 P (w i | w 1:i-1 ).S ::= 00000 | 1A 2 A i ::= 0A i+1 | 1A i+1 , for i = 2, 3, 4 A 5 ::= 0 | 1 This grammar accepts the string 00000 and all length-5 strings that start with a 1.A context-free grammar (CFG) is a quadruple G = (Σ, N , S, R), where Σ is a vocabulary of tokens (also called terminal symbols), N is a finite set of non-terminal symbols, S ∈ N is the starting non-terminal, and R is the set of production rules. An example CFG is shown in Fig. 1 . A grammar G defines a single-step derivation relation on sequences of symbols α, β, γ∈ (N ∪ Σ) * : αAγ ⇒ αβγ if A → β ∈ R.The reflexive transitive closure of this relation is called derivation and written ⇒ * . A sequence of tokens w is a sentence if it is derivable from S; the set of all sentences is called the language of the grammar G, that is,L(G) = {w ∈ Σ * | S ⇒ * w}.The following example illustrates these definitions.Example 1 (CFG Derivations). Given the CFG G sk shown in Fig. 1 , the string 00000 belongs to the language L(G sk ) because it can be derived using the derivation S ⇒ 00000. The string 10101 is also in L(G sk ) and can be derived as follows:S ⇒ 1A 2 ⇒ 10A 3 ⇒ 101A 4 ⇒ 1010A 5⇒ 10101 Each step replaces a nonterminal symbol using a production rule in G sk -e.g., in the string 10A 3 , the nonterminal A 3 is rewritten as 1A 4 by applying the rule A 3 → 1A 4 , resulting in the string 101A 4 .In addition, we define the prefix language of G as the set of all prefixes of sentences in L(G):L prefix (G) = {w ∈ Σ * | wv ∈ L(G)}.Grammar-Aligned Decoding Given a model distribution P and a CFG G, grammar-aligned decoding (GAD) is the task of sampling from the distribution Q P,G that is proportional to P but restricted to sentences in G:Q P,G (w) = 1[w ∈ L(G)] • P (w) w ′ 1[w ′ ∈ L(G)] • P (w ′ )When P and G are clear from context, we will write Q(w) instead of Q P,G (w). Example 2 (GAD). Consider the distribution P that arises from prompting an LLM to "generate a binary string that ends with a 1". We expect P to assign high probability to strings of the form (0 | 1) * 1-i.e. those that satisfy the prompt (Mixtral-8x7B-Instruct-v0.1 (temperature=1) generates binary strings that end with a 1 around 90% of the time.) A snippet of a possible distribution P is depicted in Fig. 2 .Suppose we constrain the model's output to the language of the grammar G sk in Fig. 1 , which only accepts strings of length 5. Moreover, G sk only accepts one string that starts with 0, i.e., 00000, which does not end with 1. In Fig. 2 , the grayed out parts of the trie are tokens that lead to sequences outside of the grammar G sk . According to the definition of GAD, the target sampling distribution Q P,G sk should assign: (i) high probability to all eight strings of the form 1w 2 w 3 w 4 1-which conform both to the grammar and the prompt; (ii) low probability to the string 00000-which conforms to the grammar but not the prompt; and (iii) zero probability to all other strings.… (0.1) … (0.1) … 0 (0.45) 0 (0.45) 0 (0.45) … 1 (0.3) … (0.1)1 (0.3) 1 (0.3) 1 (0.3) … $ (10 -8 ) … … … $ (0.3) … … … … … … Figure 2:Fragment of the conditional model distribution P for Ex. 2 depicted as a trie. Each node corresponds to a prefix w1:i-1, and each edge is annotated with the next token wi and its conditional probability P (wi | w1:i-1).Filled nodes are complete strings. Grayed out parts of the trie are outside of the grammar G sk .Exact GAD Can one exactly sample from Q P,G ? Rejection sampling, which repeatedly draws from P until a sample lands in L(G), provably yields exact samples according to Q P,G , but if P assigns most of its mass outside of L(G), it is intractably slow, especially if the prompt is not including information about the grammar (see [27] ). For Ex. 2, rejection sampling would be highly inefficient because the model would generate many strings that are not of length five.In contrast, exact sampling from P is efficient because its joint distribution is represented by a product of easily computed left-to-right conditionals, enabling ancestral sampling (i.e., generating tokens left to right, conditioned on already generated tokens). Can we similarly factor Q into a product of left-to-right conditionals Q P,G (w i |w 1:i-1 ), to enable ancestral sampling?For simplicity, let us assume that P is a distribution over sequences of exactly length n (although, in practice, language models can produce 'stop' tokens which allow for a valid distribution on sequences of all lengths). The exact conditionals of Q P,G are given by:EQUATIONThus, exact left-to-right sampling from Q P,G consists of sampling from model conditionals P (w i | w 1:i-1 ), with an additional weighting term c(w1:i ) = E P (wi+1:n|w1:i) [1[w ∈ L(G)]] that considers the grammar.We refer to c(w 1:i ) as expected future grammaticality (EFG), i.e. the probability that a continuation of w 1:i sampled from P lands in L(G). Using this notation, we can write the exact left-to-right sampling conditional explicitly as:EQUATIONTo see why computing this conditional is intractable, consider using dynamic programming to compute c(w 1:i ) by marginalizing over a product of potential functions: the set of model conditionals and an indicator potential for the grammar. While the indicator potential can be factorized across rules in the grammar, the model's contribution generally does not factorize: in practice, the final conditional probability P (w n | w 1:n-1 ) is a global potential function, defined by a non-linear neural network touching every variable. Thus, the main goal of this paper is to develop effective approximations to the EFG c(w 1:i ), which would enable us to compute the left-to-right conditionals of Q.Limitations of Grammar-Constrained Decoding Existing work [27, 28] has proposed grammarconstrained decoding (GCD) as a way to efficiently sample from an autoregressive language model subject to grammar constraints. Although the exact details of these techniques vary depending on class of grammars they support, the common thread is that they rely on an incremental parser, which can efficiently check whether a given string w is a prefix of a sentence in the grammar, i.e., w ∈ L prefix (G). When given a sentence w 1:i-1 , GCD techniques use this parser during decoding to mask out any next token w i that results in a prefix w 1:i for which no completion will produce a sequence in the grammar. Using the trie in Fig. 2 as an example, one can think of GCD as sampling a path through the trie by selecting only among the black outgoing edges from every node, proportional to their conditional probabilities in the diagram (e.g. the first token is 0 or 1 with equal probability).In terms of the GAD problem, we can view GCD as approximating the exact left-to-right conditionalsQ P,G (w i | w 1:i-1) by the conditional distribution QGCD (w i | w 1:i-1 ), defined as follows:QGCD (w i | w 1:i-1 ) = P (w i | w 1:i-1 ) • 1[w 1:i ∈ L prefix (G)] w ′ i P (w ′ i | w 1:i-1 ) • 1[w 1:i-1 , w ′ i ∈ L prefix (G)]Though not originally formulated in this way, we can view recent work on GCD [27, 28] as forming a binary approximation 1[w 1:i ∈ L prefix (G)] to the EFG c(w 1:i ). In other words, while GCD considers the possibility of future grammaticality, it makes no attempt to integrate the model's likelihood to estimate expected future grammaticality, which can lead to substantial bias in the sampling distribution-i.e., every EFG such that c(w 1:i ) > 0 will simply be approximated via the value 1.Example 3 (GCD). Consider again the GAD problem from Ex. 2, where our target sampling distribution Q P,G sk assigns high probability to strings that both start and end with a 1 and a low probability to the string 00000. However, we observe that GCD [8] generates strings ending with a 1 only 30% of the time-i.e., GCD has effectively ruined the LLM's ability to follow the prompt by biasing sampling towards 00000, an incorrect output.When generating the first token (0 or 1), the GCD algorithm does not know how many grammatical strings can start with each character and, more importantly, how likely these strings are under P . Since both tokens 0 and 1 have the possibility of leading to a grammatical string, GCD will estimate their expected future grammaticality as 1, and choose each of them roughly half of the time (since P (0) ≈ P (1)). Once GCD has chosen 0, however, it becomes "trapped" in the part of the search space where the only grammatical string is the low-probability sequence 00000.Ex. 3 illustrates how existing GCD approaches can hinder the language model's abilities to explore the space of possible outputs according to the learned distribution, thus highlighting the importance of designing a better approximation to the EFG c(w 1:i ); this is addressed in the next section.3 Adaptive Sampling with Approximate Expected Futures (ASAp)In this section, we propose an adaptive sampling algorithm that iteratively builds better approximations of the future grammaticality of a sequence. Our procedure operates by sampling repeatedly, each time bounding lost probability mass to provably ungrammatical areas of the search space in order to better guide the next sampling iteration. As a result, our algorithm converges over many iterations to exact samples from the constrained LLM distribution, allowing for a flexible trade-off between efficiency and accuracy.Overview of the Algorithm GCD approaches poorly approximate the desired distribution because they greedily sample prefixes without worrying about the EFG. When sampling the first token in Ex. 3, GCD simply uses the likelihood for tokens 0 and 1 assigned by the LLM without considering the probability that these next tokens would result in grammatical completions if sampling were unconstrained-i.e. without incorporating the critical EFG re-weighting terms that are necessary for unbiased sampling from the constrained LLM distribution. However, if GCD ends up sampling 0 as the first token for Ex. 3, it will necessarily sample the string 00000 since no other sequences starting with 0 are allowed by the grammar. We can "learn" from this result: the true probability mass assigned to all grammatical sequences starting with a 0 is not 0.45 as the LLM's next token probability would have us believe; instead, the total grammatical mass in this section of the search space is the joint probability of the single string 00000, which is the much lower value of 0.45 5 * 10 -8 as depicted in Fig. 3 . In other words, simply by sampling 00000, we can better approximate (in this case, exactly) the EFG of tokens along this path.1 (0.3) 1 (0.3) 1 (0.3) 1 (0.3) $ (0.3) *0.3 *0.09 + 0.3 *0.12 + 0.3 *0.13 + 0.3The key insight behind our algorithm, which we call ASAp, is that we can iterate this process of discovering lost grammatical probability mass by repeatedly sampling and revising transition weights after each sample is produced. More formally, we can think of this procedure as starting with GCD's over-approximation to each EFG c(w 1:i ) term, and then, through repeated sampling and discovery of mass assigned to non-grammatical completions, reducing each overapproximation to make it more accurate. In the limit, the approximations converge to exact EFG estimates and unbiased sampling.Two possible first iterations of the ASAp algorithm are depicted in Fig. 3 . In the first iteration (left of Fig. 3 ), after sampling the sequence 00000, the algorithm directly addresses the issue that arose in Ex. 3 by attempting to better approximate the probability mass of potential grammatical completions of each prefix of 00000 (red quantities). For example, the expected future grammaticality of the prefix 0000 it is now 0.45 * 10 -8 -i.e., the algorithm effectively "looks ahead" to determine that only one valid (but low probability) string 0$ that can follow 0000. The ideas developed in GCD allow us to efficiently compute, for a given string, the likelihood of the next tokens that will immediately result in non-grammaticality.If we only sample one string from the LLM, we cannot hope to do better than GCD in terms of sampling faithfully in a grammar-aligned way. However, if we were to now sample once more, we could now better direct our sampling strategy. In the second iteration (right of Fig. 3 ), the string 11111 is sampled and the expected future grammaticality is updated (red quantities). Note that at this point the probabilites assigned to the string 00000 from the earlier iteration have already been updated. By repeating the above approach multiple times (i.e., by producing more samples), the ASAp algorithm produces precise approximations of the expected future grammaticalities and thus better samples from the constrained LLM.The key quantity that the algorithm approximates based on past samples is the expected future grammaticality (EFG) c(w1:i ) = E p(wi+1:n|w1:i) [1[w ∈ L(G)]].At iteration m + 1, our algorithm uses the set of samples S = {s 1 , . . . , s m } observed so far to compute an overapproximation cS (w 1:i ) of c S (w 1:i ) for every possible string w 1:i . The overapproximation is inductively defined:cS (w 1:i ) = 1[w 1:i ∈ L prefix (G)]no string in S starts with w 1:i cS (wEQUATIONIntuitively, if no samples in S start with the prefix w 1:i , then cS (w 1:i ), the overapproximation of EFG is simply whether the string is or is not a valid prefix in the grammar-i.e. the same overapproximation used by GCD. If, on the other hand, we have encountered the prefix w 1:i before in previous samples in S, the overapproximation uses the next token likelihoods that were computed during the previous sampling runs of the algorithm to compute a better estimate of EFG.For example, in Fig. 3 , once we have sampled the sequences 00000 and 11111, we have that cS (0000) = 0.45 * 10 -8 and cS (110) = 1 (i.e., we have not seen a sample with the prefix 110 yet).Theorem 1. ∀w 1:i ∈ Σ * , cS (w 1:i ) ≥ c(w 1:i ).Proof. To see that cS (w 1:i ) is indeed an upperbound on c(w 1:i ), consider two cases: First, suppose w 1:i is not a prefix of any string in S. In this case, cS (w1:i ) = 1[w 1:i ∈ L prefix (G)]and, like GCD, provides a trivial upper bound. When 1[w 1:i ∈ L prefix (G)] = 0, there is no possibility of grammaticality along this path and the EFG is therefore also zero. When 1[w 1:i ∈ L prefix (G)] = 1 it trivially bounds EFG, which is a probability. Second, we need to prove that ∀w 1:i ∈ prefix(S), cS (w 1:i ) ≥ c(w 1:i ). where prefix(S) is the set of (finitely many) prefixes of string in S. We proceed by induction, where the base case is when w 1:i is in prefix(S) but no w 1:i+1 is in prefix(S) for any possible next token w i+1 . Consequently, every w 1:i+1 falls under the first case, leading us to the following inequality:cS (w 1:i ) = wi+1 P (w i+1 | w 1:i ) • cS (w 1:i+1 ) ≥ wi+1 P (w i+1 | w 1:i ) • c(w 1:i+1 ) = c(w 1:i ) (4)Next, we move on to the inductive step where w 1:i is in prefix(S) and for any w i+1 , the string w 1:i+1 can either be a node that is not a prefix of S, which falls under the first case, or it can in prefix(S), for which the property holds by induction. Therefore, the reasoning used in Eq. 4 works for the inductive case as well.The sampling procedure itself proceeds autoregressively like GCD, but using the iteratively updated EFG estimates we have just defined, cS . Specifically, the left-to-right sampling conditional for our procedure, QS (w i |w 1:i-1 ), after having previously sampled the strings in S, is defined as follows:EQUATIONAlgorithm 1 ASAp algorithmInitialize S := {}, cS (•) := 1 for m ≤ M do Draw w 1:n ∼ QS via ancestral sampling S := S ∪ {w 1:n } for i in (n -1) . . . 1 do for w ′ in {w ′ | w 1:i • w ′ / ∈ L prefix (G)} do cS (w 1:i • w ′ ) := 0 cS (w 1:i ) := w ′ P (w ′ | w 1:i ) • cS (w 1:i • w ′ ) return Final sample w 1:nOur overall algorithm, which is presented in Algorithm 1, then proceeds iteratively, using past samples to improve subsequent samples. Whenever the sample set S is updated with a new sample w 1:n , the overapproximation c is updated for the prefixes of w 1:n . The update begins at the end of the sequence and proceeds backward toward the start, by the recursive definition in Eq. 3. In the listing, we assume that we are only interested in the final sample, but in our evaluation we will analyze whether the algorithm induces the desired distribution.Next we provide a proof that this algorithm converges to exact estimates of EFG in the limit of infinite iterations, and therefore to exact samples from the constrained LLM distribution. The theorem assumes almost sure termination of ancestral sampling in the unconstrained LLM distribution P -i.e., the LLM eventually terminates. Theorem 2. Assume that as L → ∞, the distribution P assigns vanishingly small probability mass to sequences longer than length L. Now, let S m = {s 1 , . . . , s m } be the set of recorded samples up to the mth iteration of ASAp. Then, ∀w1:i ∈ L prefix (G), cSm (w 1:i ) p → c(w 1:i ) as m → ∞.Proof. Let w 1:i be an arbitrary sequence in L prefix (G). The approximation gap after m iterations of sampling with ASAp, ϵ m = cSm (w 1:i ) -c(w 1:i ), is equal to the marginal probability under P of all ungrammatical continuations of w 1:i that have not yet been encountered in the first m samples, S m . Now consider an arbitrarily small ϵ > 0. By assumption, there exists an L such that the probability mass P places on sequences longer than L is less than ϵ. Further, ASAp samples according to P , but re-weighted by an upper bound on the true EFG (Theorem 1). Thus, the probability of encountering a previously unseen ungrammatical continuation of w 1:i no longer than L on any given iteration is at least as high as the probability of encountering the same continuation when sampling directly from P . Because the number of sequences no longer than L is finite, this implies that the probability mass under P of ungrammatical continuations of w 1:i that are no longer than L and that are not yet encountered in S m becomes vanishingly small as as m → ∞. The remaining unencountered ungrammatical continuations of w 1:i are longer than L, and thus their total mass is bounded by ϵ. Therefore P (ϵ m > ϵ) → 0 as m → ∞. ; Specifications to satisfy (constraint (= (f "Nancy FreeHafer") "N.F.")) (constraint (= (f "Andrew Cencici") "A.C.")) (constraint (= (f "Jan Kotas") "J.K.")) (constraint (= (f "Mariya Sergienko") "M.S."))(a) The grammar is implicitly defined by primitives of BV logic and parameters of inv. The goal of each problem is to find an implementation for synth-fun functions that satisfies all the constraints within a specified grammari.e., to find implementation of f in the grammar (c) and inv in the grammar (d). 
experiments: 
 We implemented the ASAp algorithm as an extension of the Transformers-CFG implementation of GCD [8] . When the LLM generates a sequence w 1:n , the ASAp algorithm keeps track of the original LLM's probability P (w i | w 1:i-1 ) for 1 ≤ i ≤ n and the set of allowed next tokens {w i | w 1:i-1 , w ′ i ∈ L(G)} determined by the incremental parser in the Transformers-CFG library. After the LLM finishes generating a sequence, our implementation of ASAp updates the overapproximation cS from the end of sequence by back-propagating the quantity 1 minus probability of the tokens that will for sure lead to non-grammatical sequences. The implementation of ASAp updates cS (w 1:n-1 , w ′ n ) for all possible tokens w ′ n , and then moves on to update cS (w 1:n-2 , w ′ n-1 ) . . ., cS (w 1 , w ′ 2 ), cS (w ′ 1 ) using Equation (3).Datasets and Models. We consider the benchmark from Example 3 and three structured-decoding tasks. Two of our tasks involve solving Syntax-Guided Synthesis Problems (SyGuS) [2] . SyGuS is a standardized format where one provides a logical specification and a context free grammar of first-order terms and the goal is to synthesize a term in the grammar that satisfies the specification. SyGuS is a natural fit for GAD and we consider two tasks from the standard SyGuS benchmarks where grammars vary from benchmark to benchmark: strings with linear integer arithmetic (SLIA) and loop invariant generation with bit-vector arithmetic (INV-BV). In the former, the grammar is used to restrict what constant strings one can use when building string-manipulating programs and in the latter the grammar is used to restrict constant bit-vectors and operations used to build invariants. Fig. 4 provides examples of SLIA and INV-BV problems. For both families of benchmarks, our prompts consist of 3 in-context examples of the form (specification, solution) and the grammar is then provided as a constraint for GAD. Our third task is the constituency parsing (CP) task already used in prior GCD work [7] where the grammar is used to help the model produce well-parenthesized parse trees for English sentences.Due to constrained resources and needing to run inference multiple times to measure whether the distribution Q is faithful to Q, we randomly select 15 SLIA problems, 15 INV-BV problems, and 6 CP problems. We select the open-source Mistral-7B [12] for evaluation due to its superior reasoning and code generation capabilities.Measures. We run both algorithms for 2,000 iterations/sample on each benchmark.To assess converge to the target distribution, we measure the Kullback-Leibler (KL) divergence between the distributions of GCD and ASAp from the target distribution Q for a given number of samples. Because the ideal GAD distribution Q P,G is proportional to the original LLM's distribution P for sequences allowed by a grammar G, we can use the LLM's distribution P on all observed samples as an estimate Q P,G . The quantity KL(Q∥P ) only differs by a constant from the KL divergence between empirical distributions and the ideal GAD distribution:KL( Q∥P )=E Q log Q P =E Q log Q C•Q P,G =E Q log Q Q P,G -log C=KL( Q∥Q P,G ) -log Cwhere C = w 1[w ∈ L(G)]P (w). Thus, KL( Q∥P ) can be used to quantify the alignment between the empirical distributions of GCD and ASAp with the ideal GAD distribution.For example, Fig. 5a shows convergence results for the first 75 iterations on the illustrative Ex. 3-i.e., the KL divergence for QASAp quickly converges to 0 whereas the one for QGCD doesn't.We also compare the empirical expectations of the variables QGCD , QASAp , and P . For example, Fig. 6a shows convergence results for the first 75 iterations on the illustrative Ex. 3-i.e., QASAp converges to the right expectation. Results. Fig. 5b and Fig. 6b illustrate a benchmark in which our ASAp algorithm quickly converges to the target distribution. Fig. 5 depicts the KL divergence of a sliding window of size 500 (e.g., the points at x=800 denote the KL divergence of the samples 800-1300). Fig. 6 depicts all the samples from the experiment, as well as how the expectations converges (a point at x=i denotes the empirical expectation on the first i samples. For this case the expecation for GCD stays very close to 0.Similarly, Fig. 5c and Fig. 6c illustrate a benchmark in which our ASAp algorithm converges slowly. In this case, bot ASAp and GCD are far from the target expectation (Fig. 6c ), but because GCD happens to be biased towards the most likely outcome, it exhibits better KL divergence. The complete set of plots is shown in Sec. E.1.To better understand how the algorithms respectively converge, Fig. 7 plot for each benchmark category the expectations for each benchmark computed by GCD and ASAp against the target expectation of P after 2,000 iterations. The sum of least square difference between expectations computed by GCD and the expectations of P are 2.259 (SLIA), 1.852 (INV-BV4), and 0.109 (CP). The sum of least square difference between expectations computed by ASAp and the expectation and those of P are 1.242 (SLIA), 0.802 (INV-BV4), and 0.159 (CP). While we have too few points for CP to draw conclusions, the expectations computed by ASAp are much closer to the ones computed by GCD across our experiments.While our work is interested in the theoretical convergence of the ASAp algorithm, we also report how the GCD and ASAp differ for solving the SLIA and INV-BV4 tasks-i.e., how many of the sampled programs are correct solutions to the given problem. GCD and ASAp solve approximately the same set of problems (there is just one SLIA benchmark for which ASAp returns a valid solution on one sample and GCD never does so). ASAp produces correct samples 38% more often than GCD (geomean), whereas for SLIA benchmarks that both tools can solve, ASAp produces correct samples 73% less often than GCD (geomean). Detailed results can be found in Sec. E.2. These results are in line with the fact ASAp shows faster convergence on INV-BV4 benchmarks. For example, for the benchmark illustrated in Fig. 5b , ASAp returns the correct solution for 1588 samples, whereas GCD only returns the correct solution 12 times, whereas for the benchmark in Fig. 5c , ASAp returns the correct solution 69 times and GCD 363 times.Discussion and Limitations. As predicted by our theorems, on most benchmarks the ASAp algorithm converges to the desired distribution P whereas GCD does not improve over time (i.e., it exhibits the bias described in this paper).While ASAp has no strong effect on solving downstream tasks, we observe that on instances where the convergence is prominent, ASAp ends up sampling correct solutions more often than GCD, which is what we expect when the LLM has "learned" how to solve the given task.The key limitation of our work is the current slow convergence of the ASAp algorithm. In some benchmarks, even after 2,000 iterations the KL divergence barely improves and even though the expectation of QASAp is improving, it converges very slowly.We highlight that the contributions of this paper are discovering and formalizing the bias of existing constrained decoding approaches and proposing the first converging algorithm to address this problem. Now that we have identified the problem, there are many "low-hanging fruits" to improve our sampling strategy, which are great targets for future work-e.g., using forms of targeted beam search to bootstrap our sample set to better explore grammar paths and avoid sampling similar strings. 
related work: 
 Constrained Decoding Past work has extensively explored constrained decoding algorithms, which modify the original decoding process of LLMs to ensure the output adheres to a user-specified regular [18, 28] or context-free language [5, 6, 7, 19, 23, 24, 25, 26] in a discrete space. Other works enforce hard output constraints using dynamic monitoring and verification methods [1, 15, 27] or by modifying beam search techniques to impose lexical constraints, which require specific keywords to appear in the generated text [4, 9, 10, 16, 17, 20] . At a high level, these methods involve running the LLM decode in parallel with a monitoring scheme (e.g., parsing algorithms for CFGs) to identify which next tokens or beams can produce valid output sequences that meet the constraints. The decoder then masks out any tokens that would lead to invalid sequences, sampling only from the permissible ones.To incorporate sequence-level soft semantic or contextual constraints, Amini et al. [3] , Kumar et al.[13], Li et al. [14] , Qin et al. [21] have applied gradient-based sampling techniques that relax those constraints to differentiable ones, used them as classifiers to further guide the decoding process. While these works guarantee that the decoded output meets the specified constraints (whether in the form of grammar, monitoring schemes, or differentiable functions), they often operate greedily and introduce bias into the output distribution in the way that has been discussed in this paper. Depending on the application one considers, this problem may or may not affect downstream tasks, but as we have argued in this paper, the bias can be quite prominent and sometimes affect downstream performance.Our adaptive decoding algorithm improves decoding over time by analyzing how previous samples led to nongrammaticaility.Constraint-Aligned Decoding This paper formally defines the problem of aligning the output distribution of an LLM in the presence of a constraint. We focus our attention on constraints expressed as grammars, but our definitions and algorithm apply to any constraint for which possible satisfaction (in our case grammaticality) can be evaluated in a left-to-right manner.In some settings, one is interested in generating multiple outcomes with an LLM to approximate a distribution of interest [11, 22] -e.g., to generate a random number or a set of good test cases for a program. As we have shown, constrained decoding can heavily skew the LLMs distribution and result in biasing the model towards certain constraint-matching sequences. While our work is at this point theoretical, now that the problem of aligning an LLM's distribution with constraints has been defined, we expect advances in how sampling is performed to quickly converge to better distributions faster (e.g., using beam search to quickly explore possible paths instead of just sampling). 
conclusion: 
 We have introduced a new analysis of the ideal target for constrained sampling from an LLM using a grammar, which we call grammar-aligned decoding (GAD). We proposed a new algorithm for GAD which we call ASAp that iteratively builds better approximations to the critical re-weighting term required for GAD: the expected future grammaticality. We analyzed the convergence of our proposed algorithm and demonstrated its effectiveness in relation to existing grammar-constrained decoding techniques on a set of benchmark code generation tasks. We analyzed and evaluated our approach using constraints enforced by a context-free grammar; however, extensions of our approach might be applied to more general classes of constraints for LLM decoding.While the primary goals of this work are to formalize the likelihood misalignment problem of existing grammar-constrained decoding approaches and to provide an initial solution with provable asymptotic guarantees, future work may explore faster-converging approaches, such as sampling multiple tokens simultaneously, to improve efficiency further. We hope this work lays a solid foundation for generating structured outputs from LLMs without distorting the original distribution, advancing the field toward more efficient, trustworthy, and constraint-aligned approaches in LLM-driven generation. Grammar Constraint While most SYGUS problems contain grammar constraints, some problems have grammars implicitly defined by the theory. We explicitly converted the grammar constraint of the problem into EBNF format for constrained-decoding. The example for the last example would be root ::= "(define-fun inv ((s (BitVec 4)) (t (BitVec 4))) (BitVec 4) " Start ")" Start ::= "s" | "t" | "#x0" | "#x8" | "#x7"| "(" "bvneg" " " Start ")" | "(" "bvnot" " " Start ")" | "(" "bvadd" " " Start " " Start ")" | "(" "bvsub" " " Start " " Start ")" | "(" "bvand" " " Start " " Start ")" | "(" "bvlshr" " " Start " " Start ")" | "(" "bvor" " " Start " " Start ")" | "(" "bvshl" " " Start " " Start ")" 
 
 Appendix: For Constituency parsing task, our prompts consist of 8 in-context examples of the form. A concrete example would be Grammar Constraint For the constituency parsing (CP) task we used the grammar provided in prior GCD work [7] . The grammar is too large to attach, but it is used to help the model produce wellparenthesized parse trees and ensure that all words in a given English sentence appear in left-to-right order. We provide additional plots and experimental data. Table 1 shows how many samples (out of 2000) yielded correct solutions for each benchmark (bold is better). The task initials_long-repeat was only solved using ASAp. No significant differences in convergence rates post fine-tuning. In Section 4, we evaluate ASAp and GCD on the base model Mistral-7B. A natural extension of this evaluation is determining whether ASAp retains its advantages over GCD after fine-tuning the base model on task-specific datasets, which optimizes the LLM for higher grammatical accuracy from the start.In our fine-tuning step, we want to teach the LLM to assign higher probabilities to grammatical outputs for the specific task DSL. We randomly selected two INV-BV problems (find _ inv _ bvsge _ bvneg _ 4bit and find _ inv _ bvsgt _ bvor _ 4bit for INV-BV) and four CP problems (CP _ re _ ptb _ 215, CP _ re _ ptb _ 434, CP _ re _ ptb _ 1627 and CP _ re _ ptb _ 1643 for CP) from the test set, and instrction tuned input-output pairs of prompt and output programs in the training set for the base model Mistral-7B. We obtained two fine-tuned models, one for INV-BV and one for CP.We tested GCD and ASAp on the finetuned Mistral-7B on the randomly left-out problems and checked the convergence rates of the KL-divergence. The results from finetuned Mistral-7B did not show significant differences in terms of convergence compared to the base Mistral-7B. As done in Section 4, we computed the expectation for each benchmark obtained via GCD and ASAp after 2,000 iterations and compared it against the target expectation Q P,G of GAD. The sum of least squares difference between expectations computed by GCD and the expectations of Q P,G are 0.677 (INV-BV4), 0.278 (CP), while ASAp achieved lower errors: 0.051 (INV-BV4), 0.201 (CP), indicating that ASAp more closely aligned with the exact GAD expectations. We did not include SLIA as we did not have sufficient data for further fine-tuning. Our code, datasets, and checkpoints are available at: https://github.com/ebmoon/transformers-GAD. 


Decision: This paper focuses on the constrained decoding scenario where LLMs are expected to produce high-quality and grammatically correct outputs. The authors point out that prior methods on grammar-constrained decoding (GCD) distorts the language model's learned distribution over sequences. As mitigation strategy, they present the adaptive sampling with approximate expected futures (ASAp) approach, which is designed to enhance the quality of the output by adjusting the conditional probability to align with the model’s original output distribution while ensuring grammaticality. The evaluation is performed on code generation and structured NLP tasks showing a better likelihood for LLM’s outputs being grammar-constrained.

The paper is well written and the method is well-formalized and clear. The paper provides empirical validation that the method works and that it improves the benchmark scores. The main focus of the paper is to formalize the likelihood misalignment problem in existing grammar-constrained decoding which is an important finding. The notion of expected future grammatically will be impactful in the area of sequence decoding.

Unfortunately, ASAp is computationally expensive, requires building a large data structure to keep track of the sampled prefixes and many iterations. Even though this may limit the adaptation of ASAp, the main contribution of the paper is the finding that conventional methods on grammar-constrained decoding distorts the language model's learned distribution.

Reviews: review: paper_summary: paper_summary: This paper points out that prior methods on grammar-constrained decoding (GCD) distorts the language model's learned distribution over sequences. At the heart of this exposition is the notion of _expected future grammaticality_ (EFG), where prior GCD methods can be cast an an upper-bound approximation to the EFG. To ameliorate this problem, the authors proposed the ASAp method: through many iterations, the EFG of a prefix can be better estimated.
strength_weakness: strength_weakness: The proposed method seems very slow to run, requiring many iterations. Additionally, it requires storing a table of all seen prefixes and their future grammatically, which would be very large if the grammar itself is large.

It seems to me that the ASAp method only depends on a grammar -- it does not specifically requires a training or test set to run. I wonder if it would be possible to first sample extensively and train the ASAp EFG estimates, then decode on a set. In this way ASAp can be cast as a preprocessing step of the grammar: if it is very slow, it wouldn't matter much since it'll only be processed once. 

For example we are doing NL2SQL under many conditions. The target grammar stays the same: SQL. One can utilize a LM and generate massive amount of prefixes that has EFG > 0, then compute this estimation of $\tilde c_S$ for all these distinct prefixes.
questions: questions: - L10: "prorblem" => "problem"
 - Missing related work: R Shin, et al (2021): Constrained language models yield few-shot semantic parsers. https://aclanthology.org/2021.emnlp-main.608/
 - Alg 1: What is "ancestral sampling"? Please explain.
limitations: limitations: The authors adequately discussed the limitations of their work.
paper_summary: paper_summary: This paper proposes adaptive sampling with approximate expected futures (ASAp) for grammar-aligned decoding for LLMs. The main objective of this method is to match the conditional probability of the LLM’s distribution conditioned on the given grammar. The evaluation is performed on code generation and structured NLP tasks showing a better likelihood for LLM’s outputs being grammar-constrained.
strength_weakness: strength_weakness: - Nothing in particular. Maybe I have found Section 2 of the paper somewhat difficult to read but it is probably because of my lack of recent readings on CFG.
questions: questions: I suggest maybe some improvement in Section 2. Restructuring it maybe and providing slightly more context on CFG (or giving a concrete example of how it works as a reminder, I found Fig 1 not illustrative enough), I'm sure I won't be the only reader who doesn't have recent experience with CFG.
limitations: limitations: Yes, limitations are discussed. What I liked in particular in this paper is that the limitations of ASAp are well exposed and discussed throughout the paper and not just in the limitations section.
paper_summary: paper_summary: This paper focuses on the constrained decoding scenario where LLMs are expected to produce high-quality and grammatically correct outputs. It presents the adaptive sampling with approximate expected futures (ASAp) method, which is designed to enhance the quality of the output by adjusting the conditional probability to align with the model’s original output distribution while ensuring grammaticality. Central to ASAp is the development of effective approximations to the expected future grammaticality (EFG). More specifically, ASAp involves an extra sampling process, where the estimates of EFG are iteratively refined after each sampling and will eventually converge to exact EFG in the limit of infinite iterations. Experimental results show that the output probability distribution of ASAp is closer to the original one than that of GCD methods.
strength_weakness: strength_weakness: The algorithm heavily relies on prior samples to estimate grammatical probabilities, which can be computationally expensive and difficult to manage, especially in cases where the dataset is large or the environment is dynamically changing. Moreover, a fair comparison of decoding speed between ASAp and GCD methods is required, as ASAp needs this sampling process to produce high-quality outputs, but conducting sampling on LLMs is very time-consuming.

Only evaluating the quality of the output by KL divergence and expectations is limited because the decoding sampling algorithm, except for the greedy search, does not always obey the probability distribution. For example, when the decoding temperature is set to 1, models may not output tokens with the highest probability. To conduct a more intuitive evaluation, one can choose some constrained decoding tasks with explicit quality scores, such as constrained translation [1] with BLEU and Exact Match, and code generation, which can be evaluated by the passing rate.

Since the experiments in this paper are based on prompt-motivated LLMs, a natural step is to fine-tune LLMs and see if they can produce grammatically correct output with high quality. On the other hand, the authors can also try ASAp based on fine-tuned LLMs, which may further boost the performance of ASAp.

To enhance the readability of the article, the following suggestions can be considered.
1. It’s more intuitive to give specific input and output examples for SLIA and INV-BV tasks.
2. The names GCD and GAD are too similar to easily differentiate, even after reading the paper.
3. Other typos: In line 289, the word “both” is typed as “bot”.

[1] Wang, S., Li, P., Tan, Z., Tu, Z., Sun, M., & Liu, Y. (2022). A Template-based Method for Constrained Neural Machine Translation. arXiv preprint arXiv:2205.11255.
questions: questions: Given previous samples with the prefix $w_{1:i}$, there exist abundant future tokens beyond just the next token. However, ASAp only uses the next token likelihoods to facilitate a better estimate of EFG. Why not use other future tokens?
limitations: limitations: Yes

Comments: comment: Thanks for the response. I will keep my score since I believe that some additional work (e.g. training a neural estimate of EFG) will make this paper more contained.
Thank you for your response, which has addressed some of my concerns. I think this is an interesting work. However, I will maintain my rating score as the issues warrant consideration in a major revision of this submission.