AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
▦Deep Learning Architectures
  1. Convolutional Neural Networks (CNNs)
  2. CNN Architectures and Transfer Learning
  3. Recurrent Networks: RNN, LSTM and GRU
  4. Embeddings: Meaning as Vectors
  5. Attention and Transformers
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Deep Learning Architectures

Recurrent Networks: RNN, LSTM and GRU

Networks with memory for sequences: how a recurrent network carries a hidden state through time, why plain RNNs forget, how LSTM and GRU gates fix it, and how encoder–decoder (seq2seq) models led to attention.

Intermediate~28 min·6 references
Key terms
RNN (Recurrent Neural Network)LSTM (Long Short-Term Memory)GRU (Gated Recurrent Unit)Seq2seq (sequence-to-sequence)Vanishing (and exploding) gradientEncoderDecoderAttention

Text, speech, sensor readings, stock prices and music are sequences: order matters and the length varies. An MLP or CNN expects a fixed-size input. A recurrent neural network reads a sequence one step at a time and keeps a hidden state — a running summary of everything seen so far — that it updates at every step with the same weights. RNNs, and especially their gated versions LSTM and GRU, dominated speech recognition, machine translation and language modelling from roughly 2014 to 2018, until Transformers took over[1].

≈
Reading with a notebook
A plain RNN is like reading a story while keeping a single sticky note of what's happened — at each sentence you rewrite the whole note. After 50 sentences, details from the first page are long gone. An LSTM has a proper notebook plus three habits: an eraser (forget gate) to cross out what's no longer relevant, a pen (input gate) to add only what's new and important, and a highlighter (output gate) to choose what to read out right now. Because it adds and erases rather than rewriting everything, information can survive for a long time.

The vanilla RNN

h_t = tanh(W_xh · x_t + W_hh · h_{t−1} + b_h) ŷ_t = W_hy · h_t + b_y
x_t is the input at step t (e.g. a word Embedding), h_t the hidden state. The same W_xh, W_hh, W_hy are used at every step.
In words: “new memory = squash(what I see now + what I remembered).” The hidden state mixes the current input with the previous state, and tanh keeps every value between −1 and 1. The output at each step is a linear read-out of that memory.
Symbols(hover a symbol in the formula)
h_t
hidden state at step t (vector of hidden size, e.g. 256)
h_{t−1}
hidden state from the previous step (h₀ is usually zeros)
x_t
input at step t, e.g. a word Embedding
W_xh
input-to-hidden weight matrix (hidden × input)
W_hh
hidden-to-hidden (recurrent) weight matrix (hidden × hidden)
b_h
hidden bias vector
tanh
hyperbolic tangent: squashes any number into (−1, 1)
ŷ_t
output (prediction scores) at step t
W_hy
hidden-to-output weight matrix
b_y
output bias
▸Worked example
Scalars: W_xh = 0.5, W_hh = 0.8, b_h = 0, h₀ = 0; inputs x = 1, 1, 0 t = 1: tanh(0.5·1 + 0.8·0) = tanh(0.5) = 0.4621 t = 2: tanh(0.5·1 + 0.8·0.4621) = tanh(0.8697) = 0.7012 t = 3: tanh(0.5·0 + 0.8·0.7012) = tanh(0.5610) = 0.5087 ← no input, memory fades With W_hy = 2, b_y = 0: ŷ₃ = 2 · 0.5087 = 1.0174

Unrolled through time, an RNN is just a very deep feed-forward network with one layer per time step and shared weights. It can be used many-to-one (sentiment of a review), one-to-many (generate a caption), or many-to-many (tag every word; or translate, with an Encoder and a Decoder). Karpathy's classic post shows character-level RNNs generating surprisingly plausible Shakespeare, Linux source code and LaTeX (The Unreasonable Effectiveness of RNNs).

Loading interactive…
An RNN unrolled over four words. Press Walk through: the same cell (same W_xh, W_hh, W_hy) runs at every step and passes its hidden state to the right. The last step shows the gradient travelling back through time — keep it in mind for the next section.

Why plain RNNs forget: backprop through time

