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 and hidden state :
starting from . 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.
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 from ).
- 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.
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 numbers, and gradients over long gaps vanish or explode because the same is multiplied at every step (Vanishing Gradients). Processing is also inherently sequential: step needs step , so training cannot be parallelized over time, the main practical reason transformers replaced RNNs.
In software
nn.RNN,nn.LSTM,nn.GRUwithbatch_first=Truetake(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 , and . How many parameters?
Answer
Solution
: 200, : 400, : 20, : 100, : 5. Total 725.
Exercise 2: One step by hand
Scalar RNN: , , inputs . Compute .
Answer
, .
Solution
; . 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 for .
Answer
It decays roughly by half each step.
Solution
Near 0, , so .
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?
- The hidden state values
- The same weight matrices
- The input
- Nothing
Why can't plain RNN training be parallelized across time steps?
- The weights change every step
- Each hidden state depends on the previous one
- GPUs do not support tanh
- The loss is not differentiable
Unrolled over steps, an RNN is like…
- a single layer
- a -layer feedforward network with tied weights
- a convolution
- a lookup table