After this chapter you will be able to
explain why an additive cell state gives the gradient a path that does not multiply;
trace one LSTM cell by hand, gate by gate;
show why the forget-gate bias decides whether the LSTM starts out better than a plain RNN;
count the parameters of an RNN, a GRU and an LSTM;
name the two limits that gating leaves in place.
This chapter builds on Chapter 12, whose vanishing gradient this chapter repairs.
Chapter 12 left the recurrent network with a precise complaint and not a vague one. Equation (12.11) showed that a gradient travelling back through time is multiplied by one Jacobian per step, and each Jacobian is , so the product behaves like a number raised to the power of the distance. Below one it vanishes, above one it explodes, and nothing holds it at one.
The diagnosis contains the cure. If repeated multiplication is what destroys the gradient, then give the state a path that does not multiply. A gated network does that, keeping a memory that is updated by addition and learning how much of the old memory to carry forward.
The long short-term memory network (Hochreiter and Schmidhuber 1997) carries two vectors and not one, where the cell state is the memory and the hidden state is what the rest of the network sees. Three gates control the traffic, each a sigmoid layer reading the same input, which is the previous hidden state concatenated with the current word, so each produces numbers between and .
A gate value of closes the channel completely while a value of opens it, and everything in between is a partial opening, which is what makes the whole thing differentiable.
The cell state is then updated in a single line, and that line is the reason the architecture exists:
Read it as two decisions, where the forget gate says what fraction of the old memory survives and the input gate says how much of the new candidate to admit. The hidden state is then a filtered view of that memory:
The network can hold something in for many steps without exposing it, and it reveals the memory only when the output gate opens. This is the division of labour between the two states.
Differentiate Equation (13.1) along the cell state path, and the result is startlingly simple:
There is no weight matrix and no derivative, because the gradient is multiplied by the forget gate and nothing else. Compare the two routes directly.
| distance | RNN, factor | LSTM, | LSTM, |
|---|---|---|---|
| 1 | |||
| 10 | |||
| 47 | |||
| 100 | |||
| 500 |
At a gradient still carries a little under one per cent of its strength after steps, whereas at it is gone before step . Be careful about what has changed, because the LSTM did not remove the decay but put the decay rate under the network’s control. This is enough, and it is the whole contribution, since is learned and the network can therefore decide to keep a memory alive when the task rewards it, while was never anybody’s decision.
One detail deserves a section of its own, because skipping it is common. At the start of training the weights are small and random, so Equation (13.4) gives , and the default initialisation sets , which makes .
| after 10 | after 47 | after 100 | ||
|---|---|---|---|---|
| 0 | 0.5000 | |||
| 1 | 0.7311 | |||
| 2 | 0.8808 | |||
| 3 | 0.9526 | |||
| 5 | 0.9933 |
Look at the first row against the previous table, where a default-initialised LSTM decays at the rate the plain RNN did. It therefore starts out no better than the architecture it was invented to replace, and it has to climb out of that by learning.
Set instead, as Gers et al. (2002) recommend, and begins at , so that after steps the gradient retains and not . This is times more signal, from changing one number before training starts. The lesson generalises past LSTMs, because a model that appears incapable of a task is sometimes a model whose initialisation put it somewhere it could not leave.
Take a cell with two units and an input of size two, and set with every other bias at zero.
Every gate reads the same concatenated vector:
| gate | formula | value |
|---|---|---|
| forget | ||
| input | ||
| candidate | ||
| output | ||
| cell | ||
| hidden |
Split the cell update into its two terms and the arithmetic becomes plain enough. One term keeps the old memory and the other writes the new.
| kept from the past, | |
| added this step, | |
| new cell state, |
The forget gate sits at and , so most of the old memory survives the very first step. This is the initialisation already doing its job. Notice how was reached: by addition, not by a matrix multiplication. That single structural fact is the difference from Equation (12.14), and it is why Equation (13.3) looks the way it does.
The gated recurrent unit (Cho et al. 2014) asks whether three gates were ever necessary, and it keeps one state vector instead of two with two gates instead of three.
Equation (13.11) is the interesting line, because the coefficients are and , so they sum to one. The LSTM used two independent gates for those two jobs and could in principle forget everything while adding nothing, whereas the GRU ties them so that forgetting more means admitting more.
The reset gate does a different job, deciding how much of the old state the candidate may see, which lets the unit propose something genuinely new when the topic changes. Running the same numbers as above through a GRU gives this.
| gate | formula | value |
|---|---|---|
| update | ||
| reset | ||
| candidate | ||
| hidden |
Each gate reads a vector of length and produces numbers, so it costs parameters. Counting the gates gives the recurrent core of the model. The embedding and output matrices are left aside, since those are the same in all three.
| model | gates | parameters | what they are |
|---|---|---|---|
| plain RNN | 1 | 300,500 | one state update |
| GRU | 3 | 901,500 | update, reset, candidate |
| LSTM | 4 | 1,202,000 | forget, input, candidate, output |
Those figures use and . A GRU is three quarters the size of an LSTM, which here is fewer parameters and a proportionally faster step. On most tasks the two score within noise of each other (Jozefowicz et al. 2015), so the choice is usually made on size and speed, not on quality, and the GRU often wins on those.
Run it.
code/worked_examples/gated.pyproduces every table in this chapter.--highwaycompares the two decay routes,--biasshows what does,--stepruns the single cell through both architectures, and--paramscounts the gates.
Gating worked. From roughly 2014 to 2017 the LSTM was the default for almost every sequence task, and it powered the first generation of neural machine translation.
Two problems remained, and neither is about gradients. The first is sequential computation, because Equation (13.1) needs before it can compute , so the time steps cannot be computed in parallel however many processors are available. This is a hard ceiling on training speed, and it arrived when hardware was becoming massively parallel.
The second is the bottleneck, since everything the model knows about the prefix has to fit in one fixed-size vector. Gating made that vector’s contents last longer without making the vector bigger, and a whole paragraph still has to be squeezed into it.
Both problems have the same shape, in that they come from insisting information travel through the sequence one step at a time. The next idea lets a position look directly at another with no intervening steps, so distance stops mattering. This is attention, and it arrives in two stages. The very next chapter uses it where it was born, in translation, to let a decoder look back over all the states of its encoder, which opens the bottleneck. Chapter 17 then lets every position of one sequence look at every other, so that nothing waits for anything and the computation parallelises.
Two chapters come between those two. The first takes up a question these models have so far dodged. Everything from Chapter 10 to here has built models, and none of it has said how you would know whether one is any good. Chapter 15 answers that, taking the simplest task these models are put to and using it to establish the evaluation discipline the rest of the book depends on. The second, Chapter 16, uses recurrent models to give every word a vector that depends on its sentence.
Summary
A gated network keeps a cell state that is updated by addition, and gates learn how much of the old memory to carry, how much of the new to write and how much to reveal. The gradient along the cell path is a product of forget gates, not of matrices, so it can survive many steps. The forget-gate bias decides whether this holds at the start of training, because a default initialisation decays at the plain RNN’s rate while a bias of one retains a large factor more signal. The GRU merges the gates and drops the separate cell state, at about three quarters of the parameters, and the two perform alike. Gating did not remove the sequential bottleneck or the fixed-size summary, and attention removes both.
Key terms
long short-term memory. a recurrent cell with a cell state updated by addition and three gates.
cell state. the memory vector of an LSTM, kept separate from the hidden state.
forget gate. a gate that sets how much of the old cell state is carried forward.
gated recurrent unit. a simpler gated cell with an update gate and a reset gate and no separate cell state.
gradient highway. the additive path through the cell state along which the gradient is not multiplied by matrices.
Hochreiter and Schmidhuber (1997) published the original LSTM. Gers
et al. (2002) introduce the forget gate and the bias initialisation of
Section 13.3. Cho et al. (2014) propose the
GRU. Jozefowicz et al. (2015) search thousands of gated architectures
and find no consistent winner. This is the best evidence that the gating
idea matters more than its packaging. For the clearest diagram-led
explanation of the LSTM in existence, read Olah (2015) alongside this
chapter. Both units ship as torch.nn.LSTM and
torch.nn.GRU, and the exercise below asks you to count what
they actually allocate.
13.1 Trace one cell. Using the numbers of this chapter, verify , , and , then confirm and . Now set to zero by hand and recompute. What has the cell become, and what has it forgotten?
13.2 The gradient highway. Derive Equation (13.3) from Equation (13.1), treating as constant. Then explain why the corresponding derivative for the plain RNN, Equation (12.12), cannot be made this simple.
13.3 Initialise it wrong. Compute the surviving gradient after steps for and for . Express the ratio as a power of ten. Then argue why a paper reporting that LSTMs cannot learn long dependencies should be read with this table in hand.
13.4 Count the gates. For and , compute the parameter count for a plain RNN, a GRU and an LSTM. What fraction does the GRU save, and is that fraction independent of and ?
13.5 What the reset gate is for. Set in Equation (13.10) and describe the resulting unit. Now set . Which of the two settings would you expect at a topic boundary, and why?
Build and measure
13.6 Count what the library
allocates. Build torch.nn.RNN,
torch.nn.GRU and torch.nn.LSTM at
and
and sum their parameters. You will get
,
and
against the
,
and
counted above, an excess of
for every gate. Find the tensor responsible, explain why the arithmetic
of this chapter does not need it, and say what it would take to convince
yourself the library is not simply wasting memory.
13.7 Predict, then measure the highway. Before running anything, predict the gradient norm that reaches step from step in a plain RNN and in an LSTM with , on random input. Then measure both with autograd and compare with your prediction.
13.8 Copy task. Train an RNN, a GRU and an LSTM to repeat the first symbol of a sequence after , and steps of noise. Report the accuracy of each at each delay, and say where each fails.
13.9 Peephole thinking. The LSTM gates read and but not . Say what a gate could do if it could also read the old cell state, and name one cost.
In practice
13.10 Tie the gates. The GRU uses and where the LSTM uses independent and . Describe a sequence for which the independent pair can do something the tied pair cannot. Then say why this rarely matters in practice.
13.11 Name the remaining limit. Gating solved the vanishing gradient. State the two problems it did not solve, and for each one explain in two sentences why attention removes it.
13.12 Choosing a cell. A team must deploy a tagger on a phone and cares about memory and speed. Choose between an LSTM and a GRU, justify the choice with the parameter counts of this chapter, and say what you would check before committing.
Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.
gated.pyThe gradient highway
What the cell state replaces the Jacobian product with, and what one number does to it.
runs in your browser Run itFrom Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.