∂h_t/∂h_k = Π_{i=k+1..t} W_hhᵀ · diag(tanh′(·)) ‖·‖ ≈ λ^(t−k)
The gradient from step t back to step k multiplies the same matrix t − k times. If its scale λ < 1 it vanishes (0.9⁵⁰ ≈ 0.005); if λ > 1 it explodes (1.1⁵⁰ ≈ 117).
In words: To send the error from step t back to an earlier step k, the chain rule multiplies one factor per step in between — always the same matrix W_hh times the tanh slope. A number multiplied by itself many times either shrinks to 0 or blows up.
Symbols(hover a symbol in the formula)
∂h_t/∂h_k
how much the state at step t depends on the state at an earlier step k (a Jacobian matrix)
Π_{i=k+1..t}
product of the factors for every step i from k+1 to t
W_hhᵀ
transposed recurrent weight matrix (ᵀ = transpose)
diag(tanh′(·))
diagonal matrix of tanh slopes at each unit; tanh′ ≤ 1 and ≈ 0 when the unit is saturated
‖·‖
norm: the overall size (magnitude) of the gradient
λ^(t−k)
λ (lambda) is the typical scale of one factor; raised to the number of steps t − k
▸Worked example
Scalar RNN with W_hh = 0.8 and average tanh′ ≈ 0.9 → factor λ = 0.72 per step 10 steps back: 0.72¹⁰ ≈ 0.037 50 steps back: 0.72⁵⁰ ≈ 0.00000007 → the first words get almost no learning signal With W_hh = 1.5 and tanh′ ≈ 1: 1.5²⁰ ≈ 3,325 → exploding gradient (fix: gradient clipping)

Training uses backpropagation through time (BPTT): backprop on the unrolled network. Because the same weights are multiplied again and again, gradients over long distances either vanish — the network cannot learn that a word 50 steps ago matters — or explode, producing huge updates and NaNs[3]. Exploding gradients are tamed by Gradient clipping (rescale the gradient when its norm exceeds a threshold)[3]; long sequences are often trained with truncated BPTT (backprop only through the last k steps). Vanishing gradients need an architectural fix: gates.

LSTM: gated memory

f_t = σ(W_f·[h_{t−1}, x_t] + b_f) i_t = σ(W_i·[h_{t−1}, x_t] + b_i) o_t = σ(W_o·[h_{t−1}, x_t] + b_o)
Forget, input and output gates: sigmoids that output values between 0 (closed) and 1 (open) for every memory cell.
In words: Three small layers look at the previous output and the current input and each produce a vector of “valves” between 0 and 1 — one valve per memory cell. Same recipe, different weights: f decides what to erase, i what to write, o what to show.
Symbols(hover a symbol in the formula)
f_t
forget gate: 1 = keep the old memory, 0 = erase it
i_t
input gate: how much new content to write
o_t
output gate: how much of the memory to expose as h_t
σ
Sigmoid (logistic function) σ(z) = 1 / (1 + e^(−z)): maps any number into (0, 1)
[h_{t−1}, x_t]
the previous hidden state and the current input concatenated into one vector
W_f
weights of the forget gate (W_i, W_o likewise for the other gates)
b_f
bias of the forget gate (often initialized to ≈ 1 so the cell remembers by default)
▸Worked example
One memory cell; suppose the pre-activations (W·[h, x] + b) are 2.0, −1.0 and 0.5 f = σ(2.0) = 0.8808 → keep 88% of the old memory i = σ(−1.0) = 0.2689 → write only 27% of the new candidate o = σ(0.5) = 0.6225 → show 62% of the (squashed) memory
c̃_t = tanh(W_c·[h_{t−1}, x_t] + b_c) c_t = f_t ⊙ c_{t−1} + i_t ⊙ c̃_t h_t = o_t ⊙ tanh(c_t)
The cell state c_t is updated by element-wise addition, not by repeated matrix multiplication.
In words: Propose new content (c̃), then update the memory: keep the gated old memory and add the gated new content. Finally, read out a squashed, gated version of the memory as the output h_t. Because the update is a sum, not a matrix product, information can survive many steps.
Symbols(hover a symbol in the formula)
c̃_t
candidate content, values in (−1, 1)
W_c
weights of the candidate layer
b_c
bias of the candidate layer
c_t
new cell state (the long-term memory)
c_{t−1}
previous cell state
⊙
element-wise (Hadamard) product: multiply matching entries
h_t
new hidden state / output of this step
tanh
squashes values into (−1, 1)
▸Worked example
One cell: c_{t−1} = 2.0, f = 0.9, i = 0.3, o = 0.6, candidate pre-activation 1.0 c̃ = tanh(1.0) = 0.7616 c_t = 0.9·2.0 + 0.3·0.7616 = 1.8 + 0.2285 = 2.0285 h_t = 0.6 · tanh(2.0285) = 0.6 · 0.9660 = 0.5796 With f = 1 and i = 0 the memory would stay exactly 2.0 — the “constant error carousel”.

