Skip to content

4.3 RNNs and their limits

ready≈ 13 hoursNeeds: 4.2, 3.3
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (RNN unroller)
  4. 4 Do
  5. 5 Check

One cell, reused. The MLP of 3.8 saw a fixed window of three characters. A recurrent network keeps a hidden state ht=tanh⁡(Wxhxt+Whh⊤ht−1+b)\mathbf{h}_t = \tanh(\mathbf{W}_{xh}\mathbf{x}_t + \mathbf{W}_{hh}^\top\mathbf{h}_{t-1} + \mathbf{b}) and updates it with the same weights at every step, so in principle it can remember anything it has read, with a parameter count independent of the length. Each step’s state also produces a prediction of the next token (CS224n RNN lecture notes).

Backpropagation through time. Unroll the network over the sequence and it is an ordinary deep network whose layers share weights, so backprop works as usual. The gradient reaching ht\mathbf{h}_t has two parts: one from step tt‘s own prediction and one from every later step, passed back through ht+1\mathbf{h}_{t+1}. Because the weights are shared, their gradient is the sum over steps. In practice the sequence is cut into windows of a few dozen steps, carrying the hidden state across windows but not the gradient: truncated BPTT (Karpathy, The Unreasonable Effectiveness of RNNs).

The gradient into each hidden state (BPTT)step 1 of 5
  1. at=xt+W⊤ht−1,ht=tanh⁡(at),L=∑tℓt(ht)\mathbf{a}_t = \mathbf{x}_t + \mathbf{W}^\top\mathbf{h}_{t-1},\quad \mathbf{h}_t = \tanh(\mathbf{a}_t),\quad L = \sum_t \ell_t(\mathbf{h}_t)

Vanishing and exploding. That product of T−tT-t Jacobians is why plain RNNs forget: when its factors are below 1 in norm, distant steps contribute almost nothing to the gradient, and when they are above 1, it can blow up (Pascanu et al. 2013). Explosions are easy to treat: rescale the whole gradient whenever its global norm exceeds a threshold, which keeps its direction. Vanishing has no such fix in a plain RNN.

What came next. LSTMs and GRUs add gates and an additive memory cell whose Jacobian can stay near the identity, much like a residual connection (Hochreiter & Schmidhuber 1997). They still process tokens one at a time, which cannot be parallelized across the sequence during training. Attention (4.4) lets every position look directly at every earlier one: a path of length one instead of T−tT-t.

RNN unroller

Why RNNs forget

Static view on small screens. Open this page on a laptop to interact.

hthidden state h_t (16 units, blue +, orange −) for t = 1 … 40; inputs are random symbols 1e-121e-81e-41e01e4‖∂h_T / ∂h_t‖ for t = 0 … 39 (log scale): how much the last state still depends on each earlier one
distance 5: 5.2e-1 distance 20: 2.0e-2 memory (first distance below 10⁻²): 24

Going back one step multiplies the gradient by diag(1 − h²) Whhᵀ. Whh here is orthogonal times the scale, so in the linear network the norm is exactly scaledistance: below 1 it vanishes geometrically, above 1 it explodes. Tanh can only shrink it further (its derivative is at most 1). Above 1 the tanh network does not explode like the linear one: the states grow until units saturate, and saturated units (|h| near 1, deep colours) pass almost no gradient. A large input scale saturates them too and makes gradients vanish much faster. Clipping tames explosions but nothing in a plain RNN fixes vanishing; LSTM gates and attention do.

A 16-unit RNN reads a random sequence. A heatmap shows each unit’s hidden state at each time step, revealed one step at a time with “Step forward”. When the forward pass reaches the end, a bar chart on a log scale shows the norm of the Jacobian of the last hidden state with respect to each earlier one. Controls set the singular values of the recurrent matrix, the input scale, tanh or linear units, and the sequence length. Keyboard: Tab through the controls; arrow keys adjust sliders; Enter presses buttons.
A character RNN stubs/m4_3_rnn.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/m4_3_rnn.py and run mlc check 4.3. The tests are identical; import the results on the progress page.

Hints · rnn_loss_and_grads 0/3 revealed
Hints · hidden_grad_norms 0/3 revealed

Then train on Tiny Shakespeare (locally):

Terminal window
cd exercises && python projects/char_rnn_shakespeare.py

With the reference solution, 6,000 steps take under a minute. The loss falls from 3.35 (unigram) to about 2.0 on a slice of the training text and 2.5 on the held-out play, which brings new character names. Samples look like Shakespeare from a distance. The script then measures the trained network: the Jacobian of the last state with respect to the state 40 characters earlier has a norm of about 10⁻², and about 10⁻³ at 60 characters.

1. Why is the RNN weight gradient a sum over time steps?
2. What makes gradients vanish over long distances?
3. What does global gradient-norm clipping do?
4. In truncated BPTT, what crosses the window boundary?
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.