Skip to content

10.4 Beam search, generic over a step function

The encoder-decoder can translate, but only greedily: at each step it takes the single most likely token and never looks back. On the reversal task that is fine, because the model is nearly certain at every step. On the dates task, where the first digit of the year is often uncertain, a greedy decoder commits to a likely-looking first token and then has to live with a worse whole output. This section builds the search that fixes it, once, as a function of a step function, so that later the model zoo uses the same code for seq2seq and transformer checkpoints. The model and the search are separate pieces with a narrow interface between them, which is how production decoders (vLLM’s beam search, Hugging Face’s generate) are built too.

Concepts from other sections (9)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

You need log_softmax from Stable numerics in Mathematics, and a real decoder to search over: Seq2Seq.decode_step from the encoder-decoder section, with Luong attention. The discrete math problem set on DAGs, modular arithmetic, and hashing is useful background for counting sequences.

The solution is python/tinyllm/infer/beam.py, with Hypothesis, select_state, beam_search, and greedy_decode. It implements the contract course/contracts/py/tinyllm/infer/beam.pyi, and the oracle tests are in test_beam.py. {tinyllm} translate --beam 5 runs it, and on the dates task it beats greedy.

Learning objectives

  • Explain why greedy decoding can miss the most likely sequence, and show a case by hand where a beam of 2 finds it.
  • Implement beam search that ranks all kVkV extensions together, narrows as hypotheses finish, and stops at max_len.
  • Write select_state, which gathers any nested model state by parent index, and say why it makes the search model-agnostic.
  • Apply a length penalty to finished hypotheses and explain why it never changes the order of live ones.
SymbolMeaningType / shape
VVvocabulary sizeint
y1:ty_{1:t}a prefix: the tokens generated after boslist of ids
p(v∣y1:t)p(v \mid y_{1:t})the model’s next-token distribution, softmax of its logitsfloat64[V]
ℓ(y1:t)=∑i≤tlog⁡p(yi∣y1:i−1)\ell(y_{1:t}) = \sum_{i \le t} \log p(y_i \mid y_{1:i-1})the prefix’s log-probability (logprob)float
KKbeam_sizeint
kknumber of live hypotheses at this step, k≤Kk \le Kint
LLmax_len, the most tokens generatedint
α\alphalength_penaltyfloat ≥0\ge 0
s(y)=ℓ(y)/∣y∣αs(y) = \ell(y) / \lvert y \rvert^\alphathe score a finished hypothesis is ranked byfloat

A decoder model defines P(y)=∏ip(yi∣y1:i−1)P(y) = \prod_i p(y_i \mid y_{1:i-1}) over sequences that end with eos, and the best output is arg⁡max⁡yℓ(y)\arg\max_y \ell(y). There are VLV^L sequences of length LL; with V=32 000V = 32\,000 and L=20L = 20 exhaustive search is impossible, and dynamic programming does not help, because the model’s state depends on the whole prefix. Every practical decoder is an approximation, and the question is how to bound the work.

Greedy decoding is the cheapest answer. It takes yt=arg⁡max⁡vp(v∣y1:t−1)y_t = \arg\max_v p(v \mid y_{1:t-1}) at every step (ties to the lowest id) until eos or LL tokens. Its failure is commitment: a token that is slightly more likely now can lead to a much less likely continuation. Greedy is a beam of size 1, and that observation is the way to generalize it.

Beam search keeps up to KK prefixes, which bounds each step to one model call on at most KK rows and KVK V candidates. One step, in the contract’s op order:

  1. Call step_fn(state, y_prev); it returns logits [k, V] for the kk live hypotheses and the new state.
  2. Normalize each row with log_softmax: logits are scores, not log-probabilities.
  3. Give every extension ℓ(y1:t)+log⁡p(v∣y1:t)\ell(y_{1:t}) + \log p(v \mid y_{1:t}), a [k, V] table of candidates.
  4. Rank all kVk V candidates together, highest first, ties to the lower flat index bV+vb V + v (lower beam, then lower token id), and keep the first K−(finished so far)K - (\text{finished so far}) finite ones.
  5. A kept candidate ending in eos is finished and leaves the beam, keeping its slot, so the beam narrows by one. The rest are the next live hypotheses.
  6. The state rows of the new hypotheses are their parents’ rows: select_state(new_state, parents).

