Module 7

RNNs and LSTMs

A recurrent network reads a sequence one step at a time, carrying a state forward. Getting information to survive many steps, and getting gradients to survive the trip back, takes one more idea.

Why it matters

Text, audio and measurements over time come as sequences of any length in which order matters, and a recurrent network handles them by applying the same layer at every step: the weight sharing of module 6, moved from space to time. Its weakness, the vanishing gradient, is the clearest case of a problem that affects every deep network. And the LSTM's cure, a state that is passed along by addition and guarded by gates, is the idea behind the residual stream that carries information through a transformer in module 9.

The idea

A network with a state

A recurrent neural network (RNN) keeps a hidden state $h_t$ and updates it from each new input $x_t$ with the same weights every time:

$$h_t = \tanh\!\big(x_t W_x + h_{t-1} W_h + b\big), \qquad h_0 = 0 .$$

After the last step, $h_T$ is a summary of the whole sequence and a final layer reads the answer off it. Written out for $T$ steps, this is a $T$-layer network in which every layer has the same weights and receives its own input. Training it is ordinary backpropagation on that unrolled network, called backpropagation through time; because the weights are shared, each one's gradient is a sum of contributions from every step.

Why gradients vanish

Going back one step is formula 3 of module 3: multiply by the slope of the activation, then by the transposed weights.

$$\frac{\partial \mathcal{L}}{\partial h_{t-1}} = \left( \frac{\partial \mathcal{L}}{\partial h_t} \odot \big(1 - h_t^2\big) \right) W_h^{\top} .$$

Going back $k$ steps applies this $k$ times with the same $W_h$. The slope $1 - h_t^2$ is at most 1, so if the largest singular value of $W_h$ is $s$, the gradient shrinks by at least a factor $s$ per step and by $s^k$ over $k$ steps. With $s = 0.6$ and $k = 30$ that is about $10^{-7}$. With large weights the product can instead blow up, or the units saturate, the slopes $1 - h_t^2$ collapse towards zero, and the gradient vanishes anyway. Keeping it alive means balancing on a narrow edge.

The consequence is specific. An RNN can represent long memories. What fails is learning them: the part of the gradient that says “change how you treated the input 30 steps ago” is too small to steer the weights.

The LSTM

The long short-term memory network adds a second state, the cell state $c_t$, and three gates that control it. Each gate is a vector of numbers between 0 and 1, computed from the current input and the previous hidden state. One affine map produces everything, a vector $z$ of length $4H$ for $H$ cells, which is cut into four blocks:

$$z = x_t W_x + h_{t-1} W_h + b, \qquad i = \sigma(z_{1}),\quad f = \sigma(z_{2}),\quad g = \tanh(z_{3}),\quad o = \sigma(z_{4}),$$ $$c_t = f \odot c_{t-1} + i \odot g, \qquad h_t = o \odot \tanh(c_t) .$$

Why that helps

Look at how the cell state passes from one step to the next: $c_t = f \odot c_{t-1} + \dots$ The old state is not pushed through a weight matrix or squashed by a tanh; it is scaled by $f$ and added to. Along that path, going back one step multiplies the gradient by $f$, entry by entry, and going back $k$ steps multiplies by the product of $k$ forget gates. A cell whose forget gate stays near 1 passes its gradient back almost untouched, and the network can learn to hold that gate open for exactly the cells that need a long memory.

This does not abolish the problem. Forget gates below 1 still decay exponentially, which is why the forget-gate bias is usually initialised to a positive value so that cells remember by default.

Live demo: remember one bit for 30 steps

A vanilla RNN and an LSTM on the same memory task

How much gradient survives going back in time

Accuracy on the task during training

Inside the LSTM, along one sequence

