LSTM and GRU Gates
The long short-term memory cell (Hochreiter and Schmidhuber, 1997) fixed the vanishing gradients of plain RNNs with one idea: keep a cell state that is updated additively, and let learned gates decide what to forget, what to write and what to read. The gated recurrent unit (GRU) is a lighter variant with two gates. Both dominated sequence modeling until transformers, and the gating idea lives on in SwiGLU and in modern state-space models.
Gates
A gate is a vector of values in computed by a sigmoid from the current input and previous hidden state, used to multiply another vector elementwise: 0 blocks, 1 passes.
The LSTM cell
With the concatenation of previous state and input:
The key line is the cell update. Its Jacobian along the cell path is simply : no weight matrix, no squashing. When the forget gate is near 1, gradients pass back through many steps almost unchanged, like a residual connection in time. That is why forget-gate biases are often initialized to about 1 or 2.
import numpy as np
rng = np.random.default_rng(0)
d_in, d = 3, 4
W = {g: rng.normal(0, 0.4, (d, d + d_in)) for g in "fioc"}
b = {"f": np.full(d, 2.0), "i": np.zeros(d), "o": np.zeros(d), "c": np.zeros(d)} # forget bias 2
sig = lambda z: 1 / (1 + np.exp(-z))
def lstm_step(h, c, x):
v = np.concatenate([h, x])
f, i, o = (sig(W[g] @ v + b[g]) for g in "fio")
c_new = f * c + i * np.tanh(W["c"] @ v + b["c"])
return o * np.tanh(c_new), c_new, f
h, c = np.zeros(d), np.zeros(d)
c_grad = np.ones(d) # gradient flowing back along the cell path
for t in range(30):
h, c, f = lstm_step(h, c, rng.normal(size=d_in))
c_grad = c_grad * f
print("mean forget gate:", round(float(f.mean()), 3))
print("cell-path gradient after 30 steps:", np.round(c_grad, 3))
print("parameters:", sum(w.size for w in W.values()) + sum(v.size for v in b.values()), "= 4 * (d*(d+d_in) + d)")mean forget gate: 0.886
cell-path gradient after 30 steps: [0.007 0.012 0.016 0.013]
parameters: 128 = 4 * (d*(d+d_in) + d)
With forget gates around 0.89, the gradient along the cell path after 30 steps is still around one percent, compared with the -scale decay typical of a plain tanh RNN. Forget gates closer to 1 (a larger bias) keep even more.
The GRU
The GRU merges the cell and hidden state and uses two gates:
The new state is a convex combination of the old state and a candidate: with it copies the past. It has three weight blocks instead of four, so about 25% fewer parameters than an LSTM of the same size.
import numpy as np
rng = np.random.default_rng(1)
d_in, d = 2, 3
Wz, Wr, Wh = (rng.normal(0, 0.5, (d, d + d_in)) for _ in range(3))
sig = lambda z: 1 / (1 + np.exp(-z))
def gru_step(h, x, z_bias=0.0):
v = np.concatenate([h, x])
z = sig(Wz @ v + z_bias); r = sig(Wr @ v)
h_tilde = np.tanh(Wh @ np.concatenate([r * h, x]))
return (1 - z) * h + z * h_tilde
h0 = np.array([1.0, -1.0, 0.5])
for bias in (0.0, -4.0):
h = h0.copy()
for t in range(10):
h = gru_step(h, rng.normal(size=d_in), z_bias=bias)
print(f"update-gate bias {bias:+.0f}: state after 10 steps {np.round(h, 3)} (started at {h0})")update-gate bias +0: state after 10 steps [-0.732 -0.214 0.389] (started at [ 1. -1. 0.5])
update-gate bias -4: state after 10 steps [ 0.831 -0.682 0.428] (started at [ 1. -1. 0.5])
A strongly negative update-gate bias keeps near 0, and the state remembers its starting value through 10 noisy inputs.
Counting parameters
An LSTM with input size and hidden size has parameters (four gate blocks); a GRU has (frameworks add a second bias per block, slightly more).
In software
nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)returns(output, (h_n, c_n));nn.GRUreturns(output, h_n).- PyTorch stacks the four gate matrices into one
weight_ih_l0of shape(4d, n)for speed. - Gated linear recurrences (Mamba, xLSTM, RWKV) drop the nonlinearity on the state so that training can use a parallel scan, recovering transformer-like training speed.
Exercises
Exercise 1: LSTM size
How many parameters does an LSTM with input size 100 and hidden size 256 have (one bias per gate)?
Answer
365,568.
Solution
.
Exercise 2: Perfect memory
What gate values make an LSTM cell keep exactly and ignore the input?
Answer
, .
Solution
Then and : neither the value nor its gradient decays.
Exercise 3: Cell-path decay (code)
With a constant forget gate , the cell-path gradient after steps is . For print .
Answer
About , and .
Solution
for f in (0.5, 0.9, 0.99):
print(f, f"{f ** 100:.2e}")0.5 7.89e-31
0.9 2.66e-05
0.99 3.66e-01
Test yourself
Why do LSTMs suffer less from vanishing gradients than plain RNNs?
- They use ReLU
- The cell state is updated additively, with Jacobian along the cell path
- They have no recurrence
- They use larger learning rates
What range do gate values take?
- only
A GRU's new state is…
- the candidate only
- a gate-weighted combination of the old state and a candidate
- the input
- a product of all gates