The search stops when no hypothesis is live, or after LL tokens, when the live ones are returned unfinished. The result is the finished hypotheses ranked by score.

Each step of this recipe answers a specific need. Prefixes must be comparable across parents, because a good continuation of a mediocre prefix can beat every continuation of the best prefix. So the kVk V candidates are ranked together, not KK per parent, which would also grow the beam to K2K^2. Scores must be log-probabilities, because summing over a path requires each step’s term to be log⁡p\log p; adding raw logits would let a row’s arbitrary offset decide the ranking. A finished hypothesis can never be extended, and the result should hold KK outputs, so each finished one reduces how many live ones are kept: K−∣finished∣K - |\text{finished}|. When that reaches 0, or nothing is live, the search stops before calling the model again. The search must also terminate and return something, so at LL tokens the survivors are returned as unfinished hypotheses rather than dropped. And determinism needs a tie rule: ties go to the lower flat index bV+vbV + v, which a stable sort of the negated scores gives for free, so Python and Rust implementations agree.

The model is a black box with a state. The only coupling is step_fn(state, y_prev) -> (logits, state), with the hypothesis on axis 0 of every array in the state, and select_state is what keeps the model’s view in sync with the search’s. A state is any nesting of tuples, NamedTuples, lists, and dicts whose array leaves (anything with a shape of at least one dimension, numpy arrays and Tensors alike) have the hypothesis on axis 0. select_state gathers leaf[parents] for every leaf, where rows may repeat (two children of one parent), and passes everything else through. A Python list is a container, not an array: its elements are searched for arrays, and its own order is not gathered.

Two limiting cases pin the algorithm down. With K=1K = 1 it is greedy. With K≥VLK \ge V^L nothing is ever pruned: at step tt there are at most VtV^{t} candidates, all kept, so the result is every possible output in score order, which a test enumerates by brute force.

Every token multiplies the probability by a number below 1, so ℓ\ell always prefers shorter outputs. Wu et al. (GNMT) rank finished hypotheses by ℓ(y)/∣y∣α\ell(y) / \lvert y \rvert^\alpha; here ∣y∣\lvert y \rvert counts eos. α=0\alpha = 0 is the raw log-probability and α=1\alpha = 1 the mean per token. During the search all live hypotheses have the same length, so ranking them by ℓ\ell or by ss is the same thing; the penalty matters only when finished hypotheses of different lengths are compared, and it can change the winner.

Take three tokens, eos = 0, a = 1, b = 2, and a model that is a table of next-token probabilities:

prefixp(eos)p(\text{eos})p(a)p(a)p(b)p(b)
(empty)0.10.50.4
a0.20.10.7
b0.90.050.05

Greedy (L=2L = 2) picks a (0.5), then after a the best is b (0.7). The output is a b, unfinished, with P=0.35P = 0.35 and ℓ=ln⁡0.35=−1.0498\ell = \ln 0.35 = -1.0498.

Beam (K=2K = 2, L=2L = 2, α=0\alpha = 0). Step 1 ranks a 0.5, b 0.4, eos 0.1 and keeps a and b. Step 2 ranks all six extensions together:

candidateprobability
b eos0.4×0.9=0.360.4 \times 0.9 = 0.36
a b0.5×0.7=0.350.5 \times 0.7 = 0.35
a eos0.5×0.2=0.100.5 \times 0.2 = 0.10
a a0.05
b a, b b0.02 each

