Beam search decoding
The problem with greedy decoding
When generating sequences (translation, captioning, summarization), we want:
where and .
Greedy decoding picks 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) →
- Better path: "I" (0.6) → "am" (0.65) → "a" (0.9) → "student" (0.8) →
The greedy path missed "a" because at step 2, "am" alone looked good—but including "a" later creates a much more natural phrase.

Derivation: How beam search scores sequences
Step 1: The objective function
We want to maximize the log-probability (more numerically stable than raw probability):
Why log? Products of small probabilities underflow; sums of logs stay in range. Also: since 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):
Here 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 generated tokens (Bonjour and <END>).
- : full normalization (average log-prob per token)
- : no normalization (raw sum)
- : common in practice (slight preference for longer, less penalty)
Why ? 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 candidates but only keep . This prunes the exponential search space ( total sequences) to operations.
Worked example: Translating "Hello" to French
Setup: Vocabulary = {
Step 0: Initialize
- Beams:
[([<START>], 0.0)]
Step 1: Expand from <START>
- Candidates:
[<START>, Bonjour]:[<START>, Salut]:[<START>, <END>]:
- 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>]:[<START>, Bonjour, Salut]:
- From
Salut:[<START>, Salut, <END>]:[<START>, Salut, Bonjour]:
Normalization (divide by number of generated tokens len(seq) - 1; here each completed sequence has 2 generated tokens, so ):
Bonjour <END>:Salut <END>:
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 | 4-10 | Larger = better quality, slower. Diminishing returns after ~10. |
| Length penalty | 0.6-1.0 | Higher = prefer longer sentences. 0 = no penalty. |
| Min length | Task-dependent | Force decoder to generate at least tokens (avoid premature <END>). |
| N-gram blocking | 2-4 | Prevent repeating the same -gram (useful in summarization). |
Comparison with other decoding methods
| Method | Search space | Quality | Diversity Speed |
|---|---|---|---|
| Greedy | 1 path | Low | None |
| Beam search | paths | High | Low |
| Sampling (top-, temp) | Stochastic | Variable | High |
| Exhaustive | All | 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 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 candidate sequences and explores multiple paths, improving global sequence quality.
Why do we use log-probabilities instead of raw probabilities in beam search?
What is length normalization in beam search and why is it needed?
<START>). Without it, longer sequences always score lower (more negative terms), so the model would favor short, incomplete outputs.If beam width , what does beam search reduce to?
What is the computational complexity of beam search for a sequence of length with vocabulary size and beam width ? :: —at each of steps, we expand sequences by considering tokens each.
Why doesn't beam search guarantee finding the globally optimal sequence?
What is a typical range for beam width in production translation systems?
When should you use sampling methods instead of beam search?
What does the length penalty hyperparameter control?
Concept Map
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