TExcelTAD

Recurrent Neural Networks

A sensor reading, a sentence, a price series, a melody: the input is a sequence, its length varies, and the meaning of each element depends on what came before. An MLP needs a fixed-size input, and a CNN sees only a fixed window. A recurrent neural network (RNN) reads the sequence one step at a time and carries a hidden state hth_t, a vector that summarises everything seen so far. The same weights are used at every step, so the network handles any length, just as a convolution handles any image size by reusing its kernel.

The Mathematics lessons on RNNs and backpropagation through time derive the equations and the gradient decay. This lesson implements both in NumPy, trains an RNN to predict a noisy signal, measures how gradients fade over time steps, and matches PyTorch's nn.RNN exactly, including the details of its weight layout and output shapes.

The recurrence

At each step the cell combines the new input xtx_t with the previous state:

ht=tanh⁡(Wxxt+Whht−1+b),y^t=Wyht+by,h0=0h_t = \tanh(W_x x_t + W_h h_{t-1} + b), \qquad \hat y_t = W_y h_t + b_y, \qquad h_0 = 0

With input size DD and hidden size HH: WxW_x is H×DH \times D, WhW_h is H×HH \times H, and the cell has HD+H2+HH D + H^2 + H parameters whatever the sequence length. Unrolled over time, an RNN is a deep network with one layer per step and shared weights in every layer:

h0 = 0 tanh tanh tanh tanh h1 h2 h3 WhWhWh x1x2x3x4 Wx Wx Wx Wx y1Wy y2Wy y3Wy y4Wy

Training this unrolled graph with backpropagation is backpropagation through time (BPTT). Going backwards from the last step, the gradient reaching hth_t has two sources: the loss at step tt (through WyW_y) and the step after it (through WhW_h). With ata_t the pre-activation and δt=∂L/∂at\delta_t = \partial L / \partial a_t:

∂L∂ht=Wy⊤∂L∂y^t+Wh⊤δt+1,δt=∂L∂ht⊙(1−ht2)∂L∂Wh=∑tδt ht−1⊤,∂L∂Wx=∑tδt xt⊤,∂L∂b=∑tδt\begin{aligned} \frac{\partial L}{\partial h_t} &= W_y^\top \frac{\partial L}{\partial \hat y_t} + W_h^\top \delta_{t+1}, \qquad \delta_t = \frac{\partial L}{\partial h_t} \odot (1 - h_t^2) \\ \frac{\partial L}{\partial W_h} &= \sum_t \delta_t\, h_{t-1}^\top, \qquad \frac{\partial L}{\partial W_x} = \sum_t \delta_t\, x_t^\top, \qquad \frac{\partial L}{\partial b} = \sum_t \delta_t \end{aligned}

Because the weights are shared, their gradients are sums over time steps: every step contributes.

An RNN in NumPy, trained on a noisy sine

The task: 128 training and 64 validation sequences of a sine wave with a random phase and Gaussian noise (standard deviation 0.1), 20 steps each. At every step the network sees the current value and predicts the next one (many-to-many). The noise alone makes an MSE of 0.12=0.010.1^2 = 0.01 unavoidable. The code stores WxW_x and WhW_h in PyTorch's layout (output rows, input columns) and initialises them as nn.RNN does, uniform in ±1/H\pm 1/\sqrt{H}.

python · try it yourself
import numpy as np

def make_data(rng, n, T=20, noise=0.1):
    """n noisy sine waves (random phase), inputs x_1..x_T, targets x_2..x_{T+1}."""
    t = np.arange(T + 1)
    phase = rng.uniform(0, 2 * np.pi, size=(n, 1))
    s = np.sin(0.4 * t + phase) + noise * rng.normal(size=(n, T + 1))
    return s[:, :-1], s[:, 1:]

def init(rng, H=16, D=1):
    k = 1 / np.sqrt(H)                       # PyTorch's nn.RNN default: U(-1/sqrt(H), 1/sqrt(H))
    return {"Wx": rng.uniform(-k, k, (H, D)), "Wh": rng.uniform(-k, k, (H, H)), "b": np.zeros(H),
            "Wy": rng.uniform(-k, k, (1, H)), "by": np.zeros(1)}

