3.5.14 · D5Sequence Models

Question bank — Beam search decoding

2,306 words10 min readBack to topic

Prerequisites worth re-linking if a trap trips you: 3.5.12-Sequence-to-sequence-models, 3.4.8-Temperature-sampling, 4.2.5-BLEU-score. (Beam search operates purely on the decoder's per-step probability distribution, so it does not require attention — attention only improves the probabilities being searched, it is not part of the search itself.)

See the algorithm before you trap yourself

The traps below hinge on three moving parts — expansion, scoring, and pruning. Look at them first as a picture, then as a flowchart, so the words "beam", "candidate", and "the normalization step" have concrete meaning.

Figure 1 — one step of beam search. The left column is the current beam ( live sequences). Each is expanded by all vocabulary tokens (middle), producing candidates. We score them, sort, and keep only the top (right); the faded rows are pruned — gone forever.

Figure 2 — where normalization lives. The cumulative value carried inside each beam is the raw running sum . Normalization by is applied only as the sort key at the pruning gate — it never overwrites the stored cumulative score. This figure shows exactly that split.

Figure 3 — the control flow. The same procedure as a flowchart, so you can point to "the normalization step" and "the early-stop test" precisely.

no

yes

Start beams = one START marker, score 0

For each live beam expand by all V tokens

Build k times V candidates add log P per token

Sort candidates by raw score divided by T to the alpha

Keep top k these become the new beams

All beams end with END or hit max length

Return top k by normalized score

Figure 4 — why the length penalty exponent matters. The raw sum drops with length purely because more negative terms are added. Dividing by removes that slope but can over-reward short high-average fragments; a fractional sits between. The curves make the trade-off visible.


True or false — justify

Beam search with a large enough is guaranteed to find the globally most probable sequence.
False — unless (exhaustive), beam search still prunes. Any true-best sequence whose early token falls outside the current top is dropped forever (see the faded rows in Figure 1), so it stays an approximate search.
Greedy decoding is just beam search with .
True — with only one beam kept, "expand and keep the top 1" is exactly "pick the single most probable next token", which is the definition of greedy.
Increasing can never make the returned sequence worse in log-probability.
True for the raw un-normalized score — a bigger beam is a superset of a smaller one's survivors, so the max-scoring survivor can only stay the same or improve. But translation quality (BLEU) can drop, because the extra survivors are often mediocre.
The score of a partial sequence is a probability between 0 and 1.
False — the score is a sum of logs, which is and unbounded below. Only is the probability in .
Two sequences of different lengths can be fairly compared by their raw summed log-probability.
False — every extra token adds a negative term (Figure 4's falling raw curve), so longer sequences are systematically penalized; that is exactly why we divide by before comparing.
With the length penalty term equals 1, so scoring reduces to the raw sum.
True — for any , so dividing by it changes nothing; means no normalization.
Beam search always runs for exactly max_length steps.
False — it stops early once all live beams have emitted <END> (the "yes" branch in Figure 3); max_length is only a safety cap for sequences that never terminate.
A sequence that has already emitted <END> still keeps getting expanded token-by-token.
False — finished beams are set aside (carried as-is into candidates); expanding past <END> would waste compute and produce meaningless tail tokens.

Spot the error

"We normalize by dividing the score by len(seq), counting <START>."
Error: <START> is a fixed marker with no predicted probability, so it contributes no log-prob term. We divide by len(seq) - 1 (the generated-token count ), else the divisor and the number of summed terms disagree.
"Since , taking logs changes which sequence wins."
Error: it's the opposite — because is monotonic increasing, taking logs preserves the ranking. We use logs only for numerical stability (avoiding underflow), not to change the winner.
"Beam search at step keeps the top of the sequences, one best next token each."
Error: it keeps the top out of candidates (each of the beams tries all tokens, as in Figure 1's middle column). Keeping the best token per beam would just be parallel greedy runs and could never let one beam overtake another.
"With we explore more, so we always get a higher BLEU than ."
Error: quality typically peaks around ; beyond that, near-duplicate long sequences crowd out better short ones and BLEU can fall. More search better output.
"Length penalty with divides by , so it always prefers longer sentences."
Error: takes the average log-prob per token, which removes the length bias but does not add a preference for length. Fractional divides by a smaller number than , so it cancels less of the length penalty than full averaging — leaving a residual reward for length. This is a tuning heuristic, not a law: the GNMT paper (Wu et al., 2016) reports working well for their translation setup, and it must be re-tuned per task.
"We should compute the normalized score at every expansion inside the loop and use it as the running cumulative value."
Error: the cumulative value stored per beam is the un-normalized running sum (Figure 2, left); normalization by is applied only as the sorting key at the pruning gate (Figure 2, right), so early tokens aren't repeatedly re-scaled.
"Complexity is because there are possible sequences."
Error: the whole point of beam search is that it never enumerates all sequences. It touches candidates — the pruning is what makes it tractable.

Why questions

Why use log-probabilities instead of multiplying raw probabilities?
Products of many small probabilities underflow to 0 in floating point; summing their logs stays in a representable range, and since is monotonic the ranking is unchanged.
Why does numerical stability ever need the log-sum-exp trick if beam search only adds log-probs?
The addition of log-probs is safe on its own, but the softmax that produces each token's probability sums exponentials over the whole vocabulary; log-sum-exp shifts by the max first so no overflows or underflows to 0.
Why does a purely greedy path fail on "Je suis étudiant"?
Greedy is myopic — it locks in the locally best token at step 2 ("student" directly), never seeing that the slightly-less-obvious "a … student" phrasing yields higher total probability. Local optima ≠ global optimum.
Why divide by rather than by or not at all?
Dividing by () over-corrects and lets deceptively-high-average short fragments win; not dividing () crushes long sequences. A fractional interpolates to balance the two failure modes (Figure 4).
Why can "The dog ran" survive in a beam even though "The dog" started worse than "The cat"?
Beam search scores whole partial sequences, not per-step ranks. A high can lift the cumulative score of a weaker prefix back into the top — this is beam search's ability to recover from a bad early choice.
Why not just set and get the exact answer?
is astronomically large (e.g. ), so exhaustive search is intractable. Beam search deliberately trades exactness for a fixed cost.
Why might a min-length constraint be needed?
Length normalization plus the <END> token can make premature termination score well, so the model emits <END> too early. Forcing at least generated tokens blocks this collapse into empty or stub outputs.
Why does n-gram blocking help in summarization but matter less in short translation?
Long generations tend to loop, repeating a phrase; blocking repeated -grams breaks the loop. Short outputs rarely have room to repeat, so the fix is mostly unnecessary there.

Edge cases

What does the beam contain at step 0, before any token is generated?
A single entry: ([<START>], 0.0) — one beam holding just the start marker with cumulative log-prob 0 (since , "we're certain we started").
What happens when ?
You cannot keep more distinct sequences than there are tokens to expand at the first step, so at step 1 you have at most candidates; effective beam width is capped by the number of available continuations.
If every next-token probability is exactly equal (a uniform distribution over ), how does beam search behave?
All expansions get identical log-prob , so the top- selection is a tie — the algorithm falls back to arbitrary tie-breaking and explores essentially random paths.
What is the score of a sequence containing a token with predicted probability 0?
, so that whole partial sequence gets score and is pruned immediately — a zero-probability token is effectively forbidden.
If a beam emits <END> at step 1 (a length-1 output), what is its for normalization?
generated token (the <END>), since <START> is not counted; its normalized score is just its single log-prob divided by .
What does a negative length penalty exponent do?
Dividing by with is the same as multiplying by , which makes longer (already-negative) scores even more negative — it actively punishes length. It is the wrong sign for encouraging complete sentences and is essentially never used.
Is dividing by the only length-normalization scheme?
No — an alternative is the GNMT penalty function , which smooths the divisor so very short sequences aren't over-rewarded; another is a simple additive per-token reward at each step. All aim at the same length-bias problem via different curves.
When all beams end with <END> at the same step, what does the algorithm return?
It stops and returns the finished sequences, ranked by their length-normalized scores — the top one is the final decoded output.
How does temperature sampling differ from beam search at a conceptual level?
3.4.8-Temperature-sampling randomly samples tokens (introducing diversity/creativity), whereas beam search deterministically searches for high-probability sequences; one optimizes surprise, the other optimizes likelihood.