intermediate decoding-generation 40 min read

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 0.450.45, “was” with 0.350.35, or “fell” with 0.200.20. Greedy decoding takes “rose”, then the likeliest word after it, “sharply”, and stops: the string has probability 0.08640.0864. But “was” is followed by “flat” four times in five, and “revenue was flat” ends the sentence with probability 0.2380.238, 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:

  1. The mode is a shortest path. With edge costs −log⁡p-\log p, uniform-cost search finds it exactly, and a Markov model’s prefixes merge so that Dijkstra’s algorithm finds it in polynomial time.
  2. Greedy and beam search are pruned versions of that search. Neither has an approximation guarantee, and a wider beam can do worse.
  3. One extra number certifies success. If the best string beats every candidate the beam pruned, it is the mode.
  4. 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.
  5. 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 eos\mathrm{eos} for the end mark, the token </s> that closes every sentence.

Definition 1 (The decoding problem).

A language model over a vocabulary VV assigns a prompt xx and a string y=(y1,…,yn)y = (y_1, \dots, y_n) with yn=eosy_n = \mathrm{eos} the probability

p(y∣x)  =  ∏t=1np(yt∣x,y<t).p(y \mid x) \;=\; \prod_{t=1}^{n} p(y_t \mid x, y_{\lt t}).

The mode is y⋆=arg⁡max⁡yp(y∣x)y^\star = \arg\max_y p(y \mid x). The model is consistent if these probabilities sum to 11 over all finite strings.

A consistent model has a mode: only finitely many strings can have probability above any ε>0\varepsilon \gt 0, 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 hh, and each edge adds one token.

Proposition 1 (The mode is a shortest path).

Give the edge from hh to hwhw the weight c(h,w)=−log⁡p(w∣x,h)≥0c(h, w) = -\log p(w \mid x, h) \ge 0. Then −log⁡p(y∣x)-\log p(y \mid x) is the total weight of the path from the root to yy, and the mode is the cheapest path from the root to an eos\mathrm{eos} leaf.

Proof.

Take −log⁡-\log of the product in Definition 1. Each factor is at most 11, 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, c(h)=−log⁡π(h)c(h) = -\log \pi(h) with π(h)\pi(h) the probability that the string begins with hh, 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 eos\mathrm{eos} 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 E∣Y∣<∞\mathbb{E}|Y| \lt \infty, where ∣Y∣|Y| counts the words before eos\mathrm{eos}, the search removes at most (2+E∣Y∣)/p(y⋆)(2 + \mathbb{E}|Y|)/p(y^\star) prefixes.

Proof.

Every finished string not yet removed has a prefix on the frontier: the root is a prefix of every string, and when hh is removed its children take its place for every string through hh. In particular, a mode y⋆y^\star exists, and until it is removed one of its prefixes is on the frontier, at cost at most c(y⋆)c(y^\star). The search removes the cheapest prefix, so every prefix removed up to that point has π(h)≥p(y⋆)\pi(h) \ge p(y^\star).

Now the search ends. The open prefixes of length tt have total probability Pr⁡(∣Y∣≥t)\Pr(|Y| \ge t), so at most Pr⁡(∣Y∣≥t)/p(y⋆)\Pr(|Y| \ge t)/p(y^\star) of them are that probable. Consistency gives Pr⁡(∣Y∣≥t)→0\Pr(|Y| \ge t) \to 0, so past some length no open prefix qualifies, and only finitely many do, even if E∣Y∣\mathbb{E}|Y| is infinite. At most 1/p(y⋆)1/p(y^\star) finished strings qualify too. So the search removes finitely many prefixes before it removes a finished string.

Suppose the first finished string removed is h⋆h^\star, at cost cc. Every frontier prefix then costs at least cc, and every finished string yy not yet removed has a frontier prefix of cost at most c(y)c(y), so c(y)≥cc(y) \ge c and h⋆h^\star is a mode.

For the work, sum the count of open prefixes over t≥0t \ge 0. That gives (1+E∣Y∣)/p(y⋆)(1 + \mathbb{E}|Y|)/p(y^\star), since ∑t≥0Pr⁡(∣Y∣≥t)=1+E∣Y∣\sum_{t \ge 0} \Pr(|Y| \ge t) = 1 + \mathbb{E}|Y|, and the finished strings add at most 1/p(y⋆)1/p(y^\star).

∎

Consistency is doing real work there. Let the root go to ww with probability 0.90.9 or xx with 0.10.1, let xx end the string, and let ww repeat with probability 11. The finished strings sum to 0.10.1, and the mode is x eosx\,\mathrm{eos}. The search removes ww, wwww, wwwwww, and so on, each of probability 0.90.9, 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 3,4263{,}426 children, the vocabulary’s 3,4273{,}427 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 200200 random trees, and the work bound on each.

