◆ AI All-in-One

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
↗ Plan a path here

Read first

Recurrent Neural NetworksVanishing and Exploding Gradients

This leads to

Sequence-to-Sequence Models
The full path from zero — 19 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Supervised, Unsupervised and Reinforcement Learning
  10. Gradient Descent
  11. Supervised Learning
  12. Linear Regression
  13. The Perceptron
  14. Logistic Regression
  15. Neural Networks
  16. Recurrent Neural Networks
  17. Backpropagation
  18. Activation Functions
  19. Vanishing and Exploding Gradients
  20. 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.

σforget f σinput i tanhcandidate g σoutput o cₜ₋₁ cₜ cell state: the long-term memory line hₜ₋₁ xₜ hₜ new hidden state (also the output) tanh multiply: keepthis fraction add thenew info i·g every gate reads hₜ₋₁ and xₜ
Fig. 1 An LSTM cell. The cell state (top) flows straight through, touched only by one multiplication (forget) and one addition (new information). Four small layers read the previous hidden state and the current input: three sigmoid gates and a tanh candidate. The output gate decides how much of the squashed cell state becomes the new hidden state.

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 tt the cell reads the current input xt\mathbf{x}_t and the previous hidden state ht−1\mathbf{h}_{t-1}. It computes three gates and one candidate, all from the same two inputs, each with its own weights. σ\sigma 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.

ft=σ(Wfxt+Ufht−1+bf)forget gateit=σ(Wixt+Uiht−1+bi)input gategt=tanh⁡(Wgxt+Ught−1+bg)candidate valuesot=σ(Woxt+Uoht−1+bo)output gate\begin{aligned} \mathbf{f}_t &= \sigma(\mathbf{W}_f \mathbf{x}_t + \mathbf{U}_f \mathbf{h}_{t-1} + \mathbf{b}_f) && \text{forget gate} \\ \mathbf{i}_t &= \sigma(\mathbf{W}_i \mathbf{x}_t + \mathbf{U}_i \mathbf{h}_{t-1} + \mathbf{b}_i) && \text{input gate} \\ \mathbf{g}_t &= \tanh(\mathbf{W}_g \mathbf{x}_t + \mathbf{U}_g \mathbf{h}_{t-1} + \mathbf{b}_g) && \text{candidate values} \\ \mathbf{o}_t &= \sigma(\mathbf{W}_o \mathbf{x}_t + \mathbf{U}_o \mathbf{h}_{t-1} + \mathbf{b}_o) && \text{output gate} \end{aligned}

Then the two updates that matter. The new cell state keeps a fraction ft\mathbf{f}_t of the old one and adds a fraction it\mathbf{i}_t of the candidate. The new hidden state is a gated, squashed view of the cell state:

ct=ft⊙ct−1+it⊙gt\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \mathbf{g}_t
ht=ot⊙tanh⁡(ct)\mathbf{h}_t = \mathbf{o}_t \odot \tanh(\mathbf{c}_t)

The symbol ⊙\odot 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 ct−1=0.8c_{t-1} = 0.8, and suppose the gate layers have produced these pre-activations: forget 2.0, input −1.0, candidate 0.5, output 1.0.

  1. Forget gate: f=σ(2.0)=0.881f = \sigma(2.0) = 0.881. Keep 88% of the old memory.
  2. Input gate: i=σ(−1.0)=0.269i = \sigma(-1.0) = 0.269. Let in about a quarter of the new information.
  3. Candidate: g=tanh⁡(0.5)=0.462g = \tanh(0.5) = 0.462.
  4. New cell state: ct=0.881×0.8+0.269×0.462=0.705+0.124=0.829c_t = 0.881 \times 0.8 + 0.269 \times 0.462 = 0.705 + 0.124 = 0.829.
  5. Output gate: o=σ(1.0)=0.731o = \sigma(1.0) = 0.731.
  6. New hidden state: ht=0.731×tanh⁡(0.829)=0.731×0.680=0.497h_t = 0.731 \times \tanh(0.829) = 0.731 \times 0.680 = 0.497.

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

