Skip to content
Recurrent Networks

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 ht=tanh⁡(Whht−1+…)\mathbf{h}_t = \tanh(\mathbf{W}_h \mathbf{h}_{t-1} + \ldots): every step multiplies the gradient by Wh⊤⋅diag⁡(tanh⁡′)\mathbf{W}_h^\top \cdot \operatorname{diag}(\tanh'), 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 ct∈RD\mathbf{c}_t \in \mathbb{R}^D, which serves as a long-term memory, distinct from the hidden state ht\mathbf{h}_t that is used as the output.

The cell state is updated additively, not through a squashing nonlinearity:

ct=ft⊙ct−1+it⊙gt\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \mathbf{g}_t

Two terms add together: an old piece of memory multiplied by a forget factor ft\mathbf{f}_t, and a new piece of content gt\mathbf{g}_t multiplied by an input factor it\mathbf{i}_t. Both ft\mathbf{f}_t and it\mathbf{i}_t are vectors of values in (0,1)(0, 1) — 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:

ht=ot⊙tanh⁡(ct)\mathbf{h}_t = \mathbf{o}_t \odot \tanh(\mathbf{c}_t)

A third gate ot\mathbf{o}_t 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 [ht−1, xt][\mathbf{h}_{t-1},\, \mathbf{x}_t]. Each has its own weight matrix and bias:

ft=σ(Wf[ht−1,xt]+bf)(forget gate)\mathbf{f}_t = \sigma(\mathbf{W}_f [\mathbf{h}_{t-1}, \mathbf{x}_t] + \mathbf{b}_f) \qquad \text{(forget gate)} it=σ(Wi[ht−1,xt]+bi)(input gate)\mathbf{i}_t = \sigma(\mathbf{W}_i [\mathbf{h}_{t-1}, \mathbf{x}_t] + \mathbf{b}_i) \qquad \text{(input gate)} gt=tanh⁡(Wg[ht−1,xt]+bg)(candidate)\mathbf{g}_t = \tanh(\mathbf{W}_g [\mathbf{h}_{t-1}, \mathbf{x}_t] + \mathbf{b}_g) \qquad \text{(candidate)} ot=σ(Wo[ht−1,xt]+bo)(output gate)\mathbf{o}_t = \sigma(\mathbf{W}_o [\mathbf{h}_{t-1}, \mathbf{x}_t] + \mathbf{b}_o) \qquad \text{(output gate)}

The sigmoid function maps each element to (0,1)(0,1):

  • ft≈1\mathbf{f}_t \approx 1: keep the corresponding dimension of ct−1\mathbf{c}_{t-1} unchanged.
  • ft≈0\mathbf{f}_t \approx 0: erase that dimension — forget the information stored there.
  • it\mathbf{i}_t controls how much of the candidate gt\mathbf{g}_t enters the cell.
  • ot\mathbf{o}_t controls what the hidden state exposes from the cell.

The parameter count is four times the vanilla RNN's per-gate count: 4D(D+I+1)4D(D + I + 1) parameters in total.

tanh[h, x]f_ti_t ⊙ g_to_tc_{t-1}c_th_th_{t-1}×f+×ocell c (green): additive highway; h_t = o_t ⊙ tanh(c_t)

Why This Solves the Vanishing Gradient

The critical observation is that the cell state gradient propagates additively. When backpropagating through the cell update:

∂ct∂ct−1=diag⁡(ft)\frac{\partial \mathbf{c}_t}{\partial \mathbf{c}_{t-1}} = \operatorname{diag}(\mathbf{f}_t)

The gradient of the loss with respect to ct−k\mathbf{c}_{t-k} is:

∂L∂ct−k=∂L∂ct⊙ft⊙ft−1⊙⋯⊙ft−k+1\frac{\partial L}{\partial \mathbf{c}_{t-k}} = \frac{\partial L}{\partial \mathbf{c}_t} \odot \mathbf{f}_t \odot \mathbf{f}_{t-1} \odot \cdots \odot \mathbf{f}_{t-k+1}

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 Wh⊤⋅diag⁡(tanh⁡′)\mathbf{W}_h^\top \cdot \operatorname{diag}(\tanh') 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 ht\mathbf{h}_t serves as both memory and output.

The GRU uses two gates instead of three:

Reset gate rt=σ(Wr[ht−1,xt]+br)\mathbf{r}_t = \sigma(\mathbf{W}_r [\mathbf{h}_{t-1}, \mathbf{x}_t] + \mathbf{b}_r)

Controls how much of the previous hidden state to use when computing the new candidate. When rt≈0\mathbf{r}_t \approx 0, the candidate ignores the past entirely.

Update gate zt=σ(Wz[ht−1,xt]+bz)\mathbf{z}_t = \sigma(\mathbf{W}_z [\mathbf{h}_{t-1}, \mathbf{x}_t] + \mathbf{b}_z)

Controls the balance between keeping the old state and adopting the new candidate.

Candidate h~t=tanh⁡(Wh[rt⊙ht−1, xt]+bh)\tilde{\mathbf{h}}_t = \tanh(\mathbf{W}_h [\mathbf{r}_t \odot \mathbf{h}_{t-1},\, \mathbf{x}_t] + \mathbf{b}_h)

Update:

ht=(1−zt)⊙h~t+zt⊙ht−1\mathbf{h}_t = (1 - \mathbf{z}_t) \odot \tilde{\mathbf{h}}_t + \mathbf{z}_t \odot \mathbf{h}_{t-1}

When zt≈1\mathbf{z}_t \approx 1, the new state is mostly the old state — the unit is copying its memory forward. When zt≈0\mathbf{z}_t \approx 0, the new state comes entirely from the candidate. The gradient path when zt≈1\mathbf{z}_t \approx 1 is similarly direct: ∂ht/∂ht−1≈zt≈1\partial \mathbf{h}_t / \partial \mathbf{h}_{t-1} \approx \mathbf{z}_t \approx 1, preserving gradient magnitude.

The GRU uses 3D(D+I+1)3D(D + I + 1) parameters — 25% fewer than the LSTM.

Comparing LSTM and GRU

PropertyLSTMGRU
StatesTwo (ct\mathbf{c}_t, ht\mathbf{h}_t)One (ht\mathbf{h}_t)
Gates3 sigmoid + 1 tanh2 sigmoid + 1 tanh
Parameters4D(D+I+1)4D(D+I+1)3D(D+I+1)3D(D+I+1)
Typical advantageVery long sequencesFaster training, competitive accuracy
Standard use caseMachine translation, language modellingTime 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.