It keeps b eos (finished) and a b, which is cut at L=2L = 2 and returned unfinished. The result is b eos with ℓ=ln⁡0.36=−1.0217\ell = \ln 0.36 = -1.0217, then a b with ln⁡0.35\ln 0.35. The model was called twice, with 1 and then 2 rows. With α=1\alpha = 1 the scores are ln⁡0.36/2=−0.5108\ln 0.36 / 2 = -0.5108 and ln⁡0.35/2=−0.5249\ln 0.35 / 2 = -0.5249, the same order. A correct solution reproduces all three results: the beam, greedy, and the penalized scores.

@dataclass
class Hypothesis:
tokens: list[int]; logprob: float; score: float; finished: bool
def select_state(state: Any, idx: ArrayLike) -> Any: ...
def beam_search(step_fn, init_state, bos: int, eos: int, beam_size: int, max_len: int,
length_penalty: float = 1.0) -> list[Hypothesis]: ...
def greedy_decode(step_fn, init_state, bos: int, eos: int, max_len: int) -> Hypothesis: ...
# step_fn(state, y_prev int64 [k]) -> (logits [k, V], new_state)

A Hypothesis records its tokens (excluding bos, including eos when finished), its summed log-probability, its penalized score, and whether it finished. The step function takes the previous token of each live hypothesis and returns logits, which need not be normalized.

select_state walks containers and gathers array leaves:

def select_state(state, idx):
idx = np.asarray(idx, dtype=np.int64)
if isinstance(state, dict):
return {k: select_state(v, idx) for k, v in state.items()}
if isinstance(state, tuple):
parts = [select_state(v, idx) for v in state]
# A NamedTuple is rebuilt field by field; a plain tuple from the list.
return type(state)(*parts) if hasattr(state, "_fields") else tuple(parts)
if isinstance(state, list):
return [select_state(v, idx) for v in state] # a container: recurse, do not reorder
if isinstance(state, (set, frozenset)):
raise TypeError("select_state: a set has no row order")
shape = getattr(state, "shape", None)
if shape is None or len(shape) == 0:
return state # scalars, None, ints: passed through
return state[idx] # rows may repeat: two children of one parent

Because the encoder-decoder’s DecoderState is a NamedTuple of Tensors (and None for unused fields), this one function reorders h, c, feed, keys, mask, and proj by parent, and state.h still works afterwards.

One iteration per generated token:

def beam_search(step_fn, init_state, bos, eos, beam_size, max_len, length_penalty=1.0):
# ... (beam_size >= 1, max_len >= 1, length_penalty >= 0)
live_tokens = [[]] # one empty prefix
live_lp = np.zeros(1, dtype=np.float64)
state = init_state
y_prev = np.array([bos], dtype=np.int64)
finished = []
for t in range(max_len):
logits, state = step_fn(state, y_prev)
z = np.asarray(getattr(logits, "data", logits), dtype=np.float64) # Tensor or ndarray
k = len(live_tokens)
# ... (z must be [k, V])
V = z.shape[1]
# Normalize each row first: logits are scores, not log-probabilities.
cand = (live_lp[:, None] + log_softmax(z, axis=-1)).ravel() # [k * V]
# Highest first; a stable sort of the negated scores sends ties to the
# lower flat index b * V + v.
order = np.argsort(-cand, kind="stable")
# Every finished hypothesis takes one slot for good: the beam narrows.
n_keep = min(beam_size - len(finished), int(np.isfinite(cand).sum()))
new_tokens, new_lp, parents = [], [], []
for f in order[:n_keep]:
b, v = divmod(int(f), V) # parent row, token id
toks = live_tokens[b] + [v]
lp = float(cand[f])
if v == eos:
finished.append(Hypothesis(toks, lp, _score(lp, len(toks), length_penalty), True))
else:
new_tokens.append(toks); new_lp.append(lp); parents.append(b)
if not new_tokens or len(finished) >= beam_size:
break # never call the model with zero rows
if t == max_len - 1:
# Out of length: the survivors are returned as they stand.
for toks, lp in zip(new_tokens, new_lp):
finished.append(Hypothesis(toks, lp, _score(lp, len(toks), length_penalty), False))
break
state = select_state(state, parents) # the model's rows follow the kept prefixes
live_tokens = new_tokens
live_lp = np.array(new_lp, dtype=np.float64)
y_prev = np.array([toks[-1] for toks in new_tokens], dtype=np.int64)
# sorted() is stable: equal scores keep the order they were finalized in.
return sorted(finished, key=lambda h: -h.score)[:beam_size]

