3.5.14Sequence Models

Beam search decoding

2,429 words11 min readdifficulty · medium6 backlinks

The problem with greedy decoding

When generating sequences (translation, captioning, summarization), we want:

y=argmaxyP(yx)\mathbf{y}^* = \arg\max_{\mathbf{y}} P(\mathbf{y} \mid \mathbf{x})

where y=(y1,y2,,yT)\mathbf{y} = (y_1, y_2, \ldots, y_T) and P(yx)=t=1TP(yty<t,x)P(\mathbf{y} \mid \mathbf{x}) = \prod_{t=1}^T P(y_t \mid y_{<t}, \mathbf{x}).

Greedy decoding picks yt=argmaxP(yty<t,x)y_t = \arg\max P(y_t \mid y_{<t}, \mathbf{x}) at each step. Why this fails: the product of locally-optimal choices is NOT globally optimal.

Example: Translating "Je suis étudiant" to English.

  • Greedy might pick: "I" (0.6) → "am" (0.7) → "student" (0.3) → P=0.126P = 0.126
  • Better path: "I" (0.6) → "am" (0.65) → "a" (0.9) → "student" (0.8) → P=0.281P = 0.281

The greedy path missed "a" because at step 2, "am" alone looked good—but including "a" later creates a much more natural phrase.

Figure — Beam search decoding

Derivation: How beam search scores sequences

Step 1: The objective function

We want to maximize the log-probability (more numerically stable than raw probability):

score(y)=logP(yx)=t=1TlogP(yty<t,x)\text{score}(\mathbf{y}) = \log P(\mathbf{y} \mid \mathbf{x}) = \sum_{t=1}^T \log P(y_t \mid y_{<t}, \mathbf{x})

Why log? Products of small probabilities underflow; sums of logs stay in range. Also: argmaxP=argmaxlogP\arg\max P = \arg\max \log P since log\log is monotonic.

Step 2: Length normalization

Raw log-probability penalizes longer sequences (more terms in the sum, each negative). A 10-word sentence will almost always score lower than a 3-word sentence, even if it's better.

Fix: Divide by length (with smoothing):

scorenorm(y)=1Tαt=1TlogP(yty<t,x)\text{score}_{\text{norm}}(\mathbf{y}) = \frac{1}{T^\alpha} \sum_{t=1}^T \log P(y_t \mid y_{<t}, \mathbf{x})

Here TT is the number of generated tokens (i.e., we do not count the <START> token, since it carries no predicted probability). In the worked example below, a completed sequence like [<START>, Bonjour, <END>] has T=2T=2 generated tokens (Bonjour and <END>).

  • α=1\alpha = 1: full normalization (average log-prob per token)
  • α=0\alpha = 0: no normalization (raw sum)
  • α(0.6,0.7)\alpha \in (0.6, 0.7): common in practice (slight preference for longer, less penalty)

Why α<1\alpha < 1? Very short sequences can have deceptively high average probabilities (e.g., "I." has high avg prob but is incomplete). Partial normalization balances.

Step 3: The algorithm

Key insight: At each step, we generate k×Vk \times V candidates but only keep kk. This prunes the exponential search space (VTV^T total sequences) to O(kTV)O(kTV) operations.

Worked example: Translating "Hello" to French

Setup: Vocabulary = {, Bonjour, Salut, }, beam width k=2k=2, α=1\alpha=1.

Step 0: Initialize

  • Beams: [([<START>], 0.0)]

Step 1: Expand from <START>

  • Candidates:
    • [<START>, Bonjour]: log0.6=0.51\log 0.6 = -0.51
    • [<START>, Salut]: log0.35=1.05\log 0.35 = -1.05
    • [<START>, <END>]: log0.05=3.0\log 0.05 = -3.0
  • Keep top 2: Bonjour (-0.51), Salut (-1.05)

Why this step? We try all possible first words, score them by model's predicted probabilities, keep the 2 best.

Step 2: Expand both beams

  • From Bonjour:
    • [<START>, Bonjour, <END>]: 0.51+log0.9=0.510.11=0.62-0.51 + \log 0.9 = -0.51 - 0.11 = -0.62
    • [<START>, Bonjour, Salut]: 0.51+log0.08=0.512.53=3.04-0.51 + \log 0.08 = -0.51 - 2.53 = -3.04
  • From Salut:
    • [<START>, Salut, <END>]: 1.05+log0.85=1.050.16=1.21-1.05 + \log 0.85 = -1.05 - 0.16 = -1.21
    • [<START>, Salut, Bonjour]: 1.05+log0.1=1.052.30=3.35-1.05 + \log 0.1 = -1.05 - 2.30 = -3.35

Normalization (divide by T=T = number of generated tokens == len(seq) - 1; here each completed sequence has 2 generated tokens, so T=2T=2):

  • Bonjour <END>: 0.62/2=0.31-0.62 / 2 = -0.31
  • Salut <END>: 1.21/2=0.605-1.21 / 2 = -0.605

Keep top 2: [<START>, Bonjour, <END>] (normalized -0.31), [<START>, Salut, <END>] (normalized -0.605).

