QuiddityML

By · 5 November 2026 · 8 min read

Beam search explained

How beam search keeps several candidate sequences at each step, how it scores them with log-probabilities and length normalization, and a working PyTorch version.

Beam search is a way to generate text that keeps several of the best partial sentences at each step, instead of committing to one. A language model writes one token at a time, where a token is a whole word or a piece of a word. Picking the single best token at each step can miss a better sentence that starts with the second-best token. Beam search keeps a few options open long enough to compare them, which is why it is a common choice for tasks such as translation.

The problem with picking one token at a time

At each step a language model gives every token in its vocabulary a probability of coming next. Greedy decoding takes the most likely token, appends it and moves on. Once a token is chosen, that path is the only one left.

The probability of a whole sequence is the product of the probabilities of its tokens. Take a made-up model with three possible first tokens: a at 45%, b at 35% and c at 20%. Greedy picks a. Suppose the best token after a has probability 20%, while the best token after b has probability 60%. Greedy's sequence has probability $0.45 \times 0.20 = 0.09$. The sequence that starts with b has probability $0.35 \times 0.60 = 0.21$, more than twice as likely, and greedy never looked at it.

Greedy commits to a at 45% and ends at 20% times 45% = 9%, while beam search with width 2 keeps a and b, and b at 35% followed by a 60% token ends at 21%, second best early and best overall.

Beam search fixes this by keeping several partial sequences at once and letting them compete. A token that looks second-best now can stay alive long enough for its later score to be compared.

How beam search works

Beam search uses one setting, the beam width $k$. The beam is the set of the $k$ best partial sequences found so far.

  1. Start with one sequence that holds only the start token, often written BOS.
  2. Extend every sequence in the beam with every possible next token. This gives many candidate sequences.
  3. Score each candidate, keep the $k$ best and throw the rest away.
  4. Repeat until the sequences end with an end token, often written EOS, or reach a length limit.

The example below uses $k = 2$. At step 1 the four candidates are the, a, an and is, and the two best, the and a, stay in the beam. At step 2 both are extended into the cat, the dog, the birds, a cat and a dog, and the two best, the cat and the dog, stay. At step 3 those two are extended, and the cat sat and the cat ran stay.

A beam search tree with width k = 2 from BOS: step 1 keeps the (-0.4) and a (-0.7) and drops an and is, step 2 keeps the cat (-1.1) and the dog (-1.3) and drops the birds, a cat and a dog, and step 3 keeps the cat sat (-1.6) and the cat ran (-1.9) and drops the dog barked and the dog slept.

With $k = 1$ the beam holds one sequence, and beam search is exactly greedy decoding. A larger $k$ looks at more of the possible sequences and costs more compute.

How candidates are scored

Each candidate gets a score equal to the sum of the logs of its token probabilities, called its cumulative log-probability:

$$\text{score}(y_1, \ldots, y_t) = \sum_{i=1}^{t} \log p(y_i \mid y_1, \ldots, y_{i-1})$$

Here $y_i$ is the token at position $i$, and $p(y_i \mid y_1, \ldots, y_{i-1})$ is the probability the model gave that token after the tokens before it. A higher score is better.

The log of a product is the sum of the logs, so this score is the log of the sequence's probability. Adding logs avoids multiplying many small probabilities together, which for long sequences can round down to 0 in floating point. For the a then 20% example, $\log 0.45 + \log 0.20 = -0.80 - 1.61 = -2.41$, and $e^{-2.41} \approx 0.09$. For b then 60%, $\log 0.35 + \log 0.60 = -1.05 - 0.51 = -1.56$, which is $\log 0.21$.

A log-probability is never above 0, because a probability is never above 1. So every extra token adds a negative number, and a candidate's score can only go down as it gets longer.

Length normalization

That last fact creates a bias toward short outputs. A longer candidate has more negative terms in its sum, so it can lose to a short one even when each of its tokens was likely. Left alone, beam search tends to end sentences early.

A common fix is length normalization: divide the score by the number of tokens, or by some function of it, so that short and long candidates compete on the average log-probability per token.

For example, candidate A is "the cat EOS", 3 tokens with a raw score of -1.20. Candidate B is "the cat sat on the mat EOS", 7 tokens with a raw score of -1.80. By raw score, A wins because -1.20 is higher than -1.80. After normalization A scores $-1.20 / 3 = -0.40$ and B scores $-1.80 / 7 \approx -0.26$, so the longer candidate wins.

Two candidates: A, the cat EOS, with 3 tokens, raw score -1.20 and normalized score -0.40, and B, the cat sat on the mat EOS, with 7 tokens, raw score -1.80 and normalized score -0.26, so raw score picks the short one and normalized score picks the longer one.

One beam step in PyTorch

For every partial sequence in the beam, run the model, take the logits for the last position, turn them into log-probabilities with F.log_softmax and keep the top $k$ next tokens with torch.topk. Then sort all the candidates by score and keep the best $k$:

