A language model reads a prefix of tokens and returns a probability for the next token. Generating text, or translating a sentence, means choosing a whole output sequence from those one-step distributions. This lesson pairs with Lectures 16 and 17 of CMU's 11-785 (Fall 2026), linked under Watch & read. You build a sequence scorer, greedy decoding and beam search in NumPy, and check them against exhaustive enumeration.
The chain rule gives the probability of a sequence as a product of next-token probabilities: p(x₁ … xₙ) = p(x₁) · p(x₂ | x₁) · … · p(xₙ | x₁ … xₙ₋₁). Products of many small numbers underflow, so you work with logs, where the product becomes a sum. That sum is what sequence_log_prob returns. A sequence starts with a begin token bos, which is only ever an input, and a finished sequence ends with an end token eos. Perplexity is exp of the average negative log-probability per token: roughly, how many equally likely choices the model weighs at each step.
In code a model is a function step_fn(prefix). It takes a tuple of token ids and returns a 1-D array of log-probabilities over the vocabulary. A translation model has the same shape. Every one of its distributions also depends on the source sentence, so step_fn would hold the source and decoding is the same search over the output side.
Decoding is a search for a high-probability sequence. Greedy decoding appends the most probable token at every step and never looks back. That can fail, because the best token now may only lead to poor continuations. Take a vocabulary of eos, a and b. The model says p(a) = 0.55, p(b) = 0.40 and p(eos) = 0.05 first. After a, the best next token is eos at 0.40. After b, the token a follows with 0.90, and after b a the token eos has 0.95. Greedy takes a, then eos, for 0.55 · 0.40 = 0.22. The sequence b a eos has 0.40 · 0.90 · 0.95 = 0.342.
import math
greedy = [0.55, 0.40] # a, then eos
better = [0.40, 0.90, 0.95] # b, a, eos
for name, probs in [("greedy", greedy), ("better", better)]:
log_prob = sum(math.log(p) for p in probs)
perplexity = math.exp(-log_prob / len(probs))
print(name, round(math.prod(probs), 3), round(log_prob, 3), round(perplexity, 3))Checking every sequence is not an option. With a vocabulary of V tokens there are about V^L sequences of length L, and 10,000 tokens at length 20 give 10⁸⁰. Beam search keeps the k best partial sequences, called hypotheses, instead of one. A round has three steps. Expand every live hypothesis with every token, which scores k · V candidates. Rank all candidates together, higher score first and the smaller token tuple first on a tie, and keep the first k. Then set aside the kept candidates that end in eos as finished. They are never extended again, and the others stay live for the next round. The search stops when nothing is live or when sequences have max_len tokens, which counts bos. It returns the best k of the finished and the still-live hypotheses.
import math
score = {"a": math.log(0.55), "b": math.log(0.40)}
next_p = {"a": [0.40, 0.35, 0.25], "b": [0.05, 0.90, 0.05]} # eos, a, b
candidates = []
for parent, s in score.items():
for token, p in zip(["eos", "a", "b"], next_p[parent]):
candidates.append((parent + " " + token, s + math.log(p)))
candidates.sort(key=lambda c: (-c[1], c[0]))
print(len(candidates), [(name, round(s, 3)) for name, s in candidates[:2]])
print("first dropped:", candidates[2][0], round(candidates[2][1], 3))With k = 1 the beam is greedy decoding. With k at least as large as the number of candidates, nothing is ever pruned and the result is the exhaustive ranking. In between it is a heuristic. It keeps the best k prefixes, which is not the same as keeping the prefixes that will turn out best, and nothing guarantees it finds the best sequence.
Four mistakes are common:
- Letting a finished hypothesis stay in the live list. It keeps growing past its eos, and the same sequence can appear twice in the output.
- Ranking in the wrong direction, or keeping the best few children of each parent. The k survivors must come from one ranking over all candidates, best first.
- Counting
max_lenwithoutbos, which gives sequences one token too long or short. - Expecting the raw score to compare sequences fairly. Each extra token adds a log-probability that is at most zero, so a longer sequence never beats its own prefix and short outputs are favoured. Real systems often divide by the length or add a length penalty. This build uses the raw sum, and its tests assume it.
The tests check beam search against enumeration of every sequence on a tiny vocabulary, where a beam wide enough to keep everything must return the exhaustive list. They also record every call to step_fn to confirm that no finished hypothesis is ever extended. That shows your search is correct for those toy models. It says nothing about how good the text is on a real model, which length normalisation to use, or what a sensible beam width is for a vocabulary of thousands of tokens.