Search and control in decoding: greedy, beam search, constraints and MBR
Translation or summarization can seek a high-probability sequence, while valid JSON or a function call must obey a grammar. We study greedy decoding and length-normalized beam search, the paradox of finding a better mode but worse quality, diverse and stochastic variants, constrained decoding compiled to automata over a tokenizer vocabulary, and minimum Bayes risk decoding.
After this lesson you can
- Implement batched beam search with finished hypotheses, stopping criteria and length normalization.
- Distinguish search errors from model errors and explain the beam-search curse.
- Implement stochastic beam search with Gumbel-top-k.
- Compile a regular expression to an automaton, index it over a real tokenizer vocabulary and generate valid outputs.
- Implement minimum Bayes risk decoding and compare it with the mode and sampling.
Before you start
Search for a sequence or obey a rule
An autoregressive model assigns probability to a sequence through the product of conditional probabilities. The decoder can search for a high-probability output, draw a sample, or enforce a format. These decisions serve different goals: a valid JSON string can contain a false fact, and a more accurate mode search can find an unhelpful output.
Greedy decoding chooses the most likely token at each step. It does not necessarily maximize full-sequence probability: a slightly likelier first choice may lead to much less likely continuations. The next tree stores finished hypotheses separately from live ones; EOS is forced at the third step to make the example finite.
Keep alternatives
Beam search retains up to live hypotheses per request. For each it computes a vector of log probabilities, adds the accumulated score, and selects candidates from a matrix. Children emitting EOS move to a finished collection and are not expanded again. Implementations may reserve finished hypotheses differently, so even beam one is not always exactly the same algorithm as greedy.
A request with and scores up to 200000 extensions per step before pruning. That count excludes top-k search, model evaluation, and already finished hypotheses. In a batch, scores and states are retained per request; mixing completed hypotheses between requests or reordering their KV cache incorrectly changes the result. Physically sharing a prefix saves memory, but continuations need their own blocks or copy-on-write.
To illustrate cache cost, suppose each token occupies 0.5 MiB of keys and values across all layers. Four 150-token beams occupy 300 MiB if each duplicates the 100-token prefix and adds 50 of its own. If the prefix is physically shared, ideal accounting is MiB. A block implementation may reserve more for rounding and metadata. The saving also does not remove the need to update cache indices when selecting new beam parents.
A batched implementation often flattens beam by vocabulary, selects highest indices, and recovers each parent hypothesis index and token. Those indices must also be applied to attention states, masks, and lengths. If two children come from the same parent, both start with the same logical prefix; afterward they must diverge without overwriting each other’s state. The lab explicitly forms the score matrix and keeps each request’s finished hypotheses separate.
Without normalization, a prefix’s log probability is a sum of terms . Extending it does not increase that score. Exact uniform-cost search can use as nonnegative cost and extract the lowest-cost completion first. This does not mean the shortest sequence always wins: its conditional probabilities may be much lower. It does explain why excessive EOS probability can favor short answers.
Length and stopping
Length normalization changes comparison among sequences of different lengths. GNMT uses a length penalty of the form . Here counts generated tokens including EOS and score is . With we recover unnormalized log probability. Normalization is a decision rule, not a new normalized probability over all sequences.
Stopping upon the first EOS can miss a better live hypothesis. For unnormalized scoring, its current log probability is an upper bound on extensions. With and maximum length , a simple optimistic bound for nonpositive log probabilities is . A finished hypothesis can win early only if its score exceeds all such bounds. Beam pruning may already have discarded the optimum; stopping safely relative to live hypotheses cannot recover pruned ones.
The bound depends on the scoring rule. If positive coverage or length rewards are added, prefix log probability is insufficient without also bounding those rewards. Normalization dividing a negative number by an increasing denominator can make the score less negative even when nonpositive terms are added. Thus stopping when exceeding the live hypotheses’ current score, without considering their best possible future score, does not prove optimality.
Did search or the model fail?
A search error occurs when the decoder does not find the sequence with the highest score assigned by the model. A model error occurs when that sequence has poor quality for the objective. The beam-search curse describes cases where a wider beam improves model score but worsens a task metric. Stahlberg and Byrne find search errors even with large beams and empty modes for many examples in their translation experiment; it does not follow that every model has an empty mode.
The figure explicitly defines its utility and distribution, so its paradox can be checked by enumeration. In a real task, BLEU, human evaluation, and program correctness answer different questions. Eikema and Aziz study mode inadequacy and propose evaluating decisions based on expected utility, not maximum score alone.
Diversity and randomness
Diverse or stochastic beam search changes the exploration objective. Diverse beam search separates groups and penalizes similarity between choices to obtain alternatives; results depend on the penalty and are not necessarily the original mode. Diverse Beam Search develops this idea.
Gumbel-top-k over log probabilities of all completed sequences produces an ordered sample without replacement. Enumerating every leaf works for a tiny vocabulary but grows exponentially. Kool et al. construct conditioned perturbations over prefixes to search without enumerating the whole tree. Adding independent Gumbels to each prefix and pruning as if they were leaves does not automatically implement that algorithm. The lab uses exact enumeration of a small tree and states that limit.
Constraints on real tokens
Constrained decoding maintains an automaton or parser state. At every step it masks tokens that cannot extend the prefix toward an accepted output. The next grammar allows exactly an object with boolean ok and n from 0 to 9, without spaces and in fixed order. The figure’s index was computed for the actual SmolLM2-135M vocabulary: each token is interpreted as a byte sequence and may advance through multiple states.
The lab compiles a finite subset of regular expressions, with literals, escapes, concatenation, alternatives, groups, and ranges, to a deterministic trie. It does not support arbitrary repetition or implement a general grammar compiler. It traverses each token’s bytes, excludes special tokens except EOS, and checks the example’s 66 states against XGrammar when available. Willard and Louf describe vocabulary indices over automata; XGrammar addresses broader grammars and mask optimizations.
A BPE token is not necessarily a character or complete Unicode fragment. In the tokenizer used here, a token can represent bytes of several characters and traverse multiple edges before reaching the next state. To build the mask accept the entire token only if all transitions are valid. Decoding incomplete bytes in isolation into a replacement character can lose information; the example uses ByteLevel’s reversible table and limits the grammar to ASCII. Other tokenizers require their own representation and decoding rules.
A grammar also needs a termination policy. If the prefix is in an accepting state, EOS can be legal; before then it is not. If no allowed token remains and the state is not final, the system must treat it as an error or define recovery rather than silently choosing an invalid token. The example accepts only 20 strings and checks that each state has at least one transition or EOS. The precomputed index speeds queries, but its construction and storage cost depends on vocabulary and state count.
Masking each step does not usually sample the original distribution conditioned on the final sequence being valid. Suppose A and B initially each have probability 0.5 and both can begin a valid output. From A only 10% of future mass finishes validly; from B, 90% does. The local mask retains A and B at 0.5 each, while globally conditioning on validity gives 0.1 and 0.9. The distinction matters when a conditional-distribution sample is needed, not merely syntactically valid output.
Minimum Bayes risk
Minimum Bayes risk decoding chooses the candidate with greatest expected utility against the distribution of possible references. One approximation uses samples as references and averages for each candidate . With 32 candidates and 32 references it calculates 1024 utilities; with 128 references, 4096. Utility, samples, and candidate set determine the answer. Self-consistency also aggregates outputs, but exact-answer voting is only one particular utility.
The Monte Carlo estimate is noisy. If candidates are very close, another seed may change the winner. A candidate outside the considered set cannot win even if its expected utility is higher; increasing only references reduces uncertainty in the mean, while increasing candidates changes the decision space. Set Jaccard, used in the lab, ignores order and multiplicity: it verifies the calculation, not translation quality.
Lab: search a small model
The bigram model is estimated with smoothing over a toy corpus. Greedy, beam with separate finished hypotheses, and exact uniform-cost search are compared; on the last step EOS is forced with probability one, so the mode is exact for that modified bounded tree. Scores are not from a real language model. The Gumbel-top-k sample enumerates leaves and MBR uses Jaccard similarity between token sets and 128 sampled references.
import heapq, math
import numpy as np
BOS,EOS='<s>','</s>'
corpus=['a b c','a b c','a b','a c','b c','b c','b a','c']
vocab=['a','b','c',EOS];counts={}
for line in corpus:
seq=[BOS]+line.split()+[EOS]
for a,b in zip(seq,seq[1:]):counts[a,b]=counts.get((a,b),0)+1
def step(prefix):
last=prefix[-1] if prefix else BOS
values=np.array([counts.get((last,x),0)+.2 for x in vocab]);return values/values.sum()
def lp(length,alpha):return ((5+length)/6)**alpha
def greedy(step_fn,eos,max_len):
seq=();score=0.
for t in range(max_len):
p=step_fn(seq)
if t==max_len-1:p=np.array([1. if v==eos else 0. for v in vocab])
i=int(np.argmax(p));seq+=(vocab[i],);score+=math.log(p[i])
if seq[-1]==eos:break
return seq,score
def beam_search(step_fn,eos,width,max_len,alpha=0):
# raw = suma de log-probabilidades; no extender terminadas.
if alpha<0:raise ValueError('La cota implementada requiere alpha >= 0')
live=[((),0.)];finished=[]
for t in range(max_len):
expanded=[]
probabilities=np.stack([step_fn(seq) for seq,_ in live])
if t==max_len-1:probabilities[:]=np.array([1. if v==eos else 0. for v in vocab])
logprob=np.full_like(probabilities,-np.inf);np.log(probabilities,out=logprob,where=probabilities>0)
scores=logprob+np.array([score for _,score in live])[:,None]
for i,j in np.ndindex(scores.shape):
if not np.isfinite(scores[i,j]):continue
seq=live[i][0];token=vocab[j];item=(seq+(token,),float(scores[i,j]))
if token==eos:finished.append(item)
else:expanded.append(item)
finished=sorted(finished,key=lambda x:x[1]/lp(len(x[0]),alpha),reverse=True)[:width]
live=sorted(expanded,key=lambda x:x[1]/lp(len(x[0]),alpha),reverse=True)[:width]
# Cota optimista con α>=0: ninguna extensión añade log-prob positiva,
# y el denominador más grande posible es lp(max_len).
if finished and (not live or finished[0][1]/lp(len(finished[0][0]),alpha)>=max(x[1]/lp(max_len,alpha) for x in live)):
break
return finished[0]
def exhaustive(max_len):
# Coste uniforme exacto en el árbol finito; EOS forzado en el último paso.
heap=[(0.,())];done=[]
while heap:
cost,seq=heapq.heappop(heap)
if seq and seq[-1]==EOS:done.append((seq,-cost));continue
p=step(seq)
if len(seq)==max_len-1:p=np.array([1. if x==EOS else 0. for x in vocab])
for token,prob in zip(vocab,p):
if prob>0:heapq.heappush(heap,(cost-math.log(prob),seq+(token,)))
return done
def beam_batch(step_functions,eos,width,max_len,alpha=0):
# Cada petición conserva sus terminadas; el eje B×V se forma dentro de ella.
return [beam_search(fn,eos,width,max_len,alpha) for fn in step_functions]
all_sequences=exhaustive(5)
assert abs(sum(math.exp(score) for _,score in all_sequences)-1)<1e-12
mode=all_sequences[0]
assert beam_search(step,EOS,100,5)==mode
print('voraz',greedy(step,EOS,5))
for width in (1,2,4,100):
result=beam_search(step,EOS,width,5)
print('haz',width,'resultado',result[0],'logp',round(result[1],4))
print('modo exacto',mode[0],'logp',round(mode[1],4))
print('dos peticiones en lote:',[s for s,_ in beam_batch([step,step],EOS,4,5,.6)])
# Gumbel-top-k exacto sobre hojas enumeradas: muestra sin reemplazo.
# No es el algoritmo eficiente de perturbación condicional sobre el árbol.
rng=np.random.default_rng(7);scores=np.array([x[1] for x in all_sequences]);u=np.clip(rng.random(len(scores)),1e-12,1-1e-12)
selected=np.argsort(-(scores-np.log(-np.log(u))))[:4]
assert len(set(selected))==4
print('cuatro secuencias Gumbel-top-k:',[all_sequences[i][0] for i in selected])
def utility(a,b):
a=set(a)-{EOS};b=set(b)-{EOS};return len(a&b)/len(a|b) if a|b else 1.
probs=np.exp(scores);indices=rng.choice(len(scores),size=128,p=probs/probs.sum());refs=[all_sequences[i][0] for i in indices]
candidates=[x[0] for x in all_sequences[:8]]
utilities=np.array([np.mean([utility(c,r) for r in refs]) for c in candidates]);best=candidates[int(np.argmax(utilities))]
print('MBR con 8 candidatos y 128 muestras:',best,'utilidad media',round(float(utilities.max()),4),'evaluaciones',len(candidates)*len(refs))
Lab: grammar and local model
SmolLM2-135M on CUDA is used with the model’s byte tokenizer. The explicit compiler enumerates the finite language and builds its DFA; it then indexes tokens taking one state to another. Three seeds generate objects that pass json.loads and check fields and types. Mask timing includes tensor construction and CUDA synchronization; it is a local observation, not a production-systems comparison. Model and tokenizer must be cached. If XGrammar is optionally installed, the cell compares its CPU masks for all states; an isolated local XGrammar 0.2.9 test found zero differences over 66 states. Its cost is not directly comparable to the GPU mask including synchronization.
import os,sys,time,json
import numpy as np
import torch
from transformers import AutoModelForCausalLM,AutoTokenizer
def finite_regex(pattern):
# Subconjunto finito: literales/escapes, concatenación, |, grupos y [a-z].
# No admite *, +, ?, cuantificadores, negación ni clases Unicode.
position=0
def expr():
nonlocal position
choices=sequence()
while position<len(pattern) and pattern[position]=='|':
position+=1;choices+=sequence()
return choices
def sequence():
nonlocal position
result=['']
while position<len(pattern) and pattern[position] not in ')|':
char=pattern[position];position+=1
if char=='(':
options=expr()
if position>=len(pattern) or pattern[position]!=')':raise ValueError('grupo sin cerrar')
position+=1
elif char=='[':
if position+3>=len(pattern) or pattern[position+1]!='-' or pattern[position+3]!=']':raise ValueError('solo [a-z]')
lo,hi=ord(pattern[position]),ord(pattern[position+2]);options=[chr(i) for i in range(lo,hi+1)];position+=4
elif char=='\\':
if position>=len(pattern):raise ValueError('escape incompleto')
options=[pattern[position]];position+=1
elif char in '*+?{}':raise ValueError('operador no admitido; escapa literales')
else: options=[char]
result=[a+b for a in result for b in options]
if len(result)>10000:raise ValueError('lenguaje demasiado grande')
return result
result=expr()
if position!=len(pattern):raise ValueError('paréntesis inesperado')
return result
def trie(strings):
edges=[{}];final=set()
for text in strings:
state=0
for b in text.encode('ascii'):
if b not in edges[state]: edges[state][b]=len(edges);edges.append({})
state=edges[state][b]
final.add(state)
return edges,final
def byte_decoder():
# Correspondencia reversible byte→Unicode de GPT-2 ByteLevel BPE.
bs=list(range(ord('!'),ord('~')+1))+list(range(ord('¡'),ord('¬')+1))+list(range(ord('®'),ord('ÿ')+1))
cs=bs[:];n=0
for b in range(256):
if b not in bs:bs.append(b);cs.append(256+n);n+=1
return {chr(c):b for b,c in zip(bs,cs)}
pattern=r'\{"ok":(true|false),"n":[0-9]\}'
strings=finite_regex(pattern);edges,final=trie(strings)
assert len(strings)==20 and all(json.loads(x)['n'] in range(10) for x in strings)
model_id='HuggingFaceTB/SmolLM2-135M';tok=AutoTokenizer.from_pretrained(model_id,local_files_only=True)
decoder=byte_decoder();special=set(tok.all_special_ids);vocab=tok.get_vocab();tokens=[None]*len(tok)
for symbol,index in vocab.items():
if index in special:continue
try: tokens[index]=bytes(decoder[c] for c in symbol)
except KeyError: pass
def advance(state,payload):
for b in payload:
if b not in edges[state]:return None
state=edges[state][b]
return state
start=time.perf_counter();allowed=[]
for state in range(len(edges)):
row={i:dest for i,payload in enumerate(tokens) if payload and (dest:=advance(state,payload)) is not None}
if state in final:row[tok.eos_token_id]=state
allowed.append(row)
print('DFA estados',len(edges),'cadenas',len(strings),'índice segundos',round(time.perf_counter()-start,3))
assert all(allowed[s] for s in range(len(edges)))
assert any(len(tokens[i] or b'')>1 for row in allowed for i in row if i!=tok.eos_token_id)
if __name__=='__main__':
assert torch.cuda.is_available();device='cuda';torch.set_num_threads(1)
model=AutoModelForCausalLM.from_pretrained(model_id,local_files_only=True,dtype=torch.float32).eval().to(device)
prompt='Return only a JSON object with keys ok and n: '
initial=tok(prompt,return_tensors='pt').to(device)['input_ids']
for seed in (11,29,47):
torch.manual_seed(seed);torch.cuda.manual_seed_all(seed);ids=initial.clone();state=0;output=[];mask_seconds=0.
with torch.no_grad():
for _ in range(32):
logits=model(input_ids=ids).logits[:,-1,:].float()
torch.cuda.synchronize() # no atribuir el forward pendiente a la máscara
begin=time.perf_counter();allowed_ids=torch.tensor(list(allowed[state]),device=device);mask=torch.full_like(logits,-torch.inf);mask[0,allowed_ids]=logits[0,allowed_ids];torch.cuda.synchronize();mask_seconds+=time.perf_counter()-begin
token=int(torch.multinomial(torch.softmax(mask,dim=-1),1).item())
if token==tok.eos_token_id:assert state in final;break
output.append(token);state=allowed[state][token];ids=torch.cat([ids,torch.tensor([[token]],device=device)],dim=1)
else:raise RuntimeError('No terminó dentro del límite')
raw=b''.join(tokens[t] for t in output);text=raw.decode('ascii');decoded=tok.decode(output,skip_special_tokens=True,clean_up_tokenization_spaces=False)
assert text==decoded and text in strings and state in final
data=json.loads(text);assert isinstance(data['ok'],bool) and type(data['n']) is int and 0<=data['n']<=9
print('semilla',seed,'JSON',text,'tokens',len(output),'ms máscara/paso',round(1000*mask_seconds/(len(output)+1),3))
print('GPU',torch.cuda.get_device_name(),'coste aislado incluye crear máscara y sincronizar; no es un benchmark de producción')
try:
import xgrammar as xgr
except ImportError:
print('XGrammar no instalado: se omite la comparación opcional')
else:
start=time.perf_counter()
info=xgr.TokenizerInfo.from_huggingface(tok,vocab_size=len(tok),stop_token_ids=[tok.eos_token_id])
compiled=xgr.GrammarCompiler(info).compile_regex(pattern)
print('XGrammar compilación segundos',round(time.perf_counter()-start,3))
prefixes={0:b''};queue=[0]
while queue:
state=queue.pop()
for b,nxt in edges[state].items():prefixes[nxt]=prefixes[state]+bytes([b]);queue.append(nxt)
differences=[];elapsed=0.
for state,prefix in sorted(prefixes.items()):
matcher=xgr.GrammarMatcher(compiled)
if prefix:assert matcher.accept_string(prefix)
bits=xgr.allocate_token_bitmask(1,len(tok));start=time.perf_counter();matcher.fill_next_token_bitmask(bits);elapsed+=time.perf_counter()-start
words=bits.numpy().view(np.uint32)[0]
actual={i for i in range(len(tok)) if (int(words[i//32])>>(i%32))&1}
if actual!=set(allowed[state]):differences.append(state)
print('XGrammar estados comparados',len(prefixes),'diferencias',differences,'ms máscara CPU',round(elapsed/len(prefixes)*1000,3))
assert not differences
npm run lab and open the connection link.Exercises
Step 1 of 2. What sign does log p have for 0 < p ≤ 1?
import math
def beam_search(step_fn,bos,eos,beam,max_len,alpha):
...