                    CRANE: Reasoning with constrained LLM generation


         Debangshu Banerjee 1 * Tarun Suresh 1 * Shubham Ugare 1 Sasa Misailovic 1 Gagandeep Singh 1


                         Abstract                                    Jiang et al., 2024), logical solvers (Pan et al., 2023; Olaus-
                                                                     son et al., 2023), and theorem provers (Wu et al., 2022;
      Code generation, symbolic math reasoning, and                  Yang et al., 2023). These tools impose specific syntactic
      other tasks require LLMs to produce outputs that               and semantic constraints on their inputs, requiring LLMs
      are both syntactically and semantically correct.               to produce outputs in the correct format. For instance, if
      Constrained LLM generation is a promising direc-               an LLM provides output to a specific logical solver (Han
      tion to enforce adherence to formal grammar, but               et al., 2024), the output must be parsable by that solver.
      prior works have empirically observed that strict              Similarly, Wolfram Alpha (wolfram, 2024) translates user
      enforcement of formal constraints often dimin-                 queries about mathematical problems into a domain-specific
      ishes the reasoning capabilities of LLMs. In this              language (DSL) to utilize symbolic solvers. However, as
      work, we first provide a theoretical explanation for           highlighted in recent studies (Ugare et al., 2024b; Lundberg
      why constraining LLM outputs to very restrictive               et al., 2023; Poesia et al., 2022), pre-trained LLM outputs
      grammars that only allow syntactically valid final             do not always comply with downstream tools’ input re-
      answers reduces the reasoning capabilities of the              quirements. Constrained decoding algorithms (Ugare et al.,
      model. Second, we demonstrate that by augment-                 2024b; Poesia et al., 2022) address this issue by project-
      ing the output grammar with carefully designed                 ing the LLM output onto user-specified formal constraints
      additional rules, it is always possible to preserve            (e.g., syntactic rules defined by a context-free grammar G),
      the reasoning capabilities of the LLM while en-                thereby ensuring that the input requirements of downstream
      suring syntactic and semantic correctness in its               tasks are satisfied.
      outputs. Building on these theoretical insights,
      we propose a reasoning-augmented constrained                   As illustrated in Fig. 1, constrained decoding improves the
      decoding algorithm, CRANE, which effectively                   syntactic correctness of LLM outputs (e.g., generating a
      balances the correctness of constrained generation             well-formed mathematical expression). However, it does
      with the flexibility of unconstrained generation.              not guarantee functional correctness (e.g., ensuring the ex-
      Experiments on multiple open-source LLMs and                   pression correctly answers the user’s query). Recent works
      benchmarks show that CRANE significantly out-                  such as Tam et al. (2024) have empirically observed that
      performs both state-of-the-art constrained decod-              imposing constraints on LLM outputs can, in some cases,
      ing strategies and standard unconstrained decod-               reduce functional correctness for specific tasks. Tam et al.
      ing, showing up to 10% points accuracy improve-                (2024) attributes this reduction in functional accuracy to
      ment over baselines on challenging symbolic rea-               a decline in the LLM’s reasoning capabilities under con-
      soning benchmarks GSM-symbolic and FOLIO.                      strained decoding. This observation raises the following
                                                                     open questions:

                                                                     • RQ1: Do LLMs truly lose reasoning capabilities under
1. Introduction                                                        constrained decoding?
Transformer-based large language models (LLMs) are                   • RQ2: How can we leverage the benefits of constrained
widely used in AI systems that interact with traditional soft-         decoding in reducing syntax errors while preserving the
ware tools like Python interpreters (OpenAI, 2024; Chen                unconstrained reasoning capabilities of LLMs?
et al., 2023) for code generation (Suresh et al., 2024a;b;
                                                                     Key Challenges: First, we need to formally identify the
  *
   Equal contribution 1 Department of Computer Science, Uni-         root cause of the reduction in functional accuracy of end-
versity of Illinois Urbana-Champaign, USA. Correspondence to:        to-end systems when a pre-trained LLM operates under
Debangshu Banerjee <db21@illinois.edu>.                              constrained generation. Unlike the empirical observations
Proceedings of the 42 nd International Conference on Machine         in (Tam et al., 2024), we seek a formal justification for
Learning, Vancouver, Canada. PMLR 267, 2025. Copyright 2025          this reduction that is not limited to specific LLMs used
by the author(s).                                                    in experiments but extends to any LLM, including more

                                                                 1
                                      CRANE: Reasoning with constrained LLM generation




Figure 1. An example from the GSM-symbolic dataset (variables in blue) where unconstrained generation produces syntactically incorrect
output, while constrained generation provides a syntactically valid but incorrect answer. CRANE, however, generates a correct answer.


powerful ones developed in the future.                                  eration for producing structurally correct outputs. This
                                                                        allows the model to produce syntactically valid outputs
Second, we must design cost-efficient decoding strategies
                                                                        while enabling the LLM to reason. Our detailed exper-
that address the shortcomings of existing constrained decod-
                                                                        iments on multiple open-source LLMs and benchmarks
ing methods while improving functional accuracy. In this
                                                                        demonstrate that CRANE significantly outperforms both
work, we do not consider task-specific fine-tuning of LLMs,
                                                                        SOTA constrained decoding strategies and standard un-
as fine-tuning for each task is compute-intensive. Unlike
                                                                        constrained decoding, showing up to a 10% improvement
constrained decoding, fine-tuning does not guarantee that
                                                                        over baselines on challenging symbolic reasoning bench-
the LLM output adheres to formal constraints.
                                                                        marks GSM-symbolic (Mirzadeh et al., 2024)) and FO-
Contributions: We make the following contributions to                   LIO (Han et al., 2024).
improve the functional accuracy of the end-to-end system:
                                                                      Next, we provide the notations and necessary background
• We theoretically show that LLMs with a constant number              on constrained decoding, including the definition of Turing
  of layers, which are known to be capable of simulating              machines and relevant circuit complexity classes.
  n steps of any given Turing machine M with O(n) rea-
  soning steps (Merrill & Sabharwal, 2024), can only solve            2. Preliminaries
  problems within a relatively restrictive circuit complexity         Notations: In the rest of the paper, we use small case letters
  class when constrained to generate outputs that always              (x) for constants, bold small case letters (x    x) for strings,
  conform to a restrictive grammar G defining only the valid                                                                        x|
                                                                      capital letters X for functions, · for string concatenation, |x
  output strings. This demonstrates that, for restrictive gram-       to denote the length of the string x . We use LLM to refer to
  mar, constrained decoding reduces the problem-solving               transformer-based LLMs with a fixed number of layers.
  capabilities of LLMs.
• We theoretically show that the loss of expressivity of
                                                                      2.1. Constrained LLM Decoding
  LLMs under constrained decoding arises because the out-
  put grammar G is too restrictive to accommodate the inter-          Autoregressive language models L decode output iteratively
  mediate reasoning steps required to compute the answer.             by generating tokens from a probability distribution over
  We further demonstrate that augmenting the grammar G                the vocabulary V . The distribution is derived by applying
  with specific additional production rules enables the LLM           the softmax function to the model’s scores S. Common
  to generate the intermediate reasoning steps while ensur-           decoding methods include greedy decoding, temperature
  ing that the final output always adheres to the intended            sampling, and beam search. Constrained LLM decoding
  output structure. With the augmented grammar Ga , the               extends this process by excluding specific tokens at certain
  LLM retains its expressivity under constrained decoding.            positions, such as avoiding harmful words or adhering to
• We propose a simple and cost-efficient decoding strat-              a user-defined output grammar for languages like JSON or
  egy, CRANE (Constrained Reasoning Augmented                         SQL (Poesia et al., 2022; Ugare et al., 2024c; Willard &
  Generation). CRANE effectively alternates between un-               Louf, 2023). At each decoding step, a binary mask m ∈
  constrained generation for reasoning and constrained gen-           {0, 1}|V | , generated by a function fm , specifies valid tokens

                                                                  2
                                    CRANE: Reasoning with constrained LLM generation

(mi = 1) and excluded tokens (mi = 0). Decoding is                   models used to analyze resource requirements (e.g. time
then performed on the masked probability distribution m ⊙            and space complexity) and the hardness of computation
softmax(S), where ⊙ denotes element-wise multiplication.             problems. Formally, a Turing machine is defined as:
                                                                     Definition 2.4 (Turing Machine). A Turing machine M
2.2. Deterministic LLM Decoding                                      with k work tapes and an output tape is a 8-tuple
CRANE is compatible with various decoding strategies,                               M = ⟨Σ, Γ, k, b, Q, q0 , δ, F ⟩,
both constrained and unconstrained, allowing the output
of L to be stochastic. However, following existing works             where Σ is the finite input alphabet, Γ is the finite tape
(Hahn, 2020; Merrill & Sabharwal, 2023; Li et al., 2024)             alphabet with Σ ⊆ Γ, b ∈ Γ \ Σ is a special blank symbol,
and for simplicity in the theoretical setup in Section 3, we         Q is a finite set of states, q0 ∈ Q is the initial state, δ :
assume that the output of L on any input string x is deter-          (Q \ F ) × Γk+2 → Q × Γk+1 × {0, +1, −1}k+2 is the
ministic in both constrained and unconstrained settings.             transition function (where −1, 1, 0 represent moving the
                                                                     tape head left, right, or staying in place, respectively), and
Similar to prior works (Merrill & Sabharwal, 2023; 2024),
                                                                     F ⊆ Q is the set of halting states.
we model a single autoregressive step as a deterministic
function Lf that predicts the next token given a specific            Let Σ∗ denote the set of all finite strings over the input
input. Formally,                                                     alphabet Σ. Given an input string s ∈ Σ∗ , the computation
Definition 2.1 (Deterministic LLM Step). A single autore-            of M on s is a sequence of configurations starting from
gressive step of an LLM is modeled as a deterministic func-          the initial configuration. Each configuration γ is a tuple
tion Lf : V ∗ → V , where V is the finite vocabulary and V ∗         containing the current state q ∈ Q, the contents of the input
represents the set of all finite strings over V . For an input       tape, the k work tapes, the output tape, and the current head
string x ∈ V ∗ , the LLM predicts the next token Lf (x x).           positions of all k + 2 tapes. For each configuration, γi (i ∈
                                                                     N), the transition function δ computes the next configuration
Definition 2.2 (Deterministic Unconstrained Decoding).
                                                                     γi+1 based on the current state q and the values on the
For an input string x , the deterministic output string y
                                                                     k + 2 tapes at the current head positions. It updates the
selected from the output distribution of a LLM using a
                                                                     head positions, writes to the output tape (possibly leaving
decoding algorithm (e.g., greedy decoding) is denoted as
                                                                     it unchanged if no new symbol is written), and advances
y = L(x x) where L : V ∗ → V ∗ . L(x x) is the most likely
                                                                     to the next configuration. For each i, computation of γi+1
output sequence according to learned distribution on x .
                                                                     from γi defines a single step of the Turing machine.
The output y = L(x   x) is computed iteratively with |yy | au-       The computation of M on input s halts if M reaches a
toregressive steps defined by Lf . For each 1 ≤ i ≤ |yy |, and       halting state q ∈ F . If M halts, the output corresponding to
                         (i)
