Lecture 4 · Recurrent Neural Networks: Unbounded Context, Vanishing Gradients, Encoder–Decoders and Attention

Advanced Natural Language Processing · Lecture 04。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 11-711 Spring 2026, Lecture 4 (01/22), slides anlp-s2026-04-rnns.pdf; course demo code 04_recurrent/ (RNN language models; an encoder–decoder with attention that reverses names containing noise characters). Readings: K. Cho, Natural Language Understanding with Distributed Representation (2015), ch. 4, §5.5–5.6, ch. 6; additional: Mikolov et al., Recurrent neural network based language model (2010); Cho et al., Learning Phrase Representations using RNN Encoder–Decoder (2014); Weber, Why LSTMs Stop Your Gradients From Vanishing (2017); Bahdanau, Cho, Bengio, Neural Machine Translation by Jointly Learning to Align and Translate (2015). Sources: the public slides (some adapted from Graham Neubig’s Fall 2024 course), the readings, and the papers cited in each section. Instead of the course’s name-reversal task, the translation demo uses English → Zorbian (word mapping plus reversed word order in each sentence; Lecture 1). Every number labelled “measured” comes from code/lecture04/, run on the author’s machine (Apple M4 Pro, Python 3.13, PyTorch 2.14, CPU). Code: code/lecture04/ — demos run in 15–105 seconds; the slowest has a --quick smoke-test mode. Reading time: ~110 minutes for the prose; ~40 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Describe a sequence model fθ(x1,…,x∣x∣)→h1,…,h∣x∣f_\theta(x_1, \dots, x_{\lvert x\rvert}) \to h_1, \dots, h_{\lvert x\rvert} and the three ways to build one (recurrence, convolution, attention).
  2. Write the Elman RNN recurrence, use it for sequence classification and language modeling, and train it with backpropagation through time.
  3. Weigh the RNN’s pros (unbounded context, fixed-size state, parameter count independent of length) against its cons (sequential computation, a single state as bottleneck, vanishing gradients).
  4. Derive why gradients vanish or explode through time from the product of Jacobians, and what gradient clipping does.
  5. Write the GRU and LSTM equations, explain how gating and additive connections create a path along which gradients survive, and why the initialization of the gates matters.
  6. Build an encoder–decoder for conditional generation, explain its bottleneck, and fix it with attention (queries, keys, score functions, context vectors).
  7. Read an attention map critically: it shows where the model looked, not necessarily why it produced its output.

0.2 Prerequisites and scope

  • Prerequisites: Lecture 3 (autoregressive LMs, maximum likelihood, perplexity, the fixed-window horizon, Errand World and its probes, the practical training toolkit) and Lecture 2 (backpropagation, cross-entropy).
  • Scope: recurrent models for language modeling, classification and conditional generation, and attention in its original encoder–decoder form.
  • Not in scope: self-attention and the Transformer (Lecture 5), decoding algorithms beyond greedy (Lecture 9).

0.3 Section → code map

SectionIdeaDemo in code/lecture04/
§2the Elman RNN; RNN language models vs fixed windows; what the state remembers01_rnn_lm.py (+ rnn.py)
§2.5sequence classification: word order finally matters02_rnn_classifier.py
§3vanishing/exploding gradients; GRU, LSTM; gate initialization; clipping03_vanishing_gradients.py
§4–5encoder–decoder; its bottleneck; attention; attention maps04_seq2seq_attention.py

0.4 Notation

SymbolMeaning
xtx_tinput at step tt (a token’s embedding)
ht∈Rdh_t \in \mathbb{R}^dhidden state after reading x1,…,xtx_1, \dots, x_t; h0=0h_0 = 0
Wh∈Rd×dW_h \in \mathbb{R}^{d \times d}, Wx∈Rd×dinW_x \in \mathbb{R}^{d \times d_\text{in}}, bbrecurrent weights, input weights, bias
σ\sigmaan activation (tanh in the Elman RNN); also the sigmoid in gate equations
⊙\odotelementwise product
hnench^\text{enc}_n, sts_tencoder state at source position nn; decoder state at target step tt
αt,n\alpha_{t,n}, ctc_tattention weight of target step tt on source position nn; context vector

1. Where we are

Lecture 3 ended with a precise diagnosis. N-gram and feed-forward models see a fixed window of the previous N−1N - 1 tokens, so a dependency longer than the window is out of reach. On Errand World, the item that follows “for tennis class … his own ___” stayed at chance (0.13) 20 tokens away for every window up to 16. The goal now is a model of the full context:

P(X)≈∏t=1Tpθ(xt∣x1,…,xt−1).P(X) \approx \prod_{t=1}^{T} p_\theta(x_t \mid x_1, \dots, x_{t-1}).

This lecture introduces recurrent neural networks, which in theory have an infinite context. Making that theory work in practice leads to gated architectures. Using RNNs for translation exposes a bottleneck, and the fix for that bottleneck, attention, becomes the subject of Lecture 5.


