Backpropagate through time in a linear RNN

Training an RNN means backpropagating through every time step. To see the mechanics without nonlinearities, use a linear RNN:

h_t = h_{t-1} @ Wh + x_t @ Wx, starting from h_0 = 0 (zeros)
loss = 0.5 * sum(h_T ** 2), the final state only

Write bptt_grad_Wh(xs, Wx, Wh) returning dL/dWh with the same shape as Wh. xs has shape (T, d_in).

Signaturedef bptt_grad_Wh(xs, Wx, Wh)

Understand the idea

Backpropagation through time unrolls the RNN over every step and applies the chain rule backwards. Since the same Wh is used at every step, its gradient is the sum of contributions from all steps. A linear RNN shows the mechanics clearly. Worked example with scalars: Wx = 1, Wh = 0.5, inputs [1, 1, 1], h0 = 0. Forward: h1 = 1, h2 = 0.5 + 1 = 1.5, h3 = 0.75 + 1 = 1.75. Loss = 0.5 x 1.75^2, so dh3 = 1.75. Step 3 adds h2 x dh3 = 2.625. Pass back: dh2 = dh3 x Wh = 0.875, step 2 adds h1 x 0.875 = 0.875. dh1 = 0.4375, step 1 adds h0 x 0.4375 = 0. Total = 3.5. Check: h3 = w^2 + w + 1, so dL/dw = h3 x (2w + 1) = 1.75 x 2 = 3.5. Rule with matrices: dh_T = h_T; for t = T down to 1, dWh += h_{t-1}^T dh_t, then dh_{t-1} = dh_t Wh^T. Repeated multiplication by Wh^T is why long RNNs get vanishing or exploding gradients.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: four stepsbptt_grad_Wh(_xs, _Wx, _Wh)
  • Sample 2: one step has zero gradientbptt_grad_Wh(_xs[:1], _Wx, _Wh)