the recurrence relation Lf (xx) = L(i−1)
                                    f     x)·Lf (L(i−1)
                                         (x        f       x))
                                                          (x         s is written on the output tape. Additional details about the
        (0)
where Lf (x
          x) = x and · denotes string concatenation. Here,           computation of the Turing machine are in Appendix A.
          y|
         |y
          y
x · y = Lf (xx). Similarly, under constrained decoding with          Before discussing existing expressivity results for constant-
a grammar G we define:                                               layer LLMs, we briefly introduce relevant uniform constant-
Definition 2.3 (Deterministic Constrained Decoding un-               depth circuit complexity classes, e.g. logspace uniform-
der Grammar). Under constrained decoding with a formal               T C 0 , which provide an upper bound on the computational
grammar G, the output string y G is selected from the con-           power of LLMs that do not employ reasoning steps, as seen
strained output distribution and is denoted as y G = LG (x
                                                         x).         in methods like Chain-of-Thought (Wei et al., 2022).
The output of i-th constrained autoregressive step with G is         Definition 2.5 (Boolean Circuit). A Boolean circuit is a
      (i)   (i)                      y |)                            computational model for evaluating Boolean functions over
x · y G = LG (x x) and x · y G = L(|y
                                    G (x  x).
                                                                     fixed-length binary strings. It is represented as a directed
The constrained output y G is always in the grammar y G ∈            acyclic graph (DAG), where the leaf nodes correspond to
L(G) where L(G) is the language defined by G. For sound-             input binary variables or their negations, and the internal
constrained decoding algorithms, if the unconstrained out-           nodes perform operations from a predefined set of opera-
put y = L(xx) in the grammar y ∈ L(G), the constrained               tions B (e.g., AND (∧), OR (∨), etc.). One or more marked
output remains unchanged, i.e., L(x
                                  x) = LG (x x).                     nodes in the graph represent the circuit’s output.

                                                                     The structure of the DAG specifies the computation of the
2.3. LLM Expressivity
                                                                     Boolean function by propagating input values through the
We discuss the notations and background related to Turing            graph. The complexity of a circuit is determined by its
machines, and relevant uniform circuit complexity classes.           size (the number of nodes) and depth (the longest path in
Turing machines are popular mathematical computation                 the graph). Since a single circuit only defines a boolean

                                                                 3
                                        CRANE: Reasoning with constrained LLM generation

function for fixed-length inputs, a family of circuits is re-            LLM with a constant number of layers on an input of length
quired—one for each input length—to characterize a com-                  n can be simulated by a logspace-uniform constant-depth
putational problem where input lengths vary. Unlike Turing               threshold circuit family. This result allows the LLM to use
machines, whose computation does not depend on input                     floating-point numbers with log(n) precision when process-
length, circuit families have a separate circuit for each input          ing inputs of size n, ensuring that the precision scales with n
length, which can differ entirely. This non-uniformity can               and preventing floating-point representation issues for large
lead to degenerate cases where non-uniform circuit fam-                  n. We denote such LLMs as log-precision LLMs.
ilies solve undecidable problems (Arora & Barak, 2009).
                                                                         Let x ·yy (i) denote the output after the i-th autoregressive step
To address this issue, complexity theorists enforce unifor-
                                                                         of an LLM L under constrained decoding with an output
mity conditions, requiring circuits for different input sizes                                                                        (i)
to be related, resulting in uniform circuit families. For                grammar G on input x. Then, we have x · y (i) = LG (x           x),
                                                                                           y (i)
further details and formal definitions of circuit classes, re-           and for any i,          is always a valid prefix of a string in
fer to (Arora & Barak, 2009). In this work, we focus on                  L(G), i.e., there exists a (possibly empty) string α(i) such
constant-depth, polynomial-sized logspace-uniform thresh-                that y (i) · α(i) ∈ L(G). Now, for any output grammar Gc
old circuits (T C 0 ), where B contains only threshold gates             where the output set O = L(Gc ) is finite, we show that
(a formal definition is in Appendix B).                                  the output LGc (x   x) for any input x of size |x  x| = n can be
                                                                         computed using constant-depth threshold circuits.
3. Expressivity of Constrained Decoding                                  Proposition 3.1. For any log-precision LLM L with con-
                                                                         stant layers there exists a logspace-uniform thershold circuit
First, we show that any constant-layer LLM L under con-                  T hn such that LGc (xx) = T hn (x x) holds for all inputs x with
strained decoding loses expressivity. We identify the class                    x| = n and n ∈ N.
                                                                         size |x
of problems and the corresponding output grammars G such
that when imposed on the outputs of any constant-layer                   Proof: The formal proof is in Appendix C.
LLM, the problems cannot be solved unless there is a col-
                                                                         From Proposition 3.1, it follows that for any decision prob-
lapse in fundamental complexity classes that are widely
                                                                         lem under constrained decoding, an LLM can only solve
believed to be unequal (e.g., T C 0 ̸= N L)1 .
                                                                         problems within the logspace-uniform T C 0 class (constant-
3.1. Limitation of Constrained Decoding                                  depth threshold circuits). Consequently, any decision prob-
                                                                         lem believed to lie outside this class cannot be solved un-
Next, we present the high-level idea behind Proposition 3.1              der constrained decoding. The previously mentioned st-
that shows the limitation of constrained LLM decoding                    connectivity problem is known to be N L-complete (Arora
when the output grammar is too restrictive. We consider                  & Barak, 2009). This implies that unless T C 0 = N L, no
problems where the number of possible outputs is finite, and             LLM under constrained decoding can solve st-connectivity.
thus the set of all possible outputs O can be expressed as               Additionally, (Li et al., 2024; Merrill & Sabharwal, 2024)
a simple regular language. Consequently, Gc that encodes                 show that given any Turing machine M there exists a log-
the output set O, i.e., O = L(Gc ), where L(Gc ) denotes                 precision LLM with a constant number of layers that can
the language defined by the grammar Gc . For instance, any               simulate O(t(n)) steps of M using O(t(n)) autoregressive
decision problem (yes/no answer) such as st-connectivity                 steps, where t(n) denotes a polynomial in the input size n.
that asks for vertices s and t in a directed graph, if t is reach-
                                                                         Lemma 3.2. For any Turing machine M with tape alphabet
able from s can be answered within a single-bit output i.e.
                                                                         Γ, there exists a constant depth LLM LM with finite vocabu-
L(Gc ) = {0, 1}. This implies that constrained decoding
                                                                         lary Γ ⊆ VM and log-precision that can simulate t(n) steps
with the output grammar Gc allows only a single autoregres-
                                                                         of M with t(n) autoregressive steps.
sive step for any L on all inputs.
A series of existing works (Hahn, 2020; Hao et al., 2022;                Proof: The proof follows from Theorem 2 in (Merrill &
Merrill et al., 2022; Merrill & Sabharwal, 2023) establish               Sabharwal, 2024) further details in Appendix C.
that, under suitable assumptions, a single autoregressive                Proposition 3.1 and Lemma 3.2 together imply that there ex-
step on an input with length n for any constant-depth LLM                ist problems, such as st-connectivity, an LLM can solve that
can be represented as a constant-depth circuit. Since, for de-           in an unconstrained setting but cannot be solved under con-
cision problems, the constrained decoding step permits only              strained decoding (unless logspace-uniform T C 0 = N L).
a single autoregressive step, any LLM can only solve prob-
lems within the corresponding circuit complexity class. We               3.2. Reasoning with Augmented Grammar
build on the most recent result from (Merrill & Sabharwal,
2023), which shows that a single autoregressive step of any              The reduction in LLM expressivity under constrained de-
   1
                                                                         coding, as established in Proposition 3.1, arises primarily
       NL refers to nondeterministic log-space                           because the language of all valid output strings, L(Gc ),

                                                                     4
                                      CRANE: Reasoning with constrained LLM generation

is too restrictive and does not permit large (non-constant)              {0, +1, −1} denote either staying in place (0), moving left
reasoning chains. This naturally leads to the question of                (−1), or moving right (+1) by a single position. Since the
whether it is possible to augment any output grammar G                   set of states Q, the tape alphabet Γ, and the number of tapes
with additional production rules to construct an augmented               k are all constants, the total number of possible encodings γ
grammar Ga that can accommodate reasoning steps while                    is also constant. Let Γ denote the set of all possible configu-
preserving the expressivity of L even under constrained                  ration encodings, i.e., Γ = {γ(1) , . . . , γ(l) }, where l = |Γ|.
decoding. At the same time, Ga should remain nontriv-                    Given Γ is finite and enumerable, we can define the rules of
ial—meaning it should not accept all possible strings, as in             the augmented grammar Ga accordingly as follows.
the unconstrained setting—so that it aligns with the practi-
cal objective of constrained decoding: guiding the LLM to
generate syntactically and semantically valid outputs.
                                                                           Ga → RM G; RM → SRM ; S → γ(1) | · · · |γ(l)
To achieve this, we enforce that the augmented grammar
Ga always follows the structure Ga → RG, where the                       The set of reasoning strings in L(RM ) essentially define a
nonterminal symbol R captures the reasoning steps, and                   regular language over the configuration encodings Γ. Let,
G represents the final output. This guarantees that for any              for any input x with size n = |xx| a given Turing machine
string s ∈ L(Ga ), the final answer a extracted from s =                 M halts and compute the output M (x x) in t(n) steps that are
r · a always belongs to the original output grammar G, i.e.,             polynomial in n. Then there exist LM compute M (x    x) with
a ∈ L(G), with r serving as the reasoning sequence leading               t(n) autoregressive steps under constrined decoding with
up to the final output.                                                  the augmented grammar Ga → RM G. Suppose, LM,Ga (x         x)
Formally, we show that for any Turing machine M and a                    denotes the output of the LLM LM on input x under con-
grammar G containing all valid outputs of M , there exists               strained decoding with grammar Ga then
an LLM LM with a constant number of layers and log-                      Proposition 3.3. For any Turing machine M with tape
precision, along with an augmented grammar Ga in the                     alphabet Γ, there exists a constant depth LLM LM with
specified format, such that LM can simulate t(n) steps of M              finite vocabulary Γ ⊆ VM and log precision such that for
using t(n) autoregressive steps under constrained decoding               any input x with |xx| = n, LM,Ga (x x) = r · M (x
                                                                                                                         x) with
with Ga . Here n ∈ N and t(n) is a polynomial over n. The                       ∗
                                                                         r ∈ VM   assuming M halts on x in t(n) steps.
augmented grammar Ga may not be unique, and we provide
one such construction.                                                   Proof: The proof is in Appendix C.
At a high level, LM simulates the Turing machine M by
computing the encoded representations γi of the machine’s                4. CRANE Algorithm
configurations γi at each step i and storing them within the             Given any Turing machine M , Proposition 3.3 establishes
reasoning component (i.e., the string r ) of the output. Dur-            that constrained decoding with the augmented grammar Ga
ing each autoregressive step, LM generates the next configu-             on a specific LLM LM can simulate the computation of
ration based on the transition function of M and appends its             M . However, this result does not directly translate into a
encoding to the reasoning sequence. This process continues               practical constrained decoding algorithm that preserves the
until M reaches a halting state, at which point LM produces              expressivity of general LLMs. The construction assumes
the final output a , which belongs to L(G). For any given                a specific LLM LM with the vocabulary VM and knowl-
M , we define the rules RM that can parse the encodings γ                edge of the particular Turing machine M for defining the
of all possible configurations γ. This ensures that the output           rules RM . In practice, we require an efficient approach
LGa (x  x) represents the full reasoning-augmented sequence,             that can be applied to diverse open-source LLMs, various
i.e., γ1 · · · γt(n) · M (x              x) is the final output of
                            x), where M (x                               grammars, and different constrained decoding algorithms.
M on input x of size n after t(n) computational steps. The               Importantly, we know that enforcing the output grammar G
encodings γ1 , . . . , γt(n) correspond to the configurations            from the beginning can limit expressivity. Instead, we im-
γ1 , . . . , γt(n) , as described below.                                 pose grammar constraints judiciously to avoid restricting the
We begin by defining the vocabulary VM for LM , which                    LLM’s reasoning capabilities. For example, in the case of a
contains all tape symbols Γ of M along with a finite set of              reasoning-augmented output of the form γ1 · · · γt(n) · M (x
                                                                                                                                    x),
auxiliary symbols γ that encode the corresponding config-                we apply constrained decoding only from the t(n) + 1-th
urations γ. Similar to prior works (Merrill & Sabharwal,                 autoregressive step onward, ensuring that the reasoning pro-
2024), each configuration encoding γ represents the cur-                 cess remains unrestricted while the final answer adheres to
rent state q, the symbols at the current head position of                the desired grammar.
k + 2 tapes (input, output and k work tapes), and the head               The primary challenge here is deciding when to transition
movement directions {0, +1, −1} for each tape. Directions                between an unconstrained generation for reasoning and a

                                                                     5
                                       CRANE: Reasoning with constrained LLM generation

constrained generation. For instance, grammar for general-                Algorithm 1 CRANE Algorithm
purpose programming languages such as Python can allow                     1: Input: LLM, tokens, CSD (constrained decoder), G
any text string at the start (e.g. program starting variable                  (output grammar), S1 (start delimiter), S2 (end delim-
names) making it hard to detect the end of reasoning string.                  iter)
To avoid this, we augment the output grammar with specific                 2: Output: Output string
delimiter symbols S1 and S2 that mark the start and end                    3: G′ ← S1 GS2
of the constrained generation. We incentivize the LLM                      4: CSD . INITIALIZE(G′ )
to generate these delimiters via explicit instructions in the              5: pointer ← len(tokens)
prompt and few-shot examples. This aligns with common                      6: isConstrained ← False
general-purpose LLMs that already use specific delimiters                  7: while True do
such as backticks (‘‘‘) for programs like python, SQL, and                 8:      currGen ← detokenize(tokens[pointer :])
(<<, >>) to enclose math-expression blocks. This approach                  9:      if S1 ∈ currGen then
allows a simple and cost-efficient approach for detecting                 10:           isConstrained ← True
the transitions to and from constrained decoding. For the                 11:      else
construction in the previous section, in this setup, we will              12:           isConstrained ← False
                                x) · S2 where the reasoning r is
