TExcelTAD
Home › Math for Deep Learning & LLMs › LSTM and GRU Gates

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 (0,1)(0, 1) 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 [ht−1;xt][\mathbf{h}_{t-1}; \mathbf{x}_t] the concatenation of previous state and input:

ft=σ(Wf[ht−1;xt]+bf)forget gateit=σ(Wi[ht−1;xt]+bi)input gateot=σ(Wo[ht−1;xt]+bo)output gatec~t=tanh⁡(Wc[ht−1;xt]+bc)candidatect=ft⊙ct−1+it⊙c~tcell stateht=ot⊙tanh⁡(ct)hidden state\begin{aligned} \mathbf{f}_t &= \sigma(W_f[\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_f) && \text{forget gate} \\ \mathbf{i}_t &= \sigma(W_i[\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_i) && \text{input gate} \\ \mathbf{o}_t &= \sigma(W_o[\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_o) && \text{output gate} \\ \tilde{\mathbf{c}}_t &= \tanh(W_c[\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_c) && \text{candidate} \\ \mathbf{c}_t &= \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tilde{\mathbf{c}}_t && \text{cell state} \\ \mathbf{h}_t &= \mathbf{o}_t \odot \tanh(\mathbf{c}_t) && \text{hidden state} \end{aligned}

The key line is the cell update. Its Jacobian along the cell path is simply ∂ct∂ct−1=diag⁡(ft)\frac{\partial\mathbf{c}_t}{\partial\mathbf{c}_{t-1}} = \operatorname{diag}(\mathbf{f}_t): 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.

python · try it yourself
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 10−610^{-6}-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:

zt=σ(Wz[ht−1;xt])update gatert=σ(Wr[ht−1;xt])reset gateh~t=tanh⁡(Wh[rt⊙ht−1;xt])ht=(1−zt)⊙ht−1+zt⊙h~t\begin{aligned} \mathbf{z}_t &= \sigma(W_z[\mathbf{h}_{t-1}; \mathbf{x}_t]) && \text{update gate} \\ \mathbf{r}_t &= \sigma(W_r[\mathbf{h}_{t-1}; \mathbf{x}_t]) && \text{reset gate} \\ \tilde{\mathbf{h}}_t &= \tanh(W_h[\mathbf{r}_t \odot \mathbf{h}_{t-1}; \mathbf{x}_t]) \\ \mathbf{h}_t &= (1 - \mathbf{z}_t) \odot \mathbf{h}_{t-1} + \mathbf{z}_t \odot \tilde{\mathbf{h}}_t \end{aligned}

The new state is a convex combination of the old state and a candidate: with zt≈0\mathbf{z}_t \approx 0 it copies the past. It has three weight blocks instead of four, so about 25% fewer parameters than an LSTM of the same size.

python · try it yourself
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 z\mathbf{z} near 0, and the state remembers its starting value through 10 noisy inputs.

Counting parameters

An LSTM with input size nn and hidden size dd has 4(d(d+n)+d)4(d(d + n) + d) parameters (four gate blocks); a GRU has 3(d(d+n)+d)3(d(d + n) + d) (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.GRU returns (output, h_n).
  • PyTorch stacks the four gate matrices into one weight_ih_l0 of 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

4(256⋅356+256)=4(91,136+256)=365,5684(256 \cdot 356 + 256) = 4(91{,}136 + 256) = 365{,}568.

Exercise 2: Perfect memory

What gate values make an LSTM cell keep ct−1\mathbf{c}_{t-1} exactly and ignore the input?

Answer

ft=1\mathbf{f}_t = \mathbf{1}, it=0\mathbf{i}_t = \mathbf{0}.

Solution

Then ct=ct−1\mathbf{c}_t = \mathbf{c}_{t-1} and ∂ct/∂ct−1=I\partial\mathbf{c}_t/\partial\mathbf{c}_{t-1} = I: neither the value nor its gradient decays.

Exercise 3: Cell-path decay (code)

With a constant forget gate ff, the cell-path gradient after kk steps is fkf^k. For f=0.5,0.9,0.99f = 0.5, 0.9, 0.99 print f100f^{100}.

Answer

About 8×10−318 \times 10^{-31}, 2.7×10−52.7 \times 10^{-5} and 0.370.37.

Solution
python · try it yourself
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?

  1. They use ReLU
  2. The cell state is updated additively, with Jacobian diag⁡(ft)\operatorname{diag}(\mathbf{f}_t) along the cell path
  3. They have no recurrence
  4. They use larger learning rates

What range do gate values take?

  1. (−1,1)(-1, 1)
  2. (0,1)(0, 1)
  3. [0,∞)[0, \infty)
  4. {0,1}\{0, 1\} only

A GRU's new state is…

  1. the candidate only
  2. a gate-weighted combination of the old state and a candidate
  3. the input
  4. a product of all gates