Trace it on the hand example. Step 1 has one row, candidates ln⁡(0.1,0.5,0.4)\ln(0.1, 0.5, 0.4), and n_keep = 2; it keeps a and b, with parents [0, 0]. Step 2 has two rows and six candidates; the top two are b eos (finished, slot spent) and a b. Since t == max_len - 1, a b is appended unfinished. That is two model calls, with 1 and 2 rows.

_score is logprob / n ** length_penalty, and greedy_decode is literally a beam of 1 with length_penalty=0.0, so its score equals its log-probability:

def greedy_decode(step_fn, init_state, bos, eos, max_len):
hyps = beam_search(step_fn, init_state, bos, eos, 1, max_len, length_penalty=0.0)
if not hyps:
raise ValueError("greedy_decode: every token is -inf at the first step")
return hyps[0]

The full solution is beam.py.

The cost is at most LL model calls on at most KK rows each, and per step O(KV)O(K V) for the normalization and O(KVlog⁡(KV))O(K V \log(K V)) for the full sort, plus the state gather. A partial selection (argpartition) would be O(KV)O(K V), but would need extra work to keep the tie rule; at these sizes the sort is not the bottleneck, the model is.

Why rank all kVkV together rather than top-KK per parent? Per-parent selection keeps K2K^2 rows, and it can still miss the global best because it does not compare across parents.

Why let finished hypotheses spend slots? The alternative, keeping KK live rows until all KK finished outputs are found, does more model calls and returns a different set. The narrowing beam is the classic formulation and bounds the work by KLK L rows total.

Why a step-function interface? The search never needs to know the model’s architecture, so one implementation serves the toy table, Seq2Seq, and a transformer with a KV cache. The price is that the state must have hypotheses on axis 0 of every array.

One known limitation remains: beam search is not exact, and larger beams can even find worse translations (Stahlberg and Byrne). The length penalty partly compensates for the bias toward short outputs.

The suite test_beam.py uses oracles: expected values from an independent computation, not from the implementation. For beam search the oracle is brute force. A tiny model (a table, or logits from a hash of the prefix) has every output enumerated for V=3V = 3 and L=4L = 4, each scored with an independent log-softmax, and compared with an exhaustive beam. The suite adds greedy equivalence, the hand-worked numbers, a model that never says eos, a mask, ties, and select_state on a NamedTuple inside a dict. Its toy state is an array (an object array of prefixes works), because a Python list is searched for arrays, not gathered.

The full list of behaviors a correct solution must have:

