AI from scratch · Elective · Seq2seq and beam search
Seq2seq and beam search
Translation, summarization, speech to text, "October 15, 2026" to "2026-10-15": the input is a sequence, the output is another of a different length. The encoder-decoder (sequence-to-sequence, seq2seq) design handles all of them: one network reads, another writes. It's also where attention was invented, a few years before transformers made it the whole model. This lesson covers how the decoder writes, why it once choked on long sentences, and how to choose its words: greedily, by beam search, or by sampling.
1. Read, then write
The encoder (an RNN, or chapter 7's transformer) reads the input into vectors. The decoder writes the output one token at a time, each step seeing what it has written so far: the same next-token prediction as chapter 10, now conditioned on the input. In training the decoder is fed the correct previous token at every step, not its own guess (teacher forcing), so all positions learn in parallel from the right history.
The first translators (Sutskever and colleagues, 2014) squeezed the whole input into the encoder's last state, one vector, and decoded from it. Long sentences lost their beginnings in that bottleneck (the RNN lesson's fixed-size state). The fix (Bahdanau, Cho and Bengio, 2015): at every output step, let the decoder look back at all the encoder's vectors and take a weighted average, weights from how well each matches what it's about to write. That's attention, chapter 7's \(\operatorname{softmax}(qK^\top)V\) with the decoder state as the query. Transformers kept the attention and dropped the recurrence.
Writing "2026-10-15" from "October 15, 2026", where should the decoder's attention be while it writes "10"?
- On "2026"
- On "October": that's the input that decides those two characters
- Spread evenly over the whole input
An encoder reads the input, a decoder writes the output token by token while attending to the encoder's vectors, the step that freed translation from a one-vector bottleneck.
2. Choosing the words
At each step the decoder gives a probability for every next token. How to turn those into a sentence matters as much as the model. The demo uses a small character model of the 379 NYC station names (counts of which character follows each 3-character context, with a little smoothing). Type the start of a name:
- Greedy: always the single most likely next token. Fast, but one early choice that looked best can lead into a poor sequence overall.
- Beam search: keep the \(k\) best partial sequences at every step, extend each by every token, keep the best \(k\) by total log-probability. Width 1 is greedy. Translation and speech recognition use widths of 4 to 10.
- Sampling (chapter 10's temperature): draw from the distribution. Varied, sometimes odd; the right choice for open-ended writing, where the single most likely text is bland and repetitive.
Green names are real stations. Try "B": greedy commits to "Beach…" and ends at a long, less likely name, while the beam finds "Broadway" and "Bedford Av", both more probable and both real. Total log-probability always favors shorter sequences (every extra character multiplies by a probability below 1); tick length-normalize to rank by log-probability per character instead and watch longer names move up (the box below explains). Sampling invents new names, some plausible, some not.
Why does beam search compare candidates by the sum of log-probabilities rather than the product of probabilities?
- They rank sequences identically, and the sum doesn't underflow to 0 after many tokens (Start 3)
- Sums give different, better rankings
- Because probabilities can be negative
Greedy takes the best next token, beam search keeps the k best sequences by total log-probability, and sampling draws for variety; the task decides which.
Why the most likely sequence is often too short, and what length normalization does
- Every token multiplies the sequence's probability by something below 1, so its log-probability only goes down as it gets longer.
- So a model that can end a sentence early (an end token with decent probability) makes short outputs look better: "The cat." beats a faithful 20-word translation.
- Beam search finds exactly what it's told to, the highest total log-probability, so it inherits that bias toward brevity.
- The common fix divides by length (or by length to a power α ≈ 0.6–0.7): candidates are compared by average log-probability per token, not total.
- A deeper version of the same problem: the single most probable output of a language model is often degenerate (repetitive, generic), which is why open-ended generation samples instead of searching.
3. Scoring a translation: BLEU
A translation can be right in many wordings, so BLEU counts how many of the candidate's word sequences of length 1 to 4 (n-grams) appear in one or more reference translations, combines the four precisions by geometric mean, and penalizes candidates shorter than the reference.
BLEU rewards exact wording: the reordered sentence keeps its meaning and loses about a third of its score. It works for comparing systems over thousands of sentences, poorly for judging one. Modern evaluation adds learned metrics and model judges (the evaluating-LLMs lesson).
BLEU scores overlapping n-grams with a reference, clipped and length-penalized: useful across a test set, blind to paraphrase in a single sentence.
Where it breaks: exposure bias and blind metrics
- Exposure bias. Teacher forcing trains every step on the correct history; at generation time the model reads its own outputs, mistakes included, a situation it never trained on. One wrong character and the rest can unravel (chapter 10's "no undo"). Training with some of the model's own samples, or simply larger models, reduces it.
- Beams that agree too much. The k beams often differ only in their last token. Diverse beam search penalizes near-duplicates when several distinct outputs are wanted.
- Metrics blind to meaning. BLEU gives a fluent wrong translation that shares words with the reference a better score than a correct paraphrase. Check a sample by hand, and pair BLEU with human or model judgments.
4. What to carry forward
- Encoder-decoder: read the input, write the output token by token; teacher forcing in training.
- Attention over the encoder's vectors removed the one-vector bottleneck, and grew into the transformer.
- Decoding: greedy, beam search (k best by log-probability, length-normalized), sampling for open-ended text.
- BLEU for system-level comparison; humans or judges for meaning.
All lessons: AI from scratch. Papers: Sutskever, Vinyals and Le (2014); Bahdanau, Cho and Bengio (2015); Papineni et al., "BLEU" (2002).
Last updated