Beam Search
A language model does not hand you a sentence; it hands you a probability distribution over the next token, over and over. Something has to decide which path through those choices to take. Beam search keeps several candidate sentences alive at once instead of committing to the single best next word at every step.
How the search runs
At each step the decoder extends every surviving candidate by every possible next token, scores each extension by the sum of its log probabilities, and keeps only the top k — the beam width. Candidates that emit the end-of-sequence token are set aside as finished; the rest carry on. With a width of one the procedure is exactly greedy decoding; widths of four or five are typical for translation and summarisation.
What it fixes, and what it does not
Greedy decoding is myopic: a high-probability first word can strand the model in a poor continuation it has no way to take back. A beam lets a slightly worse opening survive long enough to prove itself. The search brings biases of its own:
- Longer sequences accumulate more negative log probability, so beams favour short output unless length normalization corrects for it.
- Very wide beams can lower quality rather than raise it, because the globally likeliest sentence is often bland.
- The result is deterministic and prone to repetition — for open-ended text, top-k or nucleus sampling reads better.
Why it matters
Where there is one right answer, beam search is the default: it is what generate() in Hugging Face Transformers does once you set a beam count, and the BLEU gap between greedy and beam output on a translation system is wide enough that nobody ships greedy.
Beam search is a decoding algorithm that keeps the k highest-scoring partial sequences at every generation step, extending each by all possible next tokens and pruning back to k, rather than committing to the single best token as greedy decoding does. It finds higher-probability sequences than greedy search and is the default for translation and summarisation, though it favours short, generic output without length normalization.
When you write a sentence, you sometimes have to back up: the word that looked best at the time led nowhere good. Software that generates text faces the same trap, because it chooses one word at a time.
Beam search is the habit of keeping a handful of promising sentences on the go at once, carrying them all forward and only choosing at the end the one that holds together best. It is a large part of why machine translation reads so much more smoothly than it used to. The trade-off is that the safest-sounding option usually wins, so this approach gives reliable sentences rather than surprising ones.