Simple Algorithm
Deep Learning · Emergence · 26 min

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 pθ(y∣x)p_{\boldsymbol\theta}(\mathbf y\mid\mathbf x) good; decoding must turn it into one output. The classical answer is the single most probable output, maximum a posteriori (MAP) decoding:

y^=arg max⁡y log⁡pθ(y∣x)=arg max⁡y ∑t=1∣y∣log⁡pθ(yt∣y<t,x),y ranging over token strings ending in ⟨eos⟩\hat{\mathbf y}=\argmax_{\mathbf y}\ \log p_{\boldsymbol\theta}(\mathbf y\mid\mathbf x)=\argmax_{\mathbf y}\ \sum_{t=1}^{|\mathbf y|}\log p_{\boldsymbol\theta}(y_t\mid y_{<t},\mathbf x),\qquad\mathbf y\text{ ranging over token strings ending in }\langle\text{eos}\rangle
The decoder's state depends on the whole prefix, so there is no dynamic program of the Viterbi kind, which needs a state of bounded size; MAP decoding is a search through a tree with ∣V∣|\mathcal V| branches per node.
Predict before you look

How large is that tree? There are 32,0002032{,}000^{20} token sequences of length 20 over a vocabulary of 32,000 tokens. What is log⁡10\log_{10} of this number?

Show the answer

90

20log⁡1032,000=20×4.505≈90.120\log_{10}32{,}000=20\times4.505\approx90.1, so about 109010^{90} sequences, against roughly 108010^{80} 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.

DerivationTwo consequences
  1. log⁡p(yz∣x)<log⁡p(y∣x)≤log⁡p(f∣x)for every continuation z\log p(\mathbf y\mathbf z\mid\mathbf x)<\log p(\mathbf y\mid\mathbf x)\le\log p(\mathbf f\mid\mathbf x)\qquad\text{for every continuation }\mathbf z

    Beam search's stopping rule is safe. Suppose a finished output f\mathbf f scores at least as high as the best live prefix y\mathbf y. Every completion yz\mathbf y\mathbf z of a live prefix scores below that prefix, hence below f\mathbf f, so no extension of the current beam can overtake f\mathbf f:

  2. log⁡p(y∣x)≤γ⟹prune y and all of its completions\log p(\mathbf y\mid\mathbf x)\le\gamma\quad\Longrightarrow\quad\text{prune }\mathbf y\text{ and all of its completions}

    Exact search by branch and bound (Stahlberg & Byrne, 2019). Run beam search to get a complete output whose score γ\gamma is a lower bound on the optimum. Then search depth first, trying ⟨eos⟩\langle\text{eos}\rangle first at every node, raising γ\gamma whenever a better complete output turns up, and abandoning any prefix whose score falls to γ\gamma or below:

  3. log⁡p(y^≤t∣x)>log⁡p(y^∣x)≥γfor all t<∣y^∣\log p(\hat{\mathbf y}_{\le t}\mid\mathbf x)>\log p(\hat{\mathbf y}\mid\mathbf x)\ge\gamma\qquad\text{for all }t<|\hat{\mathbf y}|

    Correctness. Every proper prefix of the optimum y^\hat{\mathbf y} scores above log⁡p(y^∣x)≥γ\log p(\hat{\mathbf y}\mid\mathbf x)\ge\gamma, so none is ever pruned and the search reaches y^\hat{\mathbf y}. The worst case is still exponential, but the bound prunes well enough to decode a full WMT test set exactly with a transformer.

  4. log⁡p(y∣x)+λ∣y∣orlog⁡p(y∣x)∣y∣αcan increase as ∣y∣ grows\log p(\mathbf y\mid\mathbf x)+\lambda|\mathbf y|\quad\text{or}\quad\frac{\log p(\mathbf y\mid\mathbf x)}{|\mathbf y|^{\alpha}}\quad\text{can increase as }|\mathbf y|\text{ grows}

    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: O(k)\order{k} decoder evaluations and a top-kk selection among k∣V∣k|\mathcal V| candidates per step, fixed in advance. Neural translation systems typically used kk 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:

DecoderBLEUSearch errorsMode is the empty output
Greedy29.373.6%(not reached)
Beam, k=10k=1030.357.7%(not reached)
Exact search2.10%51.8% of sentences
A transformer-base translator on all 2,169 sentences of WMT'15 English→German. A search error is a sentence on which the decoder missed the model's highest-scoring output; even k=100k=100 missed it on 53.6% of sentences. In the same study the empty translation (a lone ⟨eos⟩\langle\text{eos}\rangle) was the mode for 47.7% of sentences under an LSTM model and 25.8% under the larger Transformer-Big.

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 kkOutputTokensProbability
1 (greedy)"… little girl who lived in a small village."90.025%
2depends on how ties are broken9 or 80.025% or 0.070%
3–9"… little girl who lived in a castle." (or forest, or village)80.070%
10–22"… king who lived in a castle." (or forest, or village)70.105%
23–36depends on how ties are broken7 down to 20.105%–0.932%
37 and up"… king." or "… dragon.", the two tied modes20.932%
Overall, wider beams find more probable and shorter stories. Many stories tie exactly in this hand-built model ("castle", "forest" and "village" are equally likely endings), so the table lists only results that hold however ties are broken. " king." needs a wide beam because after two tokens 30 unfinished partial stories are more probable than it, and six more tie with it, although it is already complete.
Check your understanding

In the model of (b) with q=0.05q=0.05 and m=1,000m=1{,}000, which statement is true?

  1. The mode is an output of length 19, the expected length
  2. The mode is the empty output, although 95% of samples are non-empty and the mean length of a sample is 19
  3. All outputs of length 19 tie for the mode
  4. 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 q=0.05q=0.05; any single 19-token output has 0.05×(0.95/1000)19≈2×10−590.05\times(0.95/1000)^{19}\approx2\times10^{-59}. 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 e−12.5≈4×10−6e^{-12.5}\approx4\times10^{-6}, so the empty output wins as soon as the model puts more than that on ⟨eos⟩\langle\text{eos}\rangle 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 log⁡p(y∣x)/lp(y)+β∑ilog⁡min⁡(∑jpij,1)\log p(\mathbf y\mid\mathbf x)/\mathrm{lp}(\mathbf y)+\beta\sum_i\log\min\big(\sum_jp_{ij},1\big), a length normalization plus a coverage penalty, where pijp_{ij} is the attention of target word jj on source word ii: 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 RR for which beam search is exact: it returns arg max⁡y(log⁡p(y∣x)−λR(y))\argmax_{\mathbf y}\big(\log p(\mathbf y\mid\mathbf x)-\lambda R(\mathbf y)\big). Write the surprisal of a token as ut(w)=−log⁡p(w∣y<t,x)u_t(w)=-\log p(w\mid y_{<t},\mathbf x), so that MAP decoding minimizes the total surprisal ∑tut(yt)\sum_tu_t(y_t).