∂ct∂ct−1=ft\frac{\partial c_t}{\partial c_{t-1}} = f_t

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:

0 0.25 0.5 0.75 1 0 20 40 60 80 100 ×0.5 per steptypical vanilla RNN: gone in ~10 steps forget gate 0.90.00003 left after 100 steps forget gate 0.9937% left after 100 steps steps back in time fraction that survives
Fig. 2 How much of a signal survives as it is carried back through time. A vanilla RNN typically multiplies by much less than 1 at each step and forgets within about 10 steps. An LSTM whose forget gate stays at 0.99 still keeps 37% after 100 steps.

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:

zt=σ(Wzxt+Uzht−1+bz)update gatert=σ(Wrxt+Urht−1+br)reset gateh~t=tanh⁡(Whxt+Uh(rt⊙ht−1)+bh)candidateht=(1−zt)⊙ht−1+zt⊙h~t\begin{aligned} \mathbf{z}_t &= \sigma(\mathbf{W}_z \mathbf{x}_t + \mathbf{U}_z \mathbf{h}_{t-1} + \mathbf{b}_z) && \text{update gate} \\ \mathbf{r}_t &= \sigma(\mathbf{W}_r \mathbf{x}_t + \mathbf{U}_r \mathbf{h}_{t-1} + \mathbf{b}_r) && \text{reset gate} \\ \tilde{\mathbf{h}}_t &= \tanh(\mathbf{W}_h \mathbf{x}_t + \mathbf{U}_h(\mathbf{r}_t \odot \mathbf{h}_{t-1}) + \mathbf{b}_h) && \text{candidate} \\ \mathbf{h}_t &= (1 - \mathbf{z}_t) \odot \mathbf{h}_{t-1} + \mathbf{z}_t \odot \tilde{\mathbf{h}}_t \end{aligned}

The update gate zt\mathbf{z}_t 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 z\mathbf{z} and 1−z1 - \mathbf{z}. 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 = ln⁡2\ln 2). 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 σ(0)=0.5\sigma(0) = 0.5, 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.LSTM returns output, (h_n, c_n). output holds the hidden state at every step, h_n only the last one, per layer. For padded batches, the "last" step of a short sequence is not output[:, -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

  1. 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.
  2. Remove the forget-bias line and train the LSTM for 2,000 steps. Does it eventually learn? Then increase T to 100 with the bias line restored.
  3. By hand: repeat the worked example with forget pre-activation −2.0 instead of 2.0. What happens to ctc_t, and what does that gate value mean?

Hint for 3: σ(−2)≈0.119\sigma(-2) \approx 0.119, so ct≈0.119×0.8+0.124≈0.22c_t \approx 0.119 \times 0.8 + 0.124 \approx 0.22. The cell has mostly forgotten its old content.

Check your understanding

4 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A one-slot LSTM has old cell state 0.8. Its forget gate is 0.881, its input gate 0.269 and its candidate 0.462. What is the new cell state?

  2. Why can gradients survive hundreds of steps along an LSTM's cell state?

  3. You build an LSTM in PyTorch and it learns long-range tasks no better than a vanilla RNN. Which setting is the likely culprit?

  4. You need a small recurrent model for a phone keyboard and want it as cheap as possible. How does a GRU compare with an LSTM of the same hidden size?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

Understanding LSTM Networks

Christopher Olah · 2015 · Intermediate · Free

The clearest explanation of LSTMs ever written, with the diagrams everyone copies.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Paper

Long Short-Term Memory

Hochreiter & Schmidhuber · 1997 · Advanced · Paid

Introduced the LSTM cell, which solved the vanishing-gradient problem for recurrent networks.

Paper

LSTM: A Search Space Odyssey

Greff et al. · 2015 · Advanced · Free

A large study of eight LSTM variants. None beat the standard design; the forget gate and output activation matter most.

Paper

xLSTM: Extended Long Short-Term Memory

Beck et al. (Hochreiter group) · 2024 · Advanced · Free

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