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"?

The practice notebook trains exactly this model and draws its attention: a near-diagonal pattern, jumping to the year first, then the month word, then the day. The model learns the reordering itself.

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:

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?

log is increasing, so the order is preserved; and 30 tokens at probability 0.01 each is \(10^{-60}\), close to the edge of what floats hold, while the log sum is just −138.

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
  1. Every token multiplies the sequence's probability by something below 1, so its log-probability only goes down as it gets longer.
  2. 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.
  3. Beam search finds exactly what it's told to, the highest total log-probability, so it inherits that bias toward brevity.
  4. 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.
  5. 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

4. What to carry forward

All lessons: AI from scratch. Papers: Sutskever, Vinyals and Le (2014); Bahdanau, Cho and Bengio (2015); Papineni et al., "BLEU" (2002).

Last updated