DerivationProof
  1. Rgreedy(y)=0  ⟺  yt=arg min⁡wut(w)  for every t  ⟺  y=gR_{\text{greedy}}(\mathbf y)=0\iff y_t=\argmin_wu_t(w)\ \text{ for every }t\iff\mathbf y=\mathbf g

    Rgreedy≥0R_{\text{greedy}}\ge0, with equality exactly when every token is the most probable one at its step. With no ties, the greedy output g\mathbf g is the only complete output of zero regret:

  2. δ=min⁡y≠gRgreedy(y)>0,Δ=max⁡ylog⁡p(y∣x)−log⁡p(g∣x)≥0\delta=\min_{\mathbf y\ne\mathbf g}R_{\text{greedy}}(\mathbf y)>0,\qquad\Delta=\max_{\mathbf y}\log p(\mathbf y\mid\mathbf x)-\log p(\mathbf g\mid\mathbf x)\ge0

    With bounded length and a finite vocabulary there are finitely many outputs, so the smallest positive regret and the largest log-probability advantage over g\mathbf g are attained:

  3. log⁡p(y∣x)−λRgreedy(y)≤log⁡p(g∣x)+Δ−λδ<log⁡p(g∣x)−λRgreedy(g)■\log p(\mathbf y\mid\mathbf x)-\lambda R_{\text{greedy}}(\mathbf y)\le\log p(\mathbf g\mid\mathbf x)+\Delta-\lambda\delta<\log p(\mathbf g\mid\mathbf x)-\lambda R_{\text{greedy}}(\mathbf g)\qquad\blacksquare

    For λ>Δ/δ\lambda>\Delta/\delta every other output loses to g\mathbf g:

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 ⟨eos⟩\langle\text{eos}\rangle probability 10−510^{-5} at the first step. The empty output packs all its surprisal into that one improbable token, −log⁡10−5≈11.5-\log10^{-5}\approx11.5 nats, while the translation spends 0.5 nats on each token, 12.5 in all. MAP prefers the empty output, 11.5<12.511.5<12.5. A squared-surprisal penalty λ∑tut2\lambda\sum_tu_t^2 charges 11.52≈132.511.5^2\approx132.5 against 25×0.52=6.2525\times0.5^2=6.25, and the translation wins for every λ\lambda above about 0.0080.008.

The experiments bear this out. Beam search under UID-style objectives no longer collapses as the beam widens:

Objectivek=5k=5k=10k=10k=100k=100k=500k=500
MAP (no regularizer)36.4236.3032.8314.66
Length normalization36.0235.9435.8035.11
Greedy regularizer RgreedyR_{\text{greedy}}36.4536.4936.2236.15
Squared surprisal ∑tut2\sum_tu_t^236.9236.4236.1335.96
BLEU on the first 1,000 sentences of WMT'14 English→French newstest2014, with a fairseq transformer (Meister et al., 2020, Table 1). Exact decoding of the regularized objectives, with Dijkstra's algorithm, likewise approaches the BLEU of the best beam width, while exact MAP decoding does not.

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, yt∼p(⋅∣y<t,x)y_t\sim p(\cdot\mid y_{<t},\mathbf x), is faithful to the model but admits tokens from its long and unreliable low-probability tail. Truncation samples but cuts the tail: top-kk sampling keeps the kk most probable tokens (Fan, Lewis & Dauphin, 2018), and nucleus sampling keeps the smallest set whose probability reaches pp:

V(p)=arg min⁡S⊆V{∣S∣: ∑w∈Sp(w∣y<t,x)≥p},q(w)=p(w∣y<t,x) 1[w∈V(p)]∑w′∈V(p)p(w′∣y<t,x)V^{(p)}=\argmin_{S\subseteq\mathcal V}\Big\{|S|:\ \sum_{w\in S}p(w\mid y_{<t},\mathbf x)\ge p\Big\},\qquad q(w)=\frac{p(w\mid y_{<t},\mathbf x)\,\mathbb 1[w\in V^{(p)}]}{\sum_{w'\in V^{(p)}}p(w'\mid y_{<t},\mathbf x)}
The nucleus adapts its size to the distribution: a handful of tokens after a confident prefix, many after an open one. A temperature τ\tau reshapes the distribution first, pτ(w)∝p(w)1/τp_\tau(w)\propto p(w)^{1/\tau}.

