Provably Tractable NFA-Constrained Language Generation via HMMs
Organizations: University of Toronto
Abstract
Constrained generation aims to sample from language models (LMs) conditioned on hard constraints. Existing constrained-generation techniques for nondeterministic finite automaton (NFA) constraints either distort the distribution or sacrifice efficiency. Theoretically, this task reduces to counting the length- sequences accepted by an NFA (#NFA), and the exact #NFA problem is #P-complete. Recent work has shown that #NFA admits a fully polynomial randomized approximation scheme (FPRAS). Inspired by this result, we propose NFA-LM, a polynomial-time engine for NFA-constrained generation with theoretical guarantees under mild assumptions. Experiments show that NFA-LM efficiently generates high-quality outputs with theoretically bounded approximation error.
Figures & tables
| Family | Constraint | NFA states | DFA states |
|---|---|---|---|
| kth_last | The -th token from the end is one of the tracked keywords. | ||
| repeat_after_k | Some tracked keyword repeats tokens apart. | ||
| at_least_k | Some tracked keyword appears at least times. | ||
| exactly_once | Some tracked keyword occurs exactly once. | ||
| left_not_right | Some tracked keyword occurs on the left of the separator but not on the right. | ||
| right_not_left | Some tracked keyword occurs on the right of the separator but not on the left. |
| Method | Success | Time (s) | Quality |
|---|---|---|---|
| LLM-only | |||
| GPT-5.6 Luna | 306 (61.2%) | 1.9 | 2.93 |
| Qwen3.5-2B | 190 (38.0%) | 1.0 | 1.89 |
| Gemma-4-E2B | 227 (45.4%) | 1.0 | 2.70 |
| XGrammar | |||
| Qwen3.5-2B | 500 (100.0%) | 2.8 | 1.75 |
Appendix figures & tables1 asset
Supplementary material from the paper’s appendix.