def forward(P, X):
    """X: (N, T) one feature per step. Returns predictions (N, T) and the hidden states."""
    N, T = X.shape
    hs = [np.zeros((N, P["Wh"].shape[0]))]   # h_0 = 0
    for t in range(T):
        hs.append(np.tanh(X[:, t:t + 1] @ P["Wx"].T + hs[-1] @ P["Wh"].T + P["b"]))
    H = np.stack(hs[1:], axis=1)             # (N, T, H)
    return (H @ P["Wy"].T + P["by"])[..., 0], hs

def loss_and_grads(P, X, Y):
    pred, hs = forward(P, X)
    N, T = X.shape
    loss = np.mean((pred - Y) ** 2)
    dpred = 2 * (pred - Y) / (N * T)
    g = {k: np.zeros_like(v) for k, v in P.items()}
    dh_next = np.zeros_like(hs[0])
    for t in reversed(range(T)):             # backpropagation through time
        h, h_prev = hs[t + 1], hs[t]
        dy = dpred[:, t:t + 1]
        g["Wy"] += dy.T @ h
        g["by"] += dy.sum(0)
        dh = dy @ P["Wy"] + dh_next          # from the output at t and from step t+1
        da = dh * (1 - h ** 2)               # through tanh
        g["Wx"] += da.T @ X[:, t:t + 1]
        g["Wh"] += da.T @ h_prev
        g["b"] += da.sum(0)
        dh_next = da @ P["Wh"]               # to h_{t-1}
    return loss, g

rng = np.random.default_rng(0)
X_tr, Y_tr = make_data(rng, 128)
X_va, Y_va = make_data(rng, 64)
P = init(rng)
print("input", X_tr.shape, " hidden per step", P["Wh"].shape[0],
      " parameters", sum(v.size for v in P.values()))

# Gradient check on 8 sequences
loss, g = loss_and_grads(P, X_tr[:8], Y_tr[:8])
worst = 0.0
for name in P:
    for _ in range(4):
        i = tuple(int(rng.integers(s)) for s in P[name].shape)
        old = P[name][i]
        P[name][i] = old + 1e-5; lp, _ = loss_and_grads(P, X_tr[:8], Y_tr[:8])
        P[name][i] = old - 1e-5; lm, _ = loss_and_grads(P, X_tr[:8], Y_tr[:8])
        P[name][i] = old
        num = (lp - lm) / 2e-5
        worst = max(worst, abs(num - g[name][i]) / max(1e-12, abs(num) + abs(g[name][i])))
print("BPTT gradient check:", "ok" if worst < 1e-6 else f"FAILED {worst:.2e}")

# Train with Adam, full batch
m = {k: np.zeros_like(v) for k, v in P.items()}; v2 = {k: np.zeros_like(v) for k, v in P.items()}
for step in range(1, 401):
    loss, g = loss_and_grads(P, X_tr, Y_tr)
    for k in P:
        m[k] = 0.9 * m[k] + 0.1 * g[k]; v2[k] = 0.999 * v2[k] + 0.001 * g[k] ** 2
        P[k] -= 0.01 * (m[k] / (1 - 0.9 ** step)) / (np.sqrt(v2[k] / (1 - 0.999 ** step)) + 1e-8)
    if step in (1, 100, 200, 400):
        va = np.mean((forward(P, X_va)[0] - Y_va) ** 2)
        print(f"step {step:3d}  train MSE {loss:.4f}  val MSE {va:.4f}")

pred = forward(P, X_va)[0]
print(f"val MSE from step 5 on: RNN {np.mean((pred[:, 5:] - Y_va[:, 5:]) ** 2):.4f}, "
      f"repeat-last-value {np.mean((X_va[:, 5:] - Y_va[:, 5:]) ** 2):.4f}, noise floor 0.0100")