The same applies to nucleus sampling whenever the nucleus leaves out the least probable token. The remedies are to keep ⟨eos⟩\langle\text{eos}\rangle in every candidate set, which makes top-kk and nucleus sampling consistent because the decoder's ⟨eos⟩\langle\text{eos}\rangle probability is then at least the model's, or to build models whose ⟨eos⟩\langle\text{eos}\rangle probability provably rises along the sequence (Welleck et al.'s self-terminating model).

DerivationMinimum Bayes risk: deciding with the whole distribution
  1. h^MBR=arg max⁡h∈H Ey∼p(⋅∣x)[u(y,h)]\hat h_{\text{MBR}}=\argmax_{h\in\mathcal H}\ \E_{\mathbf y\sim p(\cdot\mid\mathbf x)}\big[u(\mathbf y,h)\big]

    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 NN-best lists):

  2. Ey∼p[1[y=h]]=p(h∣x)⟹h^MBR=y^MAP\E_{\mathbf y\sim p}\big[\mathbb 1[\mathbf y=h]\big]=p(h\mid\mathbf x)\quad\Longrightarrow\quad\hat h_{\text{MBR}}=\hat{\mathbf y}_{\text{MAP}}

    With exact-match utility the expectation is the probability of hh, 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.

  3. h^=arg max⁡i≤N 1N−1∑j≠iu(y(j),y(i)),y(1),…,y(N)∼iidp(⋅∣x)\hat h=\argmax_{i\le N}\ \frac{1}{N-1}\sum_{j\ne i}u\big(\mathbf y^{(j)},\mathbf y^{(i)}\big),\qquad\mathbf y^{(1)},\dots,\mathbf y^{(N)}\overset{\text{iid}}{\sim}p(\cdot\mid\mathbf x)

    In practice draw NN 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 N(N−1)N(N-1) 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-kk, nucleus) cuts the unreliable tail; any decoder that can drop ⟨eos⟩\langle\text{eos}\rangle 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.

Question 1

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?

  1. Computing each step's probabilities with a softmax at temperature 0.50.5
  2. Adding a reward of λ>0\lambda>0 per output token to the log-probability
  3. Switching the decoder from an LSTM to a transformer
  4. Doubling the vocabulary
Show the answer

B. Adding a reward of λ>0\lambda>0 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.

Question 2

Exact search returned the empty translation for 51.8% of test sentences, while beam search with k=10k=10 scored 30.3 BLEU. What follows?

  1. The exact search must be buggy, since the model was trained on non-empty translations
  2. Beam search with k=10k=10 finds the model's most probable output on most sentences
  3. The model puts its highest probability on bad outputs, and beam search does well partly because it fails to find them
  4. 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.

Question 3

Minimum Bayes risk decoding picks arg max⁡hEy∼p(⋅∣x)[u(y,h)]\argmax_h\E_{\mathbf y\sim p(\cdot\mid\mathbf x)}[u(\mathbf y,h)]. With the utility u(y,h)=1[y=h]u(\mathbf y,h)=\mathbb 1[\mathbf y=h] it is the same as…

  1. greedy decoding
  2. ancestral sampling
  3. nucleus sampling
  4. MAP decoding
Show the answer

D. MAP decoding

Ey∼p[1[y=h]]=p(h∣x)\E_{\mathbf y\sim p}[\mathbb 1[\mathbf y=h]]=p(h\mid\mathbf x), so maximizing expected exact-match utility is maximizing probability. MBR with a graded utility instead rewards outputs that resemble many probable outputs.

Question 4

A recurrent language model's hidden state is bounded, so p(⟨eos⟩∣prefix)≥ξ>0p(\langle\text{eos}\rangle\mid\text{prefix})\ge\xi>0 at every step and its outputs are finite with probability one. How can greedy decoding of this model still produce an infinite sequence?

  1. Greedy decoding samples from the tail of the distribution
  2. If ⟨eos⟩\langle\text{eos}\rangle is never the single most probable token, greedy decoding never picks it, however large its probability floor
  3. A bounded hidden state makes ⟨eos⟩\langle\text{eos}\rangle impossible
  4. It cannot: a model that stops with probability one forces every decoder to stop
Show the answer

B. If ⟨eos⟩\langle\text{eos}\rangle 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 ⟨eos⟩\langle\text{eos}\rangle logit is always the lowest, so greedy, beam and top-kk 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).