Vanilla RNNs
The concrete equations behind the recurrent cell: weight matrices, tanh, and backpropagation through time.
The previous article established what a sequential model needs: a hidden state that is updated at every step using the same function . It left undefined. This article fills that gap with the simplest possible implementation — the vanilla RNN — and examines both how it works and where it breaks down.
The Cell Equation
The vanilla RNN defines the update function as a linear transformation of the concatenated input and previous state, followed by a hyperbolic tangent:
Three sets of parameters are shared across every time step:
- : the recurrent weight matrix, mapping the previous state to the new pre-activation.
- : the input weight matrix, mapping the current input to the pre-activation.
- : a bias vector.
The two terms are summed, the bias is added, and the result is squashed element-wise through tanh to produce the next state. The total parameter count is , independent of sequence length. An RNN with hidden units and -dimensional inputs has parameters — the same whether the sequence contains 5 tokens or 5,000.
Why tanh? Tanh bounds every element of to , preventing the state from growing without limit as it passes through step after step. An unbounded activation would cause the state to diverge on any non-trivial input. Tanh is also zero-centered, which helps gradients flow more evenly. The cost — as the Activation Functions article noted — is that tanh saturates for large inputs, squashing its gradient toward zero. This cost becomes severe during training, as we will see below.
The Output Layer
The hidden state is not the final output. A separate linear layer maps the state to the task-specific output:
For a many-to-one task (e.g., sentiment classification), only — the output at the final step — is used, and the loss is computed once. For a many-to-many task (e.g., language modelling), is computed at every step, and the loss is summed across all positions. The state-update parameters , , are shared across steps; , are applied at output positions only.
The Forward Pass
Running a sequence of inputs through the RNN is a simple loop. Each step takes the current input and the previous state, applies the cell equation, and emits the new state.
Numerical example. With , , and:
Processing , , :
At each step the state blends the new input with a decayed version of the previous state ( scales each dimension by ). After three steps, reflects the influence of all three inputs, with recent inputs weighted more heavily than earlier ones.
Backpropagation Through Time
Training the RNN uses the same loss, backward pass, and optimizer from the Training section. The twist is that the computation graph is unrolled through time: every application of the cell equation is a node in the graph, and the shared parameters , , appear at every step.
When .backward() is called, gradients accumulate from every node where the parameters were used (the gradient accumulation rule from the Computation Graph article). For , the gradient sums contributions:
Computing for steps far from the output requires propagating gradients backward through every intermediate step. The gradient at step reaching step involves the product:
This is a product of matrices. What happens to this product over many steps is the central practical problem of vanilla RNNs.
Vanishing and Exploding Gradients
The behaviour of the Jacobian product depends on the spectral radius of : the largest absolute eigenvalue, denoted .
Since , the product of the two factors is at most . If , the norm of the gradient decays geometrically with : after 20 steps back in time, the gradient contribution is at most , and after 50 steps it is below . The parameters at early steps receive virtually no gradient signal and cannot be updated to capture long-range patterns. If , the gradient grows without bound, causing numerical overflow and training divergence.
The flat "stable" curve requires exactly — a condition impossible to maintain throughout training. In practice, gradient norms almost always collapse to near-zero or explode. The vanishing case is by far the more common and the harder to fix.
Practical Mitigations
Gradient clipping. Exploding gradients can be controlled by rescaling the gradient whenever its norm exceeds a threshold :
This prevents overflow but does nothing about gradients that are already near zero.
Truncated BPTT. Rather than unrolling the full sequence at training time, gradients are propagated backward only steps. This bounds the computational cost and avoids extreme vanishing, but the model cannot learn dependencies longer than steps by construction.
Both mitigations address symptoms rather than the root cause. They make vanilla RNNs trainable on short sequences but leave long-range dependencies out of reach.
When Vanilla RNNs Are Sufficient
Despite their limitations, vanilla RNNs work well for tasks where relevant context is local:
- Short sequences (up to ~20 steps): the vanishing gradient is mild enough that all positions contribute meaningful gradients.
- Character-level language modelling with limited context: predicting the next character in a word requires little history.
- Shallow sequence classification where the final state provides a reasonable summary of the full input.
For tasks requiring genuine long-range memory — a word referring back to something stated 50 tokens earlier, or a time series pattern spanning hundreds of steps — vanilla RNNs consistently fail. That failure, and the architectural solution to it, is the subject of the next article.
In Code
import torch
import torch.nn as nn
import torch.nn.functional as F
# ── VanillaRNN as a proper nn.Module ─────────────────────────────────────────
# h_t = tanh(linear_h(h_{t-1}) + linear_x(x_t))
# Two nn.Linear layers replace the raw Wh, Wx, bh tensors:
# linear_h: hidden → hidden, no bias (Wh @ h_{t-1})
# linear_x: input → hidden, with bias (Wx @ x_t + bh)
class VanillaRNN(nn.Module):
def __init__(self, input_size: int, hidden_size: int):
super().__init__()
self.hidden_size = hidden_size
self.linear_h = nn.Linear(hidden_size, hidden_size, bias=False)
self.linear_x = nn.Linear(input_size, hidden_size, bias=True)
def forward(self, xs, h=None):
if h is None:
h = torch.zeros(self.hidden_size)
hs = []
for x in xs:
# The graph is unrolled through time: BPTT happens automatically
h = torch.tanh(self.linear_h(h) + self.linear_x(x))
hs.append(h)
return hs # one hidden state per input step
# ── Forward pass ─────────────────────────────────────────────────────────────
rnn = VanillaRNN(input_size=2, hidden_size=4)
inputs = [torch.tensor([1.0, 0.0]), torch.tensor([0.0, 1.0]), torch.tensor([0.5, 0.5])]
hs = rnn(inputs)
print(hs[-1]) # final hidden state, shape (4,)
for name, p in rnn.named_parameters():
print(name, tuple(p.shape))
# linear_h.weight (4, 4)
# linear_x.weight (4, 2)
# linear_x.bias (4,)
# ── Many-to-one classifier: RNN + output linear layer ────────────────────────
# The final hidden state is fed into a Linear layer to produce class logits.
class RNNClassifier(nn.Module):
def __init__(self, input_size: int, hidden_size: int, num_classes: int):
super().__init__()
self.rnn = VanillaRNN(input_size, hidden_size)
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, xs):
hs = self.rnn(xs)
h_final = hs[-1] # only the last state carries the full context
return self.fc(h_final) # (num_classes,) logits
model = RNNClassifier(input_size=2, hidden_size=8, num_classes=3)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
# Toy task: fixed 5-step sequence, the target class is 1
seq = [torch.randn(2) for _ in range(5)]
target = torch.tensor([1])
for step in range(30):
optimizer.zero_grad()
logits = model(seq)
loss = F.cross_entropy(logits.unsqueeze(0), target)
loss.backward() # backpropagates through all 5 unrolled steps (BPTT)
# Gradient clipping: essential for RNN stability, it caps exploding gradients
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
if step % 10 == 0:
print(f"step {step:2d} loss={loss.item():.4f} pred={logits.argmax().item()}")
# step 0 loss=1.2xxx pred=?
# step 10 loss=0.5xxx pred=1
# step 20 loss=0.2xxx pred=1
# ── The built-in version: nn.RNN wraps the full sequence loop ────────────────
rnn = nn.RNN(
input_size=2,
hidden_size=4,
batch_first=True, # input shape: (batch, seq_len, input_size)
nonlinearity="tanh",
)
# Input: batch=2, seq_len=5, input_size=2
x = torch.randn(2, 5, 2)
h0 = torch.zeros(1, 2, 4) # (num_layers, batch, hidden_size)
output, hn = rnn(x, h0)
print(output.shape) # torch.Size([2, 5, 4]) — h_t at every step
print(hn.shape) # torch.Size([1, 2, 4]) — h_T only
# Many-to-one classifier
fc = nn.Linear(4, 3)
logits = fc(hn.squeeze(0)) # (batch, 3)
# Many-to-many (e.g., sequence labelling)
logits_all = fc(output) # (batch, seq_len, 3)
The vanilla RNN is the direct translation of the hidden-state abstraction into differentiable operations. It works, but its reliance on repeated matrix multiplication means that long-range gradients either vanish or explode. Fixing this requires an architecture that can selectively retain, update, and forget information over many steps — the gating mechanisms introduced in the next article.