input (128, 20)  hidden per step 16  parameters 305
BPTT gradient check: ok
step   1  train MSE 0.5117  val MSE 0.4338
step 100  train MSE 0.0297  val MSE 0.0301
step 200  train MSE 0.0279  val MSE 0.0290
step 400  train MSE 0.0247  val MSE 0.0258
val MSE from step 5 on: RNN 0.0137, repeat-last-value 0.1005, noise floor 0.0100

The 305 parameters (16+256+1616 + 256 + 16 for the cell, 16+116 + 1 for the output) are the same at all 20 steps. The hand-written BPTT agrees with central differences, and Adam brings the validation MSE from 0.4338 at the first step to 0.0258 after 400 steps. The overall number includes the first few steps, where the hidden state has not yet seen enough of the wave to know its phase; from step 5 on, the RNN's validation MSE is 0.0137, close to the noise floor of 0.0100 and far below the 0.1005 of the naive forecast "the next value equals the current one". The hidden state has learned where in the cycle the wave is.

How far back does the gradient reach?

The factor that carries a gradient one step back is Wh⊤diag⁡(1−ht2)W_h^\top \operatorname{diag}(1 - h_t^2). Over kk steps these factors multiply, so the gradient from step TT reaching step T−kT - k shrinks or grows roughly like a power of the largest singular value of WhW_h, damped further by the tanh derivatives, which are at most 1. The experiment below builds WhW_h as a scaled orthogonal matrix (all singular values equal to the scale), runs 40 steps, sends a unit gradient back from the last step and prints its norm kk steps earlier.

python · try it yourself
import numpy as np

# How much of a gradient arriving at the last step reaches step T - k?
rng = np.random.default_rng(0)
H, T = 16, 40
Q = np.eye(H)
for _ in range(3):                                   # product of Householder reflections:
    v = rng.normal(size=H)                           # orthogonal, every singular value is 1
    Q = Q @ (np.eye(H) - 2 * np.outer(v, v) / (v @ v))
x = 0.5 * rng.normal(size=(T, H))                    # input contributions W_x x_t, fixed

for scale in (0.5, 0.9, 1.0, 1.5):
    Wh = scale * Q                                   # spectral radius = scale
    hs = [np.zeros(H)]
    for t in range(T):
        hs.append(np.tanh(Wh @ hs[-1] + x[t]))
    g = np.ones(H) / np.sqrt(H)                      # dL/dh_T with norm 1
    norms = {0: 1.0}
    for k in range(1, T):
        h = hs[T - k + 1]                            # h_{T-k+1}
        g = Wh.T @ (g * (1 - h ** 2))                # dL/dh_{T-k}
        norms[k] = float(np.linalg.norm(g))
    print(f"scale {scale:3.1f}: " + "  ".join(f"k={k:2d} {norms[k]:.1e}" for k in (1, 5, 10, 20, 39)))

# Remove the tanh (a linear RNN): now a scale above 1 explodes
for scale in (0.9, 1.1):
    g = np.ones(H) / np.sqrt(H)
    for k in range(39):
        g = (scale * Q).T @ g
    print(f"linear, scale {scale}: after 39 steps {np.linalg.norm(g):.2e}  (= {scale}^39 = {scale ** 39:.2e})")
scale 0.5: k= 1 4.2e-01  k= 5 9.4e-03  k=10 1.1e-04  k=20 1.5e-08  k=39 2.0e-15
scale 0.9: k= 1 7.0e-01  k= 5 1.2e-01  k=10 1.8e-02  k=20 6.3e-04  k=39 3.9e-07
scale 1.0: k= 1 7.6e-01  k= 5 2.1e-01  k=10 4.8e-02  k=20 4.0e-03  k=39 6.9e-06
scale 1.5: k= 1 8.8e-01  k= 5 1.6e+00  k=10 1.0e+00  k=20 2.1e-01  k=39 1.2e-01
linear, scale 0.9: after 39 steps 1.64e-02  (= 0.9^39 = 1.64e-02)
linear, scale 1.1: after 39 steps 4.11e+01  (= 1.1^39 = 4.11e+01)

