AI Wiki中文/EN

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.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

“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.

Exhaustive valid probabilities expose a search failure and distinguish feasibility masks from conditioning.
Exhaustive valid probabilities expose a search failure and distinguish feasibility masks from conditioning.

Define both the language of valid outputs and the objective

Let C(y)C(y) mean that complete sequence yy satisfies the requirement. A constrained maximum-probability decoder seeks:

y∗=arg max⁡y:C(y)P(y).y^*=\operatorname*{arg\,max}_{y:C(y)}P(y).

The original autoregressive probability is:

P(y1:T)=∏t=1Tp(yt∣y<t).P(y_{1:T})=\prod_{t=1}^{T}p(y_t\mid y_{<t}).

Production searches normally accumulate log probabilities to avoid multiplying very small numbers:

log⁡P(y1:T)=∑t=1Tlog⁡p(yt∣y<t).\log P(y_{1:T})=\sum_{t=1}^{T}\log p(y_t\mid y_{<t}).

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:

δ(s,a)={2,s=2 or (s=1 and a=B),1,s≠2 and a=A,0,otherwise.\delta(s,a)=\begin{cases}2,&s=2\text{ or }(s=1\text{ and }a=B),\\1,&s\ne2\text{ and }a=A,\\0,&\text{otherwise}.\end{cases}

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 F(h)F(h) as the probability that the target model completes prefix hh into a valid length-TT sequence. At the horizon, it is one for a valid completed sequence and zero otherwise. Before the horizon:

F(h)=∑ap(a∣h)F(ha).F(h)=\sum_a p(a\mid h)F(ha).

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 F(h)>0F(h)>0, the original model conditioned on final validity has next-token distribution:

p(a∣h,C)=p(a∣h)F(ha)F(h).p(a\mid h,C)=\frac{p(a\mid h)F(ha)}{F(h)}.

This follows by factoring the joint event “next token is aa 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:

qlocal(a∣h)=p(a∣h)1{F(ha)>0}∑bp(b∣h)1{F(hb)>0}.q_{\mathrm{local}}(a\mid h)=\frac{p(a\mid h)\mathbf1\{F(ha)>0\}}{\sum_b p(b\mid h)\mathbf1\{F(hb)>0\}}.

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 (0.35,0.05,0.60)(0.35,0.05,0.60). Exact conditioning gives approximately (0.794595,0.010811,0.194595)(0.794595,0.010811,0.194595).

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 3T3^T sequences and is deliberately limited to length eight. The future-mass dynamic program has at most a quantity proportional to T∣S∣VT|S|V states and considers VV outgoing tokens each, for O(T∣S∣V2)O(T|S|V^2) 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

  1. Which of AXB, BXA and AAB contains the required contiguous phrase? Answer: Only AAB. Its last two tokens are AB. Merely containing both token types, or preserving their order with a gap, is insufficient.
  2. Why does the global width-one feasible search miss ABX? Answer: At step one it keeps the higher-probability X and prunes A. Feasibility proves that X can finish, not that its best completion outranks completions of A.
  3. What is the conditioned probability of first token X? Answer: 0.072/0.370.072/0.37, 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.
  4. 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?

Choose one answer

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

  1. Lexically Constrained Decoding for Sequence Generation Using Grid Beam Search
    Chris Hokamp; Qun Liu · 2017
  2. 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.