generate the string r · S1 · M (x                                         13:      if isConstrained then
generated unconstrained and the LLM moves to constrained                  14:           constrained ← extractConstrained(currGen)
mode after seeing the symbol S1 . However, in practical                   15:           ti ∼ LLM(tokens) ⊙ CSD(constrained)
cases, the delimiters may be generated multiple times (ie.                16:      else
for intermediate operations), even during the reasoning step.             17:           ti ∼ LLM(tokens)
Therefore, upon encountering the end symbol S2 , we switch
                                                                          18:      tokens ← tokens + ti
back to unconstrained generation to avoid unnecessarily
                                                                          19:      if ti = EOS then
restricting the output.
                                                                          20:           break
                                                                          21:      if isConstrained then
                                                                          22:           constrained ← constrained + detokenize(ti )
                                                                          23:           if constrained.endswith(S2 ) then
                                                                          24:               pointer ← len(tokens)
                                                                          25: return detokenize(tokens)



                                                                          If S1 is not present, the next token is computed directly
                                                                          without any constraints applied. Additionally, if the current
Figure 2. CRANE adaptively switches between constrained LLM               constrained window ends with S2 , the pointer is updated to
generation and unconstrained LLM generation based on start and            the length of the current token sequence, effectively switch-
end delimiters (in this example << and >>). Using these delimiters,       ing back to unconstrained generation until S1 is generated
CRANE dynamically tracks which windows (highlighted in the                again. Figure 2 further illustrates LLM generation with
figure) of the LLM generation constraints should be applied to.           CRANE. The underlined portion of the LLM generation
                                                                          represents currGen, and the current constrained window
We implement our approach into the CRANE algorithm
                                                                          is highlighted in yellow.
(Algo 1), which extends standard autoregressive LLM gen-
eration. CRANE takes an arbitrary LLM, constrained de-
coding algorithm (denoted as CSD), output grammar G, and                  5. Evaluation
symbols S1 and S2 as input. It first initializes CSD with G′ ,
                                                                          In this section, we evaluate CRANE on a math reasoning
the output grammar augmented with S1 and S2 . CRANE
                                                                          task (GSM-Symbolic (Mirzadeh et al., 2024)) and a logical
starts in unconstrained generation and maintains a pointer
                                                                          reasoning task (FOLIO (Han et al., 2024)) and demonstrate
that marks the start of the current window of LLM gen-
                                                                          significant improvement over both unconstrained and SOTA
eration following the last constrained generation. In each
                                                                          constrained generation baselines.
iteration, the algorithm checks if S1 is present in the current
generation window currGen, which is the portion of the                    Experimental Setup. We run experiments on a 48-core
sequence from the current pointer position onwards. If S1 is              Intel Xeon Silver 4214R CPU with 2 NVidia RTX A5000
detected, CRANE switches to constrained generation mode.                  GPUs. CRANE is implemented using PyTorch (Paszke
In this mode, the current constrained window (the portion                 et al., 2019) and the HuggingFace transformers library (Wolf
of currGen that is in G′ ) is extracted, and the next token               et al., 2020). Our primary baseline for unconstrained gen-
is sampled based on the constraints defined by the CSD.                   eration is Chain-of-Thought (CoT) Prompting (Wei et al.,

                                                                      6
                                   CRANE: Reasoning with constrained LLM generation

2022), which enables LLMs to decompose and reason about
a problem through a series of intermediate steps before out-
putting the final answer. Furthermore, we run constrained
semantic generation for GSM-Symbolic (Mirzadeh et al.,
2024) with the I TER G EN library (Ugare et al., 2024a) and
use the S YN C ODE framework for FOLIO (Han et al., 2024)
evaluation. In all experiments, CRANE is initialized with
the same constrained decoders and uses the same constraints
as the constrained generation baselines.
GSM-Symbolic: We first evaluate CRANE on GSM-
Symbolic (Mirzadeh et al., 2024), a dataset consisting of
math word problems designed to assess LLMs’ mathemati-              Figure 3. Accuracy (%) of Qwen2.5-Math-7B-Instruct By Method
cal reasoning skills. In the word problems, names and nu-           and Number of Shots on GSM-Symbolic
merical values are replaced with symbolic variables, and the
LLMs are tasked with generating correct symbolic expres-
sion solutions (see Appendix D.1 for examples). To evaluate         As shown in the table, CRANE consistently improves func-
correctness, we extract the final expressions from the LLM          tional correctness across all evaluated models. For exam-
generations and verify if they are functionally equivalent to       ple, with the Qwen2.5-Math-7B-Instruct model, CRANE
the ground truth expressions with the Z3 solver (De Moura           achieves 38% accuracy, outperforming both constrained
& Bjørner, 2008).                                                   generation and unconstrained generation with CoT, which
We compare CRANE against three baselines: (1) uncon-                achieves 29% accuracy. Moreover, CRANE significantly
strained generation without chain-of-thought prompting, (2)         enhances the syntactic correctness of generated expressions
unconstrained generation with CoT, and (3) constrained gen-         compared to unconstrained generation. Notably, none of
eration. We use I TER G EN for the constrained generation           the expressions generated using CRANE contain syntax
baseline and also initialize CRANE with I TER G EN. For             errors, whereas 10% of the expressions from unconstrained
I TER G EN and CRANE, we enforce syntactic constraints              generation with CoT do. Although, for several instances,
via the context-free grammar provided in Appendix D.5.1             CRANE produces slightly more syntax errors than a purely
and apply the semantic constraint ensuring that generated           constrained generation, it offers a substantial improvement
expressions contain only valid problem-defined variables.           in functional correctness over this baseline.
Since I TER G EN uses selective rejection sampling to enforce       Ablation Study on Few-shot examples: We evaluate
semantic constraints, we also include comparisong against           CRANE and baselines on varying numbers of few-shot
unconstrained generation with sampling in Table 4 in the            examples in the prompt and display the results for Qwen2.5-
Appendix. For CRANE, we use << and >> for the delime-               Math-7B-Instruct in Figure 3. Results for all models are
ters S1 and S2 , respectively. We evaluate Qwen2.5-1.5B-            presented in Table 3 in the Appendix. CRANE consis-
Instruct (Qwen, 2024), Qwen2.5-Math-7B-Instruct (Qwen,              tently achieves higher accuracy on GSM-Symbolic than the
2024), Qwen2.5-Coder-7B-Instruct (Qwen, 2024),Llama-                baselines for all evaluated numbers of few-shot examples.
3.1-8B-Instruct (Llama, 2024), DeepSeek-R1-Distill-Qwen-
7B (DeepSeek-AI et al., 2025), DeepSeek-R1-Distill-                 FOLIO: We further evaluate CRANE on the validation
Llama-8B (DeepSeek-AI et al., 2025), Qwen2.5-Coder-                 split of FOLIO dataset, which comprises 203 expert-written
14B-Instruct (Qwen, 2024), DeepSeek-R1-Distill-Qwen-                natural language reasoning instances and corresponding
14B (DeepSeek-AI et al., 2025), and QwQ-32B (Team,                  first-order logic (FOL) annotations. We evaluate the ability
2025). We use greedy decoding with a maximum new token              of LLMs to correctly translate the natural language reason-
limit of 600 and prompt the LLMs with the 8-shot examples           ing instances into FOL formulas and leverage Prover9 (Mc-
from GSM-Symbolic (Mirzadeh et al., 2024) (the prompts              Cune, 2005–2010) a FOL solver to verify the correctness of
can be found in Appendix D.1).                                      the LLM-generated FOL formulas.
Table 1 compares the performance of CRANE with the                  We compare CRANE against grammar-constrained genera-
baseline methods. The Accuracy (%) column reports the               tion with S YN C ODE using the Prover9 grammar (Appendix
percentage of functionally correct LLM-generated expres-            D.5.2). The Prover9 grammar divides FOL formulas into
sions, Parse (%) indicates the percentage of syntactically          Predicates, Premises, and Conclusions and allows interme-
valid expressions (i.e., expressions without invalid opera-         diate reasoning in comments (an example can be found in
tions), and Tokens provides the average number of tokens            Appendix D.2). We also compare CRANE against un-
generated.                                                          constrained generation with CoT. For all approaches and
                                                                    models, we run greedy decoding with a maximum new to-

                                                                7
                                     CRANE: Reasoning with constrained LLM generation

kens limit of 800 and use 2 few-shot examples in the prompt.           ing the LLM’s expressivity by reasoning chains.
We also compare CRANE against unconstrained CoT with
                                                                       LLM Expressivity: (Strobl et al., 2024) provides a detailed
temperature sampling in Table 5 in the Appendix.
                                                                       survey of existing results from the perspective of formal
Appendix table 2 presents the results of our experiment. The           language theory and complexity classes. A series of existing
Accuracy (%) column in the table reports the percentage of             works (Hahn, 2020; Hao et al., 2022; Merrill et al., 2022;
functionally correct FOL translations while the Compiles               Merrill & Sabharwal, 2023) establish that, under suitable
(%) column reports the percentage of FOL formulas ex-                  assumptions, a single autoregressive step on an input of
tracted from LLM output that are syntactically valid and               any length for a constant-depth LLM can be represented
compile into a Prover9 program. CRANE outperforms the                  as a constant-depth Boolean circuit. (Merrill & Sabharwal,
unconstrained and constrained generation baselines for all             2024; Li et al., 2024) show that the expressivity of LLMs
models evaluated.                                                      significantly improves under popular reasoning approaches
                                                                       like Chain of Thought (CoT) (Wei et al., 2022), where LLMs
Limitation: Our work has the following limitations. First,
                                                                       take intermediate steps before generating the final answer.
Proposition 3.1 only demonstrates a reduction in expressiv-
                                                                       To the best of our knowledge, there is no prior work on
ity when the language L(Gc ) is finite. This leaves open
                                                                       LLM expressivity under grammar constraints.
the question of whether Proposition 3.1 can be extended
to grammars G where L(G) is infinite. Second, CRANE
                                                                       7. Conclusion
for constrained decoding relies on existing tools (Ugare
et al., 2024b) that require access to output logits, rendering         In conclusion, tasks requiring both syntactic and seman-
CRANE inapplicable to models that do not expose logits.                tic correctness, such as code generation and symbolic
                                                                       math reasoning, benefit significantly from constrained de-
6. Related Works                                                       coding strategies. However, strict enforcement of con-
                                                                       straints can hinder LLM reasoning capabilities. Theoret-
Constrained LLM Decoding: Recent works have intro-
                                                                       ically, we demonstrate why restrictive grammars dimin-
duced techniques to enforce LLM generations to adhere to
                                                                       ish reasoning and show that augmenting grammars with
a context-free grammar using constrained decoding (Ugare
                                                                       carefully designed rules preserves reasoning while main-
et al., 2024c; Willard & Louf, 2023; Beurer-Kellner et al.,
                                                                       taining correctness. Building on these insights, our pro-
2024; Melcer et al., 2024a). Additionally, Poesia et al.
                                                                       posed reasoning-augmented constrained decoding algo-
(2022); Ugare et al. (2024a) have extended grammar-guided
                                                                       rithm, CRANE, achieves state-of-the-art performance, with
generation to incorporate task-specific semantic constraints.
                                                                       up to 10% improvement on symbolic reasoning benchmarks
These approaches demonstrate that constrained decoding
                                                                       such as GSM-symbolic and FOLIO, effectively balancing
can improve the syntactic and semantic quality of LLM
                                                                       the strengths of constrained and unconstrained generation.
outputs for various structured generation tasks.
More recently, Tam et al. (2024) demonstrated that con-
strained structured generation can negatively impact the
quality of generated outputs. Similarly, Park et al. (2024)
showed that greedily masking out tokens that do not lead to
a valid string during next-token prediction can distort the
output distribution, causing it to deviate from the true distri-
bution of all grammatically valid outputs of L for a given
input. To mitigate the distortion introduced by the greedy
masking approach, these “grammar aligned” methods (Park
et al., 2024; Melcer et al., 2024b) use a trie to track previ-
ous generations, reducing generation divergence iteratively.
However, they are computationally expensive and require a
large no. of resamplings per prompt to converge.
In contrast, our work focuses on the fundamental question
of the theoretical expressivity of any constant layered con-
strained LLM, even under an ideal constrained decoding
algorithm, and uses the insights to propose a practical so-
lution. We propose an adaptive constrained decoding ap-
proach that can support various constrained decoding meth-
ods, including grammar-aligned techniques while preserv-


                                                                   8
                      CRANE: Reasoning with constrained LLM generation




        Table 1. Comparison of CRANE and baselines with different models on GSM-Symbolic.
Model                              Method                     Acc. (%)     Parse (%)        Tokens
                                   Unconstrained w/o CoT          21           97            23.34
                                   Constrained                    22           97            25.29
Qwen2.5-1.5B-Instruct              Unconstrained CoT              26           90           128.97
                                   CRANE                          31          100            131.3
                                   Unconstrained w/o CoT          36           94            17.92
                                   Constrained                    35           99            25.28
Qwen2.5-Coder-7B-Instruct          Unconstrained CoT              37           88           138.38
                                   CRANE                          39           94           155.32
                                   Unconstrained w/o CoT          27           89             25.7
                                   Constrained                    29           99            26.81
Qwen2.5-Math-7B-Instruct           Unconstrained CoT              29           82           155.26
                                   CRANE                          38           94           158.86
                                   Unconstrained w/o CoT          21           73           128.38
                                   Constrained                    26           98            35.97
Llama-3.1-8B-Instruct              Unconstrained CoT              30           95           163.55
                                   CRANE                          33           95           170.22
                                   Unconstrained w/o CoT          18           89            21.64
                                   Constrained                    20           99            17.21
DeepSeek-R1-Distill-Qwen-7B        Unconstrained CoT              24           89           212.24
                                   CRANE                          29           92           235.78
                                   Unconstrained w/o CoT          12           77             29.2
                                   Constrained                    13           96            16.89
DeepSeek-R1-Distill-Llama-8B       Unconstrained CoT              21           87           250.83
                                   CRANE                          31           92           268.82
                                   Unconstrained w/o CoT          42           93            18.52
                                   Constrained                    42           96            25.62
Qwen2.5-Coder-14B-Instruct         Unconstrained CoT              42           95           157.71
                                   CRANE                          45           95           158.54
                                   Unconstrained w/o CoT          29           82             20.9
                                   Constrained                    30           91            30.48
DeepSeek-R1-Distill-Qwen-14B       Unconstrained CoT              32           87           233.42
                                   CRANE                          38           93           244.98
                                   Unconstrained w/o CoT          37           80            54.93
                                   Constrained                    38           91             34.2
QwQ-32B                            Unconstrained CoT              43           87           222.62
                                   CRANE                          46           88           237.98




                                               9
                                     CRANE: Reasoning with constrained LLM generation

Impact Statement                                                         Zhang, Y., Shi, Y., Xiong, Y., He, Y., Piao, Y., Wang, Y.,
                                                                         Tan, Y., Ma, Y., Liu, Y., Guo, Y., Ou, Y., Wang, Y., Gong,
This paper introduces research aimed at advancing the field              Y., Zou, Y., He, Y., Xiong, Y., Luo, Y., You, Y., Liu, Y.,
of Machine Learning. We do not identify any specific so-                 Zhou, Y., Zhu, Y. X., Xu, Y., Huang, Y., Li, Y., Zheng,
cietal consequences of our work that need to be explicitly               Y., Zhu, Y., Ma, Y., Tang, Y., Zha, Y., Yan, Y., Ren, Z. Z.,
emphasized here.                                                         Ren, Z., Sha, Z., Fu, Z., Xu, Z., Xie, Z., Zhang, Z., Hao,
                                                                         Z., Ma, Z., Yan, Z., Wu, Z., Gu, Z., Zhu, Z., Liu, Z., Li,
References                                                               Z., Xie, Z., Song, Z., Pan, Z., Huang, Z., Xu, Z., Zhang,
                                                                         Z., and Zhang, Z. Deepseek-r1: Incentivizing reasoning
Arora, S. and Barak, B. Computational Complexity: A
                                                                         capability in llms via reinforcement learning, 2025. URL
  Modern Approach. Cambridge University Press, USA,
                                                                         https://arxiv.org/abs/2501.12948.
  1st edition, 2009. ISBN 0521424267.
                                                                       Hahn, M. Theoretical limitations of self-attention in neural
Beurer-Kellner, L., Fischer, M., and Vechev, M. Guiding
                                                                         sequence models. Transactions of the Association for
  llms the right way: Fast, non-invasive constrained gener-
                                                                         Computational Linguistics, 8:156–171, 2020. doi: 10.
  ation, 2024.
                                                                        1162/tacl a 00306. URL https://aclanthology.
Chen, W., Ma, X., Wang, X., and Cohen, W. W. Pro-                        org/2020.tacl-1.11/.
  gram of thoughts prompting: Disentangling computation
  from reasoning for numerical reasoning tasks. Transac-               Han, S., Schoelkopf, H., Zhao, Y., Qi, Z., Riddell, M., Zhou,
  tions on Machine Learning Research, 2023. ISSN 2835-                   W., Coady, J., Peng, D., Qiao, Y., Benson, L., Sun, L.,
  8856. URL https://openreview.net/forum?                                Wardle-Solano, A., Szabo, H., Zubova, E., Burtell, M.,
  id=YfZ4ZPt8zd.                                                         Fan, J., Liu, Y., Wong, B., Sailor, M., Ni, A., Nan, L.,
                                                                         Kasai, J., Yu, T., Zhang, R., Fabbri, A. R., Kryscinski, W.,
De Moura, L. and Bjørner, N. Z3: an efficient smt                        Yavuz, S., Liu, Y., Lin, X. V., Joty, S., Zhou, Y., Xiong,
  solver. In Proceedings of the Theory and Practice of                   C., Ying, R., Cohan, A., and Radev, D. Folio: Natural
  Software, 14th International Conference on Tools and                   language reasoning with first-order logic, 2024. URL
 Algorithms for the Construction and Analysis of Systems,                https://arxiv.org/abs/2209.00840.
  TACAS’08/ETAPS’08, pp. 337–340, Berlin, Heidelberg,
  2008. Springer-Verlag. ISBN 3540787992.                              Hao, Y., Angluin, D., and Frank, R. Formal language
                                                                         recognition by hard attention transformers: Perspectives
DeepSeek-AI, Guo, D., Yang, D., Zhang, H., Song, J.,                     from circuit complexity. Transactions of the Associa-
  Zhang, R., Xu, R., Zhu, Q., Ma, S., Wang, P., Bi, X.,                  tion for Computational Linguistics, 10:800–810, 07 2022.
  Zhang, X., Yu, X., Wu, Y., Wu, Z. F., Gou, Z., Shao,                   ISSN 2307-387X. doi: 10.1162/tacl a 00490. URL
  Z., Li, Z., Gao, Z., Liu, A., Xue, B., Wang, B., Wu, B.,               https://doi.org/10.1162/tacl_a_00490.
  Feng, B., Lu, C., Zhao, C., Deng, C., Zhang, C., Ruan,
  C., Dai, D., Chen, D., Ji, D., Li, E., Lin, F., Dai, F., Luo,        Jiang, J., Wang, F., Shen, J., Kim, S., and Kim, S. A survey
  F., Hao, G., Chen, G., Li, G., Zhang, H., Bao, H., Xu,                  on large language models for code generation, 2024. URL
  H., Wang, H., Ding, H., Xin, H., Gao, H., Qu, H., Li,                   https://arxiv.org/abs/2406.00515.
  H., Guo, J., Li, J., Wang, J., Chen, J., Yuan, J., Qiu, J.,
  Li, J., Cai, J. L., Ni, J., Liang, J., Chen, J., Dong, K.,           Li, Z., Liu, H., Zhou, D., and Ma, T. Chain of thought em-
  Hu, K., Gao, K., Guan, K., Huang, K., Yu, K., Wang, L.,                powers transformers to solve inherently serial problems.
  Zhang, L., Zhao, L., Wang, L., Zhang, L., Xu, L., Xia,                 In The Twelfth International Conference on Learning
  L., Zhang, M., Zhang, M., Tang, M., Li, M., Wang, M.,                  Representations, 2024. URL https://openreview.
  Li, M., Tian, N., Huang, P., Zhang, P., Wang, Q., Chen,                net/forum?id=3EWTEy9MTM.
  Q., Du, Q., Ge, R., Zhang, R., Pan, R., Wang, R., Chen,              Llama. The llama 3 herd of models, 2024. URL https:
  R. J., Jin, R. L., Chen, R., Lu, S., Zhou, S., Chen, S., Ye,           //arxiv.org/abs/2407.21783.
  S., Wang, S., Yu, S., Zhou, S., Pan, S., Li, S. S., Zhou,
  S., Wu, S., Ye, S., Yun, T., Pei, T., Sun, T., Wang, T.,             Lundberg, S., Ribeiro, M. T. A. p., and et. al. Guidance-
  Zeng, W., Zhao, W., Liu, W., Liang, W., Gao, W., Yu, W.,               ai/guidance: A guidance language for controlling large
  Zhang, W., Xiao, W. L., An, W., Liu, X., Wang, X., Chen,               language models., 2023. URL https://github.
  X., Nie, X., Cheng, X., Liu, X., Xie, X., Liu, X., Yang,               com/guidance-ai/guidance.
  X., Li, X., Su, X., Lin, X., Li, X. Q., Jin, X., Shen, X.,
  Chen, X., Sun, X., Wang, X., Song, X., Zhou, X., Wang,               McCune,     W.      Prover9 and   mace4.
  X., Shan, X., Li, Y. K., Wang, Y. Q., Wei, Y. X., Zhang,              http://www.cs.unm.edu/˜mccune/prover9/,
 Y., Xu, Y., Li, Y., Zhao, Y., Sun, Y., Wang, Y., Yu, Y.,               2005–2010.

                                                                  10
                                   CRANE: Reasoning with constrained LLM generation

Melcer, D., Fulton, N., Gouda, S. K., and Qian, H. Con-             Paszke, A., Gross, S., Massa, F., Lerer, A., Bradbury, J.,
 strained decoding for fill-in-the-middle code language               Chanan, G., Killeen, T., Lin, Z., Gimelshein, N., Antiga,
 models via efficient left and right quotienting of context-          L., Desmaison, A., Kopf, A., Yang, E., DeVito, Z., Raison,
 sensitive grammars, 2024a. URL https://arxiv.                        M., Tejani, A., Chilamkurthy, S., Steiner, B., Fang, L.,
 org/abs/2402.17988.                                                  Bai, J., and Chintala, S. Pytorch: An imperative style,
                                                                      high-performance deep learning library. In Advances
Melcer, D., Gonugondla, S., Perera, P., Qian, H., Chiang,             in Neural Information Processing Systems 32, pp. 8024–
 W.-H., Wang, Y., Jain, N., Garg, P., Ma, X., and Deoras, A.          8035. Curran Associates, Inc., 2019.
 Approximately aligned decoding, 2024b. URL https:
 //arxiv.org/abs/2410.01103.                                        Poesia, G., Polozov, A., Le, V., Tiwari, A., Soares, G.,
                                                                      Meek, C., and Gulwani, S. Synchromesh: Reliable
Merrill, W. and Sabharwal, A. The parallelism tradeoff:
                                                                      code generation from pre-trained language models. In
 Limitations of log-precision transformers. Transactions
                                                                      International Conference on Learning Representations,
 of the Association for Computational Linguistics, 11:531–
                                                                      2022. URL https://openreview.net/forum?
 545, 2023. doi: 10.1162/tacl a 00562. URL https:
                                                                      id=KmtVD97J43e.
 //aclanthology.org/2023.tacl-1.31/.

Merrill, W. and Sabharwal, A. The expressive power of               Qwen. Qwen2.5: A party of foundation models, September
 transformers with chain of thought. In The Twelfth                  2024. URL https://qwenlm.github.io/blog/
 International Conference on Learning Representations,               qwen2.5/.
 2024. URL https://openreview.net/forum?
 id=NjNGlPh8Wh.                                                     Strobl, L., Merrill, W., Weiss, G., Chiang, D., and Angluin,
                                                                       D. What formal languages can transformers express? a
Merrill, W., Sabharwal, A., and Smith, N. A. Sat-                      survey. Trans. Assoc. Comput. Linguistics, 12:543–561,
 urated transformers are constant-depth threshold cir-                 2024. URL https://doi.org/10.1162/tacl_
 cuits. Transactions of the Association for Computa-                   a_00663.
 tional Linguistics, 10:843–856, 2022. doi: 10.1162/tacl
 a 00493. URL https://aclanthology.org/                             Suresh, T., Reddy, R. G., Xu, Y., Nussbaum, Z., Mulyar,
 2022.tacl-1.49/.                                                     A., Duderstadt, B., and Ji, H. Cornstack: High-quality
                                                                      contrastive data for better code ranking, 2024a. URL
Mirzadeh, I., Alizadeh, K., Shahrokhi, H., Tuzel, O., Ben-            https://arxiv.org/abs/2412.01007.
 gio, S., and Farajtabar, M. Gsm-symbolic: Understand-
 ing the limitations of mathematical reasoning in large             Suresh, T., Ugare, S., Singh, G., and Misailovic, S. Is
 language models, 2024. URL https://arxiv.org/                        watermarking llm-generated code robust?, 2024b. URL
 abs/2410.05229.                                                      https://arxiv.org/abs/2403.17983.
Olausson, T., Gu, A., Lipkin, B., Zhang, C., Solar-Lezama,          Tam, Z. R., Wu, C.-K., Tsai, Y.-L., Lin, C.-Y., Lee, H.-y.,
  A., Tenenbaum, J., and Levy, R. Linc: A neurosymbolic               and Chen, Y.-N. Let me speak freely? a study on the
  approach for logical reasoning by combining language                impact of format restrictions on large language model
  models with first-order logic provers. In Proceedings               performance. In Dernoncourt, F., Preoţiuc-Pietro, D., and
  of the 2023 Conference on Empirical Methods in Natu-                Shimorina, A. (eds.), Proceedings of the 2024 Confer-
  ral Language Processing. Association for Computational              ence on Empirical Methods in Natural Language Pro-
  Linguistics, 2023. doi: 10.18653/v1/2023.emnlp-main.                cessing: Industry Track, pp. 1218–1236, Miami, Florida,
  313. URL http://dx.doi.org/10.18653/v1/                             US, November 2024. Association for Computational
  2023.emnlp-main.313.                                                Linguistics. doi: 10.18653/v1/2024.emnlp-industry.
                                                                      91. URL https://aclanthology.org/2024.
OpenAI. Opneai tools, 2024. URL https://platform.
                                                                      emnlp-industry.91/.
  openai.com/docs/assistants/tools.

Pan, L., Albalak, A., Wang, X., and Wang, W. Y. Logic-              Team, Q. Qwq-32b: Embracing the power of reinforce-
  lm: Empowering large language models with symbolic                  ment learning, March 2025. URL https://qwenlm.
  solvers for faithful logical reasoning, 2023. URL https:            github.io/blog/qwq-32b/.
  //arxiv.org/abs/2305.12295.
                                                                    Ugare, S., Gumaste, R., Suresh, T., Singh, G., and Mi-
Park, K., Wang, J., Berg-Kirkpatrick, T., Polikarpova, N.,            sailovic, S. Itergen: Iterative structured llm gener-
  and D’Antoni, L. Grammar-aligned decoding, 2024. URL                ation, 2024a. URL https://arxiv.org/abs/
  https://arxiv.org/abs/2405.21047.                                   2410.07295.

                                                               11
                                  CRANE: Reasoning with constrained LLM generation

Ugare, S., Suresh, T., Kang, H., Misailovic, S., and Singh,
  G. Syncode: Llm generation with grammar augmentation,
  2024b.
Ugare, S., Suresh, T., Kang, H., Misailovic, S., and Singh,
  G. Syncode: Llm generation with grammar augmen-
  tation, 2024c. URL https://arxiv.org/abs/
  2403.01632.

Wei, J., Wang, X., Schuurmans, D., Bosma, M., Ichter, B.,
 Xia, F., Chi, E. H., Le, Q. V., and Zhou, D. Chain-of-
 thought prompting elicits reasoning in large language
 models. In Proceedings of the 36th International Confer-
 ence on Neural Information Processing Systems, NIPS
 ’22, Red Hook, NY, USA, 2022. Curran Associates Inc.
 ISBN 9781713871088.
Willard, B. T. and Louf, R. Efficient guided generation for
 large language models, 2023.
Wolf, T., Debut, L., Sanh, V., Chaumond, J., Delangue,
 C., Moi, A., Cistac, P., Rault, T., Louf, R., Funtow-
 icz, M., Davison, J., Shleifer, S., von Platen, P., Ma,
 C., Jernite, Y., Plu, J., Xu, C., Le Scao, T., Gugger,
 S., Drame, M., Lhoest, Q., and Rush, A. Transform-
 ers: State-of-the-art natural language processing. In Liu,
 Q. and Schlangen, D. (eds.), Proceedings of the 2020
 Conference on Empirical Methods in Natural Language
 Processing: System Demonstrations, pp. 38–45, Online,
 October 2020. Association for Computational Linguistics.
 doi: 10.18653/v1/2020.emnlp-demos.6. URL https:
 //aclanthology.org/2020.emnlp-demos.6.

wolfram. Wolfram alpha, 2024. URL https://
 writings.stephenwolfram.com/.
Wu, Y., Jiang, A. Q., Li, W., Rabe, M. N., Staats, C. E.,
 Jamnik, M., and Szegedy, C. Autoformalization with
 large language models. In Oh, A. H., Agarwal, A.,
 Belgrave, D., and Cho, K. (eds.), Advances in Neural
 Information Processing Systems, 2022. URL https:
 //openreview.net/forum?id=IUikebJ1Bf0.
Yang, K., Swope, A. M., Gu, A., Chalamala, R., Song,
  P., Yu, S., Godil, S., Prenger, R., and Anandkumar, A.
  Leandojo: Theorem proving with retrieval-augmented
  language models, 2023. URL https://arxiv.org/
  abs/2306.15626.




                                                              12
                                      CRANE: Reasoning with constrained LLM generation

A. Turing Machine Computation
A Turing machine processes an input string x ∈ Σ∗ . Its configuration consists of a finite state set Q, an input tape c0 , k
work tapes c1 , . . . , ck , and an output tape ck+1 . Additionally, each tape τ has an associated head position hτ .
Initially, the machine starts in the initial state q0 ∈ Q with the input tape c00 containing x , positioned at index 0, and
surrounded by infinite blank symbols (b). The head on the input tape is set to h00 = 0, while all other tapes contain only
blank symbols bs and have their heads positioned at 0.
At each time step i, if qi ∈
                           / F (F is a set of halting states), the configuration updates recursively by computing:
                                                   i
                            ⟨qi+1 , γ1i , . . . , γk+1 , di0 , . . . , dik+1 ⟩ = δ(qi , ci0 [hi0 ], . . . , cik+1 [hik+1 ])

where δ is the transition function. The machine updates each tape τ by setting ci+1      i      i
                                                                                    τ [hτ ] = γτ , leaving all other tape cells
                                                             i+1      i    i
unchanged. The head position for each tape is updated as hτ = hτ + dτ . If qi ∈ F , the Turing machine halts and outputs
the sequence of tokens on the output tape, starting from the current head position and continuing up to (but not including) the
first blank symbol (b). A Turing machine can also function as a language recognizer by setting the input alphabet Σ = {0, 1}
and interpreting the first output token as either 0 or 1.

B. Thershold Circuit Class
T C 0 is a class of computational problems that can be recognized by constant-depth, polynomial-size circuits composed of
threshold gates. A threshold gate, such as θ≤k , outputs 1 if the sum of its input bits is at most k, while θ≥k outputs 1 if the
sum is at least k. These circuits also include standard logic gates like ∧, ∨, and ¬ as special cases of threshold functions.
Since T C 0 circuits can simulate AC 0 circuits ( a polysize, constant-depth {∧, ∨, ¬}-circuit family), they are at least as
powerful as AC 0 in the computational hierarchy. The circuit families we have defined above are non-uniform, meaning
that there is no requirement for the circuits processing different input sizes to be related in any way. In degenerate cases,
non-uniform circuit families can solve undecidable problems making them an unrealizable model of computation (Arora &
Barak, 2009). Intuitively, a uniform circuit family requires that the circuits for different input sizes must be ”somewhat
similar” to each other. This concept is formalized by stating that there exists a resource-constrained Turing machine that,
given the input 1n , can generate a serialization of the corresponding circuit Cn for that input size. Specifically, a logspace
uniform T C 0 family can be constructed by a logspace-bounded Turing machine from the string 1n .

C. Proofs
Lemma C.1 (Constant depth circuit for Lf ). For any log-precision constant layer transformer-based LLM L with finite
vocabulary V , a single deterministic auto-regressive step Lf (x) operating on any input of size n ∈ N with x ∈ V n can be
simulated by a logspace-uniform threshold circuit family of depth C where C is constant.

Proof. The construction is from Theorem 2 in (Merrill & Sabharwal, 2023).
Proposition 3.1. For any log-precision LLM L with constant layers there exists a logspace-uniform thershold circuit T hn
such that LGc (x                                               x| = n and n ∈ N.
                          x) holds for all inputs x with size |x
               x) = T hn (x

Proof. The language L(Gc ) is finite; therefore, for any string s ∈ L(Gc ), the length satisfies |ss| ≤ N , where N is a constant.
Consequently, for any input x , the output y G = LG (xx) has a constant length, i.e., |yy G | ≤ N . The number of autoregressive
steps is also bounded by N .
From Lemma C.1, each unconstrained autoregressive computation Lf (x      x) can be simulated by a constant-depth threshold
circuit C. This implies that Lf (x
                                 x, Gc ) can also be simulated by a constant-depth threshold circuit since it only involves an
additional multiplication by a constant-sized precomputed Boolean mask {0, 1}|V | (see Section 2).
Given that the number of autoregressive steps is a constant N , and each step can be simulated by a constant-depth circuit C,
we can simulate all N steps using a depth N × C circuit by stacking the circuits for each step sequentially. For uniformity,
we are just stacking together a constant number of constant depth circuits we can do it in a log-space bounded Turning
machine M .
Note that this proof holds only because L(Gc ) allows only constant-size strings in the output.

                                                                         13
                                     CRANE: Reasoning with constrained LLM generation

Lemma 3.2. For any Turing machine M with tape alphabet Γ, there exists a constant depth LLM LM with finite vocabulary
Γ ⊆ VM and log-precision that can simulate t(n) steps of M with t(n) autoregressive steps.

Proof. The construction follows from Theorem 2 (Merrill & Sabharwal, 2024).

In this construction, the deterministic Turing machine run captured by a sequence of γ1 , . . . , γt(n) capturing the state entered,
tokens written, and directions moved after each token before generating the output M (xx). Then on any input the x the output
LM (x                              x) (assuming M halts within on x within t(n) steps where n = |x
      x) = γ1 , · · · , γt(n) · M (x                                                                  x| and t(n) is a polynomial
over n).
Proposition 3.3. For any Turing machine M with tape alphabet Γ, there exists a constant depth LLM LM with finite
                                                                                                            ∗
                                                                    x| = n, LM,Ga (x
vocabulary Γ ⊆ VM and log precision such that for any input x with |x                          x) with r ∈ VM
                                                                                   x) = r · M (x              assuming
M halts on x in t(n) steps.

           x)) = γ1 · · · γt(n) · M (x
Proof. LM (x                                              x) ∈ L(Ga ). Ga → RM G. Since, G is output grammar of M
                                     x). We show that LM (x
                                                                        ∗
        x) ∈ L(G). For all 1 ≤ i ≤ t(n) γi ∈ Γ. Then, γ1 · · · γt(n) ∈ Γ ⊆ L(RM ).
