LSTMs & GRUs
Gates that let gradients and memories survive hundreds of steps.
In 1997 Hochreiter and Schmidhuber built a recurrent cell around one idea: give the error signal a path through time on which nothing shrinks it. Add gates that decide when to write, keep and read, and you get the LSTM, the workhorse of speech recognition and machine translation in the 2010s, and its leaner sibling the GRU. Here you write both cells out, count their parameters, and derive why their gradients survive.
What you’ll learn
- Write the LSTM and GRU equations with shapes, and derive their parameter counts: and , four and three times a vanilla layer.
- Explain the constant error carousel and derive , with its consequences for gradient flow.
- Relate the forget-gate bias to the memory time scale , and justify initializing it at 1 or more.
- Describe the practical variants (peepholes, coupled gates, layer normalization, dropout placement) and what large ablation studies found.
The constant error carousel
The analysis of Recurrent Neural Networks ends in a dilemma: the error signal crosses each step through a factor , and a product of many such factors almost always vanishes or explodes. Hochreiter (1991) had diagnosed the problem in his diploma thesis; Hochreiter & Schmidhuber (1997) designed around it. Consider a single linear unit connected to itself with weight 1, . Its local factor is , so an error signal flows back through it unchanged for any number of steps. They called this the constant error carousel.
A bare carousel has two problems. Every input is added to it, so irrelevant inputs overwrite what it stores, and whatever it stores leaks into every unit that reads it. The 1997 LSTM therefore wrapped the carousel in multiplicative gates: an input gate that decides when to write and an output gate that decides when the stored value is visible.
Think first If a self-connection of weight exactly 1 preserves the gradient perfectly, why did Gers, Schmidhuber & Cummins (2000) add a gate that makes it smaller?
Because a memory that can never forget keeps accumulating. On a continual input stream with no natural sequence boundaries, the original LSTM's cell states grew without bound and the network broke down. A learned forget gate lets a cell reset itself when its content is no longer needed. Gers and colleagues showed that standard LSTMs failed on a continual version of a grammar-learning benchmark that LSTMs with forget gates solved. The forget gate is now part of every LSTM.
The LSTM cell
With input , hidden state and cell state , an LSTM layer computes three sigmoid gates and a tanh candidate from the same two inputs, then updates the cell additively:
import torch, torch.nn as nn
class LSTMCell(nn.Module):
def __init__(self, d, n, forget_bias=1.0):
super().__init__()
self.lin = nn.Linear(d + n, 4 * n) # all four blocks in one matmul
with torch.no_grad():
self.lin.bias[n:2 * n].fill_(forget_bias) # block order: i, f, g, o
def forward(self, x, state):
h, c = state
i, f, g, o = self.lin(torch.cat([x, h], dim=-1)).chunk(4, dim=-1)
i, f, o = torch.sigmoid(i), torch.sigmoid(f), torch.sigmoid(o)
c = f * c + i * torch.tanh(g) # the additive cell update
h = o * torch.tanh(c)
return h, (h, c)One matrix of shape computes all four pre-activations at once, which is also how library implementations work. torch.nn.LSTM orders its blocks the same way (input, forget, candidate, output) but keeps two bias vectors per layer.
Parameter count. Each of the four blocks has an matrix, an matrix and biases, so an LSTM layer has parameters, four times a vanilla RNN layer's ; with PyTorch's two bias vectors, . The cost per step is four times a vanilla step's, and the work is just as sequential in time.
An LSTM layer has units and reads -dimensional inputs. How many parameters does it have, using ?
Show the answer
394240 parameters
. A vanilla layer of the same size has and a GRU . PyTorch's nn.LSTM reports , the extra being its second bias vector.
How gradients survive
The cell state is the carousel with a learned leak. To see what reaches from , differentiate the cell update. Every gate depends on , so besides the direct term there are terms through the gates.
Differentiate with the product rule. The first term is the direct path; the others pass through :
Each bracketed term contains a recurrent matrix and gate slopes, for example . These paths behave like a vanilla RNN's and can still shrink or grow. The direct term has no weight matrix at all:
Along the direct path, unit 's error is multiplied by , numbers the network controls. If its forget gate sits at a constant , the signal decays as , with a time constant of steps. Because , this path can never amplify, but it can carry a signal for hundreds of steps when is near 1.
Why the forget-gate bias matters. At initialization the gate's weighted inputs are small and . Since , the time scale is exactly : 2 steps at , 3.7 at , 8.4 at , 21 at . With the default zero bias the cell halves its memory, and its gradient, at every step before learning has begun. Gers et al. (2000) already advocated positive forget biases, and Jozefowicz, Zaremba & Sutskever (2015) found that a bias of 1 closed the gap they had measured between the LSTM and the GRU. The Emergence lesson Gating, Time Scales & Chrono Initialization derives a principled choice.
What forget-gate bias makes when the gate's other inputs are zero?
Show the answer
4.6
Invert the sigmoid: . The time scale is steps. Every extra unit of bias multiplies the time scale by about , so a few units of bias span orders of magnitude of memory.
The GRU
The gated recurrent unit (Cho et al., 2014), introduced alongside the RNN encoder–decoder, keeps the gating idea with less machinery: two gates, no separate cell and no output gate. The hidden state itself is the gated memory.
Read the last line as an LSTM with the input gate tied to the forget gate (, with played by ), no output gate and the cell equal to the hidden state. The direct path through time now has factor , so a unit whose update gate stays near 1 carries both its memory and its gradient across many steps. With three blocks instead of four, a GRU layer has parameters.
| Property | Vanilla RNN | LSTM | GRU |
|---|---|---|---|
| State | and cell | ||
| Gates | none | input, forget, output | reset, update |
| Parameters per layer | |||
| Direct path back one step | on the cell | on the state | |
| State range | with tanh | cell unbounded; |
In the GRU above, one unit's update gate stays at for many steps. What happens to that unit?
- It is overwritten by the candidate at almost every step
- Its reset gate takes over and erases it
- It keeps almost all of its state, the candidate barely enters, and the gradient passes back with a factor near 0.99 per step along the direct path
- Its gradient explodes, since is close to 1
Show the answer
C. It keeps almost all of its state, the candidate barely enters, and the gradient passes back with a factor near 0.99 per step along the direct path
: the unit is a slow memory with a time scale of about 100 steps, and the direct-path factor lets gradients survive just as long.
LSTMs in practice
Which parts of the cell matter? Greff, Srivastava, Koutník, Steunebrink & Schmidhuber (2017) compared the standard LSTM with eight variants on speech recognition, handwriting recognition and polyphonic music modeling, in 5,400 runs worth about 15 years of CPU time. None of the variants improved significantly on the standard cell. Removing the forget gate or the output activation (the tanh on ) hurt most; coupling the input and forget gates, or dropping the peephole connections that let gates see the cell state (Gers & Schmidhuber, 2000), cost little. Their analysis of hyperparameters found them nearly independent of each other, so they can be tuned one at a time.
Jozefowicz, Zaremba & Sutskever (2015) evaluated over ten thousand recurrent architectures found by search. Some beat both the LSTM and the GRU on some tasks, none on all, and simply adding 1 to the LSTM's forget-gate bias closed the gap between the LSTM and the GRU. Chung et al. (2014) found GRUs and LSTMs comparable, and both clearly better than tanh RNNs.
A practical recipe follows. Initialize the forget-gate bias at 1 or more (or with chrono initialization), clip the gradient norm, and consider layer normalization of the gate pre-activations, which Ba, Kiros & Hinton (2016) introduced partly for recurrent networks: its statistics are computed separately at every time step, so it behaves the same in training and testing and needs no running averages. For dropout, apply it to the connections between layers rather than to the recurrent connections (Zaremba, Sutskever & Vinyals, 2014), or sample one dropout mask per sequence and reuse it at every step (Gal & Ghahramani, 2016), so that the recurrence does not see fresh noise at every step.
Key takeaways
- The constant error carousel, a self-connection of weight 1, lets error flow back unchanged; the LSTM guards it with input and output gates, and the forget gate (Gers et al., 2000) makes forgetting learnable.
- An LSTM layer computes , , and , with parameters.
- contains , a path with no weight matrix that cannot amplify; with at initialization the memory lasts about steps, hence forget biases of 1 or more. Paths through can still explode.
- The GRU uses a reset and an update gate and no cell, with parameters; with multiplying the old state (Cho et al., PyTorch), a larger update-gate bias means a longer memory. GRUs and LSTMs perform comparably.
- Ablations find the forget gate and output activation critical and most variants unnecessary; in practice add a positive forget bias, gradient clipping, per-step layer normalization, and dropout that does not resample noise on the recurrent path at every step.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
How does the parameter count of an LSTM layer with units and inputs compare with a vanilla RNN layer of the same size?
- It is the same, since the gates have no weights of their own
- It is four times larger, : the input, forget and output gates and the candidate each have their own , and bias
- It is twice as large, because of the separate cell state
- It is times larger, because each unit has its own gates
Show the answer
B. It is four times larger, : the input, forget and output gates and the candidate each have their own , and bias
Each of the four blocks is a full recurrent layer's worth of weights: recurrent, input, biases. The cell state adds no parameters, only computation and memory.
Which statement about gradient flow in an LSTM is correct?
- The direct path through the cell multiplies the gradient by the forget gates, with no weight matrix, so it cannot grow along that path; the paths through can still vanish or explode
- LSTMs make exploding gradients impossible, so clipping is unnecessary
- The output gate alone decides whether gradients survive
- Gradients flow only through ; the cell state is not differentiated
Show the answer
A. The direct path through the cell multiplies the gradient by the forget gates, with no weight matrix, so it cannot grow along that path; the paths through can still vanish or explode
contains plus terms through the gates and . The first is a product of numbers below 1 that the network can hold near 1; the others involve recurrent matrices and behave like a vanilla RNN's Jacobians.
Why is the LSTM's forget-gate bias usually initialized at 1 or more rather than 0?
- To make the cell state larger, which speeds up the forward pass
- To make the LSTM equivalent to a GRU
- Because a zero bias makes the forget gate output exactly 0, erasing the cell
- At zero bias the gate starts near , a memory of about steps; a bias of gives about steps, so gradients along the cell survive long enough for long-range learning to start
Show the answer
D. At zero bias the gate starts near , a memory of about steps; a bias of gives about steps, so gradients along the cell survive long enough for long-range learning to start
The time scale equals : 2 steps at , 3.7 at 1, 21 at 3. Early in training the gate inputs are small, so the bias alone sets how long memories and gradients last.
In the convention , what does a large positive bias on the update gate do at initialization?
- It makes the unit replace its state with the candidate at every step
- It switches off the reset gate
- It pushes toward 1, so units keep their old state longer: a longer memory and longer-lived gradients
- It has no effect, since the update gate's bias is always cancelled by the reset gate
Show the answer
C. It pushes toward 1, so units keep their old state longer: a longer memory and longer-lived gradients
Here multiplies the old state, so it plays the LSTM forget gate's role and a large bias lengthens memory. In the opposite convention the same bias would shorten it.
What did the large ablation study of Greff et al. (2017) find about LSTM variants?
- Peephole connections are essential; removing them breaks the LSTM
- No variant significantly beat the standard LSTM; the forget gate and the output activation were the most critical components
- Every gate can be removed without loss, given enough units
- The GRU outperformed every LSTM variant on every task
Show the answer
B. No variant significantly beat the standard LSTM; the forget gate and the output activation were the most critical components
Across speech, handwriting and music tasks and 5,400 runs, simplifications such as coupled input and forget gates or no peepholes cost little, while removing the forget gate or the output activation hurt substantially.
Go deeper
- Gating, Time Scales & Chrono Initialization · Why gates are learned time constants, and how to initialize them.
- Fast Weights & Test-Time Memory · From fast-weight programmers and the delta rule to layers whose memory learns while reading.
- Recurrence Returns: xLSTM & Parallel RNNs · Exponential gating, matrix memories and recurrent networks that train in parallel.
Further reading
- S. Hochreiter & J. Schmidhuber, "Long short-term memory," Neural Computation 9(8), 1735–1780 (1997).
- F. A. Gers, J. Schmidhuber & F. Cummins, "Learning to forget: Continual prediction with LSTM," Neural Computation 12(10), 2451–2471 (2000).
- K. Cho, B. van Merriënboer, C. Gulcehre, D. Bahdanau, F. Bougares, H. Schwenk & Y. Bengio, "Learning phrase representations using RNN encoder–decoder for statistical machine translation," EMNLP (2014).
- K. Greff, R. K. Srivastava, J. Koutník, B. R. Steunebrink & J. Schmidhuber, "LSTM: A search space odyssey," IEEE Transactions on Neural Networks and Learning Systems (2017).
- R. Jozefowicz, W. Zaremba & I. Sutskever, "An empirical exploration of recurrent network architectures," ICML (2015).