2. Recurrent neural networks

2.1 Sequence models

A sequence model (序列模型) maps a sequence of inputs to a sequence of hidden states, one per position:

fθ(x1,…,x∣x∣)→h1,…,h∣x∣,ht∈Rd.f_\theta(x_1, \dots, x_{\lvert x\rvert}) \to h_1, \dots, h_{\lvert x\rvert}, \qquad h_t \in \mathbb{R}^d.

For language modeling, pθ(⋅∣x<t)=softmax⁡(Wht⊤)p_\theta(\cdot \mid x_{<t}) = \operatorname{softmax}(W h_t^\top), where hth_t may depend only on x1,…,xtx_1, \dots, x_t. There are three ways to build fθf_\theta:

  • Recurrence: condition each representation on an encoding of the history (this lecture);
  • Convolution: condition on a local window of context (the feed-forward LM of Lecture 3 is its simplest case);
  • Attention: condition on a weighted average of all tokens (§5 here, then Lecture 5).

2.2 The Elman RNN

The recurrent neural network (循环神经网络) of Elman (1990) updates a hidden state once per token:

ht=σ(Whht−1+Wxxt+b),θ={Wh∈Rd×d,  Wx∈Rd×din,  b∈Rd},h_t = \sigma\big(W_h h_{t-1} + W_x x_t + b\big), \qquad \theta = \{W_h \in \mathbb{R}^{d \times d},\; W_x \in \mathbb{R}^{d \times d_\text{in}},\; b \in \mathbb{R}^d\},

with σ\sigma an activation (tanh, ReLU, …) and h0=0h_0 = 0. “a bad movie” is read as h1=σ(Whh0+Wxxa+b)h_1 = \sigma(W_h h_0 + W_x x_\text{a} + b), h2=σ(Whh1+Wxxbad+b)h_2 = \sigma(W_h h_1 + W_x x_\text{bad} + b), h3=…h_3 = \ldots. The same weights are applied at every step.

Intuitively, the hidden state is a memory: a fixed-size summary of everything read so far, overwritten a little at each step. Nothing in the formula limits how far back information can come from. That is the “in theory, infinite context”. rnn.ElmanRNN writes the loop out explicitly, and its self-test checks that it gives exactly the same states as PyTorch’s nn.RNN.

2.3 Two uses

Sequence classification: read the whole sequence, then classify from the last state, [p1,p2,p3]=softmax⁡(WhT)[p_1, p_2, p_3] = \operatorname{softmax}(W h_T).

Language modeling (Mikolov et al., 2010): at every position, predict the next token from the current state, p(xt∣x<t)=softmax⁡(Wht−1)p(x_t \mid x_{<t}) = \operatorname{softmax}(W h_{t-1}). With teacher forcing (Lecture 3), all positions of a sentence are trained at once.

2.4 Training: backpropagation through time

Each position contributes a loss (cross-entropy against the label at that step, for an LM the next token), and the total loss is their sum. Unrolled over the sequence, the RNN is an ordinary directed acyclic computation graph: h3h_3 depends on h2h_2, which depends on h1h_1, and so on. Backpropagation (Lecture 2) applies unchanged. Historically this is called backpropagation through time (随时间反向传播, BPTT). For language modeling the objective is again maximum likelihood:

max⁡θ∑x∈Dtrainlog⁡pθ(x)  ≡  min⁡θ−∑x∈Dtrain∑tlog⁡pθ(xt∣x<t).\max_\theta \sum_{x \in \mathcal{D}_\text{train}} \log p_\theta(x) \;\equiv\; \min_\theta -\sum_{x \in \mathcal{D}_\text{train}} \sum_t \log p_\theta(x_t \mid x_{<t}).

Pros and cons of RNNs as language models.

procon
unbounded context, in principlesequential: hth_t needs ht−1h_{t-1}, which needs ht−2h_{t-2}, …, so the TT steps of a forward (and backward) pass cannot run in parallel. Training is hard to parallelize on GPUs
fixed-size state: memory per step does not grow with the contexteverything must fit through one dd-dimensional vector
parameter count independent of context length (unlike a window that grows)vanishing gradients make long dependencies hard to learn (§3)

2.5 Measured: language models and classifiers

Language modeling on Errand World (demo 01; 2,000 training sentences; recurrent models with 2 seeds; floor 0.754):

modelparameterstest NLLlong 8long 14long 20agreement
feed-forward, window 853,9870.8640.960.140.141.00
feed-forward, window 1686,7550.8470.980.970.131.00
Elman RNN41,8270.8230.640.430.360.98
GRU (§3.4)83,2990.8010.790.730.740.98
LSTM (§3.4)104,0350.7880.910.890.880.99

Every recurrent model beats the best fixed window on overall NLL, and the 20-token dependency — at chance for every window — becomes reachable. But the plain RNN’s score falls with distance (0.64 → 0.43 → 0.36), while the gated GRU and LSTM hold roughly level. Single runs vary: the LSTM’s 20-back score was 0.95 with one seed and 0.81 with the other, so architecture comparisons need several seeds (Lecture 14).

What does the state remember? Train a linear classifier (a probe) to read the activity back out of hth_t at each position of “for ACT class , which met on monday and on wednesday and on friday , he wanted to buy his own ___” (demo 01 Part B; chance 12.5%):

cellafter ACTafter “monday”after “wednesday”after “friday”after “he”after “own”
RNN100%100%100%67%61%20%
GRU100%100%100%100%94%91%
LSTM100%100%100%100%100%100%

The plain RNN’s memory fades through the clause until, 20 tokens later, the activity is barely recoverable. The LSTM still holds it perfectly.

Classification on Cinema World (demo 02; 2,000 reviews; 2 seeds). At last, a model reads the words in order:

modeldevnegationcontrasttwins both right (of 125)negation, unseen pair
Deep CBoW (Lecture 2)84.9%57530 / 030%
Elman RNN89.3%8592101 / 10772%
GRU94.2%8496121 / 11470%
LSTM93.7%8394112 / 11272%

The adjective-swapped twins of Lectures 1–2 (“the acting is great , but the plot is dull .” vs ”… dull , but … great .”) were impossible for every bag model, provably. A recurrent classifier gets both twins right in ~90% of pairs. Negation on (negator, word) pairs never seen in training rises from 30% to ~70%: reading “not” before the adjective, the model can carry it in its state and apply it to words it never saw negated. The fourth symptom of the bag of words, sentence structure, finally has a cure. (The GRU–LSTM difference, 0.4 points, is within the seed-to-seed spread of 1.3–3.2 points.)


3. Vanishing gradients and gated architectures

3.1 The symptom

The gradient of a loss at the end of a sequence with respect to earlier hidden states shrinks as it is pushed back: ∂L/∂h3\partial L / \partial h_3 normal, ∂L/∂h2\partial L / \partial h_2 small, ∂L/∂h1\partial L / \partial h_1 tiny, ∂L/∂h0\partial L / \partial h_0 very tiny. If almost no gradient reaches step 0, the parameters receive almost no signal about how step 0 should have been processed. Long dependencies cannot be learned.

3.2 Why: a product of Jacobians

For a normal RNN with ht=tanh⁡(Winxt+Wht−1)h_t = \tanh(W_\text{in} x_t + W h_{t-1}) and output yT=WouthTy_T = W_\text{out} h_T, the gradient with respect to the recurrent weights sums over all steps:

∂L∂W=∑t=0T∂L∂yT∂yT∂hT∂hT∂ht∂ht∂W,∂hT∂ht=∏t′=tT−1∂ht′+1∂ht′,∂ht′+1∂ht′=diag⁡ ⁣(tanh⁡′(Winxt′+1+Wht′)) W.\frac{\partial L}{\partial W} = \sum_{t=0}^{T} \frac{\partial L}{\partial y_T} \frac{\partial y_T}{\partial h_T} \frac{\partial h_T}{\partial h_t} \frac{\partial h_t}{\partial W}, \qquad \frac{\partial h_T}{\partial h_t} = \prod_{t' = t}^{T-1} \frac{\partial h_{t'+1}}{\partial h_{t'}}, \qquad \frac{\partial h_{t'+1}}{\partial h_{t'}} = \operatorname{diag}\!\big(\tanh'(W_\text{in} x_{t'+1} + W h_{t'})\big)\, W.

The derivative of tanh lies in [0,1][0, 1], so each factor is at most WW “squashed”. Write W=VDV−1W = V D V^{-1} (eigendecomposition). The product contains WT−t=VDT−tV−1W^{T - t} = V D^{T - t} V^{-1}. When the dominant eigenvalue has magnitude below 1, DT−t→0D^{T - t} \to 0 exponentially: the gradient vanishes. When it is well above 1 and the units are not saturated, the product grows exponentially: the gradient explodes.

Measured (demo 03 Part A): ‖∂L/∂h_{T−k}‖ for a 60-step sequence, at initialization:

cellk = 0k = 5k = 10k = 20k = 40
tanh RNN, spectral radius 0.58.05.4e−23.7e−42.4e−81.2e−16
tanh RNN, spectral radius 1.08.01.21.9e−14.6e−34.3e−6
tanh RNN, spectral radius 1.58.04.92.91.11.4e−1
tanh RNN, spectral radius 3.08.0261101.5e+31.3e+5
GRU, PyTorch default8.04.8e−13.8e−23.1e−42.3e−8
LSTM, PyTorch default8.09.3e−26.7e−34.9e−52.1e−9
GRU, keep-gate bias +38.06.14.62.79.9e−1
LSTM, forget-gate bias +38.05.4e−14.6e−14.3e−14.2e−1

Exactly as the algebra predicts: radius 0.5 loses 16 orders of magnitude in 40 steps; radius 3 gains four. Note the two “default” gated rows, a point the slides leave implicit and §3.5 explains.

3.3 Exploding gradients and clipping

Exploding gradients are the easier problem to fix. With radius 3, the gradient 59 steps back reaches 1.9×1071.9 \times 10^7. Multiplied by a learning rate of 0.01, that is an update of size ~2×1052 \times 10^5 for weights of size ~0.1: one step destroys the model (the loss becomes NaN). Gradient clipping (Pascanu, Mikolov & Bengio, 2013) rescales the whole gradient vector whenever its norm exceeds a threshold: clip_grad_norm_(params, max_norm=1). It keeps the gradient’s direction and bounds its size. Every recurrent model in these demos is trained with clipping at norm 1. Vanishing gradients cannot be fixed by rescaling, though: a gradient that carries no information about step 0 stays uninformative however you scale it. Fixing them needs a change of architecture.

3.4 A solution: gating and additive connections

Consider “The cat, which sat on the mat, was hungry”: the verb agrees with “cat”, six tokens back. The network needs to keep a piece of information unchanged across the relative clause. Two ideas make that easy.

An additive connection. Instead of recomputing the state through a squashing nonlinearity every step, learn the difference: ht=ht−1+h~th_t = h_{t-1} + \tilde h_t, a residual update. Now ∂ht/∂ht−1\partial h_t / \partial h_{t-1} contains an identity term, and the gradient has a path along which it is not multiplied by WW at every step.

A gate (门控) that decides, per dimension, how much to keep and how much to overwrite:

ht=(1−zt)⊙ht−1+zt⊙h~t,zt∈(0,1)d.h_t = (1 - z_t) \odot h_{t-1} + z_t \odot \tilde h_t, \qquad z_t \in (0, 1)^d .

If the network learns zt≈0z_t \approx 0 for some dimensions, those dimensions are copied forward unchanged, and the gradient along them is multiplied by 1−zt≈11 - z_t \approx 1 instead of vanishing.

The gated recurrent unit (GRU) (Cho et al., 2014) puts this together with two gates:

zt=σ(Wzxt+Uzht−1)update gate: should I update the previous state?rt=σ(Wrxt+Urht−1)reset gate: should I use the previous state in the candidate?h~t=tanh⁡(Whxt+Uh(rt⊙ht−1))candidate stateht=(1−zt)⊙ht−1+zt⊙h~t.\begin{aligned} z_t &= \sigma(W_z x_t + U_z h_{t-1}) && \text{update gate: should I update the previous state?}\\ r_t &= \sigma(W_r x_t + U_r h_{t-1}) && \text{reset gate: should I use the previous state in the candidate?}\\ \tilde h_t &= \tanh\big(W_h x_t + U_h (r_t \odot h_{t-1})\big) && \text{candidate state}\\ h_t &= (1 - z_t) \odot h_{t-1} + z_t \odot \tilde h_t . \end{aligned}

(rnn.ScratchGRUCell implements exactly this. PyTorch’s nn.GRUCell uses the mirror convention ht=zt⊙ht−1+(1−zt)⊙h~th_t = z_t \odot h_{t-1} + (1 - z_t) \odot \tilde h_t, so there a large zz means “keep”. The self-test maps one onto the other.)

The long short-term memory (LSTM) (Hochreiter & Schmidhuber, 1997) keeps a separate cell state ctc_t with a purely additive update, controlled by gates:

ft=σ(Wfxt+Ufht−1+bf)forget gate: how much of ct−1 to keepit=σ(Wixt+Uiht−1+bi)input gate: how much new content to writegt=tanh⁡(Wgxt+Ught−1+bg)candidate contentot=σ(Woxt+Uoht−1+bo)output gatect=ft⊙ct−1+it⊙gt,ht=ot⊙tanh⁡(ct).\begin{aligned} f_t &= \sigma(W_f x_t + U_f h_{t-1} + b_f) && \text{forget gate: how much of } c_{t-1} \text{ to keep}\\ i_t &= \sigma(W_i x_t + U_i h_{t-1} + b_i) && \text{input gate: how much new content to write}\\ g_t &= \tanh(W_g x_t + U_g h_{t-1} + b_g) && \text{candidate content}\\ o_t &= \sigma(W_o x_t + U_o h_{t-1} + b_o) && \text{output gate}\\ c_t &= f_t \odot c_{t-1} + i_t \odot g_t, \qquad h_t = o_t \odot \tanh(c_t). \end{aligned}

The slides call this a “4-gate architecture using an additional context vector”: the forget gate decides whether to update the previous cell, and the others decide how. Along the cell path, ∂ct/∂ct−1\partial c_t / \partial c_{t-1} contains diag⁡(ft)\operatorname{diag}(f_t): if the forget gates stay near 1, the gradient survives across many steps (Weber, 2017). In practice GRU and LSTM are drop-in replacements for the Elman RNN (nn.GRU, nn.LSTM), and either is a reasonable default.

3.5 Gates make memory possible, not automatic

The measurements add an important nuance. Look again at the default rows of §3.2: at PyTorch’s default initialization, the GRU and LSTM gradients vanish too (2.3e−8 and 2.1e−9 at 40 steps back). The reason is simple. Their keep-gates start near σ(0)=0.5\sigma(0) = 0.5, so the carried signal is halved at every step, 0.540≈10−120.5^{40} \approx 10^{-12}. The additive path exists, but at initialization it is not open.

Demo 03 Part B tests this with a pure memory task. Read a key token (one of 8), then LL random distractor tokens, then answer “what was the key?” (3,000 training sequences, 15 epochs, Adam, clipping):

modelL = 10L = 20L = 40L = 80
Elman RNN100%100%13%13%
GRU, default initialization100%100%11%11%
LSTM, default initialization100%100%11%14%
GRU, keep-gate bias +3100%100%100%100%
LSTM, forget-gate bias +3100%100%100%100%

(chance = 12.5%). Up to 20 distractors everything works. At 40, the default GRU and LSTM fail exactly like the plain RNN, and in a separate check they still failed with three times the training budget. Starting the keep-gate at σ(3)≈0.95\sigma(3) \approx 0.95 solves the task at 40 and 80. After training (Part C), the successful LSTM’s most-used forget gates sit at 0.981, so 46% of the cell state survives 40 steps. The failed default LSTM’s top units sit at 0.664, where 0.66440≈10−120.664^{40} \approx 10^{-12} survives.

So gates make long memory representable: there is now a path whose per-step factor can be ~1. Whether training finds that setting depends on where it starts. This is why initializing the LSTM’s forget-gate bias to a positive value (1 or more) is standard advice (Gers, Schmidhuber & Cummins, 2000; Jozefowicz, Zaremba & Sutskever, 2015).

(On Errand World, §2.5, default-initialized GRU/LSTM did carry information 20 tokens. There every purchase sentence supplies a strong, frequent learning signal through a short structured clause, which is easier than 40 tokens of pure noise. Both outcomes are real; the difference is the task.)


4. Encoder–decoder models

4.1 Motivation: conditional generation

Many tasks generate an output sequence conditioned on an input: pθ(y1,…,yT∣x)p_\theta(y_1, \dots, y_T \mid x), with xx a Japanese sentence and yy its English translation, or xx a chat history and yy the response. The basic idea: use one sequence model (the encoder (编码器)) to represent xx as a vector, and a second (the decoder (解码器)) to generate yy from it.

4.2 The architecture

The encoder RNN reads x1,…,xSx_1, \dots, x_S; its final state becomes the context vector (上下文向量) c∈Rdc \in \mathbb{R}^d. The decoder is an RNN language model over yy that is also given cc, in any of three places (Cho et al., 2014):

  • to initialize the decoder’s hidden state;
  • in the recurrent update, e.g. W[ht−1;yt−1;c]W[h_{t-1}; y_{t-1}; c];
  • in the output layer, softmax⁡(W[ht;c])\operatorname{softmax}(W[h_t; c]).

Training is maximum likelihood with teacher forcing (the decoder reads the true previous target tokens):

min⁡θ∑(x,y)∈D∑t−log⁡pθ(yt∣y<t,x).\min_\theta \sum_{(x, y) \in \mathcal{D}} \sum_t -\log p_\theta(y_t \mid y_{<t}, x).

Sutskever, Vinyals & Le (2014) built the same design with deep LSTMs and noticed a curious trick: reversing the source sentence improved translation. It shortens the distance between the first source words and the first target words, which is a hint at the problem below. rnn.Seq2Seq(attention=None) implements the Cho et al. version.

4.3 The bottleneck

A single context vector is used for every output token, so the whole input must be squeezed through dd numbers, however long it is. Can we do better? Demo 04 translates English Cinema World reviews into Zorbian: every word is mapped to a fixed made-up word, and the word order inside each sentence is reversed. Each output word therefore depends on one specific source word, often far away. The inputs have 1–4 sentences (about 7 tokens per sentence; ~28 tokens for four). Exact-match accuracy without attention (6,000 training pairs, 600 test pairs from unseen reviews):

source sentences1234
encoder–decoder, no attention: exact match72%40%2%0%
(token accuracy)94%84%61%41%

One fixed-size vector holds a 7-token sentence reasonably well but cannot hold 28 tokens.


5. Attention

5.1 The basic idea

Bahdanau, Cho & Bengio (2015): encode each token of the input into its own vector, and when decoding, take a linear combination of these vectors, weighted by attention weights that the decoder computes afresh at every step. The decoder no longer depends on one summary; it can look back at whichever input positions are relevant now.

5.2 The mechanics

  • Keys: the encoder states h1enc,…,hNench^\text{enc}_1, \dots, h^\text{enc}_N (one per source token).
  • Query: the current decoder hidden state hth_t.
  • Attention scores: an=score⁡(ht,hnenc)a_n = \operatorname{score}(h_t, h^\text{enc}_n), then weights α=softmax⁡(a)\alpha = \operatorname{softmax}(a) (non-negative, summing to 1).
  • Output: the context vector is the weighted sum ct=∑n=1Nαnhnencc_t = \sum_{n=1}^{N} \alpha_n h^\text{enc}_n, used for example as logits=Wouttanh⁡(Wc[ct;ht])\text{logits} = W_\text{out} \tanh(W_c [c_t; h_t]).

Common score functions:

namescore(q,k)(q, k)source
dot productq⊤kq^\top kLuong, Pham & Manning (2015)
bilinear (“general”)q⊤Wkq^\top W kLuong et al. (2015)
nonlinear (additive, MLP)w⊤tanh⁡(W[q;k])w^\top \tanh(W [q; k])Bahdanau et al. (2015)

The key difference from §4: a new context vector at every decoder step. (In rnn.Seq2Seq, the decoder states for all target positions are computed first and attention is then computed for all of them at once, the Luong-style arrangement. It is equivalent for training and fully parallel over time.)

5.3 Measured: the bottleneck disappears

model (exact match / token accuracy)1 sentence2 sentences3 sentences4 sentences
no attention72% / 94%40% / 84%2% / 61%0% / 41%
attention: dot100% / 100%99% / 100%93% / 97%83% / 95%
attention: bilinear98% / 99%96% / 100%93% / 98%92% / 98%
attention: MLP (additive)99% / 100%100% / 100%100% / 100%100% / 100%

With attention, four-sentence inputs that were untranslatable become translatable. The score functions do differ (the additive one is best here, dot product the weakest on long inputs), but all of those differences are small next to the gap between attention and none.

5.4 What do attention weights show?

Bahdanau et al. visualised the weights as an alignment matrix between French and English words, a famous figure in which the weights trace which source word each output word “comes from”. Demo 04 Part B prints the dot-product model’s matrix for “the pacing is terrible . it is n’t awkward at all .” Its rows run along anti-diagonals, the reversed word order of each sentence.

But a closer look is sobering. Zorbian’s true alignment is known exactly. Over all test outputs, the most-attended source position is the word actually being translated only 38.8% of the time for the dot model (48.5% for MLP, 21.9% for bilinear), though it is within one position 73% of the time. Often the decoder attends to the token right after the one it translates. A likely reason: the encoder reads left to right, so its state at position j+1j+1 also carries word jj, and attending there works just as well. (Bahdanau et al. used a bidirectional encoder, whose states summarize both sides of each word.) The translations are perfect; the attention maps are only approximately alignments. Attention weights show where the model read from, not a faithful explanation of its decision. This caveat returns whenever attention maps are used as explanations.

5.5 Attention is a general idea

Using the decoder state as the query to compute a new context vector at each step is one use of a general operation: compare a query with a set of keys, turn the scores into weights, and take the weighted sum of values. Next lecture applies it within a single sequence (self-attention), adds a few engineering pieces, and drops recurrence altogether: the Transformer.


6. Summary

  1. A recurrent network updates a fixed-size state once per token, ht=σ(Whht−1+Wxxt+b)h_t = \sigma(W_h h_{t-1} + W_x x_t + b), giving unbounded context with a parameter count independent of length. It is trained by backpropagation through time and used for classification (softmax⁡(WhT)\operatorname{softmax}(W h_T)) and language modeling.
  2. On Errand World, RNNs beat every fixed window (test NLL 0.79–0.82 vs 0.85) and reach the 20-token dependency (0.36–0.88 vs 0.13). On Cinema World, reading in order solves the adjective-swapped twins (≈90% vs 0) and negation on unseen pairs (≈70% vs 30%).
  3. The cost: computation is sequential, and gradients through time are a product of Jacobians, so they vanish (radius 0.5: 10⁻¹⁶ in 40 steps) or explode (radius 3: ×10⁴). Clipping fixes explosion; vanishing needs architecture.
  4. Gates and additive connections (GRU, LSTM) create a path whose per-step factor can be ~1. But at default initialization their gates start at 0.5 and gradients vanish just the same. Biasing the keep/forget gate toward “carry” (+3) turned a 40- and 80-step memory task from chance into 100%. Gates make long memory representable; initialization helps training find it.
  5. An encoder–decoder compresses the input into one context vector, a bottleneck: exact-match translation fell from 72% (one sentence) to 0% (four).
  6. Attention computes a new context vector at every decoder step as a softmax-weighted sum of encoder states (dot / bilinear / additive scores) and removes the bottleneck (83–100% on four sentences). Attention maps resemble alignments but are not reliable ones (39–49% exact).

Common pitfalls

  • Expecting an RNN to use long context just because it can. The plain RNN’s state lost the activity within 20 tokens (probe 20%).
  • Assuming GRU/LSTM solve vanishing gradients by default. At default initialization they vanished as fast as a plain RNN; initialize the forget/keep gate toward 1.
  • Training an RNN without gradient clipping. One exploding batch can turn the weights into NaN.
  • Reading the GRU equations across conventions. The slide’s zz means “update”, PyTorch’s means “keep”; check before setting gate biases.
  • Using the padded last position as the summary. For classification, take the state at the last real token (RNNClassifier does), or padding overwrites the summary.
  • Comparing architectures with one seed. The LSTM’s long-distance probe moved from 0.95 to 0.81 between seeds; the GRU–LSTM gap on Cinema World was smaller than the seed spread.
  • Treating attention weights as explanations. Only 39% pointed at the right source word, even when every output was correct.

Exercises

  1. Unrolling. For ht=tanh⁡(wht−1+uxt)h_t = \tanh(w h_{t-1} + u x_t) with scalars w=0.5w = 0.5, u=1u = 1, h0=0h_0 = 0 and inputs x=(1,0,0)x = (1, 0, 0), compute h1,h2,h3h_1, h_2, h_3. How much of the first input is left in h3h_3?

    Answer$h_1 = \tanh(1) = 0.762$, $h_2 = \tanh(0.381) = 0.364$, $h_3 = \tanh(0.182) = 0.180$. The trace of $x_1$ shrinks roughly by $w = 0.5$ per step (tanh is near-linear for small arguments): a scalar picture of vanishing memory.
  2. Jacobian product. In the same scalar RNN, compute ∂h3/∂h1\partial h_3 / \partial h_1 exactly. What happens to ∂hT/∂h1\partial h_T / \partial h_1 as TT grows if ∣w∣<1\lvert w\rvert < 1? If w=3w = 3 and the pre-activations stay near 0?

    Answer$\partial h_3/\partial h_1 = \tanh'(a_2) w \cdot \tanh'(a_3) w$ with $a_2 = 0.381$, $a_3 = 0.182$: $(1 - 0.364^2)(0.5)(1 - 0.180^2)(0.5) = 0.867 \cdot 0.968 \cdot 0.25 = 0.210$. Generally $\lvert\partial h_T/\partial h_1\rvert \le \lvert w\rvert^{T-1} \to 0$ for $\lvert w\rvert < 1$. With $w = 3$ and unsaturated units ($\tanh' \approx 1$) it grows like $3^{T-1}$: explosion.
  3. Clipping. A gradient vector has norm 500; you clip to max norm 5. By what factor is it scaled, and what happens to its direction? Why does clipping not help with vanishing gradients?

    AnswerScaled by 5/500 = 0.01; the direction is unchanged. A vanishing gradient is *small* (below the threshold), so clipping leaves it alone; and scaling it up would not add the missing information about early steps — the per-step factors have already destroyed it.
  4. Gate arithmetic. An LSTM unit’s forget gate is constant at ff over 40 steps, with no new writes. What fraction of c0c_0 survives for f=0.5f = 0.5, 0.950.95, 0.9810.981? Which bias gives f=σ(3)f = \sigma(3)?

    Answer$0.5^{40} \approx 9 \times 10^{-13}$; $0.95^{40} \approx 0.13$; $0.981^{40} \approx 0.46$ (demo 03 Part C measured 0.46). $\sigma(3) = 1/(1 + e^{-3}) \approx 0.953$, so a bias of +3 with near-zero other inputs.
  5. GRU conventions. Show that the slide’s GRU with update gate zz equals PyTorch’s GRU with update gate z′=1−zz' = 1 - z. Which bias sign makes each “keep the state” by default?

    AnswerSlide: $h = (1 - z) h_{t-1} + z \tilde h$. Substituting $z = 1 - z'$: $h = z' h_{t-1} + (1 - z')\tilde h$, PyTorch's form. "Keep" means $z \approx 0$ in the slide's convention (negative bias) and $z' \approx 1$ in PyTorch's (positive bias, as in demo 03's +3).
  6. Attention by hand. Encoder states h1=(1,0)h_1 = (1, 0), h2=(0,1)h_2 = (0, 1), h3=(1,1)h_3 = (1, 1); decoder query q=(2,0)q = (2, 0); dot-product scores. Compute the attention weights and the context vector.

    AnswerScores: 2, 0, 2. Softmax: $e^2/(2e^2 + 1) = 7.389/15.778 = 0.468$ for $h_1$ and $h_3$, $1/15.778 = 0.063$ for $h_2$. Context: $0.468(1,0) + 0.063(0,1) + 0.468(1,1) = (0.937, 0.532)$.
  7. Why reversing the source helped. Sutskever et al. (2014) translated better when the source sentence was reversed but the target was not. Using the bottleneck and the distance between corresponding words, explain why — and why attention made the trick unnecessary.

    AnswerWithout attention, the decoder starts from the encoder's final state. Reversing puts the first source words *last* in the encoder, so they are freshest in that state exactly when the decoder produces the first target words, and the minimal distance between corresponding words shrinks (the average distance is unchanged, but many short dependencies make optimization easier). With attention, every source word is directly reachable at every decoder step, so distance in the encoder no longer matters.
  8. Parallelism. For a sequence of length TT, how many sequential steps does a forward pass of an RNN need? Of a feed-forward window model? Why does this matter more on a GPU than on the single CPU thread of these demos?

    AnswerRNN: $T$ (each state needs the previous one). Window model: 1 per layer (all positions are independent). A GPU runs thousands of operations in parallel, so independent positions are processed simultaneously, while a sequential chain leaves most of it idle. A single CPU thread processes everything one operation after another anyway, so the difference in wall-clock time is small there.
  • Assignment 1 — Build your own LLaMa uses a Transformer (Lecture 5), not an RNN, but the ideas of this lecture appear inside it: residual (additive) connections are the Transformer’s answer to vanishing gradients; attention (§5) is its core operation; gradient clipping and careful initialization are part of its training. These notes do not provide assignment code.

Further reading

  • K. Cho, Natural Language Understanding with Distributed Representation, arXiv:1511.07916, ch. 4, §5.5–5.6, ch. 6 (course reading).
  • J. L. Elman, “Finding Structure in Time”, Cognitive Science 14, 1990.
  • T. Mikolov, M. Karafiát, L. Burget, J. Černocký, S. Khudanpur, “Recurrent neural network based language model”, Interspeech 2010.
  • S. Hochreiter, J. Schmidhuber, “Long Short-Term Memory”, Neural Computation 9(8), 1997; F. A. Gers, J. Schmidhuber, F. Cummins, “Learning to Forget: Continual Prediction with LSTM”, Neural Computation 12, 2000.
  • K. Cho et al., “Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation”, EMNLP 2014; I. Sutskever, O. Vinyals, Q. V. Le, “Sequence to Sequence Learning with Neural Networks”, NeurIPS 2014.
  • R. Pascanu, T. Mikolov, Y. Bengio, “On the difficulty of training recurrent neural networks”, ICML 2013 — vanishing/exploding gradients and clipping.
  • R. Jozefowicz, W. Zaremba, I. Sutskever, “An Empirical Exploration of Recurrent Network Architectures”, ICML 2015 — forget-gate bias.
  • D. Bahdanau, K. Cho, Y. Bengio, “Neural Machine Translation by Jointly Learning to Align and Translate”, ICLR 2015; M.-T. Luong, H. Pham, C. D. Manning, “Effective Approaches to Attention-based Neural Machine Translation”, EMNLP 2015.
  • T. Weber, “Why LSTMs Stop Your Gradients From Vanishing: A View from the Backwards Pass” (blog, 2017).
  • S. Jain, B. C. Wallace, “Attention is not Explanation”, NAACL 2019 — and the reply by S. Wiegreffe, Y. Pinter, “Attention is not not Explanation”, EMNLP 2019.

Preview of Lecture 5 — Attention and Transformers

Attention fixed the encoder–decoder bottleneck by letting each output step look at every input position. The Transformer asks: what if every position attends to every other position, in every layer, with no recurrence at all? Then there is no sequential chain, so training parallelizes across the whole sequence, and no long path through repeated multiplications, so any two tokens are one attention step apart. We will build one from its five core concepts: positional encodings, scaled dot-product self-attention, multi-head attention, residual connections with layer normalization, and feed-forward layers. Then we compare the original 2017 design with the modern LLaMA-style one (pre-norm, RMSNorm, SwiGLU, rotary positions, grouped-query attention), train both on Errand World against the RNNs of today, and derive the Adam optimizer used throughout.


术语表 (Glossary, English → 中文)

English中文
sequence model序列模型
recurrence / convolution / attention循环 / 卷积 / 注意力
recurrent neural network (RNN) / Elman RNN循环神经网络 / Elman 循环网络
hidden state / memory隐藏状态 / 记忆
unrolling展开
backpropagation through time (BPTT)随时间反向传播
sequence classification序列分类
parallelization并行化
vanishing gradient / exploding gradient梯度消失 / 梯度爆炸
Jacobian / eigenvalue / spectral radius雅可比矩阵 / 特征值 / 谱半径
saturation饱和
gradient clipping梯度裁剪
gate / gating门 / 门控
additive (residual) connection加性(残差)连接
gated recurrent unit (GRU) / update gate / reset gate门控循环单元 / 更新门 / 重置门
candidate state候选状态
long short-term memory (LSTM) / cell state长短期记忆网络 / 细胞状态
forget gate / input gate / output gate遗忘门 / 输入门 / 输出门
forget-gate bias initialization遗忘门偏置初始化
linear probe线性探针
conditional generation条件生成
encoder / decoder / encoder–decoder编码器 / 解码器 / 编码器–解码器
context vector / bottleneck上下文向量 / 瓶颈
teacher forcing教师强制
greedy decoding贪心解码
attention / attention weights / attention scores注意力 / 注意力权重 / 注意力得分
query / key / value查询 / 键 / 值
dot-product / bilinear / additive (MLP) score点积 / 双线性 / 加性(多层感知机)打分
alignment对齐
bidirectional encoder双向编码器
explanation / interpretability解释 / 可解释性
← 返回课程目录