then M (x
Then LM (x                                                           x) remains unchanged and LM (x
          x) ∈ L(Ga ) then under constrained decoding the output LM (x                            x) = LM,Ga (x
                                                                                                              x) =
       x) where r = γ1 · · · γt(n) .
r · M (x




                                                                14
                                        CRANE: Reasoning with constrained LLM generation

     D. FOLIO Results

                               Table 2. Comparison of CRANE and baselines with various models on FOLIO.
                  Model                            Method                Acc. (%)     Compiles (%)        Tokens
                                                   Unconstrained CoT       18.72           54.19          629.59
                  Qwen2.5-Math-7B-Instruct         Constrained             28.08           76.85          679.44
                                                   CRANE                   31.03           75.86          690.17
                                                   Unconstrained CoT       36.95           70.94          350.64
                  Qwen2.5-7B-Instruct              Constrained             37.44           87.68          775.62
                                                   CRANE                   42.36           87.68          726.88
                                                   Unconstrained CoT       32.02           57.14          371.52
                  Llama-3.1-8B-Instruct            Constrained             39.41           86.21          549.75
                                                   CRANE                   46.31           85.71          449.77

     D.1. GSM-Symbolic Examples and Prompt
     GSM-Symbolic Problem Solution Examples:
 1    Question: A fog bank rolls in from the ocean to cover a city. It takes {t} minutes to cover every {d}
           miles of the city. If the city is {y} miles across from oceanfront to the opposite inland edge,
           how many minutes will it take for the fog bank to cover the whole city?
 2
 3    Answer: y//d*t
 4
 5    Question: {name} makes {drink} using teaspoons of sugar and cups of water in the ratio of {m}:{n}. If
           she used a total of {x} teaspoons of sugar and cups of water, calculate the number of
           teaspoonfuls of sugar she used.
 6
 7    Answer: ((m*x)//(m+n))


                                        Listing 1. Problem Solution Examples for GSM-Symbolic

     GSM-Symbolic Prompt:
 1    You are an expert in solving grade school math tasks. You will be presented with a grade-school math
           word problem with symbolic variables and be asked to solve it.
 2
 3    Before answering you should reason about the problem (using the <reasoning> field in the response
           described below). Intermediate symbolic expressions generated during reasoning should be wrapped
           in << >>.
 4
 5    Then, output the symbolic expression wrapped in << >> that answers the question. The expressions must
           use numbers as well as the variables defined in the question. You are only allowed to use the
           following operations: +, -, /, //, %, (), and int().
 6
 7    You will always respond in the format described below:
 8    Let’s think step by step. <reasoning> The final answer is <<symbolic expression>>
 9
10    There are {t} trees in the {g}. {g} workers will plant trees in the {g} today. After they are done,
           there will be {tf} trees. How many trees did the {g} workers plant today?
11
12    Let’s think step by step. Initially, there are {t} trees. After planting, there are {tf} trees. The
           number of trees planted is <<tf - t>>. The final answer is <<tf - t>>.
13
14    If there are {c} cars in the parking lot and {nc} more cars arrive, how many cars are in the parking
           lot?
15
16    Let’s think step by step. Initially, there are {c} cars. {nc} more cars arrive, so the total becomes
           <<c + nc>>. The final answer is <<c + nc>>.
17
18    {p1} had {ch1} {o1} and {p2} had {ch2} {o1}. If they ate {a} {o1}, how many pieces do they have left
           in total?
19
20    Let’s think step by step. Initially, {p1} had {ch1} {o1}, and {p2} had {ch2} {o1}, making a total of
           <<ch1 + ch2>>. After eating {a} {o1}, the remaining total is <<ch1 + ch2 - a>>. The final answer
           is <<ch1 + ch2 - a>>.
21
22    {p1} had {l1} {o1}. {p1} gave {g} {o1} to {p2}. How many {o1} does {p1} have left?
23



                                                                 15
                                    CRANE: Reasoning with constrained LLM generation

24   Let’s think step by step. {p1} started with {l1} {o1}. After giving {g} {o1} to {p2}, {p1} has <<l1 -
          g>> {o1} left. The final answer is <<l1 - g>>.
25
26   {p1} has {t} {o1}. For Christmas, {p1} got {tm} {o1} from {p2} and {td} {o1} from {p3}. How many {o1}
          does {p1} have now?
27
28   Let’s think step by step. {p1} started with {t} {o1}. {p1} received {tm} {o1} from {p2} and {td} {o1}
          from {p3}. The total is <<t + tm + td>>. The final answer is <<t + tm + td>>.
29
30   There were {c} {o1} in the server room. {nc} more {o1} were installed each day, from {d1} to {d2}. How
           many {o1} are now in the server room?
31
32   Let’s think step by step. Initially, there were {c} {o1}. {nc} {o1} were added each day for <<d2 - d1
          + 1>> days, which is <<nc * (d2 - d1 + 1)>>. The total is <<c + nc * (d2 - d1 + 1)>>. The final
          answer is <<c + nc * (d2 - d1 + 1)>>.
33
34   {p1} had {gb1} {o1}. On {day1}, {p1} lost {l1} {o1}. On {day2}, {p1} lost {l2} more. How many {o1}
          does {p1} have at the end of {day2}?
35
36   Let’s think step by step. Initially, {p1} had {gb1} {o1}. After losing {l1} {o1} on {day1}, {p1} had
          <<gb1 - l1>>. After losing {l2} {o1} on {day2}, the total is <<gb1 - l1 - l2>>. The final answer
          is <<gb1 - l1 - l2>>.
37
38   {p1} has ${m}. {p1} bought {q} {o1} for ${p} each. How much money does {p1} have left?
39
40   Let’s think step by step. Initially, {p1} had ${m}. {p1} spent <<q * p>> on {q} {o1}. The remaining
          money is <<m - q * p>>. The final answer is <<m - q * p>>.
41
42   {question}


                                  Listing 2. CoT Prompt Template For GSM-Symbolic Evaluation

 1   You are an expert in solving grade school math tasks. You will be presented with a grade-school math
          word problem with symbolic variables and be asked to solve it.
 2
 3   Only output the symbolic expression wrapped in << >> that answers the question. The expression must
          use numbers as well as the variables defined in the question. You are only allowed to use the
          following operations: +, -, /, //, %, (), and int().
 4
 5   You will always respond in the format described below:
 6   <<symbolic expression>>
 7
 8   There are {t} trees in the {g}. {g} workers will plant trees in the {g} today. After they are done,
          there will be {tf} trees. How many trees did the {g} workers plant today?
 9
10   <<tf - t>>
11
12   If there are {c} cars in the parking lot and {nc} more cars arrive, how many cars are in the parking
          lot?
13
14   <<c + nc>>
15
16   {p1} had {ch1} {o1} and {p2} had {ch2} {o1}. If they ate {a} {o1}, how many pieces do they have left
          in total?
17
18   <<ch1 + ch2 - a>>
19
20   {p1} had {l1} {o1}. {p1} gave {g} {o1} to {p2}. How many {o1} does {p1} have left?
21
22   <<l1 - g>>
23
24   {p1} has {t} {o1}. For Christmas, {p1} got {tm} {o1} from {p2} and {td} {o1} from {p3}. How many {o1}
          does {p1} have now?
25
26   <<t + tm + td>>
27
28   There were {c} {o1} in the {loc}. {nc} more {o1} were installed each day, from {d1} to {d2}. How many
          {o1} are now in the {loc}?
29
30   <<c + nc * (d2 - d1 + 1)>>
31
32   {p1} had {gb1} {o1}. On {day1}, {p1} lost {l1} {o1}. On {day2}, {p1} lost {l2} more. How many {o1}
          does {p1} have at the end of {day2}?
33
34   <<gb1 - l1 - l2>>
35
36   {p1} has ${m}. {p1} bought {q} {o1} for ${p} each. How much money does {p1} have left?
37
38   <<m - q * p>>



                                                              16
                                     CRANE: Reasoning with constrained LLM generation

39
40    {question}


                               Listing 3. Prompt Template For GSM-Symbolic Evaluation Without CoT


     D.2. FOLIO Examples and Prompt
     FOLIO Problem Solution Examples:
 1    Question:
 2    People in this club who perform in school talent shows often attend and are very engaged with school
           events.
 3    People in this club either perform in school talent shows often or are inactive and disinterested
           community members.
 4    People in this club who chaperone high school dances are not students who attend the school.
 5    All people in this club who are inactive and disinterested members of their community chaperone high
           school dances.
 6    All young children and teenagers in this club who wish to further their academic careers and
           educational opportunities are students who attend the school.
 7    Bonnie is in this club and she either both attends and is very engaged with school events and is a
           student who attends the school or is not someone who both attends and is very engaged with school
            events and is not a student who attends the school.
 8    Based on the above information, is the following statement true, false, or uncertain? Bonnie performs
           in school talent shows often.
 9    ###
10
11    FOL Solution:
12    Predicates:
13    InClub(x) ::: x is a member of the club.
14    Perform(x) ::: x performs in school talent shows.
15    Attend(x) ::: x attends school events.
16    Engaged(x) ::: x is very engaged with school events.
17    Inactive(x) ::: x is an inactive and disinterested community member.
18    Chaperone(x) ::: x chaperones high school dances.
19    Student(x) ::: x is a student who attends the school.
20    Wish(x) ::: x wishes to further their academic careers and educational opportunities.
21    Premises:
22    {forall} x (InClub(x) {and} Attend(x) {and} Engaged(x) {implies} Attend(x)) ::: People in this club
           who perform in school talent shows often attend and are very engaged with school events.
23    {forall} x (InClub(x) {implies} (Perform(x) {xor} Inactive(x))) ::: People in this club either perform
            in school talent shows often or are inactive and disinterested community members.
24    {forall} x (InClub(x) {and} Chaperone(x) {implies} {not}Student(x)) ::: People in this club who
           chaperone high school dances are not students who attend the school.
25    {forall} x (InClub(x) {and} Inactive(x) {implies} Chaperone(x)) ::: All people in this club who are
           inactive and disinterested members of their community chaperone high school dances.
26    {forall} x (InClub(x) {and} (Young(x) {or} Teenager(x)) {and} Wish(x) {implies} Student(x)) ::: All
           young children and teenagers in this club who wish to further their academic careers and
           educational opportunities are students who attend the school.
27    {forall} x (InClub(x) {implies} (Attend(x) {and} Engaged(x)) {xor} {not}(Attend(x) {and} Engaged(x)) {
           and} {not}Student(x) {xor} Student(x)) ::: Bonnie is in this club and she either both attends and
            is very engaged with school events and is a student who attends the school or is not someone who
            both attends and is very engaged with school events and is not a student who attends the school.
28    Conclusion:
29    InClub(bonnie) {and} Perform(bonnie) ::: Bonnie performs in school talent shows often.
30
31    Answer: Uncertain


                                         Listing 4. Problem Solution Examples for FOLIO

     FOLIO Prompt:
 1    Given a problem description and a question. The task is to parse the problem and the question into
           first-order logic formulas.
 2    The grammar of the first-order logic formula is defined as follows:
 3    1) logical conjunction of expr1 and expr2: expr1 {and} expr2
 4    2) logical disjunction of expr1 and expr2: expr1 {or} expr2
 5    3) logical exclusive disjunction of expr1 and expr2: expr1 {xor} expr2
 6    4) logical negation of expr1: {not}expr1
 7    5) expr1 implies expr2: expr1 {implies} expr2
 8    6) expr1 if and only if expr2: expr1 {iff} expr2
 9    7) logical universal quantification: {forall} x