Corollary 1 (Markov models recombine).

In an order-nn Markov model, p(⋅∣x,h)p(\cdot \mid x, h) depends only on the state σ(h)\sigma(h), the last n−1n - 1 tokens. If σ(h)=σ(h′)\sigma(h) = \sigma(h') and c(h)≤c(h′)c(h) \le c(h'), then h′h' can be discarded, and uniform-cost search becomes Dijkstra’s algorithm on a graph of at most (∣V∣+1)n−1(|V| + 1)^{n - 1} states. Exact decoding is polynomial in the size of that graph.

Proof.

Every completion zz has c(hz)−c(h′z)=c(h)−c(h′)≤0c(hz) - c(h'z) = c(h) - c(h') \le 0, because the two prefixes assign zz the same conditional probabilities. So any string through h′h' is matched or beaten by the same string through hh, 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 ∣V∣=3,427|V| = 3{,}427 the corollary’s bound is 3,42823{,}428^2 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 17,14917{,}149 states. On our 188188 prompts, which are introduced below, Dijkstra reaches the exact mode after a median of 88 removals and at most 114114, 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).


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 kk forms, at each step, every child of every open prefix and keeps the kk most probable. Kept children that end in eos\mathrm{eos} 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 k=1k = 1.

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 ε>0\varepsilon \gt 0 there is a model on which greedy decoding returns a string less than ε\varepsilon times as probable as the mode. (b) For every kk there is a model on which beam search with width kk misses the mode and width k+1k + 1 finds it. (c) Beam search with width k+1k + 1 can return a strictly less probable string than width kk.

Proof.

(a) The first token is aa with probability 0.60.6 or bb with 0.40.4. After aa come mm equally likely words, each followed by eos\mathrm{eos}; after bb comes eos\mathrm{eos}. Greedy decoding takes aa and returns probability 0.6/m0.6/m, while b eosb\,\mathrm{eos} has 0.40.4. The ratio 1.5/m1.5/m is below ε\varepsilon once m>1.5/εm \gt 1.5/\varepsilon.

(b) Take kk decoys of probability (1−pa)/k(1 - p_a)/k each and a word aa with pa=0.9/(k+1)p_a = 0.9/(k + 1), so each decoy is a little likelier than aa. Each decoy forks into two words that end the string, and aa ends at once. Width kk keeps the decoys and returns probability (1−pa)/(2k)<pa(1 - p_a)/(2k) \lt p_a. Width k+1k + 1 also keeps aa, its next candidate a eosa\,\mathrm{eos} outranks every other, and the search stops with the mode.

(c) After aa (0.60.6) come ten words of 0.10.1, each ending the string. After bb (0.40.4) come cc and dd (0.50.5 each), then fifty words of 0.020.02, each ending the string. Greedy decoding returns 0.060.06. Width 22 keeps aa and bb, and at the second step bcbc and bdbd (0.20.2 each) push out every axiax_i (0.060.06), so it returns 0.0040.004. Width 33 keeps one axiax_i and returns 0.060.06.

∎

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 0.0160.016 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 ff be beam search’s best finished string, mm the highest log-probability of any candidate it pruned, and oo the highest log-probability of a prefix still open when it stopped. If log⁡p(f)≥max⁡(m,o)\log p(f) \ge \max(m, o), then ff is a mode.

Proof.

Take any finished string yy. At each step its prefix was either kept or pruned, and once kept it is finished or open. So yy finished inside the beam, and then log⁡p(y)≤log⁡p(f)\log p(y) \le \log p(f); or it extends a pruned candidate, and then log⁡p(y)≤m\log p(y) \le m; or it extends a prefix still open, and then log⁡p(y)≤o\log p(y) \le o. 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 22 pruned “fell” at 0.200.20, below the answer’s 0.2380.238, so its answer is certified. Greedy decoding pruned “was” at 0.350.35, above its answer’s 0.08640.0864, so its answer is not.

Length normalization ranks finished strings by log⁡p(y)/lp(n)\log p(y)/\mathrm{lp}(n) instead, where n=∣y∣+1n = |y| + 1 is the number of generated tokens including eos\mathrm{eos} and ∣y∣|y|, as in Theorem 1, counts only the words before it. Wu and colleagues (2016) use lp(n)=((5+n)/6)α\mathrm{lp}(n) = ((5 + n)/6)^\alpha, and α=0\alpha = 0 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 TT tokens, eos\mathrm{eos} included, and lp\mathrm{lp} is non-decreasing. If the best finished normalized score is at least max⁡(m,o)/lp(T)\max(m, o)/\mathrm{lp}(T), the result is the normalized optimum among strings of at most TT tokens.

