Seq2seq, encoder–decoder and beam search
Reading a whole sentence into a vector, then writing a new one out
The encoder–decoder pattern is the grammar of modern AI: an encoder turns an input into representations, a decoder generates an output step by step. You will meet the same two words in transformers (7.1 Attention Is All You Need: the big picture, 7.7 Encoder–decoder: T5, BART and choosing an architecture), autoencoders (4.10 Autoencoders, embeddings and representation learning), diffusion U-Nets (8.9 Generative models II: Diffusion and flow matching) and speech models (8.10 Multimodal models). Teacher forcing, exposure bias and beam search — all introduced here — are still how LLMs are trained and decoded (7.6 Decoder-only: GPT and autoregressive generation, 8.5 Decoding and sampling), and the fixed-vector bottleneck is the exact problem attention was invented to solve (6.7 Attention is born).
You'll be able to
- Describe the encoder–decoder architecture and its training objective with teacher forcing
- Explain exposure bias and the difference between training-time and inference-time inputs
- Run beam search by hand with length normalization and contrast it with greedy decoding
- Compute modified n-gram precision and BLEU, and state why BLEU is an imperfect metric
Key ideas
- Seq2seq = encoder RNN compressing the source into a context vector + decoder RNN generating the target as a conditional language model.
- Training maximizes Σₜ log P(yₜ | y<ₜ, x) with teacher forcing (true previous token as input); inference feeds back the model's own predictions.
- Exposure bias: the decoder never saw its own errors in training; scheduled sampling and RL-based training are mitigations.
Show 4 more key ideas
- Beam search keeps the B best partial hypotheses by cumulative log-probability (length-normalized by T^α); it can beat greedy but huge beams favor short, generic outputs.
- BLEU = brevity penalty × geometric mean of clipped n-gram precisions; useful at corpus level, blind to synonyms and paraphrase.
- The fixed-size context vector is a bottleneck that degrades with sentence length — the problem attention solves.
- Encoder/decoder vocabulary recurs everywhere: BERT (encoder-only), GPT (decoder-only), T5/Whisper (encoder–decoder), autoencoders/VAEs.
Suggested path through this lesson
Two networks, one vector
Machine translation maps a source sequence to a target sequence of a different length with a different word order — a many-to-many task with no alignment (6.4 Recurrent neural networks and BPTT). Sutskever, Vinyals & Le (2014) and Cho et al. (2014) solved it with two RNNs. The encoder reads the source and compresses it into its final hidden state, the context vector . The decoder is a conditional language model (6.2 Classical NLP and n-gram language models) initialized with that emits the target one token at a time:
Training maximizes the log-likelihood of reference translations, — the same next-token cross-entropy as every language model, now conditioned on an input. The 2014 system used 4-layer LSTMs with 1,000-dimensional states and found that reversing the source sentence helped a lot, because it shortened the distance between the first source words and the first target words — a hint that the fixed vector was already straining.
Teacher forcing and exposure bias
During training the decoder receives the true previous token as input (teacher forcing), so all steps can be computed with the reference prefix and the loss is well-defined. At inference there is no reference: the decoder feeds back its own prediction . This mismatch is exposure bias — the model has never seen its own mistakes during training, so one wrong token can push it into states it never learned to recover from. Mitigations include scheduled sampling (occasionally feed the model's own sample during training), sequence-level training with the evaluation metric as reward, and, in the LLM era, reinforcement learning on sampled outputs (8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI).
Decoding: greedy vs beam search
The decoder defines a distribution over all target sequences; we want a high-probability one. Greedy decoding takes at each step — fast, but an early safe choice can rule out a better sentence. Beam search keeps the best partial hypotheses: at each step expand every hypothesis by all tokens, score them by cumulative log-probability and keep the top ; a hypothesis is finished when it emits ⟨/s⟩. Because log-probabilities are negative, longer sequences are penalized, so scores are usually length-normalized, with –.
Worked example (). Step 1 probabilities: 0.5, 0.3, 0.2 → log-probs , , ; keep and . Step 2: after the model spreads out ( 0.35, 0.33, 0.32); after it is confident ( 0.9). Cumulative scores: , . The beam keeps (probability ) ahead of () — but greedy would have committed to at step 1 and returned . Beam sizes of 4–10 are typical for translation; much larger beams often hurt (the "beam search curse": the model's highest-probability outputs are often short or generic). For open-ended generation with LLMs, sampling methods replace beam search entirely (8.5 Decoding and sampling).
BLEU and why it is not enough
BLEU compares a candidate translation with one or more references using modified n-gram precision: the count of each candidate n-gram is clipped at its maximum count in any reference. The classic example — candidate "the the the the the the the" against the reference "the cat is on the mat" — gets , because the occurs at most twice in the reference. BLEU combines geometrically and multiplies by a brevity penalty so that short outputs cannot game precision:
with the candidate length and the reference length (computed at corpus level). BLEU correlates with human judgement at the corpus level but not sentence by sentence: it is blind to synonyms and paraphrase, depends on tokenization, and rewards matching the reference's surface form. Character-level chrF, learned metrics such as COMET and BERTScore, and LLM-as-judge evaluation (8.7 Evaluating LLMs) are used alongside it today.
The bottleneck
Everything the decoder knows about the source must squeeze through one vector of a few hundred numbers. Cho et al. showed translation quality dropping sharply as sentence length grew beyond the training lengths; Sutskever's source reversal was a workaround, not a fix. The 2015 remedy was to let the decoder look back at all encoder states at every step, weighting them by relevance — attention, the subject of 6.7 Attention is born and the seed of the transformer.
The vocabulary you will reuse
| term | meaning | later appearances |
|---|---|---|
| encoder | maps an input to representations | BERT 7.5 Encoder-only: BERT and friends (and sentence embeddings), ViT 5.7 Vision Transformers, CLIP's towers 8.10 Multimodal models |
| decoder | generates outputs autoregressively, conditioned on representations | GPT 7.6 Decoder-only: GPT and autoregressive generation, diffusion sampling loops 8.9 Generative models II: Diffusion and flow matching |
| encoder–decoder | both, connected by cross-attention or a context vector | T5/BART 7.7 Encoder–decoder: T5, BART and choosing an architecture, Whisper 8.10 Multimodal models |
| autoencoder | encoder–decoder trained to reconstruct its input | 4.10 Autoencoders, embeddings and representation learning, VAE 8.8 Generative models I: VAEs and GANs |
Where this shows up later
- Attention removes the bottleneck — 6.7 Attention is born; the transformer's encoder, decoder and cross-attention — 7.1 Attention Is All You Need: the big picture, 7.7 Encoder–decoder: T5, BART and choosing an architecture.
- Autoregressive generation, teacher forcing and exposure bias in LLM training — 7.6 Decoder-only: GPT and autoregressive generation, 8.3 Alignment: RLHF, PPO, DPO, GRPO and Constitutional AI; sampling instead of beam search — 8.5 Decoding and sampling.
- Encoder–decoder speech and multimodal models — 8.10 Multimodal models; BLEU's limits foreshadow LLM evaluation problems — 8.7 Evaluating LLMs.
Common pitfalls (4)
- Comparing beam hypotheses of different lengths without length normalization — the shortest hypothesis wins by default.
- Evaluating with sentence-level BLEU, or comparing BLEU across different tokenizations.
- Thinking teacher forcing is a trick: it is what makes the training loss computable in parallel over positions (also in transformers).
- Assuming a bigger beam is always better.
Recap: all 7 key points
- Seq2seq = encoder RNN compressing the source into a context vector + decoder RNN generating the target as a conditional language model.
- Training maximizes Σₜ log P(yₜ | y<ₜ, x) with teacher forcing (true previous token as input); inference feeds back the model's own predictions.
- Exposure bias: the decoder never saw its own errors in training; scheduled sampling and RL-based training are mitigations.
- Beam search keeps the B best partial hypotheses by cumulative log-probability (length-normalized by T^α); it can beat greedy but huge beams favor short, generic outputs.
- BLEU = brevity penalty × geometric mean of clipped n-gram precisions; useful at corpus level, blind to synonyms and paraphrase.
- The fixed-size context vector is a bottleneck that degrades with sentence length — the problem attention solves.
- Encoder/decoder vocabulary recurs everywhere: BERT (encoder-only), GPT (decoder-only), T5/Whisper (encoder–decoder), autoencoders/VAEs.
Watch
Builds a tiny translation model and shows the context vector handing off from encoder to decoder.
Read
Exercises
- Beam search on paper
A decoder gives step-1 probabilities (A 0.4, B 0.35, C 0.25). After A: (D 0.5, E 0.5); after B: (D 0.95, E 0.05); after C: (D 0.6, E 0.4). Run beam search with B = 2 for two steps and compare with greedy. Expected: greedy returns A→D (0.20); beam returns B→D (0.3325).
- Clipped precision and BLEU
Candidate: "the cat the cat on the mat". Reference: "the cat is on the mat". Compute and with clipping, the brevity penalty, and a 2-gram BLEU (geometric mean of times BP). Expected: (clipped: the ×2, cat ×1, on, mat), , BP = 1 (candidate longer than reference).
- Exposure bias, observed
Train the PyTorch seq2seq tutorial model for a few epochs. Decode 50 validation sentences greedily, and separately decode them while feeding the reference prefix (teacher-forced decoding). Compare BLEU. Expected: teacher-forced decoding scores noticeably higher — the gap is exposure bias made visible.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →