3.5.14 · D3Sequence Models

Worked examples — Beam search decoding

3,208 words15 min readBack to topic

This page is a drill. We take the machinery from Beam search decoding and run it through every kind of situation it can meet: normal cases, tie cases, the special zero/degenerate inputs, the limiting values of the beam width and the penalty , a real-world word problem, and an exam-style trap. If you have not yet seen the algorithm, read the parent first — here we assume you know what beam search does and we practise doing it.

One symbol appears in every formula, so we name it before anything else:

Three quantities we lean on constantly, restated in plain words so no symbol is unearned:

The scenario matrix

Every worked example below is tagged with one of these cells. Together they cover the whole table.

Cell What makes it special Example
A. Baseline Normal , all beams finish, one clear winner Ex 1
B. Greedy vs beam disagree The path beam finds beats the greedy path Ex 2
C. Length matters flips the winner between a short and a long sequence Ex 3
D. Tie Two candidates share a score — how ties are broken Ex 4
E. Degenerate Beam collapses to greedy Ex 5
F. Limiting Exhaustive search — beam finds the true optimum Ex 5
G. Zero-probability token , a token is effectively forbidden Ex 6
H. Premature <END> Min-length forcing changes the answer Ex 7
I. Real-world word problem Captioning with -gram blocking Ex 8
J. Exam twist "Beam search is optimal?" — prove it is not Ex 9

We use natural logs everywhere. Handy reference values: , , , , , , , .


Example 1 — Baseline run (Cell A)

Forecast: Guess now — will A <END> or B <END> win, and roughly what score?

The figure below is the tree we build: <START> at the left, its three children in the middle (two blue = kept, one red = pruned), and the two finished sequences on the right with the winner arrowed in yellow. Trace it as you read the steps.

  1. Expand <START>. Scores: A , B , <END> . Why this step? Beam search always tries all next tokens (here , minus <START> which cannot be re-emitted), then prunes — this is the left fan-out in the figure.
  2. Apply with . Keep A () and B (); drop the immediate <END> (the greyed red node in the figure). Why this step? means only the two best partial sequences survive; is exactly the sort-and-cut operation from the preliminaries.
  3. Expand both survivors. A <END> . B <END> (the two green paths on the right). Why this step? Each surviving beam is extended by one more token.
  4. Normalize (, , so divide by ). A <END> ; B <END> . Why this step? We compare finished sequences by average log-prob per token, not raw sum — the numbers printed beside the green nodes.

Answer: A <END> wins with normalized score (the yellow arrow in the figure).

Verify: and ; the more-probable first word wins, as expected. ✓


Example 2 — Greedy loses, beam wins (Cell B)

Forecast: Greedy takes the single best next word at each step. At I am, the biggest single token is cat (). Will greedy's early commitment to cat beat beam's willingness to also explore the lower-probability a branch? Guess before reading. (All numbers are now used exactly as stated — nothing is silently changed.)

  1. Beam step at I am — actually run . The three candidate partial sequences and their raw scores (each ):

    • I am a:
    • I am cat:
    • I am <END>:

    Sort by score: I am cat () best, then I am a and I am <END> tied at ; the tie-break (lower vocab index — say a precedes <END>) keeps a. keeps I am cat and I am a. Why this step? This is the heart of "doing beam search": we generate every child, score it, sort, and cut to . Greedy () would keep only I am cat and lose the a branch entirely — that is the difference we are about to exploit.

  2. Greedy path commits to I am cat, then ends: I am cat <END> raw . Normalized (): . Why this step? Greedy kept only cat at I am; from cat the end probability is a mediocre , so its sentence is short and not very probable.

  3. Beam expands the surviving I am a branch. I am a cat: ; then I am a cat <END>: . Normalized (): . Why this step? By keeping the lower-probability a, beam discovered the excellent tail a → cat → <END> (each ), a completion greedy never saw.

  4. Compare normalized scores. Beam's I am a cat <END> = beats greedy's I am cat <END> = . Why this step? Beam wins because a cheap early token (a, prob ) unlocked a high-probability tail, and length normalization rewards the more complete sentence. This is the exact condition under which beam pays off.

Answer: Beam outputs I am a cat (normalized ); greedy outputs I am cat (normalized ). Beam wins.

Verify: greedy raw , norm ; beam raw , norm ; . ✓ This is a different answer to the myopia problem than temperature sampling (which is stochastic).


Example 3 — Length penalty flips the winner (Cell C)

Forecast: The short one wins with no penalty. Does the long one ever win?

The figure plots each candidate's normalized score as increases: blue = short Hi, green = long Hello there friend. Watch where the green curve crosses above the blue — that crossing is the tie we solve for.

  1. (divide by ): Hi , Hello there friend . Short wins (left edge of the plot). Why this step? Raw sums punish long sequences: more negative terms.
  2. (divide by ): Hi ; Hello there friend . Short still wins, barely — the curves have nearly met. Why this step? Full normalization averages per token — now they are close.
  3. Find the tie (the red dot in the figure). Solve . Since : . Why this step? We want the exact at which the long sentence starts to win.

Answer: For the short wins; for the long wins; equality at .

Verify: at : short's score. ✓ This is why practitioners pick : they don't want length to dominate.


Example 4 — A tie (Cell D)

Forecast: Two candidates, identical score, but keeps only one. Which?

  1. Both score . Truly equal. Why this step? Ties are legal; the model genuinely can't distinguish.
  2. Apply the tie-break rule of . As defined in the preliminaries, on equal scores keeps the token with the lower vocabulary index. Say Blue has the lower index; it survives. Why this step? The rule was fixed up front precisely so this output is deterministic and reproducible.