10    8) logical existential quantification: {exists} x. These are the ONLY operations in the grammar.
11    ------
12
13    Answer the question EXACTLY like the examples.
14



                                                              17
                                    CRANE: Reasoning with constrained LLM generation

15   Problem:
16   All people who regularly drink coffee are dependent on caffeine. People either regularly drink coffee
          or joke about being addicted to caffeine. No one who jokes about being addicted to caffeine is
          unaware that caffeine is a drug. Rina is either a student and unaware that caffeine is a drug, or
           neither a student nor unaware that caffeine is a drug. If Rina is not a person dependent on
          caffeine and a student, then Rina is either a person dependent on caffeine and a student, or
          neither a person dependent on caffeine nor a student.
17   Question:
18   Based on the above information, is the following statement true, false, or uncertain? Rina is either a
           person who jokes about being addicted to caffeine or is unaware that caffeine is a drug.
19   ###
20
21   We take three steps: first, we define the necessary predicates and premises, and finally, we encode
          the question ‘Rina is either a person who jokes about being addicted to caffeine or is unaware
          that caffeine is a drug.‘ in the conclusion. Now, we will write only the logic program, nothing
          else.
22   Predicates:
23   Dependent(x) ::: x is a person dependent on caffeine.
24   Drinks(x) ::: x regularly drinks coffee.
25   Jokes(x) ::: x jokes about being addicted to caffeine.
26   Unaware(x) ::: x is unaware that caffeine is a drug.
27   Student(x) ::: x is a student.
28   Premises:
29   {forall} x (Drinks(x) {implies} Dependent(x)) ::: All people who regularly drink coffee are dependent
          on caffeine.
