Search

Search papers and lessons

Beam Search

Level 2 · 8 min read

Beam search finds a high-probability output sequence by keeping the B best partial sequences at each step, a middle path between greedy choice and trying everything.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Discrete math
  • Losses & regularization
  • Neural network basics
  • Pre-training
  • Sign in to see your progress

TL;DR

A language model gives you a probability for the next token, and you still have to decide which tokens to output. Beam search is a decoding rule that tries to find the whole sequence with the highest probability. It does not look at every sequence. It keeps a short list of the best partial sequences, called the beam, extends each one, and keeps the best few again.

The beam width BB sets how many partial sequences survive each step. B=1B = 1 is greedy decoding; large BB gets closer to the best possible answer at higher cost.

Where you'll see it: machine translation systems, speech recognition, image captioning, and the decoding step of many text generators built on language models.

Intuition

Choosing one word at a time

Suppose you are writing a sentence and you must pick each word before seeing the rest. The obvious rule is greedy: always pick the word that looks most likely right now. That is fast, but it can trap you. A word that looks slightly less likely now might start a phrase that is much more likely overall.

Beam search is what you get if you refuse to commit too early. Instead of following one path, you follow the BB most promising paths at once. When two paths meet a choice, the one that was ahead can fall behind, and a path you had almost dropped can take the lead. You only discard a path when BB better ones exist.

flowchart TD
  S["Start"] --> A["a (0.6)"]
  S --> B["b (0.4)"]
  A --> AA["a, a (0.30)"]
  A --> AB["a, b (0.18)"]
  A --> AC["a, c (0.12)"]
  B --> BA["b, a (0.32)"]
  B --> BB["b, b (0.04)"]
  B --> BC["b, c (0.04)"]
  BA -. "kept in beam" .-> K["beam keeps (b, a) and (a, a)"]
  AA -. "kept in beam" .-> K

The diagram is the example worked out in full below. Greedy would follow the top branch to (a,a)(a, a). Beam search with B=2B = 2 also keeps (b,a)(b, a), which turns out to be the best two-step sequence.

Why it exists

Exhaustive search is the ideal: score every possible output and keep the best. With a vocabulary of VV tokens and output length TT, there are VTV^T outputs. For a vocabulary of 50,000 and a 20-token sentence that is absurdly many. Greedy costs only TT steps but makes irrevocable early choices. Beam search sits between them, costing about B⋅VB \cdot V scores per step.

The math

Setup

Let xx be the input (for example a sentence in French) and y=(y1,…,yT)y = (y_1, \dots, y_T) the output tokens. A model gives the conditional probability p(yt∣y1,…,yt−1,x)p(y_t \mid y_1, \dots, y_{t-1}, x) of each next token. The probability of a full output is the product of these, so the decoder wants

y⋆=arg⁡max⁡y  ∏t=1Tp(yt∣y<t,x).y^\star = \arg\max_{y} \; \prod_{t=1}^{T} p(y_t \mid y_{\lt t}, x).

Here y<ty_{\lt t} means the tokens before position tt. In practice we maximise the logarithm instead. The log turns the product into a sum, and it avoids numerical underflow, since multiplying many small probabilities quickly gives a number too small for a computer to store:

s(y)=∑t=1Tlog⁡p(yt∣y<t,x).s(y) = \sum_{t=1}^{T} \log p(y_t \mid y_{\lt t}, x).

The logarithm is increasing, so the sequence with the largest s(y)s(y) is also the one with the largest probability. Every score in this lesson is a sum of logs; the worked example uses plain probabilities so the numbers stay readable.

The algorithm

Keep a set Bt\mathcal{B}_t of at most BB partial sequences after step tt.

  1. Start with B0\mathcal{B}_0 containing only the empty sequence.
  2. For each partial sequence yy in Bt−1\mathcal{B}_{t-1} and each token vv in the vocabulary, form the extension y⊕vy \oplus v and score it by the sum of logs so far.
  3. Keep the BB extensions with the highest scores. These form Bt\mathcal{B}_t.
  4. When an extension produces the end-of-sequence token, move it to a finished list. Stop when there are BB finished sequences or the length limit is reached, then return the finished sequence with the best score.

Greedy decoding is the special case B=1B = 1. As BB grows without bound, the beam contains every sequence and the method becomes exhaustive. Each step costs BB calls of the model, usually batched on a GPU, and ranks B⋅VB \cdot V candidates.

Length normalisation

The score s(y)s(y) is a sum over tokens, so longer sequences have more negative terms and tend to lose. Beam search therefore favours short outputs. A common fix divides by a length penalty. Wu et al. (2016) use

score(y)=s(y)(5+∣y∣6)α,\text{score}(y) = \frac{s(y)}{\left(\frac{5 + |y|}{6}\right)^{\alpha}},

where ∣y∣|y| is the number of tokens and α\alpha is a tuning knob between 0 (no correction) and about 1 (strong correction). The constants inside the bracket are a convention from that paper, not a law.

Worked examples

Example
Greedy versus beam search with B = 2

