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.
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].
The vanilla RNN
- 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
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).
Why plain RNNs forget: backprop through time
- ∂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
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
- 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
- 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
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].
GRU: a lighter alternative
- 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
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 RNN | LSTM | GRU | |
|---|---|---|---|
| Weight sets per layer | 1 | 4 (3 gates + candidate) | 3 (2 gates + candidate) |
| Params (input 100, hidden 256, PyTorch) | 91,648 | 366,592 | 274,944 |
| Long-range memory | Poor (≈ 10–20 steps) | Good (hundreds of steps) | Good |
| Typical use today | Teaching, tiny models | Streaming speech, time series, on-device | Same as LSTM when compute is tight |
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).
- 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.
- 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 innn.LSTM.
- 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.
- 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.
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()torch.nn.LSTM docs for the shape conventions).- Padding without masking: if sequences are padded to equal length, the final hidden state may come from padding tokens. Use
pack_padded_sequenceor pick each sequence's true last step. - `batch_first` confusion:
nn.LSTMdefaults 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
References
- [1]Deep Learning — Chapter 10: Sequence Modeling: Recurrent and Recursive NetsBookGoodfellow, Bengio & Courville2016deeplearningbook.org
- [2]Long Short-Term MemoryPaperHochreiter & Schmidhuber1997doi.org
- [3]On the difficulty of training Recurrent Neural NetworksPaperPascanu, Mikolov & Bengio2013arxiv.org
- [4]Understanding LSTM NetworksArticleOlah2015colah.github.io
- [5]Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine TranslationPaperCho et al.2014arxiv.org
- [6]Sequence to Sequence Learning with Neural NetworksPaperSutskever, Vinyals & Le2014arxiv.org