30   {forall} x (Drinks(x) {xor} Jokes(x)) ::: People either regularly drink coffee or joke about being
          addicted to caffeine.
31   {forall} x (Jokes(x) {implies} {not}Unaware(x)) ::: No one who jokes about being addicted to caffeine
          is unaware that caffeine is a drug.
32   (Student(rina) {and} Unaware(rina)) {xor} {not}(Student(rina) {or} Unaware(rina)) ::: Rina is either a
           student and unaware that caffeine is a drug, or neither a student nor unaware that caffeine is a
           drug.
33   Conclusion:
34   Jokes(rina) {xor} Unaware(rina) ::: Rina is either a person who jokes about being addicted to caffeine
           or is unaware that caffeine is a drug.
35   ------
36
37   Problem:
38   Miroslav Venhoda was a Czech choral conductor who specialized in the performance of Renaissance and
          Baroque music. Any choral conductor is a musician. Some musicians love music. Miroslav Venhoda
          published a book in 1946 called Method of Studying Gregorian Chant.
39   Question:
40   Based on the above information, is the following statement true, false, or uncertain? Miroslav Venhoda
           loved music.
41   ###
42
43   We take three steps: first, we define the necessary predicates and premises, and finally, we encode
          the question ‘Miroslav Venhoda loved music.‘ in the conclusion. Now, we will write only the logic
           program, nothing else.
