Grammar-constrained decoding makes large language models better logical parsers
With Tanir Özçelebi and Mike Holenderski, Eindhoven University of Technology
If you let a language model translate a logic problem into a formal program and hand the reasoning to a theorem prover, the weak link is syntax: one misplaced bracket and the solver can't run it. I forced the model's output to follow the solver's grammar while it generates, and small models went from almost never producing runnable programs to almost always doing so.
Read the full storyClose
The problem
LLMs look good on reasoning benchmarks like GSM8K, but their scores drop when problems are lightly perturbed, which suggests they're pattern-matching rather than reasoning. A popular fix is to split the job: the LLM acts as a parser that turns the natural-language problem into a symbolic program, and a solver such as Prover9 does the actual inference. That moves the failure point to syntax. The usual remedies are few-shot examples in the prompt, or asking the model to check and fix its own output, and neither guarantees a valid program.
The approach
I wrote context-free grammars for first-order logic (for FOLIO) and for arithmetic programs (for GSM-symbolic), and used grammar-constrained decoding: at every generation step, tokens that would break the grammar are masked out. The model can still choose what to say, but it can only say it in a form the solver accepts.
What I found
I tested 13 instruction-tuned open models from four families (Gemma 2, Llama 3, Mistral, Qwen 2.5), from 0.5B to 27B parameters, with 0, 2 and 5 in-context examples. The chart shows the share of generated programs the solver could actually run, with no examples in the prompt.
Show the numbers
- Constraints helped every model, and helped small models most. Llama 3.2 1B went from 0.00 to 0.98 executable programs on GSM-symbolic.
- In most cases, zero-shot with constraints beat unconstrained five-shot, which matters wherever expert-written examples are scarce or the prompt budget is tight.
- Constraints and examples are complementary: the best scores usually came from using both.
- For the largest models with several examples, unconstrained decoding sometimes won on accuracy. This fits recent theoretical work showing that constrained decoding biases the output distribution. My reading is that grammars steer small models toward good outputs, but once a model is good enough, the bias starts to cost more than it saves.
- A context-free grammar guarantees syntax, not meaning. Errors like inconsistent predicates still slip through, which is where I think the next step lies.