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.
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- Dynamic programming (DP): solving a problem by breaking it into overlapping subproblems and storing each subproblem’s answer the first time it is computed, which turns an exponential recursion into a polynomial computation. Read more: Chapter 9: Dynamic programming in Programming and Algorithms
- Op order: the fixed sequence of random draws that makes masking reproducible across implementations. Read more: 12.2 BERT: the bidirectional encoder and masked language modeling
- tie rule: the fixed backtrace preference (diagonal, deletion, insertion) that makes the S, D, I split deterministic. Read more: 15.5 Multimodal eval metrics: WER, CER, VQA, captions, zero-shot
- Stable sort: a sort that keeps equal elements in their input order; heapsort is not one. Read more: 18.4 Binary heap in Programming and Algorithms
- KV cache: per-layer storage of past keys and values, so each decode step processes only the new token. Read more: 21.2 The KV cache, incremental decoding, and generate
- Expected value: the average outcome across many repetitions of a situation under the model. Read more: Chapter 4: Uncertainty and evidence in Mathematics
- logit scale (temperature): the learned factor that multiplies cosines before the loss. Read more: 14.5 Contrastive image-text: CLIP and SigLIP
- block table: a request’s list of the physical KV blocks holding its tokens, used by attention to read the paged cache. Read more: 20.6 Inside an Inference Engine: How vLLM and SGLang Run a Model
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 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.
Notation
Section titled “Notation”| Symbol | Meaning | Type / shape |
|---|---|---|
| vocabulary size | int | |
a prefix: the tokens generated after bos | list of ids | |
| the model’s next-token distribution, softmax of its logits | float64[V] | |
the prefix’s log-probability (logprob) | float | |
beam_size | int | |
| number of live hypotheses at this step, | int | |
max_len, the most tokens generated | int | |
length_penalty | float | |
| the score a finished hypothesis is ranked by | float |
The search problem
Section titled “The search problem”A decoder model defines over sequences that end with eos, and the best output is . There are sequences of length ; with and 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 at every step (ties to the lowest id) until eos or 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.
The algorithm
Section titled “The algorithm”Beam search keeps up to prefixes, which bounds each step to one model call on at most rows and candidates. One step, in the contract’s op order:
- Call
step_fn(state, y_prev); it returns logits[k, V]for the live hypotheses and the new state. - Normalize each row with
log_softmax: logits are scores, not log-probabilities. - Give every extension , a
[k, V]table of candidates. - Rank all candidates together, highest first, ties to the lower flat index (lower beam, then lower token id), and keep the first finite ones.
- A kept candidate ending in
eosis finished and leaves the beam, keeping its slot, so the beam narrows by one. The rest are the next live hypotheses. - 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 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 candidates are ranked together, not per parent, which would also grow the beam to . Scores must be log-probabilities, because summing over a path requires each step’s term to be ; 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 outputs, so each finished one reduces how many live ones are kept: . 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 tokens the survivors are returned as unfinished hypotheses rather than dropped. And determinism needs a tie rule: ties go to the lower flat index , which a stable sort of the negated scores gives for free, so Python and Rust implementations agree.
The state, gathered by parent
Section titled “The state, gathered by parent”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 equivalences
Section titled “Two equivalences”Two limiting cases pin the algorithm down. With it is greedy. With nothing is ever pruned: at step there are at most candidates, all kept, so the result is every possible output in score order, which a test enumerates by brute force.
Length normalization
Section titled “Length normalization”Every token multiplies the probability by a number below 1, so always prefers shorter outputs. Wu et al. (GNMT) rank finished hypotheses by ; here counts eos. is the raw log-probability and the mean per token. During the search all live hypotheses have the same length, so ranking them by or by is the same thing; the penalty matters only when finished hypotheses of different lengths are compared, and it can change the winner.
Working it by hand
Section titled “Working it by hand”Take three tokens, eos = 0, a = 1, b = 2, and a model that is a table of next-token probabilities:
| prefix | |||
|---|---|---|---|
| (empty) | 0.1 | 0.5 | 0.4 |
a | 0.2 | 0.1 | 0.7 |
b | 0.9 | 0.05 | 0.05 |
Greedy () picks a (0.5), then after a the best is b (0.7). The output is a b, unfinished, with and .
Beam (, , ). Step 1 ranks a 0.5, b 0.4, eos 0.1 and keeps a and b. Step 2 ranks all six extensions together:
| candidate | probability |
|---|---|
b eos | |
a b | |
a eos | |
a a | 0.05 |
b a, b b | 0.02 each |
It keeps b eos (finished) and a b, which is cut at and returned unfinished. The result is b eos with , then a b with . The model was called twice, with 1 and then 2 rows. With the scores are and , the same order. A correct solution reproduces all three results: the beam, greedy, and the penalized scores.
Designing the API
Section titled “Designing the API”@dataclassclass Hypothesis: tokens: list[int]; logprob: float; score: float; finished: booldef 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.
Building it step by step
Section titled “Building it step by step”Gathering the state
Section titled “Gathering the state”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 parentBecause 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.
The search loop
Section titled “The search loop”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 , 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.
Greedy as a special case
Section titled “Greedy as a special case”_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.
Why this design
Section titled “Why this design”The cost is at most model calls on at most rows each, and per step for the normalization and for the full sort, plus the state gather. A partial selection (argpartition) would be , 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 together rather than top- per parent? Per-parent selection keeps 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 live rows until all 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 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.
Testing it
Section titled “Testing it”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 and , 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:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| hand example beam beats greedy | unit | b eos (0.36) then a b (0.35), calls [1, 2] | pins down the algorithm |
hand example: greedy commits to a | unit | greedy gives a b, score equal to logprob | the baseline beam search must beat |
| hand example length penalty | unit | scores and | the penalty counts eos |
| beam one is greedy | differential | a beam of 1 equals the test’s own greedy loop on 6 prefix-dependent models | greedy is a special case, not a second code path |
| exhaustive beam equals brute force | differential | all 31 outputs of a , model, by score, | the search is exact when nothing is pruned |
| small beam at is the top of the exhaustive ranking | property | with the beam is the most likely first tokens | ranking over all candidates |
| beam never holds more than beam size | property | the step function never sees more than rows | the cost bound of beam search |
eos finishes and shrinks the beam | property | eos once and last; logprob equals the path sum; the beam never grows back | finished outputs are final |
| search stops when the last hypothesis finishes | boundary | exactly two calls when eos is certain at step 2 | no call with zero rows |
max_len returns unfinished | boundary | a model that never says eos gives unfinished outputs of length | decoding always terminates |
| length penalty changes the winner | unit | picks a eos, picks b b b eos; results ranked by score | why translation systems use a penalty |
| ties go to the lowest id | boundary | uniform logits keep tokens 0 and 1 first | the same order in Python and Rust |
| logits need not be normalized | property | adding a constant per row changes nothing | models return logits |
| masked tokens are never chosen | boundary | -inf is never kept, even if the beam is not full | grammar and stop-list masks |
logprob is the sum along the path | property | logprob and score recomputed from the model | rescoring and comparison across searches |
select_state keeps the structure | unit | NamedTuple, dict, list, repeated rows, non-array leaves; a set raises | any model’s state works |
| state follows parents in a real search | property | every state row extends a prefix the search kept | the step function scores the right prefixes |
| validation | boundary | bad sizes, wrong logits shape, nothing finite | caller bugs fail loudly |
beam decodes a Seq2Seq | differential | over Seq2Seq with Luong attention: beam 1 equals greedy, every hypothesis’s logprob equals teacher-forced rescoring | the zoo’s call site |
What can go wrong
Section titled “What can go wrong”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:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| keeping the best tokens of each hypothesis | the beam grows to rows, then more | one argsort over the flattened [k * V] table |
| adding raw logits instead of log-probabilities | rows with a larger logit scale win; disagrees with brute force | log_softmax(z, axis=-1) before adding to live_lp |
an eos hypothesis that keeps going | outputs with tokens after eos, a search that never ends early | an eos extension goes to finished, not to new_tokens, and keeps its slot |
dropping the live hypotheses at max_len | an empty result for a model that rarely says eos | at t == max_len - 1 survivors are appended with finished=False |
keeping -inf candidates to fill the beam | masked tokens appear in the output | n_keep is capped by np.isfinite(cand).sum() |
| state rows not gathered by parent | the model scores one prefix and the search records another | select_state(state, parents) after every step |
eos left out of the length | scores disagree with the formula | _score(lp, len(toks), ...) where toks includes eos |
| results ranked by logprob, not score | the length penalty has no effect | the final sorted(..., key=lambda h: -h.score) |
| ties to the highest index | Python and Rust disagree on near-uniform rows | np.argsort(-cand, kind="stable") |
| survivors finalized one step early | outputs one token short | survivors are finalized only at t == max_len - 1, after the last token is appended |
| a NamedTuple rebuilt as a tuple | the decoder’s state.h access fails | type(state)(*parts) when the tuple has _fields |
| lists not searched | an LSTM’s per-layer state list is never reordered | lists are recursed into element by element |
| greedy scored with length penalty 1 | greedy_decode’s score is not its logprob | greedy_decode passes length_penalty=0.0 |
| the model called after every hypothesis finished | a call with zero rows, wasted work | if not new_tokens ...: break before the next call |
Warning: Forgetting
select_stateproduces no error at all. Row 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.
Where this leads
Section titled “Where this leads”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 piece | Production equivalent | What it adds | Where to look |
|---|---|---|---|
beam_search | Hugging Face generate(num_beams=...) | batched beams across many inputs, early_stopping modes, num_return_sequences | transformers/generation/utils.py (_beam_search), beam_search.py (BeamHypotheses) |
select_state | the KV-cache reorder | gathers 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_penalty | GNMT’s and coverage penalty | a smoother penalty and a term for source words never attended | Wu et al. 2016, section 7; fairseq sequence_generator.py |
| exact search for tiny | exact decoding studies | shows the most likely output is often empty: the beam’s errors help | Stahlberg and Byrne, “On NMT Search Errors and Model Errors” (2019) |
Further reading
Section titled “Further reading”- 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).
Key terms
Section titled “Key terms”- greedy decoding: taking the single most likely token at every step; a beam of size 1.
- beam search: keeping the 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 to counter the bias toward short outputs.
Summary
Section titled “Summary”- Greedy decoding commits to the best next token and can miss the best sequence; beam search keeps the
beam_sizebest prefixes and finds it in the worked example, 0.36 against greedy’s 0.35. - All
k * Vextensions are ranked together, so the beam never holds more thanbeam_sizerows. - A beam of 1 is greedy decoding, and a beam of at least 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 realSeq2Seq. - Summed log-probability prefers short outputs; dividing by
len ** length_penaltycan change the winner.
Review questions
Section titled “Review questions”- In the worked example, greedy chose
afirst. Why does the beam end up preferringb eos?Answer
The 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$. - Why is
log_softmaxapplied before adding tolive_lpeven though the model “already” ranks tokens?Answer
Within 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. - What does
n_keep = min(beam_size - len(finished), isfinite(cand).sum())protect against, in each of its two terms?Answer
The 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. - Why does the length penalty not affect which live hypotheses are kept?
Answer
All 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. - What would go wrong if
select_statewere skipped?Answer
Row $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.