CaseKind of checkChecksWhy it matters downstream
hand example beam beats greedyunitb eos (0.36) then a b (0.35), calls [1, 2]pins down the algorithm
hand example: greedy commits to aunitgreedy gives a b, score equal to logprobthe baseline beam search must beat
hand example length penaltyunitscores ln⁡0.36/2\ln 0.36 / 2 and ln⁡0.35/2\ln 0.35 / 2the penalty counts eos
beam one is greedydifferentiala beam of 1 equals the test’s own greedy loop on 6 prefix-dependent modelsgreedy is a special case, not a second code path
exhaustive beam equals brute forcedifferentialall 31 outputs of a V=3V = 3, L=4L = 4 model, by score, α∈{0,1}\alpha \in \{0, 1\}the search is exact when nothing is pruned
small beam at L=1L = 1 is the top of the exhaustive rankingpropertywith L=1L = 1 the beam is the KK most likely first tokensranking over all candidates
beam never holds more than beam sizepropertythe step function never sees more than KK rowsthe cost bound of beam search
eos finishes and shrinks the beampropertyeos once and last; logprob equals the path sum; the beam never grows backfinished outputs are final
search stops when the last hypothesis finishesboundaryexactly two calls when eos is certain at step 2no call with zero rows
max_len returns unfinishedboundarya model that never says eos gives KK unfinished outputs of length LLdecoding always terminates
length penalty changes the winnerunitα=0\alpha = 0 picks a eos, α=1\alpha = 1 picks b b b eos; results ranked by scorewhy translation systems use a penalty
ties go to the lowest idboundaryuniform logits keep tokens 0 and 1 firstthe same order in Python and Rust
logits need not be normalizedpropertyadding a constant per row changes nothingmodels return logits
masked tokens are never chosenboundary-inf is never kept, even if the beam is not fullgrammar and stop-list masks
logprob is the sum along the pathpropertylogprob and score recomputed from the modelrescoring and comparison across searches
select_state keeps the structureunitNamedTuple, dict, list, repeated rows, non-array leaves; a set raisesany model’s state works
state follows parents in a real searchpropertyevery state row extends a prefix the search keptthe step function scores the right prefixes
validationboundarybad sizes, wrong logits shape, nothing finitecaller bugs fail loudly
beam decodes a Seq2Seqdifferentialover Seq2Seq with Luong attention: beam 1 equals greedy, every hypothesis’s logprob equals teacher-forced rescoringthe zoo’s call site

Beam search has many small rules, and each one has a matching bug. The table pairs every pitfall with the line of the solution that avoids it:

PitfallSymptomHow the solution avoids it
keeping the best KK tokens of each hypothesisthe beam grows to K2K^2 rows, then moreone argsort over the flattened [k * V] table
adding raw logits instead of log-probabilitiesrows with a larger logit scale win; disagrees with brute forcelog_softmax(z, axis=-1) before adding to live_lp
an eos hypothesis that keeps goingoutputs with tokens after eos, a search that never ends earlyan eos extension goes to finished, not to new_tokens, and keeps its slot
dropping the live hypotheses at max_lenan empty result for a model that rarely says eosat t == max_len - 1 survivors are appended with finished=False
keeping -inf candidates to fill the beammasked tokens appear in the outputn_keep is capped by np.isfinite(cand).sum()
state rows not gathered by parentthe model scores one prefix and the search records anotherselect_state(state, parents) after every step
eos left out of the lengthscores disagree with the formula_score(lp, len(toks), ...) where toks includes eos
results ranked by logprob, not scorethe length penalty has no effectthe final sorted(..., key=lambda h: -h.score)
ties to the highest indexPython and Rust disagree on near-uniform rowsnp.argsort(-cand, kind="stable")
survivors finalized one step earlyoutputs one token shortsurvivors are finalized only at t == max_len - 1, after the last token is appended
a NamedTuple rebuilt as a tuplethe decoder’s state.h access failstype(state)(*parts) when the tuple has _fields
lists not searchedan LSTM’s per-layer state list is never reorderedlists are recursed into element by element
greedy scored with length penalty 1greedy_decode’s score is not its logprobgreedy_decode passes length_penalty=0.0
the model called after every hypothesis finisheda call with zero rows, wasted workif not new_tokens ...: break before the next call

Warning: Forgetting select_state produces no error at all. Row ii of the state keeps describing the old prefix while the search credits a new one, so the outputs are simply wrong. The “state follows parents” test exists to catch exactly this.

Sequence metrics grade what beam search produces. In the next part, the encoder-decoder Transformer translates with beam_search over its own step function. The model zoo decodes seq2seq and transformer checkpoints with beam search and reports beam against greedy. Sampling and logit processors is the other way to pick tokens, and it shares the tie rule.

