Maps to: CMU 11-711 Spring 2026, Lecture 4 (01/22), slides
anlp-s2026-04-rnns.pdf; course demo code04_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 fromcode/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--quicksmoke-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:
- Describe a sequence model and the three ways to build one (recurrence, convolution, attention).
- Write the Elman RNN recurrence, use it for sequence classification and language modeling, and train it with backpropagation through time.
- 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).
- Derive why gradients vanish or explode through time from the product of Jacobians, and what gradient clipping does.
- 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.
- Build an encoder–decoder for conditional generation, explain its bottleneck, and fix it with attention (queries, keys, score functions, context vectors).
- 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
| Section | Idea | Demo in code/lecture04/ |
|---|---|---|
| §2 | the Elman RNN; RNN language models vs fixed windows; what the state remembers | 01_rnn_lm.py (+ rnn.py) |
| §2.5 | sequence classification: word order finally matters | 02_rnn_classifier.py |
| §3 | vanishing/exploding gradients; GRU, LSTM; gate initialization; clipping | 03_vanishing_gradients.py |
| §4–5 | encoder–decoder; its bottleneck; attention; attention maps | 04_seq2seq_attention.py |
0.4 Notation
| Symbol | Meaning |
|---|---|
| input at step (a token’s embedding) | |
| hidden state after reading ; | |
| , , | recurrent weights, input weights, bias |
| an activation (tanh in the Elman RNN); also the sigmoid in gate equations | |
| elementwise product | |
| , | encoder state at source position ; decoder state at target step |
| , | attention weight of target step on source position ; 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 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:
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:
For language modeling, , where may depend only on . There are three ways to build :
- 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:
with an activation (tanh, ReLU, …) and . “a bad movie” is read as , , . 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, .
Language modeling (Mikolov et al., 2010): at every position, predict the next token from the current state, . 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: depends on , which depends on , 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:
Pros and cons of RNNs as language models.
| pro | con |
|---|---|
| unbounded context, in principle | sequential: needs , which needs , …, so the 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 context | everything must fit through one -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):
| model | parameters | test NLL | long 8 | long 14 | long 20 | agreement |
|---|---|---|---|---|---|---|
| feed-forward, window 8 | 53,987 | 0.864 | 0.96 | 0.14 | 0.14 | 1.00 |
| feed-forward, window 16 | 86,755 | 0.847 | 0.98 | 0.97 | 0.13 | 1.00 |
| Elman RNN | 41,827 | 0.823 | 0.64 | 0.43 | 0.36 | 0.98 |
| GRU (§3.4) | 83,299 | 0.801 | 0.79 | 0.73 | 0.74 | 0.98 |
| LSTM (§3.4) | 104,035 | 0.788 | 0.91 | 0.89 | 0.88 | 0.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 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%):
| cell | after ACT | after “monday” | after “wednesday” | after “friday” | after “he” | after “own” |
|---|---|---|---|---|---|---|
| RNN | 100% | 100% | 100% | 67% | 61% | 20% |
| GRU | 100% | 100% | 100% | 100% | 94% | 91% |
| LSTM | 100% | 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:
| model | dev | negation | contrast | twins both right (of 125) | negation, unseen pair |
|---|---|---|---|---|---|
| Deep CBoW (Lecture 2) | 84.9% | 57 | 53 | 0 / 0 | 30% |
| Elman RNN | 89.3% | 85 | 92 | 101 / 107 | 72% |
| GRU | 94.2% | 84 | 96 | 121 / 114 | 70% |
| LSTM | 93.7% | 83 | 94 | 112 / 112 | 72% |
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: normal, small, tiny, 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 and output , the gradient with respect to the recurrent weights sums over all steps:
The derivative of tanh lies in , so each factor is at most “squashed”. Write (eigendecomposition). The product contains . When the dominant eigenvalue has magnitude below 1, 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:
| cell | k = 0 | k = 5 | k = 10 | k = 20 | k = 40 |
|---|---|---|---|---|---|
| tanh RNN, spectral radius 0.5 | 8.0 | 5.4e−2 | 3.7e−4 | 2.4e−8 | 1.2e−16 |
| tanh RNN, spectral radius 1.0 | 8.0 | 1.2 | 1.9e−1 | 4.6e−3 | 4.3e−6 |
| tanh RNN, spectral radius 1.5 | 8.0 | 4.9 | 2.9 | 1.1 | 1.4e−1 |
| tanh RNN, spectral radius 3.0 | 8.0 | 26 | 110 | 1.5e+3 | 1.3e+5 |
| GRU, PyTorch default | 8.0 | 4.8e−1 | 3.8e−2 | 3.1e−4 | 2.3e−8 |
| LSTM, PyTorch default | 8.0 | 9.3e−2 | 6.7e−3 | 4.9e−5 | 2.1e−9 |
| GRU, keep-gate bias +3 | 8.0 | 6.1 | 4.6 | 2.7 | 9.9e−1 |
| LSTM, forget-gate bias +3 | 8.0 | 5.4e−1 | 4.6e−1 | 4.3e−1 | 4.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 . Multiplied by a learning rate of 0.01, that is an update of size ~ 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: , a residual update. Now contains an identity term, and the gradient has a path along which it is not multiplied by at every step.
A gate (门控) that decides, per dimension, how much to keep and how much to overwrite:
If the network learns for some dimensions, those dimensions are copied forward unchanged, and the gradient along them is multiplied by instead of vanishing.
The gated recurrent unit (GRU) (Cho et al., 2014) puts this together with two gates:
(rnn.ScratchGRUCell implements exactly this. PyTorch’s nn.GRUCell uses the mirror convention , so there a large means “keep”. The self-test maps one onto the other.)
The long short-term memory (LSTM) (Hochreiter & Schmidhuber, 1997) keeps a separate cell state with a purely additive update, controlled by gates:
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, contains : 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 , so the carried signal is halved at every step, . 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 random distractor tokens, then answer “what was the key?” (3,000 training sequences, 15 epochs, Adam, clipping):
| model | L = 10 | L = 20 | L = 40 | L = 80 |
|---|---|---|---|---|
| Elman RNN | 100% | 100% | 13% | 13% |
| GRU, default initialization | 100% | 100% | 11% | 11% |
| LSTM, default initialization | 100% | 100% | 11% | 14% |
| GRU, keep-gate bias +3 | 100% | 100% | 100% | 100% |
| LSTM, forget-gate bias +3 | 100% | 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 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 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: , with a Japanese sentence and its English translation, or a chat history and the response. The basic idea: use one sequence model (the encoder (编码器)) to represent as a vector, and a second (the decoder (解码器)) to generate from it.
4.2 The architecture
The encoder RNN reads ; its final state becomes the context vector (上下文向量) . The decoder is an RNN language model over that is also given , in any of three places (Cho et al., 2014):
- to initialize the decoder’s hidden state;
- in the recurrent update, e.g. ;
- in the output layer, .
Training is maximum likelihood with teacher forcing (the decoder reads the true previous target tokens):
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 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 sentences | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| encoder–decoder, no attention: exact match | 72% | 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 (one per source token).
- Query: the current decoder hidden state .
- Attention scores: , then weights (non-negative, summing to 1).
- Output: the context vector is the weighted sum , used for example as .
Common score functions:
| name | score | source |
|---|---|---|
| dot product | Luong, Pham & Manning (2015) | |
| bilinear (“general”) | Luong et al. (2015) | |
| nonlinear (additive, MLP) | 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 sentence | 2 sentences | 3 sentences | 4 sentences |
|---|---|---|---|---|
| no attention | 72% / 94% | 40% / 84% | 2% / 61% | 0% / 41% |
| attention: dot | 100% / 100% | 99% / 100% | 93% / 97% | 83% / 95% |
| attention: bilinear | 98% / 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 also carries word , 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
- A recurrent network updates a fixed-size state once per token, , giving unbounded context with a parameter count independent of length. It is trained by backpropagation through time and used for classification () and language modeling.
- 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%).
- 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.
- 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.
- An encoder–decoder compresses the input into one context vector, a bottleneck: exact-match translation fell from 72% (one sentence) to 0% (four).
- 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 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 (
RNNClassifierdoes), 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
-
Unrolling. For with scalars , , and inputs , compute . How much of the first input is left in ?
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. -
Jacobian product. In the same scalar RNN, compute exactly. What happens to as grows if ? If 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. -
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?
Answer
Scaled 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. -
Gate arithmetic. An LSTM unit’s forget gate is constant at over 40 steps, with no new writes. What fraction of survives for , , ? Which bias gives ?
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. -
GRU conventions. Show that the slide’s GRU with update gate equals PyTorch’s GRU with update gate . Which bias sign makes each “keep the state” by default?
Answer
Slide: $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). -
Attention by hand. Encoder states , , ; decoder query ; dot-product scores. Compute the attention weights and the context vector.
Answer
Scores: 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)$. -
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.
Answer
Without 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. -
Parallelism. For a sequence of length , 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?
Answer
RNN: $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.
Related assignment (concepts only)
- 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 | 解释 / 可解释性 |