Contents Language Models Code Course home

Chapter 13Gated Recurrence: LSTM and GRU

Addition instead of multiplication

Chapter 12 left the recurrent network with a precise complaint rather than a vague one. Equation (12.5) showed that a gradient travelling back through time is multiplied by one Jacobian per step, and each Jacobian is diag⁡(tanh⁡′)U\operatorname{diag}(\tanh')\,U, 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 exactly that, keeping a memory that is updated by addition and learning how much of the old memory to carry forward.

The LSTM cell. The cell state runs across the top with only two interactions, one multiplication by the forget gate and one addition of new content. The gates below decide both quantities.

The LSTM cell

The long short-term memory network (Hochreiter and Schmidhuber 1997) carries two vectors rather than one, where the cell state CtC_t is the memory and the hidden state hth_t 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 00 and 11.

ft=σ(Wf[ht−1,xt]+bf)(forget gate),it=σ(Wi[ht−1,xt]+bi)(input gate),ot=σ(Wo[ht−1,xt]+bo)(output gate),C̃t=tanh⁡(WC[ht−1,xt]+bC)(candidate).\begin{align} f_t &= \sigma\!\big(W_f\,[h_{t-1}, x_t] + b_f\big) && \text{(forget gate)}, \label{eq:lstm-f}\\ i_t &= \sigma\!\big(W_i\,[h_{t-1}, x_t] + b_i\big) && \text{(input gate)}, \label{eq:lstm-i}\\ o_t &= \sigma\!\big(W_o\,[h_{t-1}, x_t] + b_o\big) && \text{(output gate)}, \label{eq:lstm-o}\\ \tilde{C}_t &= \tanh\!\big(W_C\,[h_{t-1}, x_t] + b_C\big) && \text{(candidate)}. \label{eq:lstm-cand} \end{align}

A gate value of 00 closes the channel completely while a value of 11 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 one line, and that line is the reason the architecture exists:

Ct=ft⊙Ct−1+it⊙C̃t.(13.1)\begin{equation} C_t \;=\; f_t \odot C_{t-1} \;+\; i_t \odot \tilde{C}_t . \label{eq:lstm-cell} \quad\text{(13.1)} \end{equation}

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:

ht=ot⊙tanh⁡(Ct).(13.2)\begin{equation} h_t \;=\; o_t \odot \tanh(C_t). \label{eq:lstm-h} \quad\text{(13.2)} \end{equation}

So the network can hold something in CtC_t for many steps without exposing it, revealing it only when the output gate opens.

Why this fixes the gradient

Differentiate Equation (13.1) along the cell state path, and the result is startlingly simple:

∂E∂Ct−1=ft⊙∂E∂Ct.(13.3)\begin{equation} \frac{\partial E}{\partial C_{t-1}} \;=\; f_t \odot \frac{\partial E}{\partial C_t}. \label{eq:lstm-grad} \quad\text{(13.3)} \end{equation}

There is no weight matrix and no tanh\tanh derivative, because the gradient is multiplied by the forget gate and nothing else. Compare the two routes directly.

distance RNN, factor 0.50.5 LSTM, f=0.9f = 0.9 LSTM, f=0.99f = 0.99
1 5.00×10−15.00 \times 10^{-1} 9.00×10−19.00 \times 10^{-1} 9.90×10−19.90 \times 10^{-1}
10 9.77×10−49.77 \times 10^{-4} 3.49×10−13.49 \times 10^{-1} 9.04×10−19.04 \times 10^{-1}
47 7.11×10−157.11 \times 10^{-15} 7.07×10−37.07 \times 10^{-3} 6.24×10−16.24 \times 10^{-1}
100 7.89×10−317.89 \times 10^{-31} 2.66×10−52.66 \times 10^{-5} 3.66×10−13.66 \times 10^{-1}
500 3.06×10−1513.06 \times 10^{-151} 1.32×10−231.32 \times 10^{-23} 6.57×10−36.57 \times 10^{-3}

At f=0.99f = 0.99 a gradient still carries a little under one per cent of its strength after 500500 steps, whereas at 0.50.5 it is gone before step 5050.

Be careful about what has changed, because the LSTM did not remove the decay but put the decay rate under the network’s control. That is enough, and it is the whole contribution, since ftf_t is learned and the network can therefore decide to keep a memory alive when the task rewards it, while diag⁡(tanh⁡′)U\operatorname{diag}(\tanh')\,U was never anybody’s decision.

The bias that decides everything

Here is a detail the lectures single out, and it is worth a section because skipping it is so common. At the start of training the weights are small and random, so Equation (13.4) gives ft≈σ(bf)f_t \approx \sigma(b_f), and the default initialisation sets bf=0b_f = 0, which makes ft≈0.5f_t \approx 0.5.

bfb_f σ(bf)\sigma(b_f) after 10 after 47 after 100
0 0.5000 9.77×10−49.77 \times 10^{-4} 7.11×10−157.11 \times 10^{-15} 7.89×10−317.89 \times 10^{-31}
1 0.7311 4.36×10−24.36 \times 10^{-2} 4.03×10−74.03 \times 10^{-7} 2.48×10−142.48 \times 10^{-14}
2 0.8808 2.81×10−12.81 \times 10^{-1} 2.57×10−32.57 \times 10^{-3} 3.07×10−63.07 \times 10^{-6}
3 0.9526 6.15×10−16.15 \times 10^{-1} 1.02×10−11.02 \times 10^{-1} 7.76×10−37.76 \times 10^{-3}
5 0.9933 9.35×10−19.35 \times 10^{-1} 7.29×10−17.29 \times 10^{-1} 5.11×10−15.11 \times 10^{-1}

Look at the first row against the previous table, where a default-initialised LSTM decays at exactly 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 bf=2b_f = 2 instead, as Gers et al. (2002) recommend, and ftf_t begins at 0.88080.8808, so that after 4747 steps the gradient retains 2.57×10−32.57 \times 10^{-3} rather than 7.11×10−157.11 \times 10^{-15}. That is 3.6×10113.6 \times 10^{11} 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.

One cell, worked

Take a cell with two units and an input of size two, and set bf=1b_f = 1 with every other bias at zero.

ht−1=(0.10,−0.20),Ct−1=(0.50,0.30),xt=(0.60,0.40).h_{t-1} = (0.10,\, -0.20), \qquad C_{t-1} = (0.50,\, 0.30), \qquad x_t = (0.60,\, 0.40).

Every gate reads the same concatenated vector:

q=[ht−1,xt]=(0.10,−0.20,0.60,0.40).q \;=\; [h_{t-1}, x_t] \;=\; (0.10,\, -0.20,\, 0.60,\, 0.40).

gate formula value
forget ft=σ(Wfq+bf)f_t = \sigma(W_f q + b_f) (+0.8038,+0.6964)(+0.8038,\, +0.6964)
input it=σ(Wiq+bi)i_t = \sigma(W_i q + b_i) (+0.5300,+0.5769)(+0.5300,\, +0.5769)
candidate C̃t=tanh⁡(WCq)\tilde{C}_t = \tanh(W_C q) (+0.0997,+0.2449)(+0.0997,\, +0.2449)
output ot=σ(Woq+bo)o_t = \sigma(W_o q + b_o) (+0.4651,+0.5842)(+0.4651,\, +0.5842)
cell Ct=ft⊙Ct−1+it⊙C̃tC_t = f_t \odot C_{t-1} + i_t \odot \tilde{C}_t (+0.4547,+0.3502)(+0.4547,\, +0.3502)
hidden ht=ot⊙tanh⁡(Ct)h_t = o_t \odot \tanh(C_t) (+0.1980,+0.1966)(+0.1980,\, +0.1966)

Split the cell update into its two terms and the arithmetic becomes plain enough.

kept from the past, ft⊙Ct−1f_t \odot C_{t-1} (+0.4019,+0.2089)(+0.4019,\, +0.2089)
added this step, it⊙C̃ti_t \odot \tilde{C}_t (+0.0528,+0.1413)(+0.0528,\, +0.1413)
new cell state, CtC_t (+0.4547,+0.3502)(+0.4547,\, +0.3502)

The forget gate sits at 0.800.80 and 0.700.70, so most of the old memory survives the very first step, which is the bf=1b_f = 1 initialisation already doing its job.

And notice how CtC_t was reached, which was by addition rather than by a matrix multiplication. That single structural fact is the difference from Equation (12.8), and it is why Equation (13.3) looks the way it does.

The GRU: the same trick, fewer parts

The gated recurrent unit (Cho et al. 2014) asks whether four gates were ever necessary, and it keeps one state vector instead of two with two gates instead of three.

zt=σ(Wz[ht−1,xt]+bz)(update gate),rt=σ(Wr[ht−1,xt]+br)(reset gate),h̃t=tanh⁡(W[rt⊙ht−1,xt]+b),ht=(1−zt)⊙ht−1+zt⊙h̃t.\begin{align} z_t &= \sigma\!\big(W_z\,[h_{t-1}, x_t] + b_z\big) && \text{(update gate)}, \label{eq:gru-z}\\ r_t &= \sigma\!\big(W_r\,[h_{t-1}, x_t] + b_r\big) && \text{(reset gate)}, \label{eq:gru-r}\\ \tilde{h}_t &= \tanh\!\big(W\,[\,r_t \odot h_{t-1},\; x_t\,] + b\big), \label{eq:gru-cand}\\ h_t &= (1 - z_t) \odot h_{t-1} \;+\; z_t \odot \tilde{h}_t. \label{eq:gru-h} \end{align}

The gated recurrent unit. One state vector, one update gate splitting it between old and new, and a reset gate deciding how much history the candidate may look at.

Equation (13.11) is the interesting line, because the coefficients are (1−zt)(1 - z_t) and ztz_t, 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 zt=σ(Wzq)z_t = \sigma(W_z q) (+0.6011,+0.4576)(+0.6011,\, +0.4576)
reset rt=σ(Wrq)r_t = \sigma(W_r q) (+0.5300,+0.5769)(+0.5300,\, +0.5769)
candidate h̃t=tanh⁡(W[rt⊙ht−1,xt])\tilde{h}_t = \tanh(W[\,r_t \odot h_{t-1}, x_t\,]) (+0.0894,+0.2739)(+0.0894,\, +0.2739)
hidden ht=(1−zt)⊙ht−1+zt⊙h̃th_t = (1 - z_t) \odot h_{t-1} + z_t \odot \tilde{h}_t (+0.0936,+0.0168)(+0.0936,\, +0.0168)

What a gate costs

Each gate reads a vector of length H+dH + d and produces HH numbers, so it costs H(H+d)+HH(H + d) + H parameters, and counting the gates gives the recurrent core of the model, leaving the embedding and output matrices 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 d=100d = 100 and H=500H = 500. A GRU is three quarters the size of an LSTM, which here is 300,500300{,}500 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 rather than on quality, and the GRU often wins on those.

Try it yourself. code/worked_examples/gated.py produces every table in this chapter. --highway compares the two decay routes, --bias shows what bfb_f does, --step runs the single cell through both architectures, and --params counts the gates.

Run it in ColabNotebookSource

The end of the recurrent road

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 Ct−1C_{t-1} before it can compute CtC_t, so the time steps cannot be computed in parallel however many processors are available. That is a hard ceiling on training speed, and it arrived exactly 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 removes that insistence by letting every position look directly at every other position with no intervening steps, so distance stops mattering and the computation parallelises because nothing waits for anything. That is attention, and it is the subject of Chapter 16.

Before that, one chapter closes Part III on a different note. 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 14 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.

Further reading.

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, which 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.

Trace one cell. Using the numbers of this chapter, verify ftf_t, iti_t, C̃t\tilde{C}_t and oto_t, then confirm CtC_t and hth_t. Now set ftf_t to zero by hand and recompute. What has the cell become, and what has it forgotten?

The gradient highway. Derive Equation (13.3) from Equation (13.1), treating ftf_t as constant. Then explain why the corresponding derivative for the plain RNN, Equation (12.6), cannot be made this simple.

Initialise it wrong. Compute the surviving gradient after 5050 steps for bf=0b_f = 0 and for bf=2b_f = 2. 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.

Count the gates. For d=200d = 200 and H=800H = 800, 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 dd and HH?

Tie the gates. The GRU uses (1−zt)(1 - z_t) and ztz_t where the LSTM uses independent ftf_t and iti_t. Describe a sequence for which the independent pair can do something the tied pair cannot. Then say why this rarely matters in practice.

What the reset gate is for. Set rt=1r_t = 1 in Equation (13.10) and describe the resulting unit. Now set rt=0r_t = 0. Which of the two settings would you expect at a topic boundary, and why?

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.

Count what the library allocates. Build torch.nn.RNN, torch.nn.GRU and torch.nn.LSTM at d=100d = 100 and H=500H = 500 and sum their parameters. You will get 301,000301{,}000, 903,000903{,}000 and 1,204,0001{,}204{,}000 against the 300,500300{,}500, 901,500901{,}500 and 1,202,0001{,}202{,}000 counted above, an excess of exactly 500500 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.

Code for this chapter

Each one reproduces the tables above. Open it in Colab, change an input and watch which numbers move.

From Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.