Constrained Decoding for Large Language Models
(a practical, “how-it-works-under-the-hood” tour)
1. Why do we need constraints?
• Generate valid JSON / SQL / code that actually parses
• Force the model to mention a required phrase, entity, or slot → “lexical constraints”
• Enforce safety (never say disallowed words)
• Steer interactive agents through a finite-state dialogue policy
• Guarantee well-formed structure for function-calling, XML, etc.
2. Two families of constraints
| Type | Typical spec | Guarantee? | Cost | Common APIs |
|---|
| Hard | Regex, CFG, DFA, trie, token whitelist/blacklist | Must be satisfied | ↑ search | prefix_allowed_tokens_fn, logit_bias=-∞ |
| Soft | Penalties, rewards, logit bias (finite) | Encouraged, not enforced | ↔︎ | logit_bias=+/-, custom scoring |
Below we focus on hard constraints because they require special decoding logic.
3. The generic recipe
Imagine we are doing normal greedy / top-k / beam decoding:
- Model produces logits
p_t for all tokens at time t.
- We pick one (or many) next tokens according to some rule.
- Repeat until
<eos> or max length.
Constrained decoding ≈ “step 2.5”: mask out any token that would violate the constraint before we sample / rank candidates.
for t in range(max_len):
logits = model(...) # 1. normal forward pass
allowed = constraint_mask(...) # 2.5 build mask (0/-∞) ⚡
logits += allowed # apply mask
token = sample(logits) # 3. pick next token
The interesting part is how we build constraint_mask.
4. How to represent the constraint
A) Trie / prefix whitelist – easiest
• Put every allowed word or phrase into a trie keyed by token IDs.
• allowed(next_token) = 1 if the current node has that child.
B) Finite-State Automaton (DFA) generated from
• A regular expression, or
• A context-free grammar turned into an LR(0)/LL parser, or
• A dialogue policy graph.
Each partial hypothesis stores its current DFA state; only arcs leaving that state are valid next tokens.
C) Hand-written function
HuggingFace:
def prefix_allowed_tokens(batch_id, partial_tokens):
if partial_tokens == [tokenizer.bos_token_id]:
return positive_word_ids # e.g., ["yes", "sure", ...]
...
5. Search variants
-
Greedy / Top-k / Nucleus with masking
Very cheap, but one bad early choice = dead end.
-
Constrained Beam Search (CBS) – Hokamp & Liu 2017
• Each beam hypothesis keeps its DFA state + language-model score.
• Expand only allowed arcs.
• Optional “satisfy-or-abort” heuristics for lexical constraints (open slots that must appear soon).
-
Token-level A* or Partial-Order Planning
Used when constraints are very tight (e.g., SQL grammar) and we still want optimal LM score.
-
Insertion-based decoding (e.g., LaViLa, ILM):
Insert missing constrained phrases later rather than strictly left-to-right.
6. A tiny code sketch (HF Transformers)
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
tok = AutoTokenizer.from_pretrained("gpt2")
model = AutoModelForCausalLM.from_pretrained("gpt2")
phrase = "openai"
phrase_ids = tok.encode(" " + phrase) # leading space for GPT-2 BPE
trie = {phrase_ids[0]: {phrase_ids[1]: {}}} # simple 2-token trie
def allowed(batch_id, prev_tokens):
# If we already produced "openai", lift all constraints
if phrase_ids[0] in prev_tokens and phrase_ids[1] in prev_tokens:
return list(range(len(tok)))
node = trie
for t in prev_tokens[-len(phrase_ids)+1:]:
node = node.get(t, {})
return list(node.keys()) if node else list(range(len(tok)))
out = model.generate(
**tok("Hello, my company is", return_tensors="pt"),
max_new_tokens=15,
prefix_allowed_tokens_fn=allowed
)
print(tok.decode(out[0], skip_special_tokens=True))
This forces the string “openai” to appear somewhere in the continuation.
7. Practical tips & caveats
• Tokenization matters: constraints are applied on token IDs, not characters. Check how your word pieces split!
• End-of-sequence: Make sure <eos> is masked until all obligations are met.
• Beam width vs. constraint tightness: Narrow beams can get “stuck” (no valid tokens) → expand beam size or allow backtracking.
• Speed: Mask building can be done in pure Python if constraint set is tiny; for grammars compile DFA into Torch/TensorFlow ops to stay on-device.
• Composability: Multiple constraints = intersect their automatons (product automaton) then decode once.
• Logit bias: For “soft” constraints, just add or subtract log-prob mass instead of hard masking.
8. Where you already see it in the wild
• OpenAI functions, json_schema → server-side constrained decoding using a JSON grammar DFA.
• ChatGPT “format your answer as markdown list” → masked newline / dash tokens (soft).
• Guardrails.ai, Outlines, LMQL, Guidance → compile user schema → constrained decoding loop.
• HuggingFace transformers ≥ v4.27 provides logits_processor subclasses for grammars/regex.
9. Take-away mental model
- Write your constraint as a machine (trie / DFA).
- During each decoding step, ask the machine “which tokens keep me legal?”.
- Mask everything else → normal sampling continues.
That’s it! You have transformed a free-form generative model into a controllable, syntax-aware generator—without retraining the network at all. 🎯