With scale 0.5 the gradient is 1.1×10−41.1 \times 10^{-4} after 10 steps and 2.0×10−152.0 \times 10^{-15} after 39: an input 10 steps back has essentially no influence on the weight update. Even at scale 1.0, where a linear recurrence would preserve the norm, the tanh derivatives shrink it to 6.9×10−66.9 \times 10^{-6}. At scale 1.5 the gradient first grows (1.6 at k=5k = 5), but the larger pre-activations saturate the tanh and pull it back to 0.12. Without the tanh, the norm is exactly 0.939=0.01640.9^{39} = 0.0164 or 1.139=41.11.1^{39} = 41.1: a linear RNN vanishes or explodes geometrically. This is the vanishing and exploding gradient problem in its native habitat; the course lesson on it covers it for deep feed-forward stacks. Exploding gradients are handled by gradient clipping; vanishing ones need a different cell, the subject of the next lesson.

nn.RNN, matched

PyTorch's nn.RNN computes

ht=tanh⁡(Wihxt+bih+Whhht−1+bhh)h_t = \tanh(W_{ih} x_t + b_{ih} + W_{hh} h_{t-1} + b_{hh})

with two bias vectors, bias_ih_l0 and bias_hh_l0. They are redundant (only their sum matters), a convention inherited from cuDNN. To copy a single NumPy bias, put it in one and zero the other, or, as below, give the NumPy code both and add them. The recorded run (CPU) copies the weights, runs the same batch through both and inspects the shapes.

python · try it yourself
import numpy as np
import torch
from torch import nn

torch.manual_seed(0)
rnn = nn.RNN(input_size=3, hidden_size=4, batch_first=True)
for name, p in rnn.named_parameters():
    print(f"{name:12s} {tuple(p.shape)}")

# NumPy weights in PyTorch's layout; PyTorch has TWO bias vectors, b_ih and b_hh
rng = np.random.default_rng(0)
Wx, Wh = rng.normal(0, 0.5, (4, 3)), rng.normal(0, 0.5, (4, 4))
b_ih, b_hh = rng.normal(0, 0.1, 4), rng.normal(0, 0.1, 4)
with torch.no_grad():
    for name, a in [("weight_ih_l0", Wx), ("weight_hh_l0", Wh), ("bias_ih_l0", b_ih), ("bias_hh_l0", b_hh)]:
        getattr(rnn, name).copy_(torch.tensor(a))

X = rng.normal(size=(2, 5, 3))                       # batch 2, 5 steps, 3 features
h = np.zeros((2, 4)); outs = []
for t in range(5):
    h = np.tanh(X[:, t] @ Wx.T + h @ Wh.T + b_ih + b_hh)   # the two biases simply add up
    outs.append(h)
out_np = np.stack(outs, axis=1)

output, h_n = rnn(torch.tensor(X, dtype=torch.float32))
print("output", tuple(output.shape), " h_n", tuple(h_n.shape))
print(f"max |torch - numpy|: {np.abs(output.detach().numpy() - out_np).max():.1e}")
print("output[:, -1] == h_n[0]:", torch.equal(output[:, -1], h_n[0]))

# Two layers, batch_first=False (the default): shapes change meaning
rnn2 = nn.RNN(3, 4, num_layers=2)
output, h_n = rnn2(torch.randn(5, 2, 3))             # (T, N, features)
print("2 layers, seq-first: output", tuple(output.shape), " h_n", tuple(h_n.shape))
print("parameters per layer:", [sum(p.numel() for n, p in rnn2.named_parameters() if n.endswith(f"l{i}")) for i in (0, 1)])
weight_ih_l0 (4, 3)
weight_hh_l0 (4, 4)
bias_ih_l0   (4,)
bias_hh_l0   (4,)
output (2, 5, 4)  h_n (1, 2, 4)
max |torch - numpy|: 1.1e-07
output[:, -1] == h_n[0]: True
2 layers, seq-first: output (5, 2, 4)  h_n (2, 2, 4)
parameters per layer: [36, 40]

