LSTMs & GRUs
Gated cells that selectively retain, update, and expose information across long sequences.
The previous article showed that vanilla RNNs fail on long sequences because gradients must pass through a product of matrices that either shrinks to zero or blows up. The root cause is the state update rule : every step multiplies the gradient by , and this factor is almost never close to one for all dimensions simultaneously.
The fix is architectural: replace the overwriting update with an additive one, and let the network control which information to carry forward. This idea — choosing what to keep and what to discard at each step — is the gating mechanism behind both LSTMs and GRUs.
Two States Instead of One
The Long Short-Term Memory (LSTM), introduced by Hochreiter and Schmidhuber in 1997, adds a second state to the cell: the cell state , which serves as a long-term memory, distinct from the hidden state that is used as the output.
The cell state is updated additively, not through a squashing nonlinearity:
Two terms add together: an old piece of memory multiplied by a forget factor , and a new piece of content multiplied by an input factor . Both and are vectors of values in — computed by sigmoid units — and they act as element-wise gates that scale each dimension independently.
The hidden state is then computed from the cell state:
A third gate controls how much of the cell state is exposed as output. The cell state itself remains bounded inside the network; only the gated version reaches the output.
The Four Gate Equations
All gates and the candidate update take the same input: the concatenation . Each has its own weight matrix and bias:
The sigmoid function maps each element to :
- : keep the corresponding dimension of unchanged.
- : erase that dimension — forget the information stored there.
- controls how much of the candidate enters the cell.
- controls what the hidden state exposes from the cell.
The parameter count is four times the vanilla RNN's per-gate count: parameters in total.
Why This Solves the Vanishing Gradient
The critical observation is that the cell state gradient propagates additively. When backpropagating through the cell update:
The gradient of the loss with respect to is:
This is an element-wise product of forget gates — not a matrix power. When the forget gates are near one (the cell chooses to remember), the product of ones preserves the gradient magnitude exactly. The network can learn to hold its forget gates open for dimensions that need to propagate long-range information, effectively creating a direct gradient path over many steps.
This is in sharp contrast to the vanilla RNN, where the gradient factor is fixed by the weight matrix and cannot be controlled per-step or per-dimension.
GRU: A Simpler Alternative
The Gated Recurrent Unit (GRU, Cho et al. 2014) achieves similar long-range capability with fewer parameters by eliminating the separate cell state. A single hidden state serves as both memory and output.
The GRU uses two gates instead of three:
Reset gate
Controls how much of the previous hidden state to use when computing the new candidate. When , the candidate ignores the past entirely.
Update gate
Controls the balance between keeping the old state and adopting the new candidate.
Candidate
Update:
When , the new state is mostly the old state — the unit is copying its memory forward. When , the new state comes entirely from the candidate. The gradient path when is similarly direct: , preserving gradient magnitude.
The GRU uses parameters — 25% fewer than the LSTM.
Comparing LSTM and GRU
| Property | LSTM | GRU |
|---|---|---|
| States | Two (, ) | One () |
| Gates | 3 sigmoid + 1 tanh | 2 sigmoid + 1 tanh |
| Parameters | ||
| Typical advantage | Very long sequences | Faster training, competitive accuracy |
| Standard use case | Machine translation, language modelling | Time series, speech, shorter sequences |
Neither consistently outperforms the other across all tasks. The GRU is often a good first choice for its simplicity and speed; the LSTM's separate cell state can give an edge on tasks with very long-range dependencies.
Both handle sequences of hundreds of steps that break vanilla RNNs. The typical threshold where gated architectures clearly outperform vanilla RNNs is around 30–50 steps, though this depends heavily on the task.
In Code
import torch
import torch.nn as nn
import torch.nn.functional as F
# ── LSTMCell as a proper nn.Module ───────────────────────────────────────────
# Each of the 4 gates uses two nn.Linear layers:
# lh_* : hidden → hidden (no bias) — the recurrent part
# lx_* : input → hidden (with bias) — the input part + gate bias
class LSTMCell(nn.Module):
def __init__(self, input_size: int, hidden_size: int):
super().__init__()
self.hidden_size = hidden_size
self.lh_f = nn.Linear(hidden_size, hidden_size, bias=False)
self.lx_f = nn.Linear(input_size, hidden_size, bias=True) # forget
self.lh_i = nn.Linear(hidden_size, hidden_size, bias=False)
self.lx_i = nn.Linear(input_size, hidden_size, bias=True) # input
self.lh_g = nn.Linear(hidden_size, hidden_size, bias=False)
self.lx_g = nn.Linear(input_size, hidden_size, bias=True) # candidate
self.lh_o = nn.Linear(hidden_size, hidden_size, bias=False)
self.lx_o = nn.Linear(input_size, hidden_size, bias=True) # output
def forward(self, x, h, c):
f = torch.sigmoid(self.lh_f(h) + self.lx_f(x)) # forget gate
i = torch.sigmoid(self.lh_i(h) + self.lx_i(x)) # input gate
g = torch.tanh( self.lh_g(h) + self.lx_g(x)) # candidate
o = torch.sigmoid(self.lh_o(h) + self.lx_o(x)) # output gate
c_new = f * c + i * g # additive cell update
h_new = o * torch.tanh(c_new)
return h_new, c_new
# ── Forward pass over a short sequence ───────────────────────────────────────
cell = LSTMCell(input_size=2, hidden_size=4)
h = torch.zeros(4)
c = torch.zeros(4)
for x in [torch.tensor([1.0, 0.5]), torch.tensor([0.2, 0.8])]:
h, c = cell(x, h, c)
print(h) # final hidden state, shape (4,)
print(c) # final cell state, shape (4,)
print(sum(p.numel() for p in cell.parameters())) # 112 = 4·D·(D + I + 1) with D=4, I=2
# ── Many-to-one LSTM classifier ──────────────────────────────────────────────
class LSTMClassifier(nn.Module):
def __init__(self, input_size: int, hidden_size: int, num_classes: int):
super().__init__()
self.hidden_size = hidden_size
self.cell = LSTMCell(input_size, hidden_size)
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, xs):
h = torch.zeros(self.hidden_size)
c = torch.zeros(self.hidden_size)
for x in xs:
h, c = self.cell(x, h, c) # BPTT graph built step by step
return self.fc(h) # classify from the final hidden state
model = LSTMClassifier(input_size=2, hidden_size=8, num_classes=3)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
seq = [torch.randn(2) for _ in range(5)]
target = torch.tensor([1])
for step in range(30):
optimizer.zero_grad()
logits = model(seq)
loss = F.cross_entropy(logits.unsqueeze(0), target)
loss.backward() # gradients flow through all 5 unrolled steps
optimizer.step()
if step % 10 == 0:
print(f"step {step:2d} loss={loss.item():.4f} pred={logits.argmax().item()}")
# ── GRUCell as an nn.Module ──────────────────────────────────────────────────
# A GRU collapses h and c into a single state and uses two gates instead of three.
class GRUCell(nn.Module):
def __init__(self, input_size: int, hidden_size: int):
super().__init__()
self.hidden_size = hidden_size
self.lh_r = nn.Linear(hidden_size, hidden_size, bias=False)
self.lx_r = nn.Linear(input_size, hidden_size, bias=True) # reset
self.lh_z = nn.Linear(hidden_size, hidden_size, bias=False)
self.lx_z = nn.Linear(input_size, hidden_size, bias=True) # update
self.lh_h = nn.Linear(hidden_size, hidden_size, bias=False)
self.lx_h = nn.Linear(input_size, hidden_size, bias=True) # candidate
def forward(self, x, h):
r = torch.sigmoid(self.lh_r(h) + self.lx_r(x)) # reset gate
z = torch.sigmoid(self.lh_z(h) + self.lx_z(x)) # update gate
h_tilde = torch.tanh( self.lh_h(h * r) + self.lx_h(x)) # candidate
return (1 - z) * h_tilde + z * h # convex blend: forget old, add new
gru = GRUCell(input_size=2, hidden_size=4)
h = torch.zeros(4)
for x in [torch.tensor([1.0, 0.5]), torch.tensor([0.2, 0.8])]:
h = gru(x, h)
print(h) # final hidden state, shape (4,)
print(sum(p.numel() for p in gru.parameters())) # 84 = 3·D·(D + I + 1): 25% fewer than the LSTM
# ── The built-in versions ────────────────────────────────────────────────────
# nn.LSTMCell: processes one step at a time (same maths as the cell above)
lstm_cell = nn.LSTMCell(input_size=2, hidden_size=4)
x = torch.randn(3, 2) # batch=3, input_size=2
h = torch.zeros(3, 4)
c = torch.zeros(3, 4)
for t in range(5): # process a sequence of 5 steps
h, c = lstm_cell(x, (h, c))
print(h.shape) # torch.Size([3, 4])
print(c.shape) # torch.Size([3, 4])
# nn.LSTM: processes entire sequences (more efficient)
lstm = nn.LSTM(input_size=2, hidden_size=4, batch_first=True)
x_seq = torch.randn(3, 10, 2) # batch=3, seq_len=10, input_size=2
output, (hn, cn) = lstm(x_seq)
print(output.shape) # torch.Size([3, 10, 4]) — h_t at every step
print(hn.shape) # torch.Size([1, 3, 4]) — h_T only
# nn.GRU
gru = nn.GRU(input_size=2, hidden_size=4, batch_first=True)
output_gru, hn_gru = gru(x_seq)
print(output_gru.shape) # torch.Size([3, 10, 4])
# Stacked LSTM (2 layers)
lstm2 = nn.LSTM(input_size=2, hidden_size=4, num_layers=2, batch_first=True,
dropout=0.3) # dropout between layers
out, (h2, c2) = lstm2(x_seq)
print(out.shape) # torch.Size([3, 10, 4])
LSTMs and GRUs solve the problem that vanilla RNNs could not: they give the network explicit control over what to remember and what to discard, enabling gradient flow over sequences of hundreds or thousands of steps. The next article examines the remaining limits of even these gated architectures — and why those limits motivated a completely different design.