Hochreiter & Schmidhuber's Long Short-Term Memory (1997) adds a separate cell state c_t that runs through time with only element-wise operations[2]. When the forget gate is near 1 and the input gate near 0, c_t ≈ c_{t−1}: information — and gradient — flows across many steps almost unchanged (the “constant error carousel”). The forget gate itself was added later by Gers et al. (2000); initializing its bias to around 1 (so the network remembers by default) is a common trick. Olah's illustrated walkthrough is the clearest visual explanation[4].

Loading interactive…
One LSTM step. Walk through the gates in order (forget → input → update → output), or tap any σ gate or × / + node. Notice that the cell state along the top is only touched by element-wise × and + — that's the gradient highway.

GRU: a lighter alternative

z_t = σ(W_z·[h_{t−1}, x_t]) r_t = σ(W_r·[h_{t−1}, x_t]) h̃_t = tanh(W·[r_t ⊙ h_{t−1}, x_t]) h_t = (1 − z_t) ⊙ h̃_t + z_t ⊙ h_{t−1}
Update gate z decides how much of the old state to keep; reset gate r decides how much of it to use when proposing the new state. (Papers differ on whether z or 1 − z multiplies h_{t−1}; this is PyTorch's convention.)
In words: The new state is a blend of the old state and a proposal: z decides the mix (keep vs replace), and r decides how much of the old state the proposal may look at. One state vector, two gates.
Symbols(hover a symbol in the formula)
z_t
update gate in (0, 1): how much of the old state to keep
r_t
reset gate in (0, 1): how much of the old state to use for the proposal
h̃_t
candidate (proposed) new state
h_t
final new hidden state
h_{t−1}
previous hidden state
σ
Sigmoid (logistic function), output in (0, 1)
W_z
update-gate weights (W_r for the reset gate, W for the candidate)
⊙
element-wise product
(1 − z_t)
the share given to the new candidate
▸Worked example
One unit: h_{t−1} = 0.5, z = 0.8, candidate h̃ = −0.2 h_t = (1 − 0.8)·(−0.2) + 0.8·0.5 = −0.04 + 0.40 = 0.36 z near 1 → the old state mostly survives; z near 0 → it is replaced by h̃.

The Gated Recurrent Unit (Cho et al., 2014) merges the cell and hidden state and uses two gates instead of three[5]. It has about ¾ of an LSTM's parameters and often performs comparably; which one wins depends on the task, so it's worth trying both.

Vanilla RNNLSTMGRU
Weight sets per layer14 (3 gates + candidate)3 (2 gates + candidate)
Params (input 100, hidden 256, PyTorch)91,648366,592274,944
Long-range memoryPoor (≈ 10–20 steps)Good (hundreds of steps)Good
Typical use todayTeaching, tiny modelsStreaming speech, time series, on-deviceSame as LSTM when compute is tight
Counts include PyTorch's two bias vectors per gate: e.g. LSTM = 4·(256·100 + 256·256 + 256 + 256).

Seq2seq and the bottleneck that led to attention

For translation, input and output lengths differ. Sutskever et al. (2014) used a sequence-to-sequence model: an encoder LSTM reads the source sentence into a fixed vector, and a decoder LSTM generates the translation word by word from it (with 4-layer LSTMs; reversing the source order helped noticeably)[6]. During training the decoder is fed the correct previous word (teacher forcing); at inference it feeds back its own predictions. The weakness: the whole sentence must squeeze through one fixed-size vector, and quality dropped for long sentences. Bahdanau et al. (2014) let the decoder look back at all encoder states and take a weighted average at each step — Attention. That idea, taken to its extreme, became the Transformer (next lessons).

Loading interactive…
Bahdanau attention for one output word. Walk through it: the decoder state s_{t−1} scores every encoder state h_j, a softmax turns the scores into weights α, and the context c_t is their weighted average. Tap the α edges and notice that the context is rebuilt for every output word — no single-vector bottleneck.
knobHidden size
What it is
Dimension of the hidden (and cell) state — how much the network can remember at once.
↑ If you increase it
More memory capacity and expressiveness; parameters grow ≈ quadratically (W_hh is hidden × hidden) and steps get slower; more overfitting on small data.
↓ If you decrease it
Faster and smaller, but the state becomes a bottleneck and long or complex dependencies are lost.
Typical values
128–1024.
knobNumber of stacked layers
What it is
How many recurrent layers are stacked, each reading the previous layer's hidden states.
↑ If you increase it
More abstract features (2–4 layers helped seq2seq a lot); beyond ~4 layers gains shrink and training gets harder without residual connections.
↓ If you decrease it
Simpler and faster; one layer is often enough for small tasks.
Typical values
1–4; use dropout= between layers in nn.LSTM.
knobBPTT length (sequence chunk)
What it is
How many time steps gradients are propagated through before truncating (for long streams split into chunks).
↑ If you increase it
Can learn longer dependencies, but memory and time grow linearly and exploding/vanishing gradients become more likely.
↓ If you decrease it
Cheaper and more stable, but the model can't learn dependencies longer than the chunk.
Typical values
35–200 steps for language models; full sequence for short inputs.
knobGradient clipping max-norm
What it is
If the global gradient norm exceeds this value, the whole gradient is rescaled down to it.
↑ If you increase it
Clips less often; at very large values it does nothing and occasional exploding gradients can wreck training.
↓ If you decrease it
More stable, but clipping almost every step slows learning (it acts like a smaller learning rate).
Typical values
0.25–5; 1.0 is a common default.
python
import torch
import torch.nn as nn

class SentimentLSTM(nn.Module):
    def __init__(self, vocab_size, emb_dim=128, hidden=256, layers=2):
        super().__init__()
        self.emb = nn.Embedding(vocab_size, emb_dim, padding_idx=0)
        self.lstm = nn.LSTM(emb_dim, hidden, num_layers=layers, batch_first=True,
                            dropout=0.2, bidirectional=True)
        self.head = nn.Linear(2 * hidden, 2)

    def forward(self, tokens):                 # tokens: (batch, seq_len) integer ids
        x = self.emb(tokens)                   # (batch, seq_len, emb_dim)
        out, (h_n, c_n) = self.lstm(x)         # h_n: (layers * 2, batch, hidden)
        last = torch.cat([h_n[-2], h_n[-1]], dim=1)   # top layer: forward + backward
        return self.head(last)

model = SentimentLSTM(vocab_size=20_000)
opt = torch.optim.Adam(model.parameters(), lr=1e-3)

tokens = torch.randint(1, 20_000, (32, 50))
labels = torch.randint(0, 2, (32,))
loss = nn.functional.cross_entropy(model(tokens), labels)
opt.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)   # tame exploding gradients
opt.step()
A bidirectional 2-layer LSTM classifier with gradient clipping (see torch.nn.LSTM docs for the shape conventions).
!
Common pitfalls
Watch out for these:
  • Padding without masking: if sequences are padded to equal length, the final hidden state may come from padding tokens. Use pack_padded_sequence or pick each sequence's true last step.
  • `batch_first` confusion: nn.LSTM defaults to (seq_len, batch, features).
  • Carrying hidden state across batches without .detach() makes autograd try to backprop through the entire history (memory blows up).
  • No gradient clipping → occasional NaN losses.
  • Bidirectional models can't stream: they need the whole sequence first, so they're unsuitable for real-time generation.
