Recurrent networks in NumPy

A hidden state carried through time, backpropagation through time, and why long sequences make gradients vanish.

What you'll learn
  • Write the Elman RNN recurrence and unroll it over a sequence
  • Explain backpropagation through time and where vanishing gradients come from
  • Verify a recurrent layer's gradients numerically

A feed-forward network sees each input on its own. A recurrent network keeps a hidden state \(h\) and updates it with every new input, so the output at step \(t\) can depend on everything before it. The Elman RNN in RNN.py concatenates the previous state with the new input and pushes both through one fully connected layer and a tanh:

\[h_t = \tanh\!\big(W_h\,[h_{t-1};\, x_t] + b_h\big), \qquad y_t = W_y\, h_t + b_y\]
input_new = np.concatenate((hidden_ax, input_ax), axis=1)   # [h_(t-1); x_t]
u_t = self.FC_h.forward(input_new)
self.h_t[b + 1] = TanH().forward(u_t)
y_t[b] = self.FC_y.forward(self.h_t[b + 1][np.newaxis, :])

In this framework the batch dimension doubles as time: row b of the input is time step b. The memorize flag carries the last hidden state into the next call, so a long sequence can be fed in chunks.

An RNN with a 2-d hidden state unrolled over eight steps. Forward fills the states left to right with the same weights; backward carries the gradient of a loss at step 8 back through time. The halo shows its size. Shrink W_hh and the early steps barely receive any gradient.

Backpropagation through time

Unrolled, an RNN is just a deep network whose layers share weights, and its gradient is the usual chain rule run backwards over time. Every step back multiplies the gradient by the same Jacobian,

\[\frac{\partial h_t}{\partial h_{t-1}} = \operatorname{diag}\!\big(1 - h_t^2\big)\, W_{hh}\]

so after \(k\) steps it has been multiplied \(k\) times. With a recurrent matrix of size 0.5, eight steps shrink a gradient to \(2.6 \times 10^{-3}\) in the animation; at 1.5 it grows instead. This is the vanishing (and exploding) gradient problem, and the reason LSTMs, with an additive cell state, were invented. The repository’s LSTM.py is marked incomplete — its forward pass reuses FC_h where the gates should be, and backward is empty.

Checking the gradient

A central-difference check of RNN.backward on a 5-step sequence shows that its weight gradient does not match: the largest difference, 0.181, is as large as the largest true gradient, 0.182. Two things combine. The gradient of the shared weights must be the sum over all time steps, but the loop keeps only one:

if count <= self.bptt:          # bptt = 0: only the first step processed
    self.gradient_weights_h = self.FC_h.gradient_weights

And FC_h.backward computes each step’s weight gradient from self.lastIn, which after the forward pass holds only the last step’s input; the line that sets self.FC_h.input_tensor writes an attribute the layer never reads. Storing each step’s concatenated input and accumulating dw over the loop fixes both.

A smaller leak: self.h_mem.append(...) runs on every forward call and nothing ever clears it — after 57 forward passes on a 5-step sequence it holds 285 arrays.

LeNet

Models/LeNet.py stacks the framework’s layers into the classic digit classifier: two convolution–ReLU–pooling stages, then three fully connected layers. Its first convolution is declared with 6 input channels, Conv((1, 1), (6, 5, 5), 6), while MNIST has one. NumPy broadcasting lets the forward pass run anyway — each kernel’s six slices are effectively summed — but the backward pass loops only over the input’s single channel, so slices 1 to 5 never receive a gradient. (1, 5, 5) is the intended shape.

Try it yourself. Write a gradient check for RNN: perturb one entry of FC_h.weights, re-run the forward pass on the same 5-step input, and compare with gradient_weights_h. Fix the layer by keeping a list of each step’s input_new and summing the per-step dw, and get the difference below \(10^{-6}\).

View source on GitHub →