Answer: Output is Blue <END> (whichever token has the lower index); score either way.

Verify: ; both candidates equal to 4 dp. ✓ Lesson: always fix the tie-break for reproducibility.


Example 5 — and (Cells E, F)

Forecast: Which value of reproduces greedy, and which is guaranteed optimal?

  1. (a) . Only one beam survives each step pure greedy. At I am it keeps only the local max cat (), giving I am cat <END> (raw , normalized ). Why this step? is greedy by definition; = , so the beam collapses to a single path and the a branch is lost.
  2. (b) . Keep every partial sequence, never prune, then compare all finished sequences by (normalized) score. It considers both I am cat <END> (norm ) and I am a cat <END> (norm ) and returns the higher, I am a cat. Why this step? With no pruning ( keeps everything) no sequence is ever lost, so the global optimum is found — at cost , intractable in practice.

Answer: greedy I am cat (norm ); exhaustive, I am a cat (norm ). Here already matched the exhaustive optimum (Ex 2). Real beam search lives strictly between .

Verify: definitionally = , = keep-all; and , so I am a cat is the normalized optimum. ✓


Example 6 — A zero-probability token (Cell G)

Forecast: What is ? Can a forbidden token appear in the beam?

  1. Score of Maybe . Why this step? The model assigned it zero probability; the log sends it to negative infinity.
  2. Effect on pruning. A score of can never be in the top of any finite candidate list, so always discards it. Maybe is effectively banned for all time — and any sequence passing through it inherits . Why this step? This is how hard constraints (-gram blocking, min-length, forbidden words) are implemented: set the log-prob to .
  3. Survivors: Yes , No . Why this step? With only two finite-scoring tokens and , both survive and Maybe cannot displace either — this confirms the trick truly removes a token from all future search.

Answer: Maybe gets and is unreachable; beam holds Yes and No.

Verify: , , and any candidate with a term is worse than every finite one. ✓


Example 7 — Premature <END> and min-length (Cell H)

Forecast: Without the rule, what does the model output? With it?

  1. No min-length: takes <END> (0.4 > 0.35), producing the empty translation [<START>, <END>], , score . Why this step? Premature <END> is a real failure mode — an empty output.
  2. Apply min-length 1: we force until at least 1 real token exists. Now Hello () is the best legal token. Why this step? Min-length is a hard constraint implemented exactly like the trick of Ex 6.
  3. Continue to a finished sequence: from Hello, emit <END> with , giving . Why this step? We must run the beam to a completed sequence (ending in <END>) before we can report a final score; this step closes the sentence and gives the number to compare.

Answer: Without the rule: empty output (). With min-length 1: Hello <END>, raw score .

Verify: ; ; . ✓


Example 8 — Real-world word problem: captioning with -gram blocking (Cell I)

Forecast: Blocking sets a token's log-prob to if it would recreate a forbidden 2-gram. Who wins?

  1. Check the block. The current last word is dog. Emitting a next would form the 2-gram . Since already appeared, it is blocked . Why this step? -gram blocking forbids repeating any bigram, stopping the "dog a … dog a …" loop that plagues captioning/summarization.
  2. Legal candidates: running , sitting . Why this step? With a set to , must choose among the remaining finite-scoring tokens, forcing diversity.
  3. Keep top : both running and sitting survive; the caption continues "a dog running…" instead of "a dog a…". Why this step? There are only two legal candidates and , so both are retained; the best (running) leads the surviving beams.

Answer: Blocking removes a (→ ); the caption continues with running () as the best.

Verify: , , and the blocked can never be top-. ✓ Better, loop-free captions here would show up as a higher BLEU score against references.


Example 9 — Exam twist: "Beam search is optimal?" — disprove it (Cell J)

Forecast: starts worst. Can beam even keep it alive to discover its brilliant continuation?

The figure shows all three first-step children: kept (blue), pruned (red). The green solid path is beam's actual output; the red dashed path is the true optimum that pruning threw away. Compare the two printed scores.

  1. Step 1 scores: , , . Why this step? has the lowest first-token probability.
  2. Prune with , : keep and ; drop (the red node). Why this step? Beam keeps only the top two — falls outside and is gone forever.
  3. Beam continues the two survivors to completion: A <END> ; B <END> . Beam's best finished sequence is A <END> (). Why this step? Beam can only finish the branches it kept; among and , wins.
  4. The true optimum (the dashed branch beam never explored) is C great <END>: . Why this step? We must compute the pruned branch's score to prove it beats what beam returned.
  5. Compare: true best beam's best . Beam returned the worse sequence. Why this step? The optimum hid behind a low first-token probability that pruning discarded — the definitive proof beam search is approximate.

Answer: Beam outputs A <END> (), but the global optimum is C great <END> (). Beam search is approximate, not optimal — exactly the parent's warning. Only (which keeps alive at step 1) recovers the optimum.

Verify: ; ; ; . ✓ This is the "larger beams can help, but only if they keep the right branch" trade-off in one clean picture.


Recall Self-test

Why do we compare finished sequences by normalized score, not raw score? ::: Raw log-prob sums grow more negative with length, so without dividing by short sequences almost always win. What log-prob does a forbidden/zero-probability token receive, and why does that ban it? ::: ; a term can never be in any finite top-, so it is permanently pruned by . Give one concrete tree where beam search misses the global optimum. ::: Ex 9: the best sequence C great <END> () starts with a low first-token prob, so is pruned at step 1 under , leaving beam with A <END> ().