The outputs agree to float32 precision (1.1×10−71.1 \times 10^{-7}). The module returns two things, and confusing them is the most common RNN bug:

  • output holds the top layer's hidden state at every step: (N, T, H) with batch_first=True, (T, N, H) without it (the default).
  • h_n holds the last step's hidden state of every layer: always (num_layers, N, H), never batch-first. With one layer, output[:, -1] equals h_n[0] exactly.

For a many-to-one task (classify a sequence) use h_n[-1] or output[:, -1]; for many-to-many (a prediction per step, as in the sine task) apply the output layer to all of output. Stacking layers (num_layers=2) feeds the first layer's outputs to the second, whose input size is then HH: here 36 parameters in layer 0 (4⋅3+4⋅4+4+44 \cdot 3 + 4 \cdot 4 + 4 + 4) and 40 in layer 1 (4⋅4+4⋅4+4+44 \cdot 4 + 4 \cdot 4 + 4 + 4). With variable-length sequences in one batch, output[:, -1] is no longer the last real step of every sequence; the sequence training lesson handles that with masks and packing.

Pitfalls

  • batch_first mismatch. The default is (T, N, features). Feeding (N, T, features) to a module built without batch_first=True runs without error and treats the batch as time.
  • output vs h_n. h_n is (num_layers, N, H) even with batch_first=True; h_n[-1] is the last layer.
  • Two biases. Copying weights from another framework or from your own code: either set both biases or zero one of them.
  • Forgetting to reset the state. Each new, unrelated sequence must start from h0=0h_0 = 0 (the default when you pass no h0). Carrying state across batches is deliberate only in truncated BPTT, and then it must be detached.
  • Long sequences with a plain RNN. If the task depends on inputs more than 10 to 20 steps back, a plain tanh RNN will hardly learn it; use an LSTM or GRU.

Practice

  1. How many parameters does nn.RNN(input_size=10, hidden_size=32, num_layers=2) have?
  2. In the NumPy sine model, change the task to many-to-one: predict only the value after the last step. Which lines of loss_and_grads change?
  3. In the gradient experiment, what does the tanh-RNN norm at k=39k = 39 become if the inputs x are multiplied by 4? Predict the direction, then run it.
Answer
  1. Layer 0: 32⋅10+32⋅32+32+32=140832 \cdot 10 + 32 \cdot 32 + 32 + 32 = 1408. Layer 1: 32⋅32+32⋅32+64=211232 \cdot 32 + 32 \cdot 32 + 64 = 2112. Total 3520.
  2. The prediction and the loss use only the last step: loss = np.mean((pred[:, -1] - y) ** 2), and dpred is zero except in its last column (2 * (pred[:, -1] - y) / N). The backward loop stays the same; only dy is zero for all earlier steps, so the earlier steps receive gradient only through dh_next.
  3. It shrinks further: larger inputs push the pre-activations into the flat parts of the tanh, so the factors 1−ht21 - h_t^2 are smaller and the gradient vanishes faster at every scale.

Test yourself

For nn.RNN(input_size=3, hidden_size=4, batch_first=True) and an input of shape (2, 5, 3), what are the shapes of output and h_n?

  1. (2, 5, 4) and (1, 2, 4)
  2. (2, 5, 4) and (2, 1, 4)
  3. (5, 2, 4) and (1, 2, 4)
  4. (2, 4) and (2, 5, 4)

Why are the gradients of WhW_h and WxW_x sums over time steps?

  1. Because the loss is a sum
  2. Because the same weights are used at every step of the unrolled network
  3. Because of the tanh
  4. Because PyTorch has two biases

In the experiment with an orthogonal WhW_h scaled by 0.5, what was the gradient norm 10 steps back from a unit gradient at the last step?

  1. About 0.5
  2. About 10−110^{-1}
  3. About 10−410^{-4}
  4. About 1

PyTorch's nn.RNN has bias_ih_l0 and bias_hh_l0. How do you reproduce it with one NumPy bias bb?

  1. Impossible, the two biases act differently
  2. Set one of them to bb and the other to zero (only the sum matters)
  3. Set both to bb
  4. Set both to b/4b/4