44   Predicates:
45   Czech(x) ::: x is a Czech person.
46   ChoralConductor(x) ::: x is a choral conductor.
47   Musician(x) ::: x is a musician.
48   Love(x, y) ::: x loves y.
49   Author(x, y) ::: x is the author of y.
50   Book(x) ::: x is a book.
51   Publish(x, y) ::: x is published in year y.
52   Specialize(x, y) ::: x specializes in y.
53   Premises:
54   Czech(miroslav) {and} ChoralConductor(miroslav) {and} Specialize(miroslav, renaissance) {and}
          Specialize(miroslav, baroque) ::: Miroslav Venhoda was a Czech choral conductor who specialized
          in the performance of Renaissance and Baroque music.
55   {forall} x (ChoralConductor(x) {implies} Musician(x)) ::: Any choral conductor is a musician.
56   {exists} x (Musician(x) {and} Love(x, music)) ::: Some musicians love music.
57   Book(methodOfStudyingGregorianChant) {and} Author(miroslav, methodOfStudyingGregorianChant) {and}
          Publish(methodOfStudyingGregorianChant, year1946) ::: Miroslav Venhoda published a book in 1946
          called Method of Studying Gregorian Chant.
58   Conclusion:
59   Love(miroslav, music) ::: Miroslav Venhoda loved music.
60   ------
61
62   {question}


                                     Listing 5. Prompt Template Used For FOLIO Evaluation




                                                             18
                                        CRANE: Reasoning with constrained LLM generation

     D.3. Case Study For GSM-Symbolic
 1    Question: {name} hires a {vehicle} from {start_hour} to {end_hour}. He gets {free_hours} hours free.
           The first paid hour is ${first_hour_cost} and each hour after that is {multiplier} the cost. How
           much did he pay?
 2
 3    Constrained: <<(int(end_hour - start_hour) - free_hours) * first_hour_cost + free_hours *
           first_hour_cost + (int(end_hour - start_hour) - free_hours - 1) * multiplier * first_hour_cost>>
 4
 5    Unconstrained With CoT: Let’s think step by step. The total time hired is from {start_hour} to {
           end_hour}, which is <<int((end_hour - start_hour).total_seconds() / 3600)>> hours. Subtracting
           the {free_hours} free hours, the paid hours are <<int((end_hour - start_hour).total_seconds() /
           3600) - free_hours>>. The final answer is <<first_hour_cost + (int((end_hour - start_hour).
           total_seconds() / 3600) - free_hours - 1) * multiplier * first_hour_cost>>.
 6
 7    CRANE: Let’s think step by step. The total time hired is from {start_hour} to {end_hour}, totaling <<
           int(end_hour - start_hour)>> hours. Subtracting {free_hours} free hours, the paid hours are <<int
           (end_hour - start_hour) - free_hours>>. The first hour costs {first_hour_cost}, and each
           additional hour costs {multiplier} times that. The final answer is <<first_hour_cost + (int(
           end_hour - start_hour) - free_hours - 1) * multiplier * first_hour_cost>>.


                                                Listing 6. Case Study for GSM-Symbolic

     CRANE effectively alternates between constrained and unconstrained generation to produce intermediate expressions, the
     final answer, and to maintain the reasoning capabilities of the LLM. In contrast, unconstrained generation with CoT results
     in a syntactically incorrect expression, while constrained generation produces a syntactically valid but incorrect expression.

     D.4. Sampling Ablation for GSM-Symbolic
     In our GSM-Symbolic case study, we use IterGen as the constrained generation baseline and initialize CRANE with IterGen.
     Both IterGen and CRANE employ selective rejection sampling to filter tokens that do not satisfy semantic constraints.
     For comparison, we also run unconstrained generation using temperature sampling and evaluate its performance against
     CRANE. Specifically, for Qwen2.5-1.5B-Instruct and Llama-3.1-8B-Instruct, we generate three samples with unconstrained
     generation at a temperature of t = 0.7 and compute pass@1/2/3 metrics.
     As shown in Table 4, CRANE with greedy decoding achieves higher accuracy than pass@1/2/3 for unconstrained generation
     with Chain-of-Thought (CoT) and temperature sampling on Qwen2.5-1.5B-Instruct. Although, for Llama-3.1-8B-Instruct,
     unconstrained generation with CoT and temperature sampling achieves a pass@3 accuracy of 35%—2% higher than
     CRANE—it generates approximately 4 times as many tokens as CRANE.

     D.5. Grammars
     D.5.1. GSM-S YMBOLIC G RAMMAR
 1    start: space? "<" "<" space? expr space? ">" ">" space?
 2
 3    expr: expr space? "+" space? term
 4         | expr space? "-" space? term
 5         | term
 6
 7    term: term space? "*" space? factor
 8         | term space? "/" space? factor
 9         | term space? "//" space? factor
