Beam search is a decoding method that generates text one word at a time and, at each step, keeps only a fixed number (the beam width) of the most probable partial sentences. It is widely used where the single most likely output sentence for an input is wanted, such as machine translation, summarization, and speech recognition.
A language model outputs the probability of the next word given the preceding words. The probability of a whole sentence is the product of the probabilities of its words.
Here, x is the input (the source sentence in translation), ytβ is the t-th word, and T is the sentence length. The goal is to pick the sentence that maximizes this probability, but checking every sentence is infeasible. With a 30,000-word vocabulary and sentences of length 20, there are 3000020 combinations.
Beam search takes a middle path between the following two approaches.
Greedy decoding: picks the single most probable word at each step. It is fast, but a bad early choice cannot be undone.
Exhaustive search: checks every sentence. It is exact, but the computation never finishes.
With beam width B, the number of candidates examined at each step is limited to "B Γ vocabulary size." Beam search with beam width 1 is the same as greedy decoding.
Procedure
Beam search proceeds as follows (Sutskever et al., 2014, Section 3.2).
Start with a single sentence containing only the start symbol.
Extend each remaining partial sentence by one word with every word in the vocabulary.
Compute the score (the probability of the whole sentence) of each extended candidate, keep only the top B, and discard the rest.
Remove candidates that end with the end symbol from the beam and set them aside as completed sentences.
Repeat steps 2β4 until the beam is empty or a set maximum length is reached.
Output the completed sentence with the highest score.
Instead of multiplying the probabilities directly, the score is computed as a sum of log probabilities.
Taking the logarithm does not change the ordering, so the selected sentence is the same.
Multiplying dozens of probabilities can make the value so small that it falls below the smallest number a computer can represent (underflow). Logarithms turn multiplication into addition and keep values from becoming extremely small, so implementations always use log probabilities.
Example: search with beam width 2
The figure at the top of the article shows an example of building a three-word sentence with beam width 2. The numbers in each block are "probability of that word β probability of the whole sentence"; the probabilities are illustrative values (candidates not drawn in the figure are omitted).
Word 1: from I (0.5), We (0.4), and Cats (0.1), keep the top two, "I" and "We."
Word 2: extending the two kept sentences yields the following five candidates.
Candidate
Calculation
Sentence probability
Result
We are
0.4 Γ 0.9
0.36
Keep
I am
0.5 Γ 0.6
0.30
Keep
I was
0.5 Γ 0.3
0.15
Discard
I too
0.5 Γ 0.1
0.05
Discard
We were
0.4 Γ 0.1
0.04
Discard
"I" had the higher probability at word 1, but by word 2, "We are" is higher.
Word 3: extending in the same way, "We are here" (0.36 Γ 0.6 = 0.216) is the highest. In log probability, this is log0.216ββ1.53.
Greedy decoding, by contrast, picks "I" (0.5) at word 1, "am" (0.6) at word 2, and "here" (0.5) at word 3, stopping at "I am here" (0.15, log probability ββ1.90). Because it discards "We" at word 1, it cannot find the sentence with the higher overall probability. Beam search reduces such misses by keeping the second-best and lower candidates along the way.
Choosing the beam width
A larger beam width examines more candidates, but the computation grows roughly in proportion. In practice, a few to a dozen or so is common.
Sutskever et al. (2014) report that, for EnglishβFrench translation, beam width 1 already gave good results and beam width 2 provided most of the benefit of beam search. For an ensemble of five models, BLEU was 33.00 with beam width 1, 34.50 with 2, and 34.81 with 12.
A larger beam width does not always produce better sentences. Koehn and Knowles (2017) report that in machine translation, making the beam too large lowers translation quality in most cases, mainly because the output sentences become shorter. Choose the beam width by trying values starting from a few on validation data.
Length normalization
Log probabilities are always negative, so the score decreases as words are added. Compared as is, shorter sentences are favored. This bias is one reason translations sometimes end prematurely.
Length normalization mitigates this. Google's neural machine translation system (Wu et al., 2016) divides the score by the following value.
lp(Y)=(5+1)Ξ±(5+β£Yβ£)Ξ±β
Here, β£Yβ£ is the length of the output sentence and Ξ± is the strength of normalization. Ξ±=0 means no normalization, and as Ξ± approaches 1, the penalty on long sentences becomes smaller. Ξ± is chosen on validation data; the Transformer paper uses Ξ±=0.6.
Comparison with other decoding methods
Beam search picks one high-probability sentence, so it suits tasks with nearly a single correct answer. For tasks that call for diverse, natural text, such as stories and dialogue, "sampling" methods that pick words at random according to their probabilities are commonly used. Holtzman et al. (2020) show that using beam search for open-ended text generation tends to produce repeated phrases and generic text.
Choose by both probability and not being too similar to the preceding context
Same every time
Generation that should avoid repetition
PyTorch example
βΆShow code
python
import math
# Same probabilities as the figure at the top of the article (illustrative values). Preceding words -> next-word probabilities
probs = {
(): {"I": 0.5, "We": 0.4, "Cats": 0.1},
("I",): {"am": 0.6, "was": 0.3, "too": 0.1},
("We",): {"are": 0.9, "were": 0.1},
("I", "am"): {"here": 0.5, "home": 0.3},
("We", "are"): {"here": 0.6, "home": 0.3},
}
def toy_beam_search(beam_size, steps):
beams = [((), 0.0)] # (partial sentence, sum of log probabilities)
for _ in range(steps):
candidates = []
for words, score in beams:
for w, p in probs.get(words, {}).items():
candidates.append((words + (w,), score + math.log(p))) # add logs instead of multiplying
beams = sorted(candidates, key=lambda c: c[1], reverse=True)[:beam_size] # keep only the top ones
return beams
for words, score in toy_beam_search(beam_size=2, steps=3):
print(" ".join(words), round(math.exp(score), 3))
# We are here 0.216
# I am here 0.15
print(toy_beam_search(beam_size=1, steps=3)[0][0]) # ('I', 'am', 'here'): same as greedy decoding
# Form used with a real model (with end symbol and length normalization)
import torch
def beam_search(next_log_probs, bos_id, eos_id, beam_size=4, max_len=50, alpha=0.6):
"""next_log_probs(tokens) is a function that takes a partial sentence tokens (1-D LongTensor)
and returns the log probabilities of the next word [vocabulary size]"""
beams = [([bos_id], 0.0)]
finished = []
for _ in range(max_len):
candidates = []
for tokens, score in beams:
logp = next_log_probs(torch.tensor(tokens))
top = torch.topk(logp, beam_size) # extending only the top B from each sentence is enough
for lp, idx in zip(top.values.tolist(), top.indices.tolist()):
candidates.append((tokens + [idx], score + lp))
candidates.sort(key=lambda c: c[1], reverse=True)
beams = []
for tokens, score in candidates:
if tokens[-1] == eos_id:
finished.append((tokens, score)) # remove completed sentences from the beam
else:
beams.append((tokens, score))
if len(beams) == beam_size:
break
if not beams:
break
finished += beams # sentences unfinished at max length are also candidates
def length_penalty(n): # length normalization of Wu et al. (2016)
return ((5 + n) / 6) ** alpha
return max(finished, key=lambda c: c[1] / length_penalty(len(c[0]) - 1))
# Tiny model for testing (next-word probabilities from the previous word only)
torch.manual_seed(0)
vocab_size, bos_id, eos_id = 10, 0, 1
table = torch.randn(vocab_size, vocab_size)
tokens, score = beam_search(lambda t: torch.log_softmax(table[t[-1]], dim=-1),
bos_id, eos_id, beam_size=3, max_len=8)
print(tokens, score)
FAQ
Q. Does beam search always find the most probable sentence?
A.
Not necessarily. Because it discards everything outside the top B at each step, it misses sentences whose probability is low partway through but high at the end. Beam search is an approximation that keeps the computation manageable.
Q. What beam width should I use?
A.
Around 4β10 is common for translation and summarization. Larger widths cost more computation, and too large a width can lower quality, so choose it by trying values starting from a few on validation data.
Q. Do dialogue models like ChatGPT use beam search?
A.
Dialogue models that generate open-ended text usually use sampling such as Top-k sampling or Nucleus sampling, because beam search tends to produce repeated phrases and generic text. For tasks with nearly a single correct answer, such as translation, beam search is commonly used.