Chapter 32 of 42 · ~28 min read & lab+85 XP
Chapter 32 · Deep Learning

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.

Why ML Engineers & Data Scientists Actually Need This

Chapter 19 is the exact historical turning point of modern AI — from RNN Seq2Seq to Attention, teeing up our Generative AI & Transformers track!

ML / AI Engineer

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.

Data Scientist

Understanding why Greedy decoding misses globally higher-probability outputs (and why log-probabilities prevent float underflow!) is core intuition for decoding any generative model.

Interview & Debug Edge

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

Step 0 · Test Your Gut Before Any Math!

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?

What You Will Master in This Chapter
  • 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
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
cSay aloud:“fixed context vector”
Plain-English Meaning
Single final encoder state passed to decoder in classic Seq2Seq (bottleneck!)
Everyday Example
Forgets early words past ~25 tokens
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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

Everyday Story First (Zero Math Yet!)

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>!

Classic Seq2Seq: Compressing an Entire Sentence Into ONE Context Vector cEncoder RNN / LSTM"Je suis étudiant … (40 words)"cBottleneck!Decoder RNN / LSTM<BOS> → I → am → a → studentFixed-size vector c forgets early words once source length exceeds ~20–30 tokens!
Classic Seq2Seq compresses an entire 50-word source sentence into ONE fixed-size context vector c — creating an information bottleneck that degrades accuracy on long sentences!

Why the Bottleneck Breaks on Long Sequences

Compressing a 5-word sentence and a 50-word paragraph into the exact same 512-float vector cc 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

Everyday Story First (Zero Math Yet!)

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 (Train) vs. Autoregressive Decoding (Inference)Training: Teacher ForcingInput: [<BOS>, y₁*, y₂*, y₃*]Target: [y₁*, y₂*, y₃*, <EOS>]Fast & stable — feeds true previous word!Inference: Autoregressive LoopFeed own prediction ŷ_{t-1} into step t1 early typo can compound (Exposure Bias!)Mitigated by Scheduled Sampling & Beam Search
Teacher Forcing feeds ground-truth tokens during training for fast convergence, while inference feeds its own predictions (autoregressive decoding), creating Exposure Bias.

Teacher Forcing vs. Autoregressive Decoding

  • Training (Teacher Forcing): Feed the ground-truth previous token yt−1∗y_{t-1}^* 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 y^t−1\hat{y}_{t-1} 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 (0.150=00.1^{50} = 0) and divide by LαL^\alpha (α≈0.6\alpha \approx 0.6) so Beam Search doesn't unfairly favor ultra-short sentences: Score(y1:L)=1Lα∑t=1Llog⁡P(yt∣y<t,x)\text{Score}(y_{1:L}) = \frac{1}{L^\alpha} \sum_{t=1}^{L} \log P(y_t \mid y_{<t}, x)
Animated Mini-Lab • Ch 19

Greedy (B=1) vs. Beam Search (B=2) Showdown

Path 1: "The" (0.50) → "dog" (0.30)
Joint Prob = 0.50 × 0.30 = 0.15
Discarded by Beam=2
Path 2: "A" (0.40) → "cat" (0.80)
Joint Prob = 0.40 × 0.80 = 0.32
← Beam=2 finds 2.1× better sentence ✓

3. Bahdanau Soft Attention → The Direct Bridge to Transformers!

Everyday Story First (Zero Math Yet!)

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!

The Bridge to Transformers: Bahdanau Soft Attention Peeks at ALL Encoder States!h₁ (Je)h₂ (suis)h₃ (étudiant)h₄ (ici)Decoder Step s_t ("student")c_t = Σᵢ α_{t,i} hᵢ (Dynamic weighted spotlight — drop the RNN & you get the Transformer!)
Beam Search tracks the top-B hypotheses to beat Greedy decoding, and Bahdanau Soft Attention lets the decoder peek directly at ALL encoder states — the direct bridge to Transformers!

Scaled Dot-Product Attention (Bridge to Generative AI Track)

Given Decoder Query QQ, Encoder Keys KK, and Encoder Values VV: Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{Q K^\top}{\sqrt{d_k}}\right) V

  • Why divide by dk\sqrt{d_k}? If q,kq, k have unit variance, q⋅kq \cdot k has variance dkd_k (std dk\sqrt{d_k}!). Dividing by dk\sqrt{d_k} 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!
Formula Anatomy · Click Any Colored Piece to Decode It
Anatomy of Scaled Dot-Product Attention

Attention(Q, K, V) = softmax(QKᵀ / √d_k) V

Alignment Scores

Dot product measuring how strongly each Query matches every Key.

In our example: (B, T_q, T_k) similarity grid
Put it together with real numbers: When translating 'étudiant' → 'student', α_{t,3} = 0.92 lights up encoder state h₃ directly regardless of whether the sentence is 5 words or 500 words long!
Walk Through With Me · Interactive Worked Example

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].

11. Raw product unfairly favors short sentencesStep 1 / 2

2-word: 0.040.04, 4-word: 0.06250.0625; with more words, multiplying numbers <1< 1 always shrinks!

Teacher's Note: Unnormalized Beam Search tends to emit <EOS> too early.
Pause & Check · Quick Intuition Pulse

Why do we divide QKᵀ by √d_k before applying Softmax in Scaled Dot-Product Attention?

Try It YourselfStandard

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?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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.

Interactive Visual Lab
Lab Challenge: Push Source Length past 35 words and toggle Bahdanau Attention ON in the Deep Lab below to see BLEU score stay high!
Interactive Animation • Ch 19 Deep Lab

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.

Translation Quality (BLEU Score)
35.0 BLEU

Decoder dynamically attends to every encoder word — no fixed-size bottleneck!

Next Track Preview: Generative AI

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!

0%
Sentence Length = 35 words • BLEU = 35.0
Intuition Takeaway: Classic Seq2Seq suffers from a fixed-vector bottleneck; Teacher Forcing speeds training, Beam Search beats Greedy decoding in log-space, and Soft Attention (softmax(QKᵀ/√d_k)V) eliminates the bottleneck — launching the Transformer era!
Where This Powers Real ML, Deep Learning & Generative AI

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.

Production NumPy & PyTorch Code Patterns
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)
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Forgetting the 1 / √d_k scaling factor in Attention.
Best Practice: Always divide QKᵀ by math.sqrt(d_k) to prevent Softmax saturation.
Trap #2: Masking padded/future tokens with 0.0 instead of -inf before Softmax.
Best Practice: exp(0) = 1, NOT 0! Always fill masked positions with -inf (or -1e9) before Softmax so their probability becomes exact 0.0!
Trap #3: Running Beam Search in raw probability space instead of log-probabilities.
Best Practice: Always sum log_softmax scores to prevent float32 underflow on long outputs!
Chapter Mastery Check (+85 XP)
Score: 0 / 5
1What value must masked positions receive BEFORE applying Softmax in Attention so their final attention weight is 0.0?
2What is the Seq2Seq 'information bottleneck'?
3What is 'Exposure Bias' in Seq2Seq models?
4Why does Beam Search sum log-probabilities instead of multiplying raw probabilities?
5Why do we divide QKᵀ by √d_k in Scaled Dot-Product Attention?

Apply What You Learned — Solve Matching Coding Problems