▸Go deeper: are RNNs obsolete?

Transformers replaced RNNs for most NLP because they process all positions in parallel during training, whereas an RNN must step through time sequentially. But RNNs have a property Transformers lack: constant memory and compute per generated step, regardless of history length. That's why recurrence is coming back in state-space models such as Mamba (Gu & Dao, 2023), which train in parallel like a Transformer but generate like an RNN. LSTMs also remain common in on-device speech, time-series forecasting and control[1].

Quiz

1.
Why do vanilla RNNs struggle to learn dependencies 100 steps apart?
2.
What lets an LSTM carry information across many steps?
3.
Your LSTM's loss is fine for a while, then suddenly becomes NaN. What's the first thing to add?
4.
What was the main weakness of the original seq2seq model that attention fixed?
5.
Compared with an LSTM of the same hidden size, a GRU has…
Score: 0/5

References

  1. [1]
    Deep Learning — Chapter 10: Sequence Modeling: Recurrent and Recursive Nets
    BookGoodfellow, Bengio & Courville2016deeplearningbook.org
  2. [2]
    Long Short-Term Memory
    PaperHochreiter & Schmidhuber1997doi.org
  3. [3]
    On the difficulty of training Recurrent Neural Networks
    PaperPascanu, Mikolov & Bengio2013arxiv.org
  4. [4]
    Understanding LSTM Networks
    ArticleOlah2015colah.github.io
  5. [5]
    Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation
    PaperCho et al.2014arxiv.org
  6. [6]
    Sequence to Sequence Learning with Neural Networks
    PaperSutskever, Vinyals & Le2014arxiv.org
← Previous
CNN Architectures and Transfer Learning
Next →
Embeddings: Meaning as Vectors