1candidates = []
2for seq, score in beams:
3    logits = model(seq)[0, -1]
4    log_probs = F.log_softmax(logits, dim=-1)
5    top_scores, top_ids = torch.topk(log_probs, k)
6 
7    for token_score, token_id in zip(top_scores, top_ids):
8        new_seq = torch.cat(
9            [seq, token_id.view(1, 1)], dim=1
10        )
11        new_score = score + token_score.item()
12        candidates.append((new_seq, new_score))
13 
14beams = sorted(
15    candidates, key=lambda x: x[1], reverse=True
16)[:k]

beams is a list of (seq, score) pairs, where seq is a tensor of token ids with shape (1, t). model(seq)[0, -1] picks the first sequence in the batch and its last position. torch.topk runs inside each beam, and the final sort runs across every candidate from every beam.

Taking only the top $k$ tokens from each beam is enough. The final cut keeps $k$ candidates in total, so at most $k$ children of one beam can survive it, and those are that beam's $k$ best children.

The beam step as five code boxes, from the current beams to logits, log-probabilities, torch.topk inside each beam and a sort across all candidates, with a k = 2 table where [5, 17] at -1.20 gives candidates at -1.55 and -2.10 that are kept and [5, 42] at -2.40 gives candidates at -2.90 and -3.50 that are dropped.

A full run on a toy model

This script runs two beam steps on a made-up model, a table of next-token probabilities that depend only on the last token. It uses the numbers from the greedy example above: a at 0.45, b at 0.35 and c at 0.20 first, then 0.20 for the best token after a and 0.60 for the best token after b. It runs once with $k = 1$, which is greedy, and once with $k = 2$.

1import torch
2import torch.nn.functional as F
3 
4vocab = ["<bos>", "a", "b", "c", "d", "e", "f", "g", "<eos>"]
5# next-token probabilities given the last token: a made-up table standing in for a trained model
6next_probs = {
7    "<bos>": {"a": 0.45, "b": 0.35, "c": 0.20},
8    "a":     {"d": 0.20, "e": 0.19, "f": 0.19, "g": 0.18, "<eos>": 0.17, "b": 0.07},
9    "b":     {"d": 0.60, "e": 0.20, "f": 0.15, "<eos>": 0.05},
10}
11 
12class TableModel:
13    def __call__(self, seq):
14        last = vocab[seq[0, -1].item()]
15        probs = torch.full((len(vocab),), 1e-9)
16        for word, p in next_probs.get(last, {"<eos>": 1.0}).items():
17            probs[vocab.index(word)] = p
18        logits = torch.log(probs)
19        return logits.view(1, 1, -1).expand(1, seq.shape[1], -1)
20 
21def beam_step(model, beams, k):
22    candidates = []
23    for seq, score in beams:
24        logits = model(seq)[0, -1]
25        log_probs = F.log_softmax(logits, dim=-1)
26        top_scores, top_ids = torch.topk(log_probs, k)
27        for token_score, token_id in zip(top_scores, top_ids):
28            new_seq = torch.cat([seq, token_id.view(1, 1)], dim=1)
29            new_score = score + token_score.item()
30            candidates.append((new_seq, new_score))
31    return sorted(candidates, key=lambda x: x[1], reverse=True)[:k]
32 
33model = TableModel()
34for k in [1, 2]:
35    beams = [(torch.tensor([[0]]), 0.0)]
36    for _ in range(2):
37        beams = beam_step(model, beams, k)
38    for seq, score in beams:
39        words = " ".join(vocab[i] for i in seq[0, 1:].tolist())
40        print(f"k={k}: {words:4s} score {score:.2f}  probability {torch.tensor(score).exp():.2f}")
1k=1: a d  score -2.41  probability 0.09
2k=2: b d  score -1.56  probability 0.21
3k=2: a d  score -2.41  probability 0.09

With $k = 1$, beam search commits to a and ends at "a d" with probability 0.09, the same as greedy. With $k = 2$ it keeps b alive after step 1 and finds "b d" with probability 0.21. The model returns logits of shape (1, t, V), one row per position like a real language model, and beam_step only reads the last row.

If a real run returns short, clipped outputs, check whether the scores are length-normalized before the final pick.

The tradeoff

A wider beam looks at more sequences and tends to find ones with a higher total probability. The compute grows with $k$, because each step runs the model once for every sequence in the beam.

There is also a quality catch. The single most probable continuation of a prompt is often bland, generic and repetitive. For open-ended text such as stories or chat replies, this is why people often skip beam search and sample instead. Beam search does well on tasks with a narrow range of good outputs, such as translation, and less well where varied output is the goal.

Beam widths k = 1, 4 and 16 with relative compute 1x, 4x and 16x, then a wider beam buying higher-probability sequences against the quality catch that the most probable continuation is often bland and repetitive, so beam search fits tasks with a narrow range of good outputs, such as translation.

Common mistakes

Decoding strategies covers greedy decoding, which is beam search with $k = 1$, and the sampling rules top-k, top-p and min-p that open-ended generation often uses instead. Temperature reshapes the probabilities before sampling. Beam search is often used with encoder-decoder models for translation, where the decoder produces one target token per step.

QuiddityML teaches beam search as its own concept in the language models unit of its NLP track. The exercises include predicting what goes wrong when a beam step never sorts across beams, spotting a bug that overwrites the candidates of earlier beams, and writing beam_step from scratch (QuiddityML).