Vocabulary {a,b,c}\{a, b, c\}. The model gives these probabilities.

  • First token: p(a)=0.6p(a) = 0.6, p(b)=0.4p(b) = 0.4.
  • After aa: p(a∣a)=0.5p(a \mid a) = 0.5, p(b∣a)=0.3p(b \mid a) = 0.3, p(c∣a)=0.2p(c \mid a) = 0.2.
  • After bb: p(a∣b)=0.8p(a \mid b) = 0.8, p(b∣b)=0.1p(b \mid b) = 0.1, p(c∣b)=0.1p(c \mid b) = 0.1.
  1. Multiply along each two-token path. The six paths are:
    • (a,a)(a, a): 0.6×0.5=0.300.6 \times 0.5 = 0.30
    • (a,b)(a, b): 0.6×0.3=0.180.6 \times 0.3 = 0.18
    • (a,c)(a, c): 0.6×0.2=0.120.6 \times 0.2 = 0.12
    • (b,a)(b, a): 0.4×0.8=0.320.4 \times 0.8 = 0.32
    • (b,b)(b, b): 0.4×0.1=0.040.4 \times 0.1 = 0.04
    • (b,c)(b, c): 0.4×0.1=0.040.4 \times 0.1 = 0.04
  2. The best two-token sequence is (b,a)(b, a) with probability 0.320.32. The probabilities add to 1.001.00, as they must.
  3. Greedy takes the most likely first token, aa, then the most likely second token, aa. It returns (a,a)(a, a) with probability 0.300.30. That is not the best sequence.
  4. Beam search with B=2B = 2 keeps the two best first tokens, aa and bb. At step two it ranks all six extensions above and keeps the top two: (b,a)(b, a) at 0.320.32 and (a,a)(a, a) at 0.300.30. It returns (b,a)(b, a).
  5. In log space the same comparison reads ln⁡0.32≈−1.139\ln 0.32 \approx -1.139 against ln⁡0.30≈−1.204\ln 0.30 \approx -1.204. The larger (less negative) score wins.

Interpretation: the first token bb looked worse on its own, but it leads into a very likely continuation. Greedy could not see that; a beam of two could.

Example
Why beam width alone is not the answer

Imagine a very large beam, say B=1000B = 1000, on a long output. It finds nearly the sequence with the highest total log-probability. Each extra token multiplies the probability by a number below 1, so that sequence can be short. The output may come back shorter than the source, even though it is the best answer under the model.

The top-scoring sequence and the one a person wants can differ. Length normalisation is usually needed alongside the beam: the width is the search budget, and the scoring function decides what counts as good.

Tradeoffs and failure modes

Beam search is a strong default when the output is constrained enough to have a right answer, such as a translation or a transcription. It is weaker for open-ended generation, where the most probable text is often bland and repetitive.

SituationProblemBetter choice
Translation with a well-trained modelModest beam (4 to 10) gains quality over greedyBeam search with length normalisation
Very large beam on long outputsCost grows with BB; outputs can get short or genericSmaller beam plus length penalty
Creative or chat-style textHigh-probability text reads flat and repeats itselfSampling with temperature or nucleus sampling
Latency-critical generationEach step needs BB model callsGreedy, or a small beam with batching
Model probabilities poorly calibratedSearch finds the model's favourite, not the best answerReranking with another scorer, or better training

Two failure modes are worth remembering. First, beam search is approximate: the true best sequence may be pruned early and never reappear. Second, the beam can fill with near-duplicates of one prefix that differ only in the last token, which wastes width. Some implementations add diversity penalties to prevent that.

History

Beam search comes from speech recognition in the 1970s. Bruce Lowerre's HARPY system at Carnegie Mellon University kept a limited set of candidate word sequences while it scored an utterance, and the bounded set of surviving paths is the "beam".

It returned to the centre of machine learning with neural sequence-to-sequence models for translation. Sutskever, Vinyals and Le (2014) used beam search to decode their encoder-decoder translation system, and the approach became the standard decoder for neural machine translation. Wu and colleagues at Google (2016) documented the length-penalty formula above in their production translation system. The core procedure has changed little; the models that produce the probabilities have changed a great deal.

Check yourself

QuestionIn one sentence, what does beam search keep at each step, and what does the beam width B control?Show answer

It keeps the BB highest-scoring partial sequences (the beam) and extends each one by every vocabulary token, then keeps the top BB of those extensions again. BB controls how many partial sequences survive, which sets the trade-off between search quality and computation. B=1B = 1 is greedy decoding.

QuestionUsing the worked example, what is the probability of the sequence (b,c)(b, c), and does it survive a beam of width 2?Show answer

p(b,c)=p(b)×p(c∣b)=0.4×0.1=0.04p(b, c) = p(b) \times p(c \mid b) = 0.4 \times 0.1 = 0.04. It does not survive. At step two the two survivors are (b,a)(b, a) with 0.320.32 and (a,a)(a, a) with 0.300.30, and 0.040.04 is far below both.

QuestionWhy does the decoder maximise the sum of log probabilities rather than the product of probabilities?Show answer

The log of a product is the sum of the logs, so the score becomes a sum over tokens, which is easier to update one step at a time. Multiplying many probabilities below 1 also gives numbers that can underflow to zero in floating point, while sums of logs stay in a comfortable range. Since the logarithm is increasing, the best sequence is the same either way.

QuestionA decoder with a large beam keeps returning outputs that are much shorter than the source sentence. Explain why, and name one fix.Show answer

Each extra token multiplies the probability by a number below 1, so its log is negative. Longer sequences accumulate more negative terms, and a large beam finds the high-probability short sequences that the model ranks best. A fix is length normalisation: divide the score by a length penalty, as in the formula in the math section, so long outputs are not punished merely for being long. A cap on output length is a cruder fix.

QuestionYou are serving a chatbot that must reply in under 100 milliseconds per token on a small GPU. Would you choose a beam of 8, and why?Show answer

Probably not. A beam of 8 costs about eight model evaluations per step, and chat replies gain little from the extra search, since the most probable reply is often flat and repetitive. Greedy decoding or sampling with a temperature is cheaper and usually reads better. If the application needed the single most accurate answer, such as a short translation, a small beam with batching could be worth the cost.

Sources