The task. Each sequence has 30 steps and two input channels. Channel 0 is +1 or −1 at the first step and zero afterwards; channel 1 is random noise at every step. After step 30 the network must say whether the first input was +1. The gradient chart shows, for the current weights, the size of the gradient of the final state with respect to the state $k$ steps earlier, relative to $k = 0$; each unit down is a factor of ten. The strips: a gate at 0 (closed) is drawn in the background shade and a gate at 1 (open) at full contrast; cell states are orange when positive and blue when negative. Both networks have six units.

Try this

  1. Before training, read the gradient chart. The RNN's line falls steadily: each step back costs a constant factor, which is exponential decay. Find its value 30 steps back in the readout and compare it with the LSTM's.
  2. Press Train both. From the starting weights shown, the LSTM reaches 100% within a few dozen steps and the RNN stays near 50%, which is guessing. Neither outcome is guaranteed: over ten random starts in our tests, the LSTM solved the task nine times and the plain RNN twice.
  3. After training, switch the example between First input +1 and First input −1. Find the cells whose state takes one colour for +1 and the other for −1 and keeps it to the end, then look at those cells' rows in the forget-gate strip.
  4. Slide the RNN's weight scale up to about 1.2 and train again a few times, pressing New random weights in between. Its gradient now fades far more slowly, and the plain RNN learns the task on a good share of starts. The memory was always representable; what was missing was a usable gradient. Push the scale to 2 and the gradient vanishes again, this time because the units saturate.
  5. Set the LSTM's forget-gate bias to −1 and compare its line in the gradient chart with the RNN's. An LSTM that forgets by default has the same vanishing gradient, and in our runs it stayed at chance on this task.

Exercise

The LSTM cell's forward pass

Write one step of an LSTM for a batch of sequences, following the equations above. The tests compare your step with a reference, check that the gates do what their names say, and then run your step inside a trained network on the demo's task: with weights trained by backpropagation through time (provided), your cell must remember a bit across 30 steps for at least 97% of 200 new sequences.

Check yourself

An RNN unrolled for 30 steps is a 30-layer network. What makes it different from the 30-layer networks of module 3?

Every layer has the same weights, and every layer receives its own input $x_t$. Because the weights are shared, the gradient for $W_h$ is the sum of the gradients it would get at each of the 30 layers.

The largest singular value of $W_h$ is 0.6. By at least what factor has the gradient shrunk 30 steps back?

$0.6^{30} \approx 2 \times 10^{-7}$. Each step back multiplies by $W_h^{\top}$, which shrinks any vector by at least that factor, and by the tanh slope, which is at most 1 and so can only make things worse.

Why does the update $c_t = f \odot c_{t-1} + i \odot g$ let gradients survive where $h_t = \tanh(\dots)$ does not?

The old cell state reaches the new one through a multiplication by $f$ and an addition, with no weight matrix and no squashing in between. So one step back multiplies the gradient by $f$, and the network is free to learn $f \approx 1$ for a cell it needs to keep. In the plain RNN the factor is tied to $W_h$ and the tanh slopes, which also have to do the work of computing the next state.

Where this leads

You have now built every classical ingredient: layers, backpropagation, good optimisers, shared weights in space and in time. Module 8 turns to networks that learn without labels by compressing their input and reconstructing it, the autoencoder, and module 9 replaces the step-by-step state of this module with attention, which lets every position look directly at every other.

Sources: J. L. Elman, “Finding structure in time”, Cognitive Science 14 (1990); Y. Bengio, P. Simard and P. Frasconi, “Learning long-term dependencies with gradient descent is difficult”, IEEE Transactions on Neural Networks 5 (1994); S. Hochreiter and J. Schmidhuber, “Long short-term memory”, Neural Computation 9 (1997); F. A. Gers, J. Schmidhuber and F. Cummins, “Learning to forget: continual prediction with LSTM”, Neural Computation 12 (2000); R. Pascanu, T. Mikolov and Y. Bengio, “On the difficulty of training recurrent neural networks”, ICML (2013); R. Jozefowicz, W. Zaremba and I. Sutskever, “An empirical exploration of recurrent network architectures”, ICML (2015).