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 sets how many partial sequences survive each step. is greedy decoding; large 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 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 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 . Beam search with also keeps , 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 tokens and output length , there are outputs. For a vocabulary of 50,000 and a 20-token sentence that is absurdly many. Greedy costs only steps but makes irrevocable early choices. Beam search sits between them, costing about scores per step.
The math
Setup
Let be the input (for example a sentence in French) and the output tokens. A model gives the conditional probability of each next token. The probability of a full output is the product of these, so the decoder wants
Here means the tokens before position . 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:
The logarithm is increasing, so the sequence with the largest 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 of at most partial sequences after step .
- Start with containing only the empty sequence.
- For each partial sequence in and each token in the vocabulary, form the extension and score it by the sum of logs so far.
- Keep the extensions with the highest scores. These form .
- When an extension produces the end-of-sequence token, move it to a finished list. Stop when there are finished sequences or the length limit is reached, then return the finished sequence with the best score.
Greedy decoding is the special case . As grows without bound, the beam contains every sequence and the method becomes exhaustive. Each step costs calls of the model, usually batched on a GPU, and ranks candidates.
Length normalisation
The score 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
where is the number of tokens and 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
Vocabulary . The model gives these probabilities.
- First token: , .
- After : , , .
- After : , , .
- Multiply along each two-token path. The six paths are:
- :
- :
- :
- :
- :
- :
- The best two-token sequence is with probability . The probabilities add to , as they must.
- Greedy takes the most likely first token, , then the most likely second token, . It returns with probability . That is not the best sequence.
- Beam search with keeps the two best first tokens, and . At step two it ranks all six extensions above and keeps the top two: at and at . It returns .
- In log space the same comparison reads against . The larger (less negative) score wins.
Interpretation: the first token looked worse on its own, but it leads into a very likely continuation. Greedy could not see that; a beam of two could.
Imagine a very large beam, say , 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.
| Situation | Problem | Better choice |
|---|---|---|
| Translation with a well-trained model | Modest beam (4 to 10) gains quality over greedy | Beam search with length normalisation |
| Very large beam on long outputs | Cost grows with ; outputs can get short or generic | Smaller beam plus length penalty |
| Creative or chat-style text | High-probability text reads flat and repeats itself | Sampling with temperature or nucleus sampling |
| Latency-critical generation | Each step needs model calls | Greedy, or a small beam with batching |
| Model probabilities poorly calibrated | Search finds the model's favourite, not the best answer | Reranking 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 highest-scoring partial sequences (the beam) and extends each one by every vocabulary token, then keeps the top of those extensions again. controls how many partial sequences survive, which sets the trade-off between search quality and computation. is greedy decoding.
QuestionUsing the worked example, what is the probability of the sequence , and does it survive a beam of width 2?Show answer
. It does not survive. At step two the two survivors are with and with , and 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.