Production decoders extend each piece:

This pieceProduction equivalentWhat it addsWhere to look
beam_searchHugging Face generate(num_beams=...)batched beams across many inputs, early_stopping modes, num_return_sequencestransformers/generation/utils.py (_beam_search), beam_search.py (BeamHypotheses)
select_statethe KV-cache reordergathers the attention cache by beam index every step; with paged attention only block tables are copied_reorder_cache in HF models; vLLM’s beam search over forked sequences
length_penaltyGNMT’s ((5+∣y∣)/6)α((5 + \lvert y \rvert)/6)^\alpha and coverage penaltya smoother penalty and a term for source words never attendedWu et al. 2016, section 7; fairseq sequence_generator.py
exact search for tiny VLV^Lexact decoding studiesshows the most likely output is often empty: the beam’s errors helpStahlberg and Byrne, “On NMT Search Errors and Model Errors” (2019)
  • Graves, “Sequence Transduction with Recurrent Neural Networks” (2012), section 3.2.
  • Wu et al., “Google’s Neural Machine Translation System” (2016), section 7 (length penalty).
  • Meister, Cotterell, and Vieira, “If beam search is the answer, what was the question?” (EMNLP 2020).
  • Stahlberg and Byrne, “On NMT Search Errors and Model Errors: Cat Got Your Tongue?” (2019).
  • greedy decoding: taking the single most likely token at every step; a beam of size 1.
  • beam search: keeping the KK best prefixes by summed log-probability, ranking all extensions together at each step.
  • hypothesis: a prefix in the beam, with its tokens, log-probability, score, and whether it has finished.
  • step function: step_fn(state, y_prev) -> (logits, state), the only interface between the search and the model.
  • length penalty: dividing a finished hypothesis’s log-probability by ∣y∣α\lvert y \rvert^\alpha to counter the bias toward short outputs.
  • Greedy decoding commits to the best next token and can miss the best sequence; beam search keeps the beam_size best prefixes and finds it in the worked example, 0.36 against greedy’s 0.35.
  • All k * V extensions are ranked together, so the beam never holds more than beam_size rows.
  • A beam of 1 is greedy decoding, and a beam of at least VLV^L is exact search; both are checked against independent oracles.
  • The model is only a step function: its state is gathered by parent with select_state, so the same search decodes a toy table and a real Seq2Seq.
  • Summed log-probability prefers short outputs; dividing by len ** length_penalty can change the winner.
  1. In the worked example, greedy chose a first. Why does the beam end up preferring b eos?
    AnswerThe beam keeps `b` alive at step 1 (0.4, second best) and then compares all six extensions together. $0.4 \times 0.9 = 0.36$ beats every continuation of `a`, the best being $0.5 \times 0.7 = 0.35$.
  2. Why is log_softmax applied before adding to live_lp even though the model “already” ranks tokens?
    AnswerWithin a row, logits and log-probabilities rank tokens the same way, but across rows they do not: each row's logits can have a different offset. Summing along a path is only meaningful for log-probabilities.
  3. What does n_keep = min(beam_size - len(finished), isfinite(cand).sum()) protect against, in each of its two terms?
    AnswerThe first keeps the total of finished plus live at most $K$, so the beam narrows as hypotheses finish. The second stops `-inf` (masked) candidates from being kept just to fill the beam.
  4. Why does the length penalty not affect which live hypotheses are kept?
    AnswerAll live hypotheses at step $t$ have exactly $t$ tokens, so dividing every score by $t^\alpha$ preserves their order. It only matters when comparing finished hypotheses of different lengths.
  5. What would go wrong if select_state were skipped?
    AnswerRow $i$ of the state would still describe the old row $i$'s prefix, while the search records `live_tokens[i]` as a different prefix. The model would score one sentence and the search would credit another.