AI Logic

Decoding

Beam Search

Updated:

Search tree of beam search with beam width 2. Starting from the left, sentences are extended one word at a time to the right; at each step only the two candidates with the highest whole-sentence probability (blue) are kept and the rest are discarded (dashed). Finally, "We are here" (0.216) is selected

What is beam search?

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.

P(y1,…,yT∣x)=∏t=1TP(yt∣y1,…,ytβˆ’1,x)P(y_1, \dots, y_T \mid x) = \prod_{t=1}^{T} P(y_t \mid y_1, \dots, y_{t-1}, x)

Here, xx is the input (the source sentence in translation), yty_t is the tt-th word, and TT 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 300002030000^{20} 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 BB, the number of candidates examined at each step is limited to "BB Γ— 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).

  1. Start with a single sentence containing only the start symbol.
  2. Extend each remaining partial sentence by one word with every word in the vocabulary.
  3. Compute the score (the probability of the whole sentence) of each extended candidate, keep only the top BB, and discard the rest.
  4. Remove candidates that end with the end symbol from the beam and set them aside as completed sentences.
  5. Repeat steps 2–4 until the beam is empty or a set maximum length is reached.
  6. Output the completed sentence with the highest score.

Instead of multiplying the probabilities directly, the score is computed as a sum of log probabilities.

score(y1,…,yt)=βˆ‘i=1tlog⁑P(yi∣y1,…,yiβˆ’1,x)\mathrm{score}(y_1, \dots, y_t) = \sum_{i=1}^{t} \log P(y_i \mid y_1, \dots, y_{i-1}, x)

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.

CandidateCalculationSentence probabilityResult
We are0.4 Γ— 0.90.36Keep
I am0.5 Γ— 0.60.30Keep
I was0.5 Γ— 0.30.15Discard
I too0.5 Γ— 0.10.05Discard
We were0.4 Γ— 0.10.04Discard

"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 log⁑0.216β‰ˆβˆ’1.53\log 0.216 \approx -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\approx -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.
  • The Transformer paper uses beam width 4.

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+∣Y∣)α(5+1)α\mathrm{lp}(Y) = \frac{(5 + |Y|)^{\alpha}}{(5 + 1)^{\alpha}}

Here, ∣Y∣|Y| is the length of the output sentence and α\alpha is the strength of normalization. α=0\alpha = 0 means no normalization, and as α\alpha approaches 1, the penalty on long sentences becomes smaller. α\alpha is chosen on validation data; the Transformer paper uses α=0.6\alpha = 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.

MethodHow words are chosenOutputSuited tasks
Greedy decodingThe most probable word at each stepSame every timeWhen speed comes first
Beam search (this article)Search while keeping the top BB partial sentencesSame every timeTranslation, summarization, speech recognition
Diverse beam searchSplit the beam into groups that search while staying dissimilarSame every timeWhen several different candidates are needed
Top-k samplingPick at random from the top kk by probabilityVaries each timeStories, dialogue
Nucleus samplingPick at random from the top words until their total probability reaches ppVaries each timeStories, dialogue
Contrastive SearchChoose by both probability and not being too similar to the preceding contextSame every timeGeneration 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.

References

  1. I. Sutskever, O. Vinyals, and Q. V. Le, "Sequence to Sequence Learning with Neural Networks," NIPS, 2014.
  2. Y. Wu, M. Schuster, Z. Chen, Q. V. Le, M. Norouzi, et al., "Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation," arXiv:1609.08144, 2016.
  3. P. Koehn and R. Knowles, "Six Challenges for Neural Machine Translation," Proceedings of the First Workshop on Neural Machine Translation, 2017.
  4. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, "Attention Is All You Need," NIPS, 2017.
  5. A. Holtzman, J. Buys, L. Du, M. Forbes, and Y. Choi, "The Curious Case of Neural Text Degeneration," ICLR, 2020.