TExcelTAD
Home › Math for Deep Learning & LLMs › Recurrent Neural Networks

Recurrent Neural Networks

Sequences (text, audio, time series) have variable length and order matters. A recurrent neural network processes them one element at a time, carrying a hidden state that summarizes everything seen so far, and reuses the same weights at every step. RNNs were the standard sequence model before transformers and remain a clean way to see weight sharing across time; their modern descendants (state-space models such as Mamba) revive the idea at scale.

The recurrence

With input xt\mathbf{x}_t and hidden state ht∈Rd\mathbf{h}_t \in \mathbb{R}^d:

ht=tanh⁡(Whhht−1+Wxhxt+bh),ot=Whyht+by\mathbf{h}_t = \tanh(W_{hh}\mathbf{h}_{t-1} + W_{xh}\mathbf{x}_t + \mathbf{b}_h), \qquad \mathbf{o}_t = W_{hy}\mathbf{h}_t + \mathbf{b}_y

starting from h0=0\mathbf{h}_0 = \mathbf{0}. The same three matrices are used at every time step, so the parameter count does not depend on the sequence length. Unrolled in time, an RNN is a very deep feedforward network with tied weights, one layer per step.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
d_in, d_h, d_out = 3, 5, 2
Wxh = rng.normal(0, 0.5, (d_h, d_in)); Whh = rng.normal(0, 0.5, (d_h, d_h)); bh = np.zeros(d_h)
Why = rng.normal(0, 0.5, (d_out, d_h)); by = np.zeros(d_out)
def run(xs):
    h = np.zeros(d_h); outs = []
    for x in xs:
        h = np.tanh(Whh @ h + Wxh @ x + bh)
        outs.append(Why @ h + by)
    return h, np.array(outs)
xs = rng.normal(size=(7, d_in))
h, outs = run(xs)
print("outputs per step:", outs.shape, " final state:", np.round(h, 3))
print("parameters:", Wxh.size + Whh.size + bh.size + Why.size + by.size, "(any sequence length)")
h2, _ = run(xs[::-1])
print("order matters (reversed input gives another state):", not np.allclose(h, h2))
outputs per step: (7, 2)  final state: [ 0.029 -0.168 -0.207  0.376 -0.883]
parameters: 57 (any sequence length)
order matters (reversed input gives another state): True

Ways to use an RNN

  • Many-to-one: read a sequence, classify from the final state (sentiment).
  • Many-to-many, aligned: one output per input (tagging, character-level language models: predict xt+1x_{t+1} from ht\mathbf{h}_t).
  • Sequence-to-sequence: an encoder RNN summarizes the input, a decoder RNN generates the output (early machine translation); the bottleneck of one fixed vector motivated attention.

A character-level RNN language model

At each step the output logits give a distribution over the next character, and the loss is the cross-entropy summed over positions (Language Modeling). Generation feeds each sampled character back as the next input.

python · try it yourself
import numpy as np

text = "hello hello hello"
chars = sorted(set(text)); idx = {c: i for i, c in enumerate(chars)}; V = len(chars)
rng = np.random.default_rng(1)
d = 8
Wxh = rng.normal(0, 0.3, (d, V)); Whh = rng.normal(0, 0.3, (d, d)); Why = rng.normal(0, 0.3, (V, d))
def loss(text):
    h = np.zeros(d); total = 0.0
    for a, b in zip(text[:-1], text[1:]):
        h = np.tanh(Whh @ h + Wxh[:, idx[a]])                 # one-hot input = column lookup
        z = Why @ h; z -= z.max(); p = np.exp(z) / np.exp(z).sum()
        total -= np.log(p[idx[b]])
    return total / (len(text) - 1)
print("vocabulary:", chars)
print(f"untrained loss per character: {loss(text):.4f}  (uniform guess ln {V} = {np.log(V):.4f})")
vocabulary: [' ', 'e', 'h', 'l', 'o']
untrained loss per character: 1.6945  (uniform guess ln 5 = 1.6094)

Training it requires backpropagating through all time steps: Backpropagation Through Time.

Limits

The hidden state must compress the entire past into dd numbers, and gradients over long gaps vanish or explode because the same WhhW_{hh} is multiplied at every step (Vanishing Gradients). Processing is also inherently sequential: step tt needs step t−1t - 1, so training cannot be parallelized over time, the main practical reason transformers replaced RNNs.

In software

  • nn.RNN, nn.LSTM, nn.GRU with batch_first=True take (B, T, d_in) tensors and return all hidden states plus the last one.
  • Variable-length batches are padded and packed (pack_padded_sequence).
  • Linear recurrences (state-space models, RWKV, Mamba) remove the tanh between steps so that training can run as a parallel scan.

Exercises

Exercise 1: Parameter count

An RNN with din=10d_{\text{in}} = 10, dh=20d_h = 20 and dout=5d_{\text{out}} = 5. How many parameters?

Answer
Solution

WxhW_{xh}: 200, WhhW_{hh}: 400, bh\mathbf{b}_h: 20, WhyW_{hy}: 100, by\mathbf{b}_y: 5. Total 725.

Exercise 2: One step by hand

Scalar RNN: ht=tanh⁡(0.5ht−1+xt)h_t = \tanh(0.5h_{t-1} + x_t), h0=0h_0 = 0, inputs 1,01, 0. Compute h1,h2h_1, h_2.

Answer

h1≈0.7616h_1 \approx 0.7616, h2≈0.3634h_2 \approx 0.3634.

Solution

h1=tanh⁡(1)=0.7616h_1 = \tanh(1) = 0.7616; h2=tanh⁡(0.3808)=0.3634h_2 = \tanh(0.3808) = 0.3634. The memory of the first input decays.

Exercise 3: Fading memory (code)

For the scalar RNN of Exercise 2, feed a single 1 followed by zeros and print hth_t for t=1,…,8t = 1, \ldots, 8.

Answer

It decays roughly by half each step.

Solution

Near 0, tanh⁡(u)≈u\tanh(u) \approx u, so ht≈0.5ht−1h_t \approx 0.5h_{t-1}.

python · try it yourself
import numpy as np
h, hs = 0.0, []
for x in [1] + [0] * 7:
    h = np.tanh(0.5 * h + x); hs.append(round(float(h), 4))
print(hs)
[0.7616, 0.3634, 0.1797, 0.0896, 0.0448, 0.0224, 0.0112, 0.0056]

Test yourself

What does an RNN reuse at every time step?

  1. The hidden state values
  2. The same weight matrices
  3. The input
  4. Nothing

Why can't plain RNN training be parallelized across time steps?

  1. The weights change every step
  2. Each hidden state depends on the previous one
  3. GPUs do not support tanh
  4. The loss is not differentiable

Unrolled over TT steps, an RNN is like…

  1. a single layer
  2. a TT-layer feedforward network with tied weights
  3. a convolution
  4. a lookup table