Encoder–Decoder Seq2Seq, Teacher Forcing, Beam Search & The Bridge to Attention
How Encoder–Decoder models translate variable-length sequences, Teacher Forcing vs. Exposure Bias, Greedy vs. Beam Search decoding, and how Bahdanau Soft Attention broke the fixed-vector bottleneck to spark the Transformer era.
Chapter 19 is the exact historical turning point of modern AI — from RNN Seq2Seq to Attention, teeing up our Generative AI & Transformers track!
Teacher Forcing, Autoregressive Decoding, Beam Search, and Scaled Dot-Product Attention (softmax(QKᵀ/√d)V) are used in every modern LLM, speech recognizer (Whisper), and translation system.
Understanding why Greedy decoding misses globally higher-probability outputs (and why log-probabilities prevent float underflow!) is core intuition for decoding any generative model.
Classic ML & NLP interview question: 'What is the Seq2Seq information bottleneck, how does Attention fix it, and why do we sum log-probabilities with length normalization in Beam Search?'
Suppose at Step 1, 'The' has prob 0.5 and 'A' has prob 0.4. At Step 2, 'The → dog' has prob 0.3 (0.15 total), while 'A → cat' has prob 0.8 (0.32 total). Which sequence does Greedy Decoding pick?
- Explain the Encoder–Decoder Seq2Seq architecture and why a single fixed context vector c creates an information bottleneck
- Contrast Teacher Forcing (training) with Autoregressive Decoding (inference) and explain Exposure Bias
- Execute Greedy vs. Beam Search (width B) decoding with length-normalized log-probabilities
- Derive Bahdanau / Dot-Product Soft Attention as the direct bridge from Seq2Seq into Transformers
Imagine translating a 2-page French letter into English by reading the whole letter once, closing it forever, and translating purely from memory (classic Seq2Seq bottleneck c!). Obviously you'll forget the middle paragraphs! Soft Attention simply lets you keep the French letter open on the desk and shine a glowing spotlight (α_{t,i}) back onto the exact source word you are translating right now!
1. Classic Encoder–Decoder Seq2Seq & The Fixed-Vector Bottleneck
How do you translate a 7-word French sentence into a 10-word English sentence when input and output lengths don't match? Use two RNNs: an Encoder reads the source into a summary vector c, and a Decoder generates target words one by one until <EOS>!
Why the Bottleneck Breaks on Long Sequences
Compressing a 5-word sentence and a 50-word paragraph into the exact same 512-float vector forces the encoder to throw away early details — BLEU translation scores plummet sharply once source length passes ~20–25 words!
2. Teacher Forcing, Exposure Bias & Greedy vs. Beam Search
Toggle Greedy (B=1) vs. Beam Search (B=2) below to watch Beam Search discover a 2.1× higher-probability sentence that Greedy pruned too early!
Teacher Forcing vs. Autoregressive Decoding
- Training (Teacher Forcing): Feed the ground-truth previous token at every step so training converges quickly and can even be parallelized in Transformers!
- Inference (Autoregressive): Ground truth doesn't exist, so the model feeds its own predicted token back in. One early mistake can derail the rest of the sentence (Exposure Bias).
- Beam Search Objective (Log-Sum + Length Penalty): Multiply probabilities in log-space to prevent float32 underflow () and divide by () so Beam Search doesn't unfairly favor ultra-short sentences:
Greedy (B=1) vs. Beam Search (B=2) Showdown
3. Bahdanau Soft Attention → The Direct Bridge to Transformers!
Instead of throwing away encoder states h₁, h₂, …, h_T, Bahdanau et al. (2015) let the decoder compute a fresh, dynamic context vector c_t at every output step by attending over ALL encoder states!
Scaled Dot-Product Attention (Bridge to Generative AI Track)
Given Decoder Query , Encoder Keys , and Encoder Values :
- Why divide by ? If have unit variance, has variance (std !). Dividing by restores unit variance so Softmax doesn't saturate into vanishing gradients!
- What Happens Next? In 2017, Vaswani et al. ("Attention Is All You Need") asked: If Attention is doing all the heavy lifting, why keep the slow sequential RNN at all? Dropping the RNN gave birth to the Transformer — which we will master from scratch in our upcoming Generative AI track!
Attention(Q, K, V) = softmax(QKᵀ / √d_k) V
Dot product measuring how strongly each Query matches every Key.
'étudiant' → 'student', α_{t,3} = 0.92 lights up encoder state h₃ directly regardless of whether the sentence is 5 words or 500 words long!Worked Example: Why Log-Space + Length Normalization Matters in Beam Search
Compare a 2-word sequence [0.2, 0.2] vs. a 4-word sequence [0.5, 0.5, 0.5, 0.5].
2-word: , 4-word: ; with more words, multiplying numbers always shrinks!
<EOS> too early.Why do we divide QKᵀ by √d_k before applying Softmax in Scaled Dot-Product Attention?
In Scaled Dot-Product Attention with Q shape (4, 10, 64) and K, V shape (4, 25, 64), what are the exact shapes of QKᵀ and the final output?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Beam Search maximizes exact likelihood — amazing for translation & speech transcription where there's one right answer, but repetitive and boring for creative chat! Top-p + Temperature sampling adds controlled diversity.
Seq2Seq Information Bottleneck → Bahdanau Attention Bridge Studio
Increase sentence length past 25 words and toggle Bahdanau Soft Attention ON to see why Attention rescued translation and sparked the Transformer revolution.
Decoder dynamically attends to every encoder word — no fixed-size bottleneck!
In 2017, "Attention Is All You Need" dropped the slow sequential RNN completely and kept parallel Multi-Head Self-Attention — launching GPT, Claude, and Gemini!
softmax(QKᵀ/√d_k)V) eliminates the bottleneck — launching the Transformer era!Neural Machine Translation & Speech (Whisper)
Encoder–Decoder Cross-Attention + Beam Search translates speech and text across 100+ languages.
Transformers & Frontier LLMs
Scaled Dot-Product Attention is the core engine of GPT, Claude, Gemini, and LLaMA.
Code & Structured Generation
Constrained Beam Search guarantees syntactically valid JSON/SQL generation.
import math
import torch
import torch.nn.functional as F
# 1. From-Scratch Scaled Dot-Product Attention (The Bridge to Transformers!)
def scaled_dot_product_attention(Q: torch.Tensor, K: torch.Tensor, V: torch.Tensor, mask: torch.Tensor | None = None):
# Q: (B, T_q, d_k), K: (B, T_k, d_k), V: (B, T_k, d_v)
d_k = Q.size(-1)
scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k) # (B, T_q, T_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, float("-inf"))
attn_weights = F.softmax(scores, dim=-1) # (B, T_q, T_k)
output = torch.matmul(attn_weights, V) # (B, T_q, d_v)
return output, attn_weights
# 2. Idiomatic Production PyTorch 2.x (uses FlashAttention automatically on GPU!)
Q = torch.randn(4, 10, 64)
K = torch.randn(4, 25, 64)
V = torch.randn(4, 25, 64)
out = F.scaled_dot_product_attention(Q, K, V) # (4, 10, 64)
1 / √d_k scaling factor in Attention.QKᵀ by math.sqrt(d_k) to prevent Softmax saturation.0.0 instead of -inf before Softmax.exp(0) = 1, NOT 0! Always fill masked positions with -inf (or -1e9) before Softmax so their probability becomes exact 0.0!log_softmax scores to prevent float32 underflow on long outputs!0.0?QKᵀ by √d_k in Scaled Dot-Product Attention?