Repository navigation
Module 12
⬅️ Module 11 · 🗺️ Curriculum · 🏠 Home · Module 13 ➡️
Level: Intermediate · Prerequisites: Modules 02, 07, 08 · Time: about 8–9 hours
On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading
Sequences — text, speech, time series, DNA — have variable length and order-dependent meaning. Recurrent neural networks (RNNs) process one element at a time while carrying a hidden state that summarises the past, sharing the same parameters across time. Their training difficulties (vanishing/exploding gradients) motivated gated cells — LSTM and GRU — whose ideas persist in modern architectures.
After this module you should be able to:
- write the RNN equations, unroll them and classify sequence tasks (many-to-one, etc.);
- derive backpropagation through time (BPTT) and explain vanishing/exploding gradients and clipping;
- write LSTM and GRU equations and explain why the cell state helps;
- compare unidirectional, bidirectional and stacked RNNs.
An RNN reads a sentence word by word, updating a "memory" vector after each word. The same update rule is applied at every step, so one model handles any length. A plain RNN's memory fades quickly; gated variants learn what to keep and what to forget.
flowchart LR
x1["x1"] --> R1["RNN cell"] --> h1["h1"] --> R2["RNN cell"] --> h2["h2"] --> R3["RNN cell"] --> h3["h3"]
x2["x2"] --> R2
x3["x3"] --> R3
h0["h0"] --> R1
h1 --> y1["y1"]
h2 --> y2["y2"]
h3 --> y3["y3"]
Figure 12.1 — Unrolled RNN: the same cell (shared weights) is applied at each time step. Original diagram.
Sequence models must handle variable length, order, and long-range dependence; sharing
Task patterns: many-to-one (sentiment: use
Predict the next character: $P(c_{t+1}\mid c_{\le t})=\mathrm{softmax}(W_{hy}\mathbf{h}t)$, loss $\sum_t-\ln P(c{t+1})$. In training with teacher forcing, the true previous token is fed as input; at inference the model's own samples are fed back, causing exposure bias (a train/test mismatch).
Unroll and apply the chain rule. The gradient of the loss at step
Parameter gradients sum contributions over all time steps. Truncated BPTT backpropagates only
With

Figure 12.2 — $\lVert W^t\rVert_2$ for random orthogonal $W$ scaled to spectral radius $0.9$, $1.0$, $1.1$ (log scale): exponential decay or growth within 50 steps. Original figure (figures/make_figs_2.py).
A bidirectional RNN runs a forward and a backward pass and concatenates states, giving each position both past and future context (not usable for online generation). Stacked (deep) RNNs feed one layer's states to the next.
The LSTM (Hochreiter & Schmidhuber 1997; forget gate by Gers et al. 2000) keeps a cell state
Since $\partial\mathbf{c}t/\partial\mathbf{c}{t-1}\approx\mathrm{diag}(\mathbf{f}t)$ (plus indirect terms), gradients flow along the cell state multiplied only by forget gates — near 1 when the network wants to remember — avoiding repeated multiplication by $W{hh}$ and
GRU (Cho et al. 2014) merges cell and hidden state with update gate
The interpolation
Scalar RNN:
Parameters (
import numpy as np
def rnn_forward(X, Wxh, Whh, b, h0):
h, H = h0, []
for x in X: # X: (T, d_x)
h = np.tanh(Wxh @ x + Whh @ h + b); H.append(h)
return np.array(H)
def clip_by_global_norm(grads, c):
n = np.sqrt(sum((g ** 2).sum() for g in grads)); s = min(1.0, c / (n + 1e-12))
return [g * s for g in grads]import torch.nn as nn
lstm = nn.LSTM(input_size=128, hidden_size=256, num_layers=2, bidirectional=True, batch_first=True, dropout=0.2)
out, (h, c) = lstm(x) # out: (B, T, 512)
# training: loss.backward(); nn.utils.clip_grad_norm_(lstm.parameters(), 1.0); opt.step()- Orthogonal/unitary RNNs, IRNN, IndRNN and state-space models (S4, Mamba) revisit linear recurrences with long memory and parallel training.
- Linear attention / RWKV / xLSTM connect recurrence and attention.
- Seq2seq and attention relieve the fixed-size bottleneck (Module 13); Transformers replace recurrence altogether (Module 14).
- Scheduled sampling and sequence-level training reduce exposure bias.
- Regularisation: variational (locked) dropout, zoneout, weight-tying; layer-norm LSTM.
-
Parallelism: RNNs are sequential in time (
$O(T)$ depth), limiting GPU utilisation — a main reason Transformers won.
- Not clipping gradients; not shuffling sequences/batches correctly; leaking hidden state across unrelated sequences.
- Padding without masking/packing so the model reads pad tokens.
- Using bidirectional RNNs for causal generation.
- Forgetting to detach the carried state between truncated-BPTT chunks (graph grows forever).
Q1. Why do RNNs share weights across time?
Same dynamics at every step, any sequence length, far fewer parameters, and better generalisation across positions.
Q2. Derive why gradients vanish in a vanilla RNN.
$\partial\mathbf{h}t/\partial\mathbf{h}k=\prod{i}\mathrm{diag}(\phi'i)W{hh}$; its norm is at most $(\gamma\sigma{\max}(W_{hh}))^{t-k}$ which decays exponentially if
Q3. Why does clipping help only with exploding gradients?
It caps large norms but cannot restore signal that has already shrunk toward zero.
Q4. How does the LSTM cell state mitigate vanishing gradients?
Memory is updated additively and $\partial\mathbf{c}t/\partial\mathbf{c}{t-1}\approx\mathbf{f}_t$; with forget gates near 1 gradients flow almost unattenuated over many steps.
Q5. Compare GRU and LSTM.
GRU has two gates and no separate cell state (≈25% fewer parameters); LSTM has three gates plus a cell state and sometimes better on long dependencies. Empirically close.
Q6. What is teacher forcing and its drawback?
Feeding ground truth tokens as inputs during training speeds learning but causes exposure bias, since at test time the model consumes its own, possibly erroneous, predictions.
Q7. When can you use a bidirectional RNN?
When the whole sequence is available (tagging, classification, encoders), not for left-to-right generation.
Q8. What does truncated BPTT trade off?
Memory and compute are bounded, but gradients cannot capture dependencies longer than the truncation length.
- Elman, J. L. (1990). Finding structure in time. Cognitive Science, 14(2).
- Bengio, Y., Simard, P., & Frasconi, P. (1994). Learning long-term dependencies with gradient descent is difficult. IEEE Trans. Neural Networks, 5(2).
- Hochreiter, S., & Schmidhuber, J. (1997). Long short-term memory. Neural Computation, 9(8).
- Gers, F. A., Schmidhuber, J., & Cummins, F. (2000). Learning to forget: continual prediction with LSTM. Neural Computation, 12(10).
- Cho, K., et al. (2014). Learning phrase representations using RNN encoder–decoder for statistical machine translation. EMNLP. arXiv:1406.1078.
- Schuster, M., & Paliwal, K. K. (1997). Bidirectional recurrent neural networks. IEEE Trans. Signal Processing, 45(11).
- Pascanu, R., Mikolov, T., & Bengio, Y. (2013). On the difficulty of training recurrent neural networks. ICML.
- Karpathy, A. (2015). The unreasonable effectiveness of recurrent neural networks (blog post).
- Gu, A., & Dao, T. (2023). Mamba: linear-time sequence modeling with selective state spaces. arXiv:2312.00752.
⬅️ Module 11 · 🗺️ Curriculum · 🏠 Home · Module 13 ➡️
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths · ❓ Question bank · 📖 Glossary · 📚 References · ✏️ Contributing
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths
❓ Question bank · 📖 Glossary · 📚 References
Jump to module:
01 02 03 04 05 06 07 08 09 10 11 12
13 14 15 16 17 18 19 20 21 22 23 24