Why this step? Both sequences ended, so we compare their length-normalized scores. "Bonjour" wins because the model assigned it higher probability.

Final output: "Bonjour" (score -0.31)

Common hyperparameters

Parameter Typical range Effect
Beam width kk 4-10 Larger = better quality, slower. Diminishing returns after ~10.
Length penalty α\alpha 0.6-1.0 Higher = prefer longer sentences. 0 = no penalty.
Min length Task-dependent Force decoder to generate at least nn tokens (avoid premature <END>).
N-gram blocking 2-4 Prevent repeating the same nn-gram (useful in summarization).

Comparison with other decoding methods

Method Search space Quality Diversity Speed
Greedy 1 path Low None
Beam search kk paths High Low
Sampling (top-pp, temp) Stochastic Variable High
Exhaustive All VTV^T Optimal N/A

When to use beam search:

  • Machine translation, summarization, captioning (want the single best output)
  • When fluency and correctness matter more than creativity

When NOT to use beam search:

  • Story generation, dialogue (want diversity; beam search produces generic responses)
  • Use sampling with temperature or nucleus sampling instead

Connections

  • Seq2seq models — Beam search is the standard decoding method for seq2seq
  • Attention mechanism — Compute P(yty<t,x)P(y_t \mid y_{<t}, \mathbf{x}) using attention over encoder states
  • Temperature sampling — Alternative to beam search for creative generation
  • BLEU score — Metric used to evaluate beam search outputs in translation
Recall Explain like I'm 12

Imagine you're playing a word game where you build a sentence one word at a time, and each word has a "goodness score" (how likely it sounds).

Greedy is like only remembering your current sentence and always picking the best next word. But sometimes, a word that sounds "okay" now leads to a much better sentence later! Like if you're making "I want to eat pizza", and you pick "I want cookies" because "cookies" scored 90 vs "to" scored 80. But "to eat pizza" would've scored 90 × 95 = 8550 total, way better than "cookies" (90) ending there.

Beam search is like having a sticky note for your top 3 sentences at each step. You try adding words to all 3, get 3 × 26 = 78 new sentences, then keep only the best 3 again. So you're exploring multiple "what if I said THIS instead" paths, but not so many that your brain explodes.

The "beam width" is how many sticky notes you have. 1 note = greedy. 100 notes = your desk is a mess and you're not getting much benefit after 10 notes anyway.


#flashcards/ai-ml

What is the key difference between greedy decoding and beam search? :: Greedy picks the single highest-probability token at each step (myopic). Beam search maintains kk candidate sequences and explores multiple paths, improving global sequence quality.

Why do we use log-probabilities instead of raw probabilities in beam search?
To avoid numerical underflow (products of small numbers become zero in floating point) and because log\log converts products to sums, which are easier to compute and compare.
What is length normalization in beam search and why is it needed?
Dividing the cumulative log-probability by TαT^\alpha, where TT is the number of generated tokens (excluding <START>). Without it, longer sequences always score lower (more negative terms), so the model would favor short, incomplete outputs.
If beam width k=1k=1, what does beam search reduce to?
Greedy decoding—only the single highest-probability sequence is kept at each step.

What is the computational complexity of beam search for a sequence of length TT with vocabulary size VV and beam width kk? :: O(kTV)O(kTV)—at each of TT steps, we expand kk sequences by considering VV tokens each.

Why doesn't beam search guarantee finding the globally optimal sequence?
It prunes the search tree—if the true best sequence has a low-probability token early that falls outside the top kk, that path is discarded and never explored, even if later tokens would make it optimal.
What is a typical range for beam width in production translation systems?
k=4k = 4 to 1010. Larger values have diminishing returns and can amplify length bias.
When should you use sampling methods instead of beam search?
For creative generation tasks (stories, dialogue, diverse responses) where you want variety and personality, not the single most probable (often generic) output.
What does the length penalty hyperparameter α\alpha control?
How strongly we normalize by sequence length. α=0\alpha=0: no normalization (favors short sequences). α=1\alpha=1: full normalization (average per token). α(0.6,0.7)\alpha \in (0.6, 0.7): common compromise.

Concept Map

requires

solved by

picks local max

fails at

motivates

keeps top k

expand by V tokens

uses

avoids underflow

penalizes long seqs

controlled by

width k=1

Find best sequence y*

Product of conditional probs

Greedy decoding

Myopic choices

Not globally optimal

Beam search

Partial sequences beam

Score k times V candidates

Sum of log-probs

Numerical stability

Length normalization

Alpha exponent

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Beam search ek aisa decoding technique hai jisse hum sequence generation mein better quality ke outputs nikalte hain. Socho translation kaam hai—agar hum sirf sabse zyada probable next word uthaye har step pe (greedy decoding), toh local level pe best choice ho sakta hai, lekin overall sentence awkward ya incomplete ban sakta hai. Jaise "I am student" grammatically galat hai compared to "I am a student."

Beam search ka idea sim

Go deeper — visual, from zero

Test yourself — Sequence Models

Connections