Simple Algorithm
Deep Learning · Representation · 24 min

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: 4n(n+d+1)4n(n+d+1) and 3n(n+d+1)3n(n+d+1), four and three times a vanilla layer.
  • Explain the constant error carousel and derive ∂ct/∂ct−1=diag⁡(ft)+(terms through ht−1)\partial\mathbf c_t/\partial\mathbf c_{t-1}=\operatorname{diag}(\mathbf f_t)+(\text{terms through }\mathbf h_{t-1}), with its consequences for gradient flow.
  • Relate the forget-gate bias to the memory time scale 1/(1−σ(bf))=1+ebf1/(1-\sigma(b_f))=1+e^{b_f}, 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 diag⁡(ϕ′(at))W\operatorname{diag}(\phi'(\mathbf a_t))W, 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, ct=ct−1+(inputt)c_t=c_{t-1}+(\text{input}_t). Its local factor is ∂ct/∂ct−1=1\partial c_t/\partial c_{t-1}=1, 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 xt∈Rd\mathbf x_t\in\R^d, hidden state ht∈Rn\mathbf h_t\in\R^n and cell state ct∈Rn\mathbf c_t\in\R^n, an LSTM layer computes three sigmoid gates and a tanh candidate from the same two inputs, then updates the cell additively:

it=σ(Wiht−1+Uixt+bi)input gateft=σ(Wfht−1+Ufxt+bf)forget gateot=σ(Woht−1+Uoxt+bo)output gategt=tanh⁡(Wght−1+Ugxt+bg)candidatect=ft⊙ct−1+it⊙gt,ht=ot⊙tanh⁡(ct)\begin{aligned}\mathbf i_t&=\sigma(W_i\mathbf h_{t-1}+U_i\mathbf x_t+\mathbf b_i)&&\text{input gate}\\ \mathbf f_t&=\sigma(W_f\mathbf h_{t-1}+U_f\mathbf x_t+\mathbf b_f)&&\text{forget gate}\\ \mathbf o_t&=\sigma(W_o\mathbf h_{t-1}+U_o\mathbf x_t+\mathbf b_o)&&\text{output gate}\\ \mathbf g_t&=\tanh(W_g\mathbf h_{t-1}+U_g\mathbf x_t+\mathbf b_g)&&\text{candidate}\\ \mathbf c_t&=\mathbf f_t\odot\mathbf c_{t-1}+\mathbf i_t\odot\mathbf g_t,\qquad\mathbf h_t=\mathbf o_t\odot\tanh(\mathbf c_t)\end{aligned}
σ\sigma is the logistic sigmoid and ⊙\odot the elementwise product. Each W∙W_\bullet is n×nn\times n, each U∙U_\bullet is n×dn\times d. The gates are values in (0,1)(0,1) computed per unit and per step, so the cell can decide, unit by unit and moment by moment, what to keep, write and reveal.
python
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 4n×(d+n)4n\times(d+n) 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 n×nn\times n matrix, an n×dn\times d matrix and nn biases, so an LSTM layer has 4n(n+d+1)4n(n+d+1) parameters, four times a vanilla RNN layer's n(n+d+1)n(n+d+1); with PyTorch's two bias vectors, 4n(n+d+2)4n(n+d+2). The cost per step is four times a vanilla step's, and the work is just as sequential in time.

Predict before you look

An LSTM layer has n=256n=256 units and reads d=128d=128-dimensional inputs. How many parameters does it have, using 4n(n+d+1)4n(n+d+1)?

Show the answer

394240 parameters

4×256×(256+128+1)=4×256×385=394,2404\times256\times(256+128+1)=4\times256\times385=394{,}240. A vanilla layer of the same size has 98,56098{,}560 and a GRU 3×98,560=295,6803\times98{,}560=295{,}680. PyTorch's nn.LSTM reports 395,264395{,}264, the extra 1,0241{,}024 being its second bias vector.

How gradients survive

The cell state is the carousel with a learned leak. To see what reaches ct−1\mathbf c_{t-1} from ct\mathbf c_t, differentiate the cell update. Every gate depends on ht−1=ot−1⊙tanh⁡(ct−1)\mathbf h_{t-1}=\mathbf o_{t-1}\odot\tanh(\mathbf c_{t-1}), so besides the direct term there are terms through the gates.

DerivationThe Jacobian of the cell update
  1. ∂ct∂ct−1=diag⁡(ft)+[diag⁡(ct−1)∂ft∂ht−1+diag⁡(gt)∂it∂ht−1+diag⁡(it)∂gt∂ht−1]∂ht−1∂ct−1\frac{\partial\mathbf c_t}{\partial\mathbf c_{t-1}}=\operatorname{diag}(\mathbf f_t)+\Big[\operatorname{diag}(\mathbf c_{t-1})\frac{\partial\mathbf f_t}{\partial\mathbf h_{t-1}}+\operatorname{diag}(\mathbf g_t)\frac{\partial\mathbf i_t}{\partial\mathbf h_{t-1}}+\operatorname{diag}(\mathbf i_t)\frac{\partial\mathbf g_t}{\partial\mathbf h_{t-1}}\Big]\frac{\partial\mathbf h_{t-1}}{\partial\mathbf c_{t-1}}

    Differentiate ct=ft⊙ct−1+it⊙gt\mathbf c_t=\mathbf f_t\odot\mathbf c_{t-1}+\mathbf i_t\odot\mathbf g_t with the product rule. The first term is the direct path; the others pass through ht−1\mathbf h_{t-1}:

  2. ∂ht−1∂ct−1=diag⁡(ot−1⊙(1−tanh⁡2ct−1)),direct path over m steps: ∏j=t−m+1tdiag⁡(fj)\frac{\partial\mathbf h_{t-1}}{\partial\mathbf c_{t-1}}=\operatorname{diag}\big(\mathbf o_{t-1}\odot(1-\tanh^2\mathbf c_{t-1})\big),\qquad\text{direct path over }m\text{ steps: }\prod_{j=t-m+1}^{t}\operatorname{diag}(\mathbf f_j)

    Each bracketed term contains a recurrent matrix and gate slopes, for example ∂ft/∂ht−1=diag⁡(ft⊙(1−ft)) Wf\partial\mathbf f_t/\partial\mathbf h_{t-1}=\operatorname{diag}(\mathbf f_t\odot(1-\mathbf f_t))\,W_f. These paths behave like a vanilla RNN's and can still shrink or grow. The direct term has no weight matrix at all:

  3. fm=emln⁡f≈e−m(1−f)⟹τ≈11−f stepsf^m=e^{m\ln f}\approx e^{-m(1-f)}\qquad\Longrightarrow\qquad\tau\approx\frac1{1-f}\ \text{steps}

    Along the direct path, unit ii's error is multiplied by ∏jfj,i\prod_jf_{j,i}, numbers the network controls. If its forget gate sits at a constant ff, the signal decays as fm=emln⁡ff^m=e^{m\ln f}, with a time constant of −1/ln⁡f≈1/(1−f)-1/\ln f\approx1/(1-f) steps. Because f<1f<1, this path can never amplify, but it can carry a signal for hundreds of steps when ff is near 1.

Why the forget-gate bias matters. At initialization the gate's weighted inputs are small and f≈σ(bf)f\approx\sigma(b_f). Since 1−σ(b)=σ(−b)=1/(1+eb)1-\sigma(b)=\sigma(-b)=1/(1+e^{b}), the time scale is exactly 1/(1−σ(bf))=1+ebf1/(1-\sigma(b_f))=1+e^{b_f}: 2 steps at bf=0b_f=0, 3.7 at bf=1b_f=1, 8.4 at bf=2b_f=2, 21 at bf=3b_f=3. 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.

Predict before you look

What forget-gate bias makes f=0.99f=0.99 when the gate's other inputs are zero?

Show the answer

4.6

Invert the sigmoid: bf=ln⁡(f/(1−f))=ln⁡99≈4.60b_f=\ln\big(f/(1-f)\big)=\ln99\approx4.60. The time scale is 1+e4.6≈1001+e^{4.6}\approx100 steps. Every extra unit of bias multiplies the time scale by about e≈2.7e\approx2.7, 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.

rt=σ(Wrht−1+Urxt+br)reset gatezt=σ(Wzht−1+Uzxt+bz)update gateh~t=tanh⁡(Wh(rt⊙ht−1)+Uhxt+bh)candidateht=zt⊙ht−1+(1−zt)⊙h~t\begin{aligned}\mathbf r_t&=\sigma(W_r\mathbf h_{t-1}+U_r\mathbf x_t+\mathbf b_r)&&\text{reset gate}\\ \mathbf z_t&=\sigma(W_z\mathbf h_{t-1}+U_z\mathbf x_t+\mathbf b_z)&&\text{update gate}\\ \tilde{\mathbf h}_t&=\tanh\big(W_h(\mathbf r_t\odot\mathbf h_{t-1})+U_h\mathbf x_t+\mathbf b_h\big)&&\text{candidate}\\ \mathbf h_t&=\mathbf z_t\odot\mathbf h_{t-1}+(1-\mathbf z_t)\odot\tilde{\mathbf h}_t\end{aligned}
In this convention, Cho et al.'s and PyTorch's, the update gate zt\mathbf z_t multiplies the old state: zt≈1\mathbf z_t\approx1 keeps it, zt≈0\mathbf z_t\approx0 replaces it with the candidate. A reset gate near 0 lets the candidate ignore the old state, for instance at a phrase boundary. PyTorch applies the reset gate after the matrix product, rt⊙(Whht−1+b)\mathbf r_t\odot(W_h\mathbf h_{t-1}+\mathbf b), a minor variant.

Read the last line as an LSTM with the input gate tied to the forget gate (i=1−f\mathbf i=1-\mathbf f, with f\mathbf f played by z\mathbf z), no output gate and the cell equal to the hidden state. The direct path through time now has factor diag⁡(zt)\operatorname{diag}(\mathbf z_t), 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 3n(n+d+1)3n(n+d+1) parameters.

PropertyVanilla RNNLSTMGRU
Stateht\mathbf h_tht\mathbf h_t and cell ct\mathbf c_tht\mathbf h_t
Gatesnoneinput, forget, outputreset, update
Parameters per layern(n+d+1)n(n+d+1)4n(n+d+1)4n(n+d+1)3n(n+d+1)3n(n+d+1)
Direct path back one stepdiag⁡(ϕ′(at))W\operatorname{diag}(\phi'(\mathbf a_t))Wdiag⁡(ft)\operatorname{diag}(\mathbf f_t) on the celldiag⁡(zt)\operatorname{diag}(\mathbf z_t) on the state
State range(−1,1)(-1,1) with tanhcell unbounded; ht∈(−1,1)\mathbf h_t\in(-1,1)[−1,1][-1,1]
The unbounded LSTM cell is what lets it count; the GRU's bounded state cannot (the Emergence lesson What Recurrent Networks Can Compute).
Check your understanding

In the GRU above, one unit's update gate stays at z≈0.99z\approx0.99 for many steps. What happens to that unit?

  1. It is overwritten by the candidate at almost every step
  2. Its reset gate takes over and erases it
  3. 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
  4. Its gradient explodes, since zz 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

ht=0.99 ht−1+0.01 h~th_t=0.99\,h_{t-1}+0.01\,\tilde h_t: the unit is a slow memory with a time scale of about 100 steps, and the direct-path factor diag⁡(zt)\operatorname{diag}(\mathbf z_t) 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 ct\mathbf c_t) 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 i,f,o=σ(⋅)\mathbf i,\mathbf f,\mathbf o=\sigma(\cdot), g=tanh⁡(⋅)\mathbf g=\tanh(\cdot), ct=ft⊙ct−1+it⊙gt\mathbf c_t=\mathbf f_t\odot\mathbf c_{t-1}+\mathbf i_t\odot\mathbf g_t and ht=ot⊙tanh⁡(ct)\mathbf h_t=\mathbf o_t\odot\tanh(\mathbf c_t), with 4n(n+d+1)4n(n+d+1) parameters.
  • ∂ct/∂ct−1\partial\mathbf c_t/\partial\mathbf c_{t-1} contains diag⁡(ft)\operatorname{diag}(\mathbf f_t), a path with no weight matrix that cannot amplify; with f≈σ(bf)f\approx\sigma(b_f) at initialization the memory lasts about 1+ebf1+e^{b_f} steps, hence forget biases of 1 or more. Paths through h\mathbf h can still explode.
  • The GRU uses a reset and an update gate and no cell, with 3n(n+d+1)3n(n+d+1) parameters; with z\mathbf z 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.

Question 1

How does the parameter count of an LSTM layer with nn units and dd inputs compare with a vanilla RNN layer of the same size?

  1. It is the same, since the gates have no weights of their own
  2. It is four times larger, 4n(n+d+1)4n(n+d+1): the input, forget and output gates and the candidate each have their own WW, UU and bias
  3. It is twice as large, because of the separate cell state
  4. It is nn times larger, because each unit has its own gates
Show the answer

B. It is four times larger, 4n(n+d+1)4n(n+d+1): the input, forget and output gates and the candidate each have their own WW, UU and bias

Each of the four blocks is a full recurrent layer's worth of weights: n×nn\times n recurrent, n×dn\times d input, nn biases. The cell state adds no parameters, only computation and memory.

Question 2

Which statement about gradient flow in an LSTM is correct?

  1. 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 ht−1\mathbf h_{t-1} can still vanish or explode
  2. LSTMs make exploding gradients impossible, so clipping is unnecessary
  3. The output gate alone decides whether gradients survive
  4. Gradients flow only through ht\mathbf h_t; 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 ht−1\mathbf h_{t-1} can still vanish or explode

∂ct/∂ct−1\partial\mathbf c_t/\partial\mathbf c_{t-1} contains diag⁡(ft)\operatorname{diag}(\mathbf f_t) plus terms through the gates and ht−1\mathbf h_{t-1}. 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.

Question 3

Why is the LSTM's forget-gate bias usually initialized at 1 or more rather than 0?

  1. To make the cell state larger, which speeds up the forward pass
  2. To make the LSTM equivalent to a GRU
  3. Because a zero bias makes the forget gate output exactly 0, erasing the cell
  4. At zero bias the gate starts near σ(0)=0.5\sigma(0)=0.5, a memory of about 1+e0=21+e^0=2 steps; a bias of bb gives about 1+eb1+e^{b} 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 σ(0)=0.5\sigma(0)=0.5, a memory of about 1+e0=21+e^0=2 steps; a bias of bb gives about 1+eb1+e^{b} steps, so gradients along the cell survive long enough for long-range learning to start

The time scale 1/(1−σ(bf))1/(1-\sigma(b_f)) equals 1+ebf1+e^{b_f}: 2 steps at bf=0b_f=0, 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.

Question 4

In the convention ht=zt⊙ht−1+(1−zt)⊙h~t\mathbf h_t=\mathbf z_t\odot\mathbf h_{t-1}+(1-\mathbf z_t)\odot\tilde{\mathbf h}_t, what does a large positive bias on the update gate do at initialization?

  1. It makes the unit replace its state with the candidate at every step
  2. It switches off the reset gate
  3. It pushes zt\mathbf z_t toward 1, so units keep their old state longer: a longer memory and longer-lived gradients
  4. It has no effect, since the update gate's bias is always cancelled by the reset gate
Show the answer

C. It pushes zt\mathbf z_t toward 1, so units keep their old state longer: a longer memory and longer-lived gradients

Here z\mathbf z 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.

Question 5

What did the large ablation study of Greff et al. (2017) find about LSTM variants?

  1. Peephole connections are essential; removing them breaks the LSTM
  2. No variant significantly beat the standard LSTM; the forget gate and the output activation were the most critical components
  3. Every gate can be removed without loss, given enough units
  4. 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

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).