Constrained decoding: a valid sequence is not necessarily the best one
约束解码
Track a required phrase with an automaton, compare beams with enumeration and distinguish local masks from conditioning.
decoding-constraints“Contains A then B” can change the whole search
A model generates three tokens from A, B and X. Require the contiguous phrase AB somewhere in the output. Unconstrained greedy decoding produces XXX, which is invalid. A width-one search that rejects prefixes with no possible valid completion returns XAB, with original model probability 0.072. Exhaustive search finds the better valid sequence ABX, with probability 0.224.
So there are already three different questions: did we satisfy the requirement, did we find the highest-scoring valid sequence, and did we sample the original model conditioned on validity? A decoder can answer one correctly while failing another.
Grid Beam Search organizes hypotheses by time and constraint coverage, so paths progressing through required words or phrases do not simply compete in one undifferentiated beam. Dynamic Beam Allocation instead distributes a fixed total beam across coverage groups. The example below illustrates state-based allocation on a tiny model; it does not implement the papers’ full translation systems.
Define both the language of valid outputs and the objective
Let mean that complete sequence satisfies the requirement. A constrained maximum-probability decoder seeks:
The original autoregressive probability is:
Production searches normally accumulate log probabilities to avoid multiplying very small numbers:
Our length-three example multiplies directly for transparent arithmetic. It fixes output length and has no EOS token, so there is no implicit length penalty. Adding EOS, a length normalization or a soft constraint penalty changes the problem and should be stated explicitly.
For phrase AB, use three automaton states: zero means not yet matched and the last token is not A; one means the latest token is A but AB has not yet appeared; two means the phrase has appeared. The update is:
The absorbing state two permits any later token. Two occurrences in the wrong order do not suffice: BXA is invalid. Nor does noncontiguous AXB satisfy a contiguous phrase. On the other hand, AAB does satisfy it because the second A begins the match. The tests compare the automaton with ordinary substring membership for every sequence up to length five.
Feasibility alone asks whether some valid completion remains. Exact conditional sampling needs more information. Define as the probability that the target model completes prefix into a valid length- sequence. At the horizon, it is one for a valid completed sequence and zero otherwise. Before the horizon:
For this finite Markov model, the memoized state can be compressed to automaton state, last token and remaining length. A general neural language model cannot usually be compressed that way; exact future-mass evaluation may require an exponential search.
When , the original model conditioned on final validity has next-token distribution:
This follows by factoring the joint event “next token is and the eventual output is valid.” Every feasible next token is weighted by how much successful future probability mass it leads to. By contrast, a local feasibility mask samples:
The mask distinguishes possible from impossible, but ignores differences among positive future masses. These distributions generally differ. In the example, all three first tokens are feasible, so the local distribution remains . Exact conditioning gives approximately .
Use exhaustive search as the baseline
The complete NumPy program declares an initial distribution and a three-by-three transition matrix. It enumerates valid outputs, computes future mass, and compares one global beam with beams allocated separately to automaton states. It also exposes local-mask and globally conditioned next-token probabilities.
"""Finite phrase-constrained decoding: enumeration, state-banked beam and conditional sampling."""
import itertools,json
from functools import lru_cache
import numpy as np
TOKENS=('A','B','X')
START=np.array([.35,.05,.60])
TRANSITION=np.array([[.05,.80,.15],[.10,.10,.80],[.15,.05,.80]])
def advance(state,token):
if state==2 or (state==1 and token==1):return 2
return 1 if token==0 else 0
def probs(prefix):return START if not prefix else TRANSITION[prefix[-1]]
def state_of(prefix):
state=0
for token in prefix:state=advance(state,token)
return state
def probability(prefix):
score=1.;previous=[]
for token in prefix:score*=probs(previous)[token];previous.append(token)
return float(score)
def enumerate_valid(length):
if type(length) is not int or not 0<=length<=8:raise ValueError('Enumeration length must be in 0..8')
rows=[(p,probability(p)) for p in itertools.product(range(3),repeat=length) if state_of(p)==2]
return sorted(rows,key=lambda row:(-row[1],row[0]))
@lru_cache(None)
def future_mass(state,last,remaining):
if remaining==0:return float(state==2)
p=START if last==-1 else TRANSITION[last]
return float(sum(p[t]*future_mass(advance(state,t),t,remaining-1) for t in range(3)))
def next_distribution(prefix,total_length,conditional):
remaining=total_length-len(prefix)
if remaining<=0:raise ValueError('No positions remain')
state=state_of(prefix);p=probs(prefix)
future=np.array([future_mass(advance(state,t),t,remaining-1) for t in range(3)])
weights=p*(future if conditional else (future>0))
if weights.sum()==0:raise ValueError('Constraint has no feasible completion')
return weights/weights.sum()
def beam(length,width=1,banked=False):
if type(length) is not int or not 1<=length<=8 or type(width) is not int or width<1:
raise ValueError('Length 1..8 and positive beam width required')
current=[((),1.)];trace=[]
for t in range(length):
candidates=[]
for prefix,score in current:
for token,p in enumerate(probs(prefix)):
nxt=prefix+(token,);s=state_of(nxt)
if p>0 and future_mass(s,token,length-len(nxt))>0:candidates.append((nxt,score*float(p)))
candidates.sort(key=lambda row:(-row[1],row[0]));counts={};current=[]
for row in candidates:
key=state_of(row[0]) if banked else 0
if counts.get(key,0)<width:current.append(row);counts[key]=counts.get(key,0)+1
trace.append(dict(step=t+1,kept=len(current),states=[state_of(p) for p,s in current]))
return (sorted(current,key=lambda row:(-row[1],row[0]))[0] if current else None),trace
def demo():
rows=enumerate_valid(3);mass=sum(s for p,s in rows);global_result,gt=beam(3);bank_result,bt=beam(3,banked=True)
greedy=[]
for _ in range(3):greedy.append(int(np.argmax(probs(greedy))))
def named(row):return None if row is None else dict(tokens=[TOKENS[t] for t in row[0]],probability=row[1])
return dict(valid_sequences=[named(r) for r in rows],valid_mass=mass,unconstrained_greedy=[TOKENS[t] for t in greedy],
global_beam=named(global_result),banked_beam=named(bank_result),global_trace=gt,banked_trace=bt,
local_feasible_first=next_distribution([],3,False).tolist(),
global_conditional_first=next_distribution([],3,True).tolist(),
scope='One phrase AB, fixed length3, no EOS; state banking is not the full GBS/DBA implementation')
if __name__=='__main__':print(json.dumps(demo()))
There are six valid length-three sequences. Their probabilities sum to 0.37. Those beginning with A, B and X have total original masses 0.294, 0.004 and 0.072; dividing by 0.37 gives the exact conditional first-token distribution. The test multiplies conditional transitions along every valid sequence and checks that the result equals its original probability divided by 0.37.
With one global slot, the first step retains X because it has probability 0.6 and still permits completion. The remaining positions must then produce A and B, giving 0.072. With one slot per automaton state, the first step retains both X in state zero and A in state one. This keeps the path that becomes ABX, recovering the exhaustive optimum 0.224 in this example.
Per-state allocation is not a general optimality proof. Several histories can have the same automaton state but different model states and future scores. Pruning them to one slot can still lose a better completion. Keeping one slot per state also increases the total beam relative to one global slot; the experiment does not pretend the computational budgets are equal.
Exhaustive enumeration considers sequences and is deliberately limited to length eight. The future-mass dynamic program has at most a quantity proportional to states and considers outgoing tokens each, for work in this Markov setting. The readable beam code repeatedly builds tuples, sorts candidates and recomputes phrase states; it is not an optimized decoder or a benchmark of GBS versus DBA.
A hard rule needs a precise unit and stopping policy
A word-level requirement and a token-level phrase requirement may differ under subword tokenization. Case, spaces and punctuation can matter. General phrase sets also need coverage of multiple constraints and handling of overlapping prefixes. This three-state machine covers only one exact two-token phrase.
GBS tracks progress through constraint tokens and distinguishes hypotheses that can generate freely from ones continuing a phrase. DBA maintains a fixed total beam and reallocates slots among coverage groups; its candidate handling also addresses interrupted phrase prefixes. Our banked search is a finite-state teaching variant, not DBA, and it does not inherit the papers’ runtime claims.
If no valid completion has positive probability within the length limit, report infeasibility instead of returning a malformed answer or dividing by zero. EOS should be allowed only under the intended completion rule. Even perfectly valid syntax or phrase coverage does not establish factual correctness, faithful translation or semantic satisfaction of a user’s request.
Separate validity, optimum and distribution
- Which of
AXB,BXAandAABcontains the required contiguous phrase? Answer: OnlyAAB. Its last two tokens areAB. Merely containing both token types, or preserving their order with a gap, is insufficient. - Why does the global width-one feasible search miss
ABX? Answer: At step one it keeps the higher-probabilityXand prunesA. Feasibility proves thatXcan finish, not that its best completion outranks completions ofA. - What is the conditioned probability of first token
X? Answer: , approximately 0.194595. A local feasibility mask leaves its original first-step probability 0.6 because every first token still has at least one valid completion. - Does matching the exhaustive optimum here prove one slot per automaton state is always enough? Answer: No. Histories with the same phrase state can have different model states and future opportunities. The exact match is an outcome of this example; general optimality requires a justified state representation and search algorithm.
Constraints change search organization, not just logits
Hokamp and Liu make constraint progress an explicit search dimension. Post and Vilar investigate how to maintain progress while keeping the total beam fixed. Both focus on generating required lexical material without treating every path as equivalent merely because its current language-model score is high.
The example adds a second comparison: search for the best valid output differs from sampling a valid-output conditional distribution. Local renormalization can enforce feasibility while changing the latter distribution. An implementation should name its objective before reporting success, then check that objective with an oracle on small cases where exact answers are available.
Make a prediction, then check
Does locally masking impossible continuations generally sample the original model conditioned on the final constraint?
Learning objectives
- Track contiguous phrase completion instead of counting tokens independently.
- Compare feasibility, beam pruning and global sequence optimality.
- Derive future-mass reweighting for globally conditioned sampling.
Prerequisites & connections
Explore related knowledge →References
- Lexically Constrained Decoding for Sequence Generation Using Grid Beam Search
Chris Hokamp; Qun Liu · 2017 - Fast Lexically Constrained Decoding with Dynamic Beam Allocation for Neural Machine Translation
Matt Post; David Vilar · 2018
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author read Hokamp ACL2017 PDF3/4 Algorithm1/Figure3 plus selected3.1/3.2 text, and Post NAACL2018 PDF3/4 sections3–3.3/Figure2. Seven paired equations and four explained exercises. Original AB automaton, all short sequences, six valid length-three probabilities, exact future mass, conditioning products and beam counterexample. Per-state beam uses more slots and is not full GBS/DBA; no universal optimality or performance claim.
- Single AI author read Hokamp ACL2017 PDF3/4 Algorithm1/Figure3 plus selected3.1/3.2 text, and Post NAACL2018 PDF3/4 sections3–3.3/Figure2. Seven paired equations and four explained exercises. Original AB automaton, all short sequences, six valid length-three probabilities, exact future mass, conditioning products and beam counterexample. Per-state beam uses more slots and is not full GBS/DBA; no universal optimality or performance claim.
- Four computed SVG variants per topic;9 numeric/geometry tests and24 responsive cases passed. Eight final Chinese-mobile/English-desktop screenshots actually inspected. Full article acceptance recorded separately.
Source locations checked:
- Lexically Constrained Decoding for Sequence Generation Using Grid Beam Search · Visually read PDF3–4, section3, Figure3 and Algorithm1: grid axes, open/closed hypotheses, start/continue constraints and finish with EOS after coverage. Original finite-state example is not full GBS or an NMT reproduction.
- Fast Lexically Constrained Decoding with Dynamic Beam Allocation for Neural Machine Translation · Visually read PDF3–4, sections3–3.3 and Figure2: fixed total beam, constraint banks, candidate generation, phrase reset and finishing. No DBA runtime or translation benchmark reproduced.
Related topics