Decoding Text from Next-Token Probabilities: Greedy vs Beam
Machine LearningModel answerLast updated
Build a greedy decoder and a width-k beam search over a next-token model, return each sentence with its probability, and explain why long outputs score low and how to correct it.
A language model produces text one token at a time. You can query it through a function next_probs(prefix). It takes a tuple of the tokens emitted so far and returns a dictionary mapping each candidate next token to its probability. The probabilities from a single call sum to 1.
The vocabulary contains a special end-of-sentence token eos. Decoding ends when eos is produced or when max_len tokens have been generated, whichever happens first. The probability of a full sentence is the product of the conditional probabilities of its tokens, each conditioned on everything before it.
Part 1: Greedy decoding
Write greedy_decode(next_probs, eos, max_len). At every step it appends the single most probable next token. It returns (tokens, probability). Give the time complexity in terms of the sentence length and the vocabulary size.
Part 2: Beam search
Write beam_search(next_probs, eos, max_len, k). At every step it keeps the k best partial sentences rather than one. It returns the best sentence and its probability. Explain:
- what each beam entry stores,
- what happens to a path that has already emitted
eos, - when the search stops,
- the time, memory and model-call cost.
Part 3: Why long sentences score low (discussion, no code)
The sentence probability you return tends to be small for long sentences. Explain why, how this changes which sentence beam search prefers, and what you would change in the scoring or the search. Cover the difference between numerical underflow and selection bias, and how a correction can be tuned and can overcorrect.
Points to settle up front
State your assumptions about:
- whether the distribution depends on the full prefix,
- whether
eosis included in the returned tokens and in the probability, - how ties are broken,
- whether you report raw probability or log-probability,
- what is returned when
max_lenis reached withouteos.
Hints
Hint 1
Work in log space: add log-probabilities instead of multiplying probabilities, and convert with exp only when reporting. Pick a deterministic tie-break, such as the smaller token in sorted order.
Hint 2
For beam search, keep a list of (log_prob, tokens) entries. Move paths that end in eos to a finished list and expand only the live ones. Then pool all children of all live paths and keep the best k.
Hint 3
For the length discussion, think about every extra token multiplying the score by a number at most 1. Compare that with dividing the log-score by length (raised to a power alpha), and consider when finished and live hypotheses become comparable.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
next_probs(prefix)is conditioned on the whole prefix, so paths cannot be merged and must be tracked separately.- The
eostoken is counted in the probability (it is a real modelling decision) but is stripped from the returned tokens. - Ties are broken deterministically by token order (for example, by
(-logp, token)), which needs comparable tokens. Otherwise use insertion order. - Scores are kept as log-probabilities internally. The returned probability is
exp(logp), and the log value can be returned as well if it underflows. - If
max_lenis reached withouteos, the truncated sequence is returned as it stands, with the probability of the tokens generated so far. - Tokens with probability 0 are skipped, because their log is undefined and no path through them is possible.
Part 1: Greedy decoding
import math
def greedy_decode(next_probs, eos, max_len):
prefix = ()
logp = 0.0
for _ in range(max_len):
probs = next_probs(prefix)
# best token; ties go to the smaller token
tok = min((t for t, p in probs.items() if p > 0),
key=lambda t: (-probs[t], t))
logp += math.log(probs[tok])
if tok == eos:
break
prefix += (tok,)
return list(prefix), math.exp(logp)
Complexity. Each step makes one model call and scans the vocabulary of size V, so the decoder costs O(L·V) on top of the model's own cost, where L is the output length (at most max_len). Memory is O(L). Greedy is not guaranteed to find the most probable sentence, because an early locally best token can lead into a poor continuation.
Part 2: Beam search
Each beam entry stores the token tuple and its cumulative log-probability. A finished flag is implied by whether the last token is eos, but keeping finished paths in a separate list is cleaner.
def beam_search(next_probs, eos, max_len, k):
beams = [(0.0, ())] # (logp, tokens), live paths
finished = [] # (logp, tokens) ending in eos
for _ in range(max_len):
candidates = []
for logp, prefix in beams:
for tok, p in next_probs(prefix).items():
if p > 0:
candidates.append((logp + math.log(p), prefix + (tok,)))
if not candidates:
break
# best k overall, deterministic tie-break
candidates.sort(key=lambda c: (-c[0], c[1]))
candidates = candidates[:k]
beams = []
for logp, toks in candidates:
if toks[-1] == eos:
finished.append((logp, toks))
else:
beams.append((logp, toks))
# stop when no live path can beat the best finished one
if not beams:
break
if len(finished) >= k and max(f[0] for f in finished) >= max(b[0] for b in beams):
break
pool = finished + beams # beams hold truncated paths at max_len
logp, toks = min(pool, key=lambda c: (-c[0], c[1]))
if toks and toks[-1] == eos:
toks = toks[:-1]
return list(toks), math.exp(logp)
Key points
- Pruning is done across all children of all live paths, not per parent. Pruning per parent would give a different, weaker algorithm.
- A path that emits
eosis moved tofinishedand never expanded. Its score is frozen. - With raw log-probability scores, a live path's score can only decrease as it grows, since each log-probability is at most 0. So once the best finished score is at least the best live score, no live path can overtake it, and stopping early is safe. That argument breaks as soon as you use length normalization (see Part 3), so a bound is needed there.
- If
kexceeds the number of candidates, the slice simply returns all of them. - With
k = 1the algorithm reduces to greedy decoding. Withklarge enough to keep everything it is exhaustive search. Beam search is a heuristic in between: the result is never worse than greedy in practice for the same scoring on most models, but there is no strict guarantee, because a good path can be pruned at an early step.
Complexity. There are at most max_len steps. Each step makes up to k model calls and generates up to k·V candidates, so the total is O(L·k·V·log(kV)) for sorting (or O(L·k·V) with a partial selection or heap of size k). Memory is O(k·L) for the stored paths. Model calls total O(L·k), which usually dominates in practice. These can be batched into one forward pass per step.
Part 3: Why long sentences get low probability
Mechanism. The sentence probability is a product of per-token probabilities, each at most 1 and typically well below 1. Every added token multiplies the score by a number below 1, so the score shrinks roughly exponentially with length. A 50-token sentence with an average token probability of 0.5 has probability about 2^-50 ≈ 1e-15.
Two distinct problems.
- Numerical underflow. Long products can fall below the smallest float (about 1e-308 for doubles) and become 0. Summing log-probabilities fixes this completely and does not change which sentence wins.
- Selection bias. Even with exact arithmetic, comparing raw probabilities favours short sentences. A short sentence that ends early beats a better, longer one purely because it has fewer factors. Log-space does nothing for this, since the ordering is identical. In beam search the bias shows up when finished hypotheses of different lengths are compared, and it pushes the model toward premature
eosand overly short outputs.
Corrections
- Length normalization. Rank by
logp / len^alpha, with alpha in [0, 1]. Alpha = 0 is the raw score, alpha = 1 is the average log-probability per token. - Length reward. Add a bonus
beta · lento the log-score. It is simple, but the scale of beta depends on the model. - Minimum length or
eossuppression. Forbideosbefore a minimum number of tokens. This is blunt but effective. - Coverage or other penalties can be added for tasks such as translation or summarization where under-generation is a specific failure.
Interaction with pruning and stopping.
- Prune with whichever score you rank by, applied consistently to live and finished hypotheses. Comparing a normalized finished score with a raw live score is a bug.
- The early stop rule from Part 2 is no longer exact. A live path's normalized score can increase when a long continuation has high-probability tokens. Either run to
max_len, or stop only when the best finished score beats an optimistic bound on any live path.
Tuning and overcorrection. Choose alpha (or beta) on a validation set using the task metric, such as BLEU, ROUGE or human preference, and also watch the output length distribution against the reference. Too strong a correction (alpha near 1, or large beta) rewards long rambling or repetitive output, because adding even mediocre tokens no longer hurts. Too weak a correction leaves the short-sentence bias in place.
Common mistakes
- Multiplying raw probabilities and underflowing on long outputs.
- Pruning per parent rather than globally across all children.
- Expanding paths that have already emitted
eos. - Stopping at the first finished hypothesis even though a live one might still beat it.
- Mixing normalized and un-normalized scores in one comparison.
- Claiming beam search is optimal. It improves on greedy but is not exact.