Level 3 In-Depth AI · Deep Learning
LSTMs and GRUs
Recurrent networks with gates that decide what to remember, what to forget and what to output. A separate memory line, the cell state, lets them keep information for hundreds of steps.
- Level
- ●●●●● Intermediate
- Reading
- 11 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 19 concepts →
- Quiz
- 4 questions ↓
This leads to
Sequence-to-Sequence ModelsThe full path from zero — 19 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- LSTMs and GRUs
Read them roughly in this order. See it on the concept map →
Why it matters
The recurrent network of the previous chapter has a short memory. Its hidden state is rewritten at every step by a multiply-and-squash. Information from 50 steps ago gets multiplied by about 50 factors smaller than one, so it fades away, and so does the training signal that could have taught the network to keep it (Vanishing and Exploding Gradients).
The long short-term memory network, or LSTM, fixes this. Its name means a short-term memory (the hidden state of an RNN) that lasts a long time. It adds a second memory line, the cell state, which is changed only by careful, gated additions. Information can ride along that line for hundreds of steps almost untouched.
LSTMs were the workhorse of sequence modelling for about five years. Google's neural machine translation system (2016) was a deep LSTM (Sequence-to-Sequence Models). Speech recognisers, handwriting recognisers and keyboard next-word predictors used them. ELMo (2018), one of the first big pretrained language models, was built from LSTMs. OpenAI Five, which beat world champions at the video game Dota 2 in 2019, had an LSTM at its core. Transformers have since taken over most language tasks, but LSTMs and their simpler cousin the GRU are still a sensible choice for small streaming problems such as sensor data, Time Series Forecasting and on-device models. Their central idea, an additive memory path controlled by gates, reappears in Residual Connections and in modern recurrent designs.
The intuition
Think of the cell state as a conveyor belt running through the whole sequence. Items on the belt travel along unchanged unless someone deliberately acts on them. Beside the belt stand three workers, each operating a valve:
- The forget gate decides what to remove from the belt. "We've reached a new sentence, so drop the old subject."
- The input gate decides what new information to put on the belt. "Here is a new subject: 'the dogs', plural."
- The output gate decides what part of the belt to read out right now as the hidden state. "The next word is a verb, so expose the number of the subject: plural, hence 'are', not 'is'."
Each gate is a small neural layer with a sigmoid output: a number between 0 (closed) and 1 (open) for every slot of the memory. Gates don't hold information themselves. They multiply other signals to let them through, partly, or not at all. And all three are learned: Backpropagation tunes them so the network keeps what turns out to be useful.
Key idea An LSTM keeps a separate cell state that is updated by addition, scaled by a learned forget gate. When the forget gate is near 1, information and gradients pass through many steps almost unchanged. That is what lets LSTMs learn long-range dependencies.
How it works
The equations
At each step the cell reads the current input and the previous hidden state . It computes three gates and one candidate, all from the same two inputs, each with its own weights. is the sigmoid, which outputs values between 0 and 1. In words: how much to forget, how much to write, what to write, and how much to show.
Then the two updates that matter. The new cell state keeps a fraction of the old one and adds a fraction of the candidate. The new hidden state is a gated, squashed view of the cell state:
The symbol means element-by-element multiplication: slot 1 times slot 1, slot 2 times slot 2, and so on. The $\mathbf{W}$s and $\mathbf{U}$s are weight matrices and the $\mathbf{b}$s are biases. That is four times the weights of a vanilla RNN with the same hidden size.
A worked example by hand
Take a one-slot LSTM. The previous cell state is , and suppose the gate layers have produced these pre-activations: forget 2.0, input −1.0, candidate 0.5, output 1.0.
- Forget gate: . Keep 88% of the old memory.
- Input gate: . Let in about a quarter of the new information.
- Candidate: .
- New cell state: .
- Output gate: .
- New hidden state: .
Most of the old memory survived, a little new information was added, and the hidden state shows about 73% of the squashed memory.
Why the gradient survives
The trick is in step 4. Ignoring the gates' own dependence on the past, the derivative of the new cell state with respect to the old one is simply
There is no weight matrix and no squashing tanh in that path, just the forget gate. Going back 100 steps multiplies 100 forget-gate values together. If the network has learned to keep the gate near 1 for a memory it needs, the product stays large:
This path is what Hochreiter and Schmidhuber called the constant error carousel: an additive self-loop along which the error signal can travel without shrinking. It is the same idea that Residual Connections later applied to depth: a path where the signal is added to, not repeatedly transformed. And because the forget gate depends on the input, the network can also choose to erase memory, which a plain residual path can't do.
Exploding gradients are still possible through the other paths, so LSTM training loops still clip gradients.
GRU: a simpler gated unit
The gated recurrent unit (GRU), introduced by Kyunghyun Cho and colleagues in 2014, merges the cell state and hidden state into one, and uses two gates instead of three:
The update gate blends old and new: near 0 it keeps the old state, near 1 it replaces it. One gate does the job of the LSTM's forget and input gates together. The reset gate decides how much of the past to use when proposing the candidate. (Some sources, including PyTorch's documentation, swap the roles of and . The idea is the same.)
GRUs have three weight blocks instead of four, so they are about 25% smaller and faster than an LSTM of the same hidden size. Comparisons have found the two roughly equal on many tasks, with neither consistently ahead. The sensible approach is to try both.
LSTM or GRU or Transformer?
| LSTM | GRU | Transformer | |
|---|---|---|---|
| Memory per step at inference | fixed (cell + hidden) | fixed (hidden) | grows with context (The KV Cache and Fast Inference) |
| Training parallel over time | no | no | yes |
| Long-range recall | hundreds of steps | hundreds of steps | anything in the context window |
| Good fit today | streaming, small devices, time series | same, slightly cheaper | most language and large-scale tasks |
In code
A test that a vanilla RNN fails and an LSTM passes. Each sequence has 30 steps of random +1/−1 values. One of the first five steps is marked, and the label is the value at the marked step. The network must store that one value and ignore the 25 or more distracting values after it.
import torch
import torch.nn as nn
T = 30 # sequence length
def make_batch(n):
"""Each step holds a random +1/-1 and a marker bit. The label is the value
at the single marked step (somewhere in the first 5). Everything after it is distraction."""
vals = torch.randint(0, 2, (n, T)).float() * 2 - 1
pos = torch.randint(0, 5, (n,))
marker = torch.zeros(n, T)
marker[torch.arange(n), pos] = 1
y = (vals[torch.arange(n), pos] > 0).long()
return torch.stack([vals, marker], dim=2), y # shape (n, T, 2)
class Classifier(nn.Module):
def __init__(self, cell):
super().__init__()
self.rnn = cell(input_size=2, hidden_size=32, batch_first=True)
self.head = nn.Linear(32, 2)
def forward(self, x):
out, _ = self.rnn(x)
return self.head(out[:, -1]) # predict from the state after the LAST step
torch.manual_seed(0)
x_test, y_test = make_batch(1000)
for name, cell in [("RNN", nn.RNN), ("LSTM", nn.LSTM)]:
torch.manual_seed(1)
model = Classifier(cell)
if name == "LSTM": # common trick: start with the forget gate open
with torch.no_grad(): # PyTorch gate order: input, forget, cell, output
model.rnn.bias_ih_l0[32:64].fill_(1.0)
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
for step in range(600):
x, y = make_batch(64)
loss = nn.functional.cross_entropy(model(x), y)
opt.zero_grad(); loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
with torch.no_grad():
acc = (model(x_test).argmax(1) == y_test).float().mean().item()
print(f"{name:4} final loss {loss.item():.3f} test accuracy {acc:.3f}")
# RNN final loss 0.690 test accuracy 0.500
# LSTM final loss 0.000 test accuracy 1.000
The RNN never gets past guessing (loss 0.69 = ). The LSTM solves it perfectly. Its input gate learns to open at the marker, and its forget gate stays near 1 afterwards. Note the line that sets the forget-gate bias to 1. Starting with the gate mostly open is a widely used trick, recommended for example by Jozefowicz, Zaremba and Sutskever (2015). In our runs the LSTM without it was still guessing after 1,000 steps on this task.
Common pitfalls
- Forget-gate bias left at zero. Then , and the cell starts out halving its memory every step, which is not much better than a vanilla RNN. Initialise it to 1 (some libraries, such as Keras, do this by default; PyTorch does not).
- Reading the wrong output.
nn.LSTMreturnsoutput, (h_n, c_n).outputholds the hidden state at every step,h_nonly the last one, per layer. For padded batches, the "last" step of a short sequence is notoutput[:, -1]. Use packed sequences or index by length. - Expecting unlimited memory. LSTMs remember far longer than vanilla RNNs, but the memory is still squeezed into one fixed-size vector. Translating a 50-word sentence through that bottleneck loses detail. That limitation is why Attention was invented (Sequence-to-Sequence Models).
- Slow training on long sequences. Every step waits for the previous one. Use cuDNN-backed
nn.LSTM(much faster than a hand-written loop), shorter truncated chunks, or a different architecture.
Watch out Gates make memory possible, not automatic. An LSTM still needs gradient clipping, sensible initialisation and enough training signal. If the dependency you care about is rare in the data, the network may never learn to keep it.
Where it leads
- Sequence-to-Sequence Models: two LSTMs, an encoder and a decoder, for translation, and the bottleneck that led to Attention.
- The Transformer: drops recurrence entirely and lets every position look at every other.
- State Space Models and Mamba: Mamba and related models bring back a fixed-size recurrent state with input-dependent ("selective") updates, gates by another name, while still training in parallel.
- xLSTM (2024), from Hochreiter's group, revisits the LSTM with exponential gating and a matrix memory to compete with Transformers at scale.
- Time Series Forecasting: LSTMs remain a common baseline for forecasting.
A bit of history
Sepp Hochreiter analysed the vanishing-gradient problem in his 1991 diploma thesis in Munich, supervised by Jürgen Schmidhuber. Together they published Long Short-Term Memory in 1997. The original design had input and output gates but no forget gate. Felix Gers, Schmidhuber and Fred Cummins added it in 2000 (Learning to Forget), and that version is the LSTM used today. In 2014 Cho and colleagues introduced the GRU while building an RNN encoder–decoder for translation. A large 2015 study, LSTM: A Search Space Odyssey by Klaus Greff and colleagues, tested eight variants and found that none beat the standard LSTM significantly, and that the forget gate and output activation mattered most. From 2014 to 2017 LSTMs powered state-of-the-art translation, speech recognition and language modelling, before the 2017 Transformer took their place in most of those roles.
Try it
- In the code, add
("GRU", nn.GRU)to the list. Does the GRU solve the task? Try initialising its gate biases too: PyTorch's GRU gate order is reset, update, new.- Remove the forget-bias line and train the LSTM for 2,000 steps. Does it eventually learn? Then increase
Tto 100 with the bias line restored.- By hand: repeat the worked example with forget pre-activation −2.0 instead of 2.0. What happens to , and what does that gate value mean?
Hint for 3: , so . The cell has mostly forgotten its old content.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Understanding LSTM Networks
The clearest explanation of LSTMs ever written, with the diagrams everyone copies.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Long Short-Term Memory
Introduced the LSTM cell, which solved the vanishing-gradient problem for recurrent networks.
Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation
Introduced the gated recurrent unit (GRU) and an RNN encoder–decoder for translation.
Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling
Head-to-head comparison of LSTMs, GRUs and vanilla RNNs on music and speech data.
LSTM: A Search Space Odyssey
A large study of eight LSTM variants. None beat the standard design; the forget gate and output activation matter most.
xLSTM: Extended Long Short-Term Memory
Revisits the LSTM with exponential gating and matrix memories to compete with Transformers at scale.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/lstm.md