TExcelTAD

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 10−410^{-4} 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

c t-1c t cell state x + x x f: sig i: sig g: tanh o: sig tanh h t h t-1 x t i * gf

An LSTM carries two vectors: the cell state ctc_t (the long-term memory, the line along the top) and the hidden state hth_t (what the cell shows to the next layer and the next step). Four layers read xtx_t and ht−1h_{t-1}:

it=σ(Wiixt+bii+Whiht−1+bhi)input gate: how much to writeft=σ(Wifxt+bif+Whfht−1+bhf)forget gate: how much to keepgt=tanh⁡(Wigxt+big+Whght−1+bhg)candidate contentot=σ(Wioxt+bio+Whoht−1+bho)output gate: how much to showct=ft⊙ct−1+it⊙gtht=ot⊙tanh⁡(ct)\begin{aligned} i_t &= \sigma(W_{ii} x_t + b_{ii} + W_{hi} h_{t-1} + b_{hi}) && \text{input gate: how much to write} \\ f_t &= \sigma(W_{if} x_t + b_{if} + W_{hf} h_{t-1} + b_{hf}) && \text{forget gate: how much to keep} \\ g_t &= \tanh(W_{ig} x_t + b_{ig} + W_{hg} h_{t-1} + b_{hg}) && \text{candidate content} \\ o_t &= \sigma(W_{io} x_t + b_{io} + W_{ho} h_{t-1} + b_{ho}) && \text{output gate: how much to show} \\ c_t &= f_t \odot c_{t-1} + i_t \odot g_t \\ h_t &= o_t \odot \tanh(c_t) \end{aligned}

The key line is ct=ft⊙ct−1+it⊙gtc_t = f_t \odot c_{t-1} + i_t \odot g_t: the memory is updated by addition, not by passing through a matrix and a squashing function. Along the cell path, ∂ct/∂ct−1=ft\partial c_t / \partial c_{t-1} = f_t (elementwise, ignoring the gates' own dependence on the state), so a gradient travelling back kk 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 rtr_t and update ztz_t:

rt=σ(Wirxt+bir+Whrht−1+bhr)zt=σ(Wizxt+biz+Whzht−1+bhz)nt=tanh⁡(Winxt+bin+rt⊙(Whnht−1+bhn))ht=(1−zt)⊙nt+zt⊙ht−1\begin{aligned} r_t &= \sigma(W_{ir} x_t + b_{ir} + W_{hr} h_{t-1} + b_{hr}) \\ z_t &= \sigma(W_{iz} x_t + b_{iz} + W_{hz} h_{t-1} + b_{hz}) \\ n_t &= \tanh(W_{in} x_t + b_{in} + r_t \odot (W_{hn} h_{t-1} + b_{hn})) \\ h_t &= (1 - z_t) \odot n_t + z_t \odot h_{t-1} \end{aligned}

The update gate plays the role of the forget gate: zt=1z_t = 1 copies the old state unchanged. These are PyTorch's equations, and one detail differs from some textbooks: the reset gate multiplies Whnht−1+bhnW_{hn} h_{t-1} + b_{hn}, after the matrix product and including its bias. A version that applies rtr_t to ht−1h_{t-1} 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 (4H,D)(4H, D) with the blocks in the order i, f, g, o, weight_hh_l0 is (4H,H)(4H, H), and there are two bias vectors of 4H4H (as in nn.RNN, only their sum matters). The GRU uses 3H3H rows in the order r, z, n. With input size DD and hidden size HH:

RNN: H(D+H)+2H,GRU: 3 (H(D+H)+2H),LSTM: 4 (H(D+H)+2H)\text{RNN: } H(D + H) + 2H, \qquad \text{GRU: } 3\,\big(H(D + H) + 2H\big), \qquad \text{LSTM: } 4\,\big(H(D + H) + 2H\big)

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.

python · try it yourself
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 D=3D = 3 and H=5H = 5 the counts are 50, 150 and 200. The LSTM returns both hTh_T and cTc_T; the GRU only hTh_T. The last three lines put numbers on the cell path: with random forget-gate pre-activations around a bias bfb_f, the average product of 30 forget gates is 1.0×10−91.0 \times 10^{-9} for bf=0b_f = 0 (gates average 0.508), 3.9×10−53.9 \times 10^{-5} for bf=1b_f = 1 and 0.19 for bf=3b_f = 3 (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.

python · try it yourself
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 10−1610^{-16}, the last digit of float64, and h_n reproduces the NumPy hTh_T printed earlier (−0.0875,0.0058,…-0.0875, 0.0058, \ldots). 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 (D=64D = 64, H=128H = 128: 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 HH rows in both layouts). The recorded run (CPU):

python · try it yourself
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 0.5590.5^{59} 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_after option that changes where the reset gate applies. Convert by reordering the row blocks.
  • Forgetting c_n. nn.LSTM returns output, (h_n, c_n); unpacking output, h_n = lstm(x) gives a tuple in h_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 HH to 2H2H) 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

  1. How many parameters does nn.LSTM(input_size=32, hidden_size=64, num_layers=2) have?
  2. Write the forget-gate bias initialisation for an nn.LSTM with 2 layers so that it applies to both layers.
  3. In the GRU equations, what happens to hth_t when zt=0z_t = 0 and rt=0r_t = 0? What does this let the cell do?
  4. 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
  1. Layer 0: 4(64⋅(32+64)+2⋅64)=4⋅6272=25,0884(64 \cdot (32 + 64) + 2 \cdot 64) = 4 \cdot 6272 = 25{,}088. Layer 1 takes H=64H = 64 inputs: 4(64⋅128+128)=33,2804(64 \cdot 128 + 128) = 33{,}280. Total 58,368.
  2. for layer in range(2): getattr(lstm, f"bias_ih_l{layer}").data[H:2 * H] = 1.0 (with H = lstm.hidden_size), and optionally zero the same block of bias_hh_l{layer}.
  3. ht=nt=tanh⁡(Winxt+bin+0)h_t = n_t = \tanh(W_{in} x_t + b_{in} + 0): 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).
  4. 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?

  1. f, i, o, g
  2. i, f, g, o
  3. i, f, o, g
  4. g, i, f, o

How many parameters does nn.GRU(input_size=3, hidden_size=5) have?

  1. 50
  2. 120
  3. 150
  4. 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?

  1. The default LSTM has fewer parameters
  2. With forget gates near 0.5, the gradient along the cell path shrinks like 0.5590.5^{59}; near 0.993 it survives
  3. The learning rate differed
  4. The default LSTM has no cell state

In a GRU, which value of the update gate ztz_t copies the previous state unchanged?

  1. zt=0z_t = 0
  2. zt=1z_t = 1
  3. zt=0.5z_t = 0.5
  4. None: a GRU always changes its state