Decoding as Search: Greedy and Beam Search
The most probable string is a shortest path: uniform-cost search finds it, greedy and beam search prune the search with no guarantee, one pruned score certifies success, and the string they converge to is shorter than the text the model learned from
Overview & Motivation
Ask a language model to continue “revenue”. In our small example its first word is “rose” with probability , “was” with , or “fell” with . Greedy decoding takes “rose”, then the likeliest word after it, “sharply”, and stops: the string has probability . But “was” is followed by “flat” four times in five, and “revenue was flat” ends the sentence with probability , almost three times as likely. Greedy decoding never looked. A beam of width two keeps both “rose” and “was”, finds “was flat”, and can prove that nothing it dropped could have done better.
That example has the whole topic in it. A model gives every string a probability, and the most probable string, the mode, is what most decoders aim for. Finding it is a search problem, and we develop it in order:
- The mode is a shortest path. With edge costs , uniform-cost search finds it exactly, and a Markov model’s prefixes merge so that Dijkstra’s algorithm finds it in polynomial time.
- Greedy and beam search are pruned versions of that search. Neither has an approximation guarantee, and a wider beam can do worse.
- One extra number certifies success. If the best string beats every candidate the beam pruned, it is the mode.
- The mode is biased toward stopping. Normalizing by length fights the bias, but it breaks exact search, and without a length cap it can have no optimum.
- Greedy decoding can loop forever, even on a model that ends every string with probability one.
Then we measure search error, missing the mode, against model error, the mode being a poor answer, on two models trained on the shared filings. Wider beams remove the first and expose the second.
Decoding as a shortest path
We write for the end mark, the token </s> that closes every sentence.
Definition 1 (The decoding problem).
A language model over a vocabulary assigns a prompt and a string with the probability
The mode is . The model is consistent if these probabilities sum to over all finite strings.
A consistent model has a mode: only finitely many strings can have probability above any , so the supremum is a maximum. The neural-language-models topic proves that a softmax recurrent model with bounded state is consistent (its Theorem 4). Picture the strings as the leaves of a tree. The root is the prompt, each node is a prefix , and each edge adds one token.
Proposition 1 (The mode is a shortest path).
Give the edge from to the weight . Then is the total weight of the path from the root to , and the mode is the cheapest path from the root to an leaf.
Proof.
Take of the product in Definition 1. Each factor is at most , so each weight is non-negative.
∎The weights are surprisals, formalML’s information content (its Definition 1). Because they are non-negative, the cost of a prefix, with the probability that the string begins with , can only grow as the prefix grows. That monotonicity is what every exact method on this page uses.
Theorem 1 (Uniform-cost search is exact).
Uniform-cost search keeps a frontier of prefixes, starting with the root, and repeatedly removes the cheapest one. If it ends in the search returns it; otherwise its children join the frontier. For a consistent model the search ends, and the string it returns is a mode. If moreover , where counts the words before , the search removes at most prefixes.
Proof.
Every finished string not yet removed has a prefix on the frontier: the root is a prefix of every string, and when is removed its children take its place for every string through . In particular, a mode exists, and until it is removed one of its prefixes is on the frontier, at cost at most . The search removes the cheapest prefix, so every prefix removed up to that point has .
Now the search ends. The open prefixes of length have total probability , so at most of them are that probable. Consistency gives , so past some length no open prefix qualifies, and only finitely many do, even if is infinite. At most finished strings qualify too. So the search removes finitely many prefixes before it removes a finished string.
Suppose the first finished string removed is , at cost . Every frontier prefix then costs at least , and every finished string not yet removed has a frontier prefix of cost at most , so and is a mode.
For the work, sum the count of open prefixes over . That gives , since , and the finished strings add at most .
∎Consistency is doing real work there. Let the root go to with probability or with , let end the string, and let repeat with probability . The finished strings sum to , and the mode is . The search removes , , , and so on, each of probability , and never reaches it.
This is Dijkstra’s algorithm (1959) on the tree, or A* with the zero heuristic (Hart, Nilsson, and Raphael 1968). Our implementation adds children lazily: removing a node pushes only its best child and its next sibling, so the frontier stays small though a trigram prefix has children, the vocabulary’s types less the unknown-word token, which we never emit. The argument survives because a sibling not yet pushed is never cheaper than the one standing in for it. The harness checks the search against brute-force enumeration on random trees, and the work bound on each.
Corollary 1 (Markov models recombine).
In an order- Markov model, depends only on the state , the last tokens. If and , then can be discarded, and uniform-cost search becomes Dijkstra’s algorithm on a graph of at most states. Exact decoding is polynomial in the size of that graph.
Proof.
Every completion has , because the two prefixes assign the same conditional probabilities. So any string through is matched or beaten by the same string through , and the search may expand each state once.
∎The length-layered form of the same dynamic program is Viterbi’s algorithm (1967). For the trigram models of the n-gram topic the state is the last two words. With the corollary’s bound is states, and it is only a bound: a context never seen in training backs off to its last word alone, so past the start of a sentence our trigram has at most states. On our prompts, which are introduced below, Dijkstra reaches the exact mode after a median of removals and at most , and a search without recombination returns the same string every time.
For a neural network nothing recombines: two prefixes never have the same future. Chen and colleagues (2018) show how hard the problem then is. For a single-layer ReLU recurrent network with rational weights, deciding whether some string has probability above a threshold is undecidable (their Theorem 8). For a consistent network it is decidable, but the best string can be longer than any computable function of the network’s size (their Theorems 9–10). Restricted to strings of polynomial length it is NP-complete (their Theorem 11).
Greedy and beam search: pruned uniform-cost search
Uniform-cost search is exact but its frontier can grow without bound. The decoders used in practice keep a frontier of fixed size.
Definition 2 (Beam search).
Beam search with width forms, at each step, every child of every open prefix and keeps the most probable. Kept children that end in move to a finished set; the rest stay open. The search stops once the best finished string is at least as probable as the best open prefix, which no extension can beat. Greedy decoding is beam search with .
The beam idea goes back to Lowerre’s speech recognizer (1976). Pruning trades the guarantee of Theorem 1 for a fixed budget, and the trade has no floor.
Theorem 2 (No approximation guarantee).
(a) For every there is a model on which greedy decoding returns a string less than times as probable as the mode. (b) For every there is a model on which beam search with width misses the mode and width finds it. (c) Beam search with width can return a strictly less probable string than width .
Proof.
(a) The first token is with probability or with . After come equally likely words, each followed by ; after comes . Greedy decoding takes and returns probability , while has . The ratio is below once .
(b) Take decoys of probability each and a word with , so each decoy is a little likelier than . Each decoy forks into two words that end the string, and ends at once. Width keeps the decoys and returns probability . Width also keeps , its next candidate outranks every other, and the search stops with the mode.
(c) After () come ten words of , each ending the string. After () come and ( each), then fifty words of , each ending the string. Greedy decoding returns . Width keeps and , and at the second step and ( each) push out every (), so it returns . Width keeps one and returns .
∎Part (c) is not only a construction. On our two corpus models a wider beam returned a strictly less probable string than a narrower one on of the prompts.
A certificate
Huang, Zhao, and Ma (2017) stop beam search as soon as the best finished string beats every open prefix, and prove the result optimal “modulo beam size”: the best among the strings the beam could have kept (their Theorem 1). One more number turns that into a guarantee about every string.
Theorem 3 (A certificate of optimality).
Let be beam search’s best finished string, the highest log-probability of any candidate it pruned, and the highest log-probability of a prefix still open when it stopped. If , then is a mode.
Proof.
Take any finished string . At each step its prefix was either kept or pruned, and once kept it is finished or open. So finished inside the beam, and then ; or it extends a pruned candidate, and then ; or it extends a prefix still open, and then . In the last two cases we use that log-probability never rises along a path.
∎The certificate is sufficient, not necessary. It stays silent whenever the beam pruned a prefix more probable than its answer, even if every completion of that prefix turned out worse. In the example of the overview, width pruned “fell” at , below the answer’s , so its answer is certified. Greedy decoding pruned “was” at , above its answer’s , so its answer is not.
Length normalization ranks finished strings by instead, where is the number of generated tokens including and , as in Theorem 1, counts only the words before it. Wu and colleagues (2016) use , and is plain probability. A longer string can now outscore its own prefix, and both Theorem 1 and Theorem 3 lose their footing. A length cap restores the certificate.
Proposition 2 (The certificate under a length cap).
Suppose strings have at most tokens, included, and is non-decreasing. If the best finished normalized score is at least , the result is the normalized optimum among strings of at most tokens.
Proof.
A completion of a prefix , with tokens, has and , so . Repeat the three cases of Theorem 3 with this bound.
∎The same bound gives the normalized beam a sound place to stop, and our implementation uses it.
Length bias
Why should the mode be short? Every word costs a factor of at most one, and stopping costs one factor too. Whenever stopping is the single most likely move, nothing after it can catch up.
Theorem 4 (The pull of the end mark).
(a) If is the likeliest next token after a prefix , then no completion of beats stopping: . (b) If every word’s step has probability at most , then , so for every finished string .
Proof.
(a) A completion that starts with a word has . (b) The word steps contribute at most and the final at most . Then , and taking logarithms reverses the inequality because .
∎Part (a) needs only that beats each word separately. With probability against spread over twenty words, it does. On the trigram the end mark is the argmax after only of the prompts, yet the mode is the empty continuation for of them: the condition is sufficient, far from necessary. Murray and Chiang (2018) relate the bias to local normalization, where every step must hand out a full unit of probability, the label bias of locally normalized models.
The usual remedies reward length: divide by , or add a reward per word. Both break the monotonicity of Proposition 1, and the first can leave nothing to find.
Proposition 3 (Normalization can have no optimum).
Under the model with and after every prefix, and with , the string has words and tokens, so its normalized score is . It is strictly increasing in and tends to , so no string attains the supremum.
Proof.
The derivative of has the sign of , which is positive because . A strictly increasing bounded sequence converges to its supremum and never reaches it, formalCalculus’ monotone convergence theorem (its Theorem 1).
∎The value is the edge. For general the derivative has the sign of . At the first term is negative and grows without bound, so the chain has an optimum: at it is ten words, scoring . At the sign stays positive, the score rises forever, and no string attains the supremum.
At , a string that keeps repeating a cycle has a normalized score tending to times the cycle’s mean cost, because grows like . The cheapest mean over all cycles is the quantity Karp (1978) characterized, so the limit is a multiple of his number, and only at . Such a limit can beat every finite string, as it does on this chain, though it need not: the finance case study below measures a corpus where it does not. Huang, Zhao, and Ma bound their per-word reward against that possibility, and a cap does the same job here.
Meister, Cotterell, and Vieira (2020) read the problem the other way round: beam search is the exact solution of a regularized decoding objective. Write for the surprisal of at step .
Proposition 4 (Greedy decoding is a regularized optimum).
Let . On a model with finitely many strings and no ties, there is a such that for every the unique maximizer of is the greedy string .
Proof.
, with equality exactly when every step of takes the likeliest token, which without ties means . Set , a maximum over finitely many strings. For and , .
∎This is their Theorem 3.1 in its simplest case, with their regularizer of Eq. 11. Their Theorem 3.2 extends it to width with a regularizer on sets of strings, which we cite. The regularizer penalizes each step whose surprisal exceeds the locally best one, a form of uniform information density: beam search prefers strings that spread their surprisal evenly, and that preference, not the mode, may be what makes its outputs read well.
Search error against model error
We now measure both kinds of error on two models trained on the shared filings. The prompts are the distinct three-word openings of held-out MD&A sentences, from Topic 3’s held-out split, whose words are all in both models’ vocabularies. The trigram is the n-gram topic’s interpolated Kneser–Ney model over words, exact by Dijkstra on its state graph. The decoder is the toy causal transformer of the scaling-laws topic: two pre-LN blocks of width over the commonest words, trained by that topic’s recipe on the training sentences, and exact by uniform-cost search with no recombination. Both are decoded under a per-step renormalization that never emits the unknown-word token.
Greedy decoding commits to “rose” and never sees “was flat”, the mode at 0.238. Width 2 keeps “was”, finds the mode, and proves it: the best prefix it pruned, “fell”, had less probability than its answer. Uniform-cost search pops prefixes in order of probability and stops at the first finished string.
At α = 0: the trigram’s prefixes recombine, so a beam of 32 already reaches the mode, and proves it; its outputs shrink to the mode’s length, a third of the text’s. Greedy decoding cycles on a share of the prompts, so its length counts only the outputs that end.
Greedy decoding on a finite-state model is a walk on its states. After “include” the likeliest word is “and”, and after “and and” it is “and” again: every looping prompt drains into the same one-word cycle, a product of Kneser–Ney backoff, since neither pair occurs in training.
The trigram’s mode often just stops. Normalization lengthens its outputs by steering them onto the 8-K template; at k = 16, 0.133 of all prompts end in “to disclose a material event”.
On the trigram, greedy decoding misses the mode on of the prompts. That count includes the of on which it never finishes, for a reason we come to below; among the it finishes, it misses on . Width misses on , width on , and width never, with every answer from there on certified by Theorem 3. Meanwhile the outputs shrink. A string that never ends has no length, so compare on greedy’s prompts: words under greedy decoding, at width , at width , and for the mode. Over all , width gives words and width reaches the mode’s . The sentences the prompts came from continue for words.
The decoder searches harder, since nothing recombines. Its exact search takes a median of removals and at most , and width still misses the mode on of the prompts. That rate belongs to one training seed, the hardest of the four we tried. Seeds to miss on , , and at width . On our seed the rate falls to at width and to at width . Its mode is never empty, though seeds to have , , and empty modes. At words (, , and on the other seeds) the mode too is shorter than the text, and our seed’s outputs shorten from words to as the beam widens.
The strings get shorter, but whether they get blander depends on how we count. On greedy’s prompts, the trigram’s cost per token averaged by prompt rises with width: nats under greedy decoding, at width , at width , and for the mode. Pooled over tokens it falls, from to . The words themselves get much cheaper, from nats to , while the final gets dearer, from to , and the average by prompt gives a short string, where that weighs most, the same vote as a long one. The mode is blander than the text by either count, as the case study below shows. Against greedy decoding, all we can say is that it is shorter.
So a wider beam is a better search for a shorter answer. Koehn and Knowles (2017) found the same in translation: quality falls beyond a moderate width, mostly because translations get shorter. Stahlberg and Byrne (2019) ran exact search on a Transformer translation model and found that the empty translation was the mode for of their test sentences. Cohen and Beck (2019) traced the damage to early discrepancies: wide beams find strings that pay for one unlikely token early and then follow a highly probable path. The fault is the model’s, not the search’s, and Eikema and Aziz (2020) argue that the mode is the wrong summary of a spread-out distribution in any case. Ours are spread out: the median mode has probability on the trigram and on the decoder.
Non-termination
Search error and model error both assume the search ends. It need not.
Theorem 5 (Greedy decoding is eventually periodic).
On an order- Markov model with state set , , greedy decoding either emits within steps or never does.
Proof.
Greedy decoding’s next token is a function of the state, so the states follow a deterministic map on the finite set . Among two coincide, say with , and from then on the states, and with them the tokens, repeat with period . If has not appeared by step , it never will.
∎On the trigram, greedy decoding cycles on of the prompts, and every cycle is the same one. After “include” the likeliest next word is “and”, and after “and and” it is “and” again. The prompts reach it by different roads, such as “analysts who cover halvorsen industrial reported revenue of million for the year include and and and”, and only of the pass through “include”. It looks like the repetition that Holtzman and colleagues (2020) observed when neural models are decoded by maximization, but here the cause is smoothing. Neither “include and” nor “and and” occurs in training. With no count to go on, Kneser–Ney backoff weighs a word by how many distinct words it follows, and “and” follows , the most of any type ( is second at ). The unseen context “and and” falls back on the bigram row of “and”, where “and” gets only that backoff share, and it still edges out “markets”, a word seen there, to . So the loop is a smoothing artifact, decided by that narrow margin.
A neural model is not finite-state, but consistency does not rescue it.
Proposition 5 (A consistent model on which beam search never ends).
Take words of probability each and of probability , the same after every prefix. The model is consistent, and beam search with width never terminates.
Proof.
, so the model is consistent. At every step, the word-children of the best open prefix score above every -child of any open prefix, so no finished string is ever kept.
∎Welleck and colleagues (2020) prove the general version: for every decoder that considers fewer than all tokens at each step, there is a consistent recurrent model on which it produces an infinite string with probability one (their Theorem 3.4). Their remedy is a model whose end-mark probability is forced to grow, under which greedy decoding and beam search provably end (their Theorems 4.2–4.3).
Where this goes next
The sampling topic, next in this track, gives up on the mode. Temperature, top-, and nucleus sampling draw strings in proportion to (a reshaped) probability, and the gap between the mode’s nats per word and the text’s , both averaged by prompt, is the typicality question it takes up: real text is not the most probable text. The BLEU and ROUGE topic supplies what this page measured only by length, a score of the output against a reference, and it is on such scores that the beam-search curse was first seen.
Three things are outside our scope. Minimum Bayes risk decoding, which Eikema and Aziz advocate, picks the string with the highest expected similarity to the model’s samples rather than the most probable one. Constrained, diverse, and speculative decoding change what is searched for or how fast. And heuristic search with learned estimates of the remaining cost, A* proper, needs a bound on the future that language models do not supply.
Honest caveats
Implementation
The companion notebook (notebookPath) imports beam_search_decoding.py, which owns every number on this page. That module imports the n-gram topic’s module for the Kneser–Ney trigram, the perplexity topic’s module for its vectorized next-word distributions, and the scaling-laws topic’s module for the causal decoder and its gradient, which it trains from scratch in NumPy for steps. It implements uniform-cost search with lazy successors and optional recombination, beam search that runs several length penalties in one pass and reports Theorem 3’s certificate, greedy orbits on finite-state models, and a cheapest-cycle search with its proof of optimality. A harness of assertion-based tests runs in about two and a half minutes on a laptop CPU, most of it the three extra decoder seeds and the widest beams. The tests cover:
- Theorem 1 against brute-force enumeration on random trees, with the work bound on each, the inconsistent model on which it fails, a consistent model with , and graph search against tree search on every trigram prompt.
- Theorem 2’s three constructions, for down to and widths to , and non-monotone widths on both corpus models.
- Theorem 3’s soundness on random trees and on both corpus models at every width, and Proposition 2’s on the normalized runs.
- Theorem 4 on every prefix and every string of random trees, Proposition 3’s monotone limit and the chain’s optimum at , and Proposition 4 on trees.
- Greedy decoding’s lengths and misses on the prompts it finishes, and the decoder’s search numbers on four seeds and at widths and .
- Every decoder score against one full forward pass of the decoded string, to in double precision.
- Theorem 5 on every trigram prompt, the backoff counts behind the loop, and Proposition 5 for widths to .
- The cheapest-cycle search against Karp’s formula on random digraphs, its against the trigram itself, the template shares, and the certificate against the cap.
The laboratory reads its data from a JSON file that one of those tests requires to equal the module’s viz_payload() exactly, so the figure cannot drift from the code.
References & Further Reading
- paper A Note on Two Problems in Connexion with Graphs — E. W. Dijkstra (1959) Numerische Mathematik 1: 269–71. The shortest-path algorithm behind Theorem 1 and its corollary
- paper A Formal Basis for the Heuristic Determination of Minimum Cost Paths — Peter E. Hart, Nils J. Nilsson, and Bertram Raphael (1968) IEEE Transactions on Systems Science and Cybernetics 4 (2): 100–107. A* and admissible heuristics; uniform-cost search is A* with the zero heuristic
- paper Error Bounds for Convolutional Codes and an Asymptotically Optimum Decoding Algorithm — Andrew J. Viterbi (1967) IEEE Transactions on Information Theory 13 (2): 260–69. The length-layered dynamic program of the corollary to Theorem 1
- paper A Characterization of the Minimum Cycle Mean in a Digraph — Richard M. Karp (1978) Discrete Mathematics 23 (3): 309–11. The cheapest cycle per edge. At α = 1 a normalized score that keeps repeating a cycle tends to −6 times its mean cost
- book The HARPY Speech Recognition System — Bruce T. Lowerre (1976) PhD diss., Carnegie-Mellon University; the CMU degree record titles it “HARPY Speech Understanding System.” The origin of beam search
- paper Six Challenges for Neural Machine Translation — Philipp Koehn and Rebecca Knowles (2017) Proceedings of the First Workshop on Neural Machine Translation, 28–39. Quality falls beyond a moderate beam width, chiefly through shorter outputs
- paper On NMT Search Errors and Model Errors: Cat Got Your Tongue? — Felix Stahlberg and Bill Byrne (2019) EMNLP-IJCNLP 2019, 3356–62. Exact search for a Transformer: the empty translation is the mode for 51.8% of sentences
- paper Is MAP Decoding All You Need? The Inadequacy of the Mode in Neural Machine Translation — Bryan Eikema and Wilker Aziz (2020) COLING 2020, 4506–20. The mode as a poor summary of a spread-out distribution, and minimum Bayes risk decoding instead
- paper Empirical Analysis of Beam Search Performance Degradation in Neural Sequence Models — Eldan Cohen and J. Christopher Beck (2019) ICML 2019, PMLR 97: 1290–99. Wide beams degrade through early discrepancies: one unlikely token followed by a highly probable path
- paper Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation — Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V. Le, Mohammad Norouzi, Wolfgang Macherey, Maxim Krikun, et al. (2016) The length penalty lp(Y) = ((5 + |Y|)/6)^α of Eq. 14, used in §4 and §7, where the length counts the end mark
- paper Correcting Length Bias in Neural Machine Translation — Kenton Murray and David Chiang (2018) Proceedings of the Third Conference on Machine Translation, 212–23. Length bias as a consequence of locally normalized models, and a per-word reward
- paper When to Finish? Optimal Beam Search for Neural Text Generation (modulo beam size) — Liang Huang, Kai Zhao, and Mingbo Ma (2017) EMNLP 2017, 2134–39. The stopping rule and its optimality modulo beam size (their Theorem 1), beside Theorem 3
- paper If Beam Search Is the Answer, What Was the Question? — Clara Meister, Ryan Cotterell, and Tim Vieira (2020) EMNLP 2020, 2173–85. Beam search as the exact solution of a regularized objective (their Theorems 3.1–3.2, Eq. 11), and uniform information density
- paper Recurrent Neural Networks as Weighted Language Recognizers — Yining Chen, Sorcha Gilroy, Andreas Maletti, Jonathan May, and Kevin Knight (2018) NAACL 2018, 2261–71. The best string of an RNN is undecidable (Theorem 8), decidable but unboundedly long for consistent RNNs (Theorems 9–10), and NP-complete at polynomial length (Theorem 11)
- paper Consistency of a Recurrent Language Model With Respect to Incomplete Decoding — Sean Welleck, Ilia Kulikov, Jaedeok Kim, Richard Yuanzhe Pang, and Kyunghyun Cho (2020) EMNLP 2020, 5553–68. Incomplete decoding (Definition 2.9), its inconsistency (Theorem 3.4), and self-terminating models (Theorems 4.2–4.3, Appendix C)
- paper The Curious Case of Neural Text Degeneration — Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, and Yejin Choi (2020) ICLR 2020. Repetition under maximization-based decoding, and the case for sampling taken up by the next topic