Decoding: Beam Search & Its Pathologies
Search versus sampling, length bias and the beam search curse.
Search harder for a translation model's most probable output and its translations get worse. Search exactly, and for half the sentences of a test set the most probable output is the empty string. This lesson takes decoding apart: when beam search's shortcuts are provably safe, why the mode of a sequence model is short and nearly arbitrary, what objective beam search really optimizes, and the decoders that use the whole distribution instead of its peak.
What you’ll learn
- Prove that prefix scores decrease monotonically, and use this to justify beam search's stopping rule and exact branch-and-bound decoding.
- Explain length bias, the beam search curse and the empty mode found by exact search, and show in a model you can solve by hand why the mode can be short and carry almost no probability.
- State and prove that greedy search exactly maximizes a uniform-information-density objective in a limit (Meister et al., 2020), and say what this does and does not explain.
- Analyze truncated sampling and minimum Bayes risk decoding, and prove that decoders which can exclude the end token may never stop, even on a model whose outputs are finite with probability one.
Decoding is search
Training made good; decoding must turn it into one output. The classical answer is the single most probable output, maximum a posteriori (MAP) decoding:
How large is that tree? There are token sequences of length 20 over a vocabulary of 32,000 tokens. What is of this number?
Show the answer
90
, so about sequences, against roughly atoms in the observable universe (the comparison is Stahlberg and Byrne's). Enumeration is hopeless; what is possible is search that prunes with a guarantee, or heuristics without one.
Beam search's stopping rule is safe. Suppose a finished output scores at least as high as the best live prefix . Every completion of a live prefix scores below that prefix, hence below , so no extension of the current beam can overtake :
Exact search by branch and bound (Stahlberg & Byrne, 2019). Run beam search to get a complete output whose score is a lower bound on the optimum. Then search depth first, trying first at every node, raising whenever a better complete output turns up, and abandoning any prefix whose score falls to or below:
Correctness. Every proper prefix of the optimum scores above , so none is ever pruned and the search reaches . The worst case is still exponential, but the bound prunes well enough to decode a full WMT test set exactly with a transformer.
Both arguments need the lemma. Length normalization and per-token rewards break it, because they can raise a score as the output grows; exact search under them needs bounds that depend on the length, and beam search needs other stopping rules (Yang, Huang & Ma, 2018).
Beam search itself buys predictability, not guarantees: decoder evaluations and a top- selection among candidates per step, fixed in advance. Neural translation systems typically used between 4 and 12 (Wu et al., 2016, found 2 or 4 only slightly worse than 8–12). How often does such a search miss the mode, and does it matter?
Search errors that help
Koehn and Knowles (2017) varied the beam width for translation systems in eight language pairs. Quality peaked at widths between 4 and about 30 and then declined; normalizing scores by length moved the best widths to 30–50 but did not stop the decline, whose main cause was shorter translations. Yang, Huang and Ma (2018) called this the beam search curse. Stahlberg and Byrne (2019) then ran the exact search above on a whole test set:
| Decoder | BLEU | Search errors | Mode is the empty output |
|---|---|---|---|
| Greedy | 29.3 | 73.6% | (not reached) |
| Beam, | 30.3 | 57.7% | (not reached) |
| Exact search | 2.1 | 0% | 51.8% of sentences |
You can watch the same curse in a model small enough to search exhaustively: the story prompt of the sampling widget below (step 4), a hand-built model whose 15,052 possible continuations can be enumerated. Beam search, exactly as in the pseudocode of Encoder–Decoder Models & Attention, gives:
| Beam width | Output | Tokens | Probability |
|---|---|---|---|
| 1 (greedy) | "… little girl who lived in a small village." | 9 | 0.025% |
| 2 | depends on how ties are broken | 9 or 8 | 0.025% or 0.070% |
| 3–9 | "… little girl who lived in a castle." (or forest, or village) | 8 | 0.070% |
| 10–22 | "… king who lived in a castle." (or forest, or village) | 7 | 0.105% |
| 23–36 | depends on how ties are broken | 7 down to 2 | 0.105%–0.932% |
| 37 and up | "… king." or "… dragon.", the two tied modes | 2 | 0.932% |
In the model of (b) with and , which statement is true?
- The mode is an output of length 19, the expected length
- The mode is the empty output, although 95% of samples are non-empty and the mean length of a sample is 19
- All outputs of length 19 tie for the mode
- There is no mode, because there are infinitely many outputs
Show the answer
B. The mode is the empty output, although 95% of samples are non-empty and the mean length of a sample is 19
The empty output has probability ; any single 19-token output has . The length 19 is typical, but each individual output of that length is astronomically unlikely, so the peak of the distribution sits on an output the model almost never produces.
Real translation models are far from uniform, but part (a) is the same arithmetic. A good 25-token translation whose tokens average 0.5 nats of surprisal has probability about , so the empty output wins as soon as the model puts more than that on at the first step. Eikema and Aziz (2020) draw the conclusion: when a model spreads its mass over very many acceptable outputs, the single most probable one carries so little of it that it is "essentially arbitrary", and its failures say more about MAP decoding than about the model. A small beam works partly because it fails to find the mode: its search errors cancel the length bias.
Fixes counter the bias directly. Wu et al. (2016) ranked finished hypotheses by , a length normalization plus a coverage penalty, where is the attention of target word on source word : outputs that leave source words with little total attention lose score. On their English→French development set the two raised BLEU from 30.3 to 31.4. Such fixes are heuristics, though, and typically need retuning for each beam width.
What beam search optimizes
If beam search's errors are what make it work, what is it optimizing? Meister, Cotterell and Vieira (2020) look for a regularizer for which beam search is exact: it returns . Write the surprisal of a token as , so that MAP decoding minimizes the total surprisal .
, with equality exactly when every token is the most probable one at its step. With no ties, the greedy output is the only complete output of zero regret:
With bounded length and a finite vocabulary there are finitely many outputs, so the smallest positive regret and the largest log-probability advantage over are attained:
For every other output loses to :
The regularizer charges for uneven surprisal: a choice much less likely than the locally best one costs quadratically. Meister et al. connect this to the uniform information density hypothesis from psycholinguistics (Levy & Jaeger, 2007): speakers tend to spread information evenly over an utterance. The empty translation is the opposite of even. Return to the 25-token translation of the last step, and let the model give probability at the first step. The empty output packs all its surprisal into that one improbable token, nats, while the translation spends 0.5 nats on each token, 12.5 in all. MAP prefers the empty output, . A squared-surprisal penalty charges against , and the translation wins for every above about .
The experiments bear this out. Beam search under UID-style objectives no longer collapses as the beam widens:
| Objective | ||||
|---|---|---|---|---|
| MAP (no regularizer) | 36.42 | 36.30 | 32.83 | 14.66 |
| Length normalization | 36.02 | 35.94 | 35.80 | 35.11 |
| Greedy regularizer | 36.45 | 36.49 | 36.22 | 36.15 |
| Squared surprisal | 36.92 | 36.42 | 36.13 | 35.96 |
Beyond the mode: sampling and risk
For open-ended generation, maximization fails in another way. Holtzman et al. (2020) found that beam search with a large language model produces bland text that falls into repetitive loops, and that once a phrase repeats, the probability that it repeats again rises with each repetition: a positive feedback loop. Human text is not maximally probable; it keeps making improbable, informative choices. Ancestral sampling, , is faithful to the model but admits tokens from its long and unreliable low-probability tail. Truncation samples but cuts the tail: top- sampling keeps the most probable tokens (Fan, Lewis & Dauphin, 2018), and nucleus sampling keeps the smallest set whose probability reaches :
The same applies to nucleus sampling whenever the nucleus leaves out the least probable token. The remedies are to keep in every candidate set, which makes top- and nucleus sampling consistent because the decoder's probability is then at least the model's, or to build models whose probability provably rises along the sequence (Welleck et al.'s self-terminating model).
Statistical decision theory picks the output with the highest expected utility under the model, letting the model's own distribution stand in for the unknown reference (Kumar & Byrne, 2004, applied it to statistical translation with -best lists):
With exact-match utility the expectation is the probability of , so MAP decoding is MBR with the harshest possible utility. A graded utility (BLEU, METEOR, a learned metric) instead rewards a consensus: an output that resembles many probable outputs, found in the bulk of the distribution rather than at its peak. An empty output resembles almost nothing the model samples, so it scores badly.
In practice draw samples, use them both as candidates and as pseudo-references, and pick the candidate with the best average utility against the others; each average is an unbiased estimate of that candidate's expected utility. The cost is utility evaluations. Eikema and Aziz (2020) used 30 samples with METEOR and were often on par with beam search, ahead of it on low-resource language pairs.
Key takeaways
- Prefix log-probabilities strictly decrease, which makes beam search's stopping rule safe and exact branch-and-bound decoding possible; length normalization and per-token rewards break this property.
- The mode of a sequence model is biased toward short outputs: under exact search a transformer translator's mode was the empty string for 51.8% of WMT'15 sentences, and wider beams lower quality (the beam search curse). Search errors hide this model error.
- Greedy and beam search are exact maximizers of uniform-information-density objectives in a limit; regularizers of that kind remove the collapse at large beam widths, which suggests beam search succeeds through its bias rather than its search.
- For open-ended text, maximization degenerates into repetition, and truncated sampling (top-, nucleus) cuts the unreliable tail; any decoder that can drop from its candidates may never stop.
- Minimum Bayes risk decoding chooses the output with the highest expected utility under the model; MAP decoding is the special case of exact-match utility.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Exact branch-and-bound decoding prunes a prefix once its score drops to the best complete score found so far. Which change to the scoring function makes this pruning unsafe?
- Computing each step's probabilities with a softmax at temperature
- Adding a reward of per output token to the log-probability
- Switching the decoder from an LSTM to a transformer
- Doubling the vocabulary
Show the answer
B. Adding a reward of per output token to the log-probability
Pruning is safe because adding a token can only lower a score. A per-token reward breaks that: a prefix below the bound can climb back above it by growing, so its completions may beat the incumbent.
Exact search returned the empty translation for 51.8% of test sentences, while beam search with scored 30.3 BLEU. What follows?
- The exact search must be buggy, since the model was trained on non-empty translations
- Beam search with finds the model's most probable output on most sentences
- The model puts its highest probability on bad outputs, and beam search does well partly because it fails to find them
- The empty translation is usually the best translation
Show the answer
C. The model puts its highest probability on bad outputs, and beam search does well partly because it fails to find them
Exact search is correct by the monotonicity argument, and the empty output really is the mode for those sentences. Beam search missed the mode on 57.7% of sentences, and those search errors hide the model's length bias. The diagnosis is a model error masked by search errors, or, in Eikema and Aziz's reading, an inadequate decision rule.
Minimum Bayes risk decoding picks . With the utility it is the same as…
- greedy decoding
- ancestral sampling
- nucleus sampling
- MAP decoding
Show the answer
D. MAP decoding
, so maximizing expected exact-match utility is maximizing probability. MBR with a graded utility instead rewards outputs that resemble many probable outputs.
A recurrent language model's hidden state is bounded, so at every step and its outputs are finite with probability one. How can greedy decoding of this model still produce an infinite sequence?
- Greedy decoding samples from the tail of the distribution
- If is never the single most probable token, greedy decoding never picks it, however large its probability floor
- A bounded hidden state makes impossible
- It cannot: a model that stops with probability one forces every decoder to stop
Show the answer
B. If is never the single most probable token, greedy decoding never picks it, however large its probability floor
Greedy decoding only ever sees the top token. Welleck et al. (2020) build a bounded tanh RNN whose logit is always the lowest, so greedy, beam and top- decoding never emit it (nor does nucleus sampling whenever its nucleus leaves out the last token), although ancestral sampling stops with probability one.
Further reading
- F. Stahlberg & B. Byrne, "On NMT search errors and model errors: Cat got your tongue?," EMNLP-IJCNLP (2019).
- P. Koehn & R. Knowles, "Six challenges for neural machine translation," Workshop on Neural Machine Translation (2017).
- C. Meister, R. Cotterell & T. Vieira, "If beam search is the answer, what was the question?," EMNLP (2020).
- A. Holtzman, J. Buys, L. Du, M. Forbes & Y. Choi, "The curious case of neural text degeneration," ICLR (2020).
- B. Eikema & W. Aziz, "Is MAP decoding all you need? The inadequacy of the mode in neural machine translation," COLING (2020).
- S. Welleck, I. Kulikov, J. Kim, R. Y. Pang & K. Cho, "Consistency of a recurrent language model with respect to incomplete decoding," EMNLP (2020).