LSTM and GRU in Practice
The previous lesson ended with a measurement: in a plain tanh RNN, a gradient arriving at the last step is about of its size 10 steps earlier, so the network cannot learn to use information from far back. Long short-term memory (LSTM, 1997) and the gated recurrent unit (GRU, 2014) fix this with gates: small sigmoid layers that decide, at every step, how much of the old state to keep and how much new information to write. When the "keep" gate is near 1, the state and its gradient pass through many steps almost unchanged.
The gate equations and their gradients are derived in the Mathematics lesson LSTM and GRU gates. This lesson writes both cells in NumPy in PyTorch's exact weight layout, matches nn.LSTM and nn.GRU to the last digit, counts their parameters, and runs a long-memory experiment where the initialisation of one gate decides between failure and success.
The LSTM cell
An LSTM carries two vectors: the cell state (the long-term memory, the line along the top) and the hidden state (what the cell shows to the next layer and the next step). Four layers read and :
The key line is : the memory is updated by addition, not by passing through a matrix and a squashing function. Along the cell path, (elementwise, ignoring the gates' own dependence on the state), so a gradient travelling back steps is multiplied by a product of forget gates. If the forget gates stay near 1, it barely shrinks.
The GRU
The GRU merges the cell and hidden state into one vector and uses two gates, reset and update :
The update gate plays the role of the forget gate: copies the old state unchanged. These are PyTorch's equations, and one detail differs from some textbooks: the reset gate multiplies , after the matrix product and including its bias. A version that applies to before the product is a different (if similar) model and will not match nn.GRU.
PyTorch's layout and the parameter count
PyTorch stores the four LSTM layers stacked in one matrix: weight_ih_l0 has shape with the blocks in the order i, f, g, o, weight_hh_l0 is , and there are two bias vectors of (as in nn.RNN, only their sum matters). The GRU uses rows in the order r, z, n. With input size and hidden size :
An LSTM has four times the parameters of a plain RNN of the same width, a GRU three times.
Both cells in NumPy
The two step functions follow the equations line by line, taking the weights in PyTorch's stacked layout and splitting the pre-activations with np.split into the gate blocks. run loops over time.
import numpy as np
sigmoid = lambda a: 1 / (1 + np.exp(-a))
def lstm_step(x, h, c, W_ih, W_hh, b_ih, b_hh):
"""PyTorch layout: W_ih (4H, D), W_hh (4H, H); gate blocks in the order i, f, g, o."""
a = x @ W_ih.T + b_ih + h @ W_hh.T + b_hh
i, f, g, o = np.split(a, 4, axis=-1)
i, f, g, o = sigmoid(i), sigmoid(f), np.tanh(g), sigmoid(o)
c = f * c + i * g # keep part of the old memory, write new content
h = o * np.tanh(c) # expose part of it
return h, c
def gru_step(x, h, W_ih, W_hh, b_ih, b_hh):
"""PyTorch layout: W_ih (3H, D), W_hh (3H, H); gate blocks in the order r, z, n."""
gx = x @ W_ih.T + b_ih
gh = h @ W_hh.T + b_hh
xr, xz, xn = np.split(gx, 3, axis=-1)
hr, hz, hn = np.split(gh, 3, axis=-1)
r, z = sigmoid(xr + hr), sigmoid(xz + hz)
n = np.tanh(xn + r * hn) # the reset gate scales W_hn h + b_hn
return (1 - z) * n + z * h # z = 1 keeps the old state
def run(step, X, H, n_state):
"""X: (N, T, D) -> outputs (N, T, H) and the final state(s)."""
N, T, _ = X.shape
state = [np.zeros((N, H)) for _ in range(n_state)]
outs = []
for t in range(T):
new = step(X[:, t], *state)
state = list(new) if isinstance(new, tuple) else [new]
outs.append(state[0])
return np.stack(outs, axis=1), state
rng = np.random.default_rng(0)
D, H = 3, 5
count = lambda gates: gates * (H * (D + H) + 2 * H) # weights + two bias vectors per gate
print("parameters RNN", count(1), " GRU", count(3), " LSTM", count(4))
X = rng.normal(size=(2, 6, D)) # batch 2, 6 steps
Wl = [rng.normal(0, 0.4, s) for s in [(4 * H, D), (4 * H, H), (4 * H,), (4 * H,)]]
out, (h, c) = run(lambda x, h, c: lstm_step(x, h, c, *Wl), X, H, 2)
print("LSTM output", out.shape, " h_T", h.shape, " c_T", c.shape)
print("LSTM h_T[0]:", np.round(h[0], 4).tolist())
Wg = [rng.normal(0, 0.4, s) for s in [(3 * H, D), (3 * H, H), (3 * H,), (3 * H,)]]
out, (h,) = run(lambda x, h: gru_step(x, h, *Wg), X, H, 1)
print("GRU h_T[0]:", np.round(h[0], 4).tolist())
# The cell path: dc_T/dc_{T-k} = product of forget gates (elementwise, ignoring the gates' own dependence on c)
for fb in (0.0, 1.0, 3.0):
f = sigmoid(fb + rng.normal(0, 0.5, size=(30, H))) # forget gates over 30 steps, bias fb
print(f"forget bias {fb}: mean f {f.mean():.3f}, cell-path factor after 30 steps {np.prod(f, axis=0).mean():.1e}")parameters RNN 50 GRU 150 LSTM 200
LSTM output (2, 6, 5) h_T (2, 5) c_T (2, 5)
LSTM h_T[0]: [-0.0875, 0.0058, -0.2493, 0.2206, -0.069]
GRU h_T[0]: [-0.0214, -0.6217, 0.1995, 0.2093, 0.274]
forget bias 0.0: mean f 0.508, cell-path factor after 30 steps 1.0e-09
forget bias 1.0: mean f 0.716, cell-path factor after 30 steps 3.9e-05
forget bias 3.0: mean f 0.947, cell-path factor after 30 steps 1.9e-01
For and the counts are 50, 150 and 200. The LSTM returns both and ; the GRU only . The last three lines put numbers on the cell path: with random forget-gate pre-activations around a bias , the average product of 30 forget gates is for (gates average 0.508), for and 0.19 for (gates average 0.947). An LSTM whose forget gates sit at 0.5 forgets about as fast as a plain RNN. That is why many implementations initialise the forget-gate bias to 1 or more, a trick that matters in the experiment below.
Matching nn.LSTM and nn.GRU
The recorded run (CPU, float64) creates the modules, copies the same NumPy weights in and compares. As a check that the gate order really is i, f, g, o, it also runs the NumPy LSTM with the g and o blocks swapped.
import numpy as np
sigmoid = lambda a: 1 / (1 + np.exp(-a))
def lstm_step(x, h, c, W_ih, W_hh, b_ih, b_hh):
"""PyTorch layout: W_ih (4H, D), W_hh (4H, H); gate blocks in the order i, f, g, o."""
a = x @ W_ih.T + b_ih + h @ W_hh.T + b_hh
i, f, g, o = np.split(a, 4, axis=-1)
i, f, g, o = sigmoid(i), sigmoid(f), np.tanh(g), sigmoid(o)
c = f * c + i * g # keep part of the old memory, write new content
h = o * np.tanh(c) # expose part of it
return h, c
def gru_step(x, h, W_ih, W_hh, b_ih, b_hh):
"""PyTorch layout: W_ih (3H, D), W_hh (3H, H); gate blocks in the order r, z, n."""
gx = x @ W_ih.T + b_ih
gh = h @ W_hh.T + b_hh
xr, xz, xn = np.split(gx, 3, axis=-1)
hr, hz, hn = np.split(gh, 3, axis=-1)
r, z = sigmoid(xr + hr), sigmoid(xz + hz)
n = np.tanh(xn + r * hn) # the reset gate scales W_hn h + b_hn
return (1 - z) * n + z * h # z = 1 keeps the old state
def run(step, X, H, n_state):
"""X: (N, T, D) -> outputs (N, T, H) and the final state(s)."""
N, T, _ = X.shape
state = [np.zeros((N, H)) for _ in range(n_state)]
outs = []
for t in range(T):
new = step(X[:, t], *state)
state = list(new) if isinstance(new, tuple) else [new]
outs.append(state[0])
return np.stack(outs, axis=1), state
import torch
from torch import nn
torch.manual_seed(0)
rng = np.random.default_rng(0)
D, H = 3, 5
X = rng.normal(size=(2, 6, D))
Xt = torch.tensor(X, dtype=torch.float64)
def copy_into(module, W):
with torch.no_grad():
for name, a in zip(["weight_ih_l0", "weight_hh_l0", "bias_ih_l0", "bias_hh_l0"], W):
getattr(module, name).copy_(torch.tensor(a))
lstm = nn.LSTM(D, H, batch_first=True).double()
print("nn.LSTM:", {n: tuple(p.shape) for n, p in lstm.named_parameters()})
Wl = [rng.normal(0, 0.4, s) for s in [(4 * H, D), (4 * H, H), (4 * H,), (4 * H,)]]
copy_into(lstm, Wl)
out_t, (h_n, c_n) = lstm(Xt)
out_np, (h, c) = run(lambda x, h, c: lstm_step(x, h, c, *Wl), X, H, 2)
print(f"LSTM max diff: output {np.abs(out_t.detach().numpy() - out_np).max():.1e}, "
f"c_n {np.abs(c_n[0].detach().numpy() - c).max():.1e}")
print("nn.LSTM h_n[0, 0]:", [round(v, 4) for v in h_n[0, 0].tolist()])
# A wrong gate order (i, f, o, g) gives different numbers
def lstm_wrong(x, h, c, W_ih, W_hh, b_ih, b_hh):
perm = np.r_[0:2 * H, 3 * H:4 * H, 2 * H:3 * H] # swap the g and o blocks
return lstm_step(x, h, c, W_ih[perm], W_hh[perm], b_ih[perm], b_hh[perm])
out_w, _ = run(lambda x, h, c: lstm_wrong(x, h, c, *Wl), X, H, 2)
print(f"LSTM with gate order i, f, o, g: max diff {np.abs(out_t.detach().numpy() - out_w).max():.2f}")
gru = nn.GRU(D, H, batch_first=True).double()
Wg = [rng.normal(0, 0.4, s) for s in [(3 * H, D), (3 * H, H), (3 * H,), (3 * H,)]]
copy_into(gru, Wg)
out_t, h_n = gru(Xt)
out_np, _ = run(lambda x, h: gru_step(x, h, *Wg), X, H, 1)
print(f"GRU max diff: output {np.abs(out_t.detach().numpy() - out_np).max():.1e}")
count = lambda m: sum(p.numel() for p in m.parameters())
for D_, H_ in [(3, 5), (64, 128)]:
print(f"D={D_}, H={H_}: RNN {count(nn.RNN(D_, H_))}, GRU {count(nn.GRU(D_, H_))}, LSTM {count(nn.LSTM(D_, H_))}"
f" (formula LSTM {4 * (H_ * (D_ + H_) + 2 * H_)})")nn.LSTM: {'weight_ih_l0': (20, 3), 'weight_hh_l0': (20, 5), 'bias_ih_l0': (20,), 'bias_hh_l0': (20,)}
LSTM max diff: output 5.6e-17, c_n 5.6e-17
nn.LSTM h_n[0, 0]: [-0.0875, 0.0058, -0.2493, 0.2206, -0.069]
LSTM with gate order i, f, o, g: max diff 0.52
GRU max diff: output 2.2e-16
D=3, H=5: RNN 50, GRU 150, LSTM 200 (formula LSTM 200)
D=64, H=128: RNN 24832, GRU 74496, LSTM 99328 (formula LSTM 99328)
The NumPy and PyTorch outputs agree to , the last digit of float64, and h_n reproduces the NumPy printed earlier (). With the g and o blocks swapped the outputs differ by up to 0.52: the layout matters, and nothing but a comparison like this one will tell you it is wrong. The module counts confirm the formulas, also at a realistic size (, : 99,328 parameters for the LSTM).
When the gates matter: remembering the first symbol
A long-memory toy task: each sequence starts with one of 4 label symbols, followed by 59 blank steps; after the 60th step the model must name the first symbol (many-to-one, chance 0.25). Nothing in between helps, so the information must survive 59 steps in the state. Four models with hidden size 32 are trained with Adam (learning rate 0.005, batches of 32, gradient clipping at norm 1) for 400 steps, three seeds each, and evaluated on 500 validation sequences: a plain RNN, an LSTM with PyTorch's default initialisation, an LSTM with the forget-gate bias set to 5, and a GRU with the update-gate bias set to 3 (the gate blocks are the second rows in both layouts). The recorded run (CPU):
import torch
from torch import nn
K, T, H = 4, 60, 32 # 4 label symbols, 60 steps, hidden size 32
def batch(n, gen):
"""Step 1: one of 4 label symbols. Steps 2..60: a blank symbol. Answer at step 60: the label."""
s = torch.full((n, T), K)
s[:, 0] = torch.randint(0, K, (n,), generator=gen)
return nn.functional.one_hot(s, K + 1).float(), s[:, 0]
class Classifier(nn.Module):
def __init__(self, cell, keep_bias=None):
super().__init__()
self.rnn = cell(K + 1, H, batch_first=True)
self.head = nn.Linear(H, K)
if keep_bias is not None: # bias of the "keep the memory" gate
block = slice(H, 2 * H) # LSTM: f is block 1 of (i, f, g, o); GRU: z is block 1 of (r, z, n)
with torch.no_grad():
self.rnn.bias_ih_l0[block] = keep_bias
self.rnn.bias_hh_l0[block] = 0.0
def forward(self, x):
out, _ = self.rnn(x)
return self.head(out[:, -1]) # many-to-one: read the last step
X_va, y_va = batch(500, torch.Generator().manual_seed(1))
def train(cell, keep_bias, seed, steps=400):
"""Returns the validation accuracy after training and the first step (checked every 50) with 100 %."""
torch.manual_seed(seed)
model = Classifier(cell, keep_bias)
opt = torch.optim.Adam(model.parameters(), lr=5e-3)
gen = torch.Generator().manual_seed(100 + seed)
solved = None
for step in range(1, steps + 1):
xb, yb = batch(32, gen)
loss = nn.functional.cross_entropy(model(xb), yb)
opt.zero_grad(); loss.backward()
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
if step % 50 == 0:
with torch.no_grad():
acc = (model(X_va).argmax(1) == y_va).float().mean().item()
if acc == 1.0 and solved is None:
solved = step
return acc, solved
for name, cell, kb in [("RNN", nn.RNN, None), ("LSTM, forget bias 0", nn.LSTM, None),
("LSTM, forget bias 5", nn.LSTM, 5.0), ("GRU, update bias 3", nn.GRU, 3.0)]:
runs = [train(cell, kb, seed) for seed in (0, 1, 2)]
print(f"{name:20s} val accuracy {[round(a, 2) for a, _ in runs]} solved at step {[s for _, s in runs]}")
print("chance: 0.25")RNN val accuracy [0.24, 0.76, 1.0] solved at step [None, None, 300]
LSTM, forget bias 0 val accuracy [0.24, 0.24, 0.27] solved at step [None, None, None]
LSTM, forget bias 5 val accuracy [1.0, 1.0, 1.0] solved at step [100, 100, 350]
GRU, update bias 3 val accuracy [1.0, 1.0, 1.0] solved at step [150, 100, 100]
chance: 0.25
The plain RNN is unreliable: 0.24, 0.76 and 1.0 on the three seeds, solving the task only once (at step 300). The LSTM with default initialisation fails on all three seeds (0.24, 0.24, 0.27, chance level): its forget gates start near 0.5, and leaves no gradient to learn from. The same LSTM with its forget bias at 5 (gates near 0.993) solves all three seeds, by step 100, 100 and 350, and the GRU with a positive update bias solves all three by step 150. The gate architecture makes long memory possible; initialising the gate to remember makes it learnable. (The RNN's occasional success is partly Adam's doing: it rescales even tiny gradients to a usable step size, so a lucky seed can still find the signal.)
LSTM or GRU? The GRU has a quarter fewer parameters and often trains as well; the LSTM's separate cell state gives it a little more capacity for long dependencies. In practice, try both, and compare them at equal parameter counts. For most sequence tasks today the next step is attention and transformers (attention from scratch), but small LSTMs and GRUs remain strong for streaming signals, small data and on-device models.
Pitfalls
- Gate order when copying weights. PyTorch: LSTM i, f, g, o; GRU r, z, n. Keras uses i, f, c, o for the LSTM and z, r, h for the GRU, and its GRU has a
reset_afteroption that changes where the reset gate applies. Convert by reordering the row blocks. - Forgetting
c_n.nn.LSTMreturnsoutput, (h_n, c_n); unpackingoutput, h_n = lstm(x)gives a tuple inh_n. To pass the state on, pass both:lstm(x2, (h_n, c_n)). - Default forget bias. PyTorch initialises all LSTM biases uniformly around 0. For long dependencies set the forget block of
bias_ih_l0(rows to ) to 1 or more. - Parameter budgets. At equal width an LSTM is four times a plain RNN; compare models at equal parameters, not equal hidden size, when you claim one is better.
- Single-seed conclusions. The memory experiment shows how much the outcome varies with the seed; report several.
Practice
- How many parameters does
nn.LSTM(input_size=32, hidden_size=64, num_layers=2)have? - Write the forget-gate bias initialisation for an
nn.LSTMwith 2 layers so that it applies to both layers. - In the GRU equations, what happens to when and ? What does this let the cell do?
- The swapped-gate check printed a maximum difference of 0.52. Why does swapping g and o change the output so much, when both are computed from the same inputs?
Answer
- Layer 0: . Layer 1 takes inputs: . Total 58,368.
for layer in range(2): getattr(lstm, f"bias_ih_l{layer}").data[H:2 * H] = 1.0(withH = lstm.hidden_size), and optionally zero the same block ofbias_hh_l{layer}.- : the old state is ignored completely and the cell restarts from the current input, which lets a GRU reset its memory at a boundary (a new sentence, a new event).
- The g block goes through tanh and becomes the content written to the cell; the o block goes through a sigmoid and scales the output. Swapping them writes sigmoid values (always positive, around 0.5) as content and gates the output with tanh values (which can be negative): a different function, not a relabelling.
Test yourself
In PyTorch's nn.LSTM, in which order are the four gate blocks stacked in weight_ih_l0?
- f, i, o, g
- i, f, g, o
- i, f, o, g
- g, i, f, o
How many parameters does nn.GRU(input_size=3, hidden_size=5) have?
- 50
- 120
- 150
- 200
Why did the LSTM with default initialisation fail to remember the first symbol over 60 steps, while the same LSTM with forget bias 5 succeeded?
- The default LSTM has fewer parameters
- With forget gates near 0.5, the gradient along the cell path shrinks like ; near 0.993 it survives
- The learning rate differed
- The default LSTM has no cell state
In a GRU, which value of the update gate copies the previous state unchanged?
- None: a GRU always changes its state