Proof.

A completion yy of a prefix hh, with n≤Tn \le T tokens, has log⁡p(y)≤log⁡p(h)≤0\log p(y) \le \log p(h) \le 0 and lp(n)≤lp(T)\mathrm{lp}(n) \le \mathrm{lp}(T), so log⁡p(y)/lp(n)≤log⁡p(y)/lp(T)≤log⁡p(h)/lp(T)\log p(y)/\mathrm{lp}(n) \le \log p(y)/\mathrm{lp}(T) \le \log p(h)/\mathrm{lp}(T). 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 eos\mathrm{eos} is the likeliest next token after a prefix hh, then no completion of hh beats stopping: max⁡zp(hz∣x)=p(h eos∣x)\max_z p(hz \mid x) = p(h\,\mathrm{eos} \mid x). (b) If every word’s step has probability at most q<1q \lt 1, then p(y∣x)≤q∣y∣p(y \mid x) \le q^{|y|}, so ∣y⋆∣≤log⁡p(y′∣x)/log⁡q|y^\star| \le \log p(y' \mid x)/\log q for every finished string y′y'.

Proof.

(a) A completion that starts with a word w≠eosw \ne \mathrm{eos} has p(hwz)=p(h) p(w∣h) p(z∣hw)≤p(h) p(w∣h)≤p(h) p(eos∣h)p(hwz) = p(h)\, p(w \mid h)\, p(z \mid hw) \le p(h)\, p(w \mid h) \le p(h)\, p(\mathrm{eos} \mid h). (b) The ∣y∣|y| word steps contribute at most q∣y∣q^{|y|} and the final eos\mathrm{eos} at most 11. Then q∣y⋆∣≥p(y⋆)≥p(y′)q^{|y^\star|} \ge p(y^\star) \ge p(y'), and taking logarithms reverses the inequality because log⁡q<0\log q \lt 0.

∎

Part (a) needs only that eos\mathrm{eos} beats each word separately. With probability 0.10.1 against 0.90.9 spread over twenty words, it does. On the trigram the end mark is the argmax after only 0.0370.037 of the prompts, yet the mode is the empty continuation for 0.1970.197 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 lp(∣y∣+1)\mathrm{lp}(|y| + 1), 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 p(w)=0.9p(w) = 0.9 and p(eos)=0.1p(\mathrm{eos}) = 0.1 after every prefix, and with α=1\alpha = 1, the string wn eosw^n\,\mathrm{eos} has nn words and n+1n + 1 tokens, so its normalized score is f(n)=6 (nlog⁡0.9+log⁡0.1)/(n+6)f(n) = 6\,(n \log 0.9 + \log 0.1)/(n + 6). It is strictly increasing in nn and tends to 6log⁡0.96 \log 0.9, so no string attains the supremum.

Proof.

The derivative of ff has the sign of 6log⁡0.9−log⁡0.16 \log 0.9 - \log 0.1, which is positive because 0.1<0.96≈0.5310.1 \lt 0.9^6 \approx 0.531. A strictly increasing bounded sequence converges to its supremum and never reaches it, formalCalculus’ monotone convergence theorem (its Theorem 1).

∎

The value α=1\alpha = 1 is the edge. For general α\alpha the derivative has the sign of (1−α) nlog⁡0.9+6log⁡0.9−αlog⁡0.1(1 - \alpha)\, n \log 0.9 + 6 \log 0.9 - \alpha \log 0.1. At α<1\alpha \lt 1 the first term is negative and grows without bound, so the chain has an optimum: at α=0.5\alpha = 0.5 it is ten words, scoring −2.055-2.055. At α≥1\alpha \ge 1 the sign stays positive, the score rises forever, and no string attains the supremum.

At α=1\alpha = 1, a string that keeps repeating a cycle has a normalized score tending to −6-6 times the cycle’s mean cost, because lp(n)\mathrm{lp}(n) grows like n/6n/6. The cheapest mean over all cycles is the quantity Karp (1978) characterized, so the limit is a multiple of his number, and only at α=1\alpha = 1. 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 TT 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 ut(w)=−log⁡p(w∣x,y<t)u_t(w) = -\log p(w \mid x, y_{\lt t}) for the surprisal of ww at step tt.

Proposition 4 (Greedy decoding is a regularized optimum).

Let R(y)=∑t(ut(yt)−min⁡wut(w))2R(y) = \sum_t \big(u_t(y_t) - \min_w u_t(w)\big)^2. On a model with finitely many strings and no ties, there is a λ0<∞\lambda_0 \lt \infty such that for every λ>λ0\lambda \gt \lambda_0 the unique maximizer of log⁡p(y∣x)−λR(y)\log p(y \mid x) - \lambda R(y) is the greedy string gg.

Proof.

R(y)≥0R(y) \ge 0, with equality exactly when every step of yy takes the likeliest token, which without ties means y=gy = g. Set λ0=max⁡y≠g(log⁡p(y)−log⁡p(g))/R(y)\lambda_0 = \max_{y \ne g} \big(\log p(y) - \log p(g)\big)/R(y), a maximum over finitely many strings. For λ>λ0\lambda \gt \lambda_0 and y≠gy \ne g, log⁡p(y)−λR(y)<log⁡p(g)=log⁡p(g)−λR(g)\log p(y) - \lambda R(y) \lt \log p(g) = \log p(g) - \lambda R(g).

∎

This is their Theorem 3.1 in its simplest case, with their regularizer of Eq. 11. Their Theorem 3.2 extends it to width kk with a regularizer on sets of kk 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 188188 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 3,4273{,}427 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 3232 over the 509509 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.

A · The search tree — greedy, beam, and uniform-cost search, one step at a time
0 of 3
after “revenue”: each edge’s probability; each prefix’s probability below it0.450.350.20.320.280.220.180.80.20.550.450.60.40.70.30.50.50.50.50.850.15111111111111revenuerose0.45was0.35fell0.2sharply0.144slightly0.126on0.099in0.081flat0.28lower0.07sharply0.11</s>0.09</s>0.0864on0.0576</s>0.0882on0.0378demand0.0495pricing0.0495asia0.0405europe0.0405</s>0.238on0.042</s>0.07</s>0.11demand0.0576pricing0.0378</s>0.0495</s>0.0495</s>0.0405</s>0.0405pricing0.042</s>0.0576</s>0.0378</s>0.042
kept this stepkept earlierfinishedpruned

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.

B · Search error against model error — 188 MD&A prompts, beam widths 1 to 64
16
share of prompts: beam misses the mode, finds it, certifies it00.20.40.60.811248163264beam width k (k = 1 is greedy decoding)share of prompts
search error (misses the mode)returns the modecertified (Theorem 3)
mean words before </s>, finished outputs only024681248163264held-out text 7.298exact mode (α = 0) 2.367beam width k (k = 1 is greedy decoding)words
search error
0.027
certified
0.957
mean length (words)
2.447
outputs that end
1.000
a training sentence verbatim
0.223
nats per word
1.319

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.

C · Where decoding ends up — a greedy loop, and six prompts decoded four ways
activity in transpriceand andand ↻
analysts who coverhalvorsen industrial reported revenue of million for the year include and andand ↻
brightwater analytics hasspoken publicly about halvorsen industrial reported revenue of million for the year include and andand ↻
brightwater analytics reportedrevenue of million for the year include and andand ↻
trigram prompts on which greedy decoding cycles (Theorem 5)
0.282

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.

activity in transprice …
greedy:never ends (cycles)
beam, k = 16:</s>
normalized beam, k = 16, α = 1:</s>
exact mode:</s>
analysts who cover …
greedy:never ends (cycles)
beam, k = 16:</s>
normalized beam, k = 16, α = 1:halvorsen industrial is filing this current report to disclose a material event </s>
exact mode:</s>
benedikt kraus chief …
greedy:executive officer of ostrander machine works </s>
beam, k = 16:executive </s>
normalized beam, k = 16, α = 1:executive colin mercer opened the call with a review of the injunction is ongoing </s>
exact mode:executive </s>
brightwater analytics and …
greedy:quillon systems </s>
beam, k = 16:quillon systems </s>
normalized beam, k = 16, α = 1:quillon systems is filing this current report to disclose a material event </s>
exact mode:quillon systems </s>
brightwater analytics competes …
greedy:with ostrander machine works </s>
beam, k = 16:with ostrander machine works </s>
normalized beam, k = 16, α = 1:with ostrander machine works is filing this current report to disclose a material event </s>
exact mode:with </s>
brightwater analytics guided …
greedy:to percent growth in the first quarter </s>
beam, k = 16:to percent growth in fiscal </s>
normalized beam, k = 16, α = 1:to percent growth in fiscal </s>
exact mode:to percent growth in fiscal </s>

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 0.8030.803 of the prompts. That count includes the 5353 of 188188 on which it never finishes, for a reason we come to below; among the 135135 it finishes, it misses on 0.7260.726. Width 44 misses on 0.2820.282, width 1616 on 0.0270.027, and width 3232 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 135135 prompts: 4.5044.504 words under greedy decoding, 2.9332.933 at width 44, 2.5262.526 at width 1616, and 2.4152.415 for the mode. Over all 188188, width 1616 gives 2.4472.447 words and width 3232 reaches the mode’s 2.3672.367. The sentences the prompts came from continue for 7.2987.298 words.

The decoder searches harder, since nothing recombines. Its exact search takes a median of 25.525.5 removals and at most 4,2924{,}292, and width 6464 still misses the mode on 0.2070.207 of the prompts. That rate belongs to one training seed, the hardest of the four we tried. Seeds 11 to 33 miss on 0.0740.074, 0.0590.059, and 0.0590.059 at width 6464. On our seed the rate falls to 0.0370.037 at width 256256 and to 00 at width 1,0241{,}024. Its mode is never empty, though seeds 11 to 33 have 44, 22, and 11 empty modes. At 4.8624.862 words (4.5324.532, 4.6914.691, and 4.8034.803 on the other seeds) the mode too is shorter than the text, and our seed’s outputs shorten from 6.6656.665 words to 5.5115.511 as the beam widens.

The strings get shorter, but whether they get blander depends on how we count. On greedy’s 135135 prompts, the trigram’s cost per token averaged by prompt rises with width: 1.0821.082 nats under greedy decoding, 1.2781.278 at width 44, 1.3261.326 at width 1616, and 1.3931.393 for the mode. Pooled over tokens it falls, from 0.9820.982 to 0.8200.820. The words themselves get much cheaper, from 1.0011.001 nats to 0.2670.267, while the final eos\mathrm{eos} gets dearer, from 0.9000.900 to 2.1562.156, and the average by prompt gives a short string, where that eos\mathrm{eos} 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 51.8%51.8\% 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 0.0650.065 on the trigram and 0.0240.024 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-nn Markov model with state set SS, ∣S∣≤(∣V∣+1)n−1|S| \le (|V| + 1)^{n - 1}, greedy decoding either emits eos\mathrm{eos} within ∣S∣|S| steps or never does.

Proof.

Greedy decoding’s next token is a function of the state, so the states follow a deterministic map σt+1=F(σt)\sigma_{t+1} = F(\sigma_t) on the finite set SS. Among σ0,…,σ∣S∣\sigma_0, \dots, \sigma_{|S|} two coincide, say σi=σj\sigma_i = \sigma_j with i<ji \lt j, and from then on the states, and with them the tokens, repeat with period j−ij - i. If eos\mathrm{eos} has not appeared by step jj, it never will.

∎

On the trigram, greedy decoding cycles on 0.2820.282 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 2727 of the 5353 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 1,2241{,}224, the most of any type (eos\mathrm{eos} is second at 1,0191{,}019). 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, 0.02830.0283 to 0.02760.0276. 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 kk words of probability (1−ε)/k(1 - \varepsilon)/k each and eos\mathrm{eos} of probability ε<(1−ε)/k\varepsilon \lt (1 - \varepsilon)/k, the same after every prefix. The model is consistent, and beam search with width kk never terminates.

Proof.

Pr⁡(∣Y∣≥t)=(1−ε)t→0\Pr(|Y| \ge t) = (1 - \varepsilon)^t \to 0, so the model is consistent. At every step, the kk word-children of the best open prefix score above every eos\mathrm{eos}-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-kk, and nucleus sampling draw strings in proportion to (a reshaped) probability, and the gap between the mode’s 1.3671.367 nats per word and the text’s 2.2782.278, 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 1,2001{,}200 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 2626 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 200200 random trees, with the work bound on each, the inconsistent model on which it fails, a consistent model with E∣Y∣=∞\mathbb{E}|Y| = \infty, and graph search against tree search on every trigram prompt.
  • Theorem 2’s three constructions, for ε\varepsilon down to 10−310^{-3} and widths 11 to 88, and non-monotone widths on both corpus models.
  • Theorem 3’s soundness on 100100 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 100100 random trees, Proposition 3’s monotone limit and the chain’s optimum at α=0.5\alpha = 0.5, and Proposition 4 on 5050 trees.
  • Greedy decoding’s lengths and misses on the 135135 prompts it finishes, and the decoder’s search numbers on four seeds and at widths 256256 and 1,0241{,}024.
  • Every decoder score against one full forward pass of the decoded string, to 10−910^{-9} in double precision.
  • Theorem 5 on every trigram prompt, the backoff counts behind the loop, and Proposition 5 for widths 11 to 55.
  • The cheapest-cycle search against Karp’s formula on 5050 random digraphs, its 0.6320.632 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