10         | term space? "%" space? factor
11         | factor space?
12
13    factor: "-" space? factor
14           | TYPE "(" space? expr space? ")"
15           | primary space?
16
17    primary: NUMBER
18            | VARIABLE
19            | "(" space? expr space? ")"
20
21    TYPE.4: "int"
22
23    space: " "
24
25    %import common.CNAME -> VARIABLE
26    %import common.NUMBER




                                                                  19
                                     CRANE: Reasoning with constrained LLM generation



                                              Listing 7. GSM-Symbolic Grammar


     D.5.2. P ROVER 9 G RAMMAR
 1   start: predicate_section premise_section conclusion_section
 2
 3   predicate_section: "Predicates:" predicate_definition+
 4   premise_section: "Premises:" premise+
 5   conclusion_section: "Conclusion:" conclusion+
 6
 7   predicate_definition: PREDICATE "(" VAR ("," VAR)* ")" COMMENT    -> define_predicate
 8   premise: quantified_expr COMMENT -> define_premise
 9   conclusion: quantified_expr COMMENT -> define_conclusion
10
11   quantified_expr: quantifier VAR "(" expression ")" | expression
12   quantifier: "{forall}" -> forall | "{exists}" -> exists
13
14   expression: bimplication_expr
15
16   ?bimplication_expr: implication_expr ("{iff}" bimplication_expr)? -> iff
17   ?implication_expr: xor_expr ("{implies}" implication_expr)? -> imply
18   ?xor_expr: or_expr ("{xor}" xor_expr)?                -> xor
19   ?or_expr: and_expr ("{or}" or_expr)?                -> or
20   ?and_expr: neg_expr ("{and}" and_expr)?              -> and
21   ?neg_expr: "{not}" quantified_expr                   -> neg
22           | atom
23
24   ?atom: PREDICATE "(" VAR ("," VAR)* ")" -> predicate
25       | "(" quantified_expr ")"
26
27   // Variable names begin with a lowercase letter
28   VAR.-1: /[a-z][a-zA-Z0-9_]*/ | /[0-9]+/
29
30   // Predicate names begin with a capital letter
31   PREDICATE.-1: /[A-Z][a-zA-Z0-9]*/
32
33   COMMENT: /:::.*\n/
34
35   %import common.WS
36   %ignore WS


                                                 Listing 8. Prover9 Grammar




                                                              20
                            CRANE: Reasoning with constrained LLM generation




Table 3. Comparison of CRANE and baselines on GSM-Symbolic based on accuracy, no. of tokens, and average time.
         Model                        k          Method            Acc. (%)    Parse (%)    Tokens
                                          Unconstrained w/o CoT        20          98         18.23
                                              Constrained              21          95         34.28
         Qwen2.5-1.5B-Instruct        2    Unconstrained CoT           22          90        130.74
                                                CRANE                  28          96        140.52
                                          Unconstrained w/o CoT        18          95         18.23
                                              Constrained              18          96         34.28
         Qwen2.5-1.5B-Instruct        4    Unconstrained CoT           24          94        130.74
                                                CRANE                  30          98        140.52
                                          Unconstrained w/o CoT        21           97        23.34
                                              Constrained              22          97         25.29
         Qwen2.5-1.5B-Instruct        8    Unconstrained CoT           26          90        128.97
                                                CRANE                  31          100        131.3
                                          Unconstrained w/o CoT        37          96         17.22
                                              Constrained              36          99         18.61
         Qwen2.5-Coder-7B-Instruct    2    Unconstrained CoT           32          84        148.87
                                                CRANE                  37          96        155.65
                                          Unconstrained w/o CoT        36           96        16.89
                                              Constrained              36          100        18.81
         Qwen2.5-Coder-7B-Instruct    4    Unconstrained CoT           35          89        151.29
                                                CRANE                  37           97       163.21
                                          Unconstrained w/o CoT        36          94         17.92
                                              Constrained              35          99         25.28
         Qwen2.5-Coder-7B-Instruct    8    Unconstrained CoT           37          88        138.38
                                                CRANE                  39          94        155.32
                                          Unconstrained w/o CoT        20          66        115.22
                                              Constrained              26          95         26.99
         Qwen2.5-Math-7B-Instruct     2    Unconstrained CoT           28          72        190.51
                                                CRANE                  32          89        195.65
                                          Unconstrained w/o CoT        22          83            47
                                              Constrained              29          98         27.08
         Qwen2.5-Math-7B-Instruct     4    Unconstrained CoT           28          76        184.35
                                                CRANE                  37          88        194.77
                                          Unconstrained w/o CoT        27          89          25.7
                                              Constrained              29          99         26.81
         Qwen2.5-Math-7B-Instruct     8    Unconstrained CoT           29          82        155.26
                                                CRANE                  38          94        158.86
                                          Unconstrained w/o CoT        19          61        157.36
                                              Constrained              23          95         45.58
         Llama-3.1-8B-Instruct        2    Unconstrained CoT           29          84        198.64
                                                CRANE                  35          94        206.85
                                          Unconstrained w/o CoT        18          68         131.5
                                              Constrained              24          96         37.38
         Llama-3.1-8B-Instruct        4    Unconstrained CoT           26          92        172.21
                                                CRANE                  30          97        179.95
                                          Unconstrained w/o CoT        21          73        128.38
                                              Constrained              26          98         35.97
         Llama-3.1-8B-Instruct        8    Unconstrained CoT           30          95        163.55
                                                CRANE                  33          95        170.22




                                                     21
                                 CRANE: Reasoning with constrained LLM generation




        Table 4. Comparison of CRANE and greedy and sampling baselines with different models on GSM-Symbolic.
  Model                     Method                             pass@1/2/3 (%)     Parse (%)                   Tokens
                            Unconstrained w/o CoT (Greedy)           21               97                        23.34
                            Unconstrained w/o CoT (t = 0.7)       15/19/22         88/96/98         20.19/39.76/60.57
                            Constrained (Greedy)                     22               97                        25.29
  Qwen2.5-1.5B-Instruct     Unconstrained CoT (Greedy)               26               90                       128.97
                            Unconstrained CoT (t = 0.7)           21/25/30         78/91/96      146.22/292.96/444.61
                            CRANE                                    31              100                        131.3
                            Unconstrained w/o CoT (Greedy)           21               73                       128.38
                            Unconstrained w/o CoT (t = 0.7)       15/21/25         51/74/84      106.88/232.75/369.86
                            Constrained (Greedy)                     26               98                        35.97
  Llama-3.1-8B-Instruct     Unconstrained CoT (Greedy)               30               95                       163.55
                            Unconstrained CoT (t = 0.7)           24/29/35         89/98/98       196.01/403.68/607.7
                            CRANE (Greedy)                           33               95                       170.22




           Table 5. Comparison of CRANE and greedy and sampling baselines with different models on FOLIO.
Model                     Method                        pass@1/2/3 (%)         Compile (%)                      Tokens
                          Unconstrained CoT (Greedy)          36.95                70.94                         350.64
                          Unconstrained CoT (t = 0.7)   16.75/28.57/34.98    35.96/55.67/68.47     401.5/800.19/1219.33
Qwen2.5-7B-Instruct       Constrained (Greedy)                37.44                87.68                         775.62
                          CRANE (Greedy)                      42.36                87.68                         726.88
                          Unconstrained CoT (Greedy)          32.02               57.14                          371.52
                          Unconstrained CoT (t = 0.7)   14.29/22.66/29.06    33.99/46.8/57.64     435.35/877.33/1307.45
Llama-3.1-8B-Instruct     Constrained (Greedy)                39.41               86.21                          549.75
                          CRANE (Greedy)                      46.31               85.71                          449.77




                                                          22
