Back Along the Chain

Recurrent NetworksHard+30 XP+30

Back Along the Chain

A plain RNN with a one-number hidden state reads TTT tokens and makes a single prediction at the end.

The forward pass, for t=1,2,…,Tt = 1, 2, \dots, Tt=1,2,…,T:

at=w ht−1+u xt+b,ht=tanh⁡(at)a_t = w\, h_{t-1} + u\, x_t + b, \qquad h_t = \tanh(a_t)at​=wht−1​+uxt​+b,ht​=tanh(at​)

h0h_0h0​ is a fixed starting value, handed to the network rather than learned. The prediction is the final hidden state hTh_ThT​, and the loss is its squared error against a target yyy:

L=(hT−y)2L = (h_T - y)^2L=(hT​−y)2

Only three numbers are learned — www, uuu and bbb — and the same three are used at every one of the TTT steps.

Task: write bptt_grads(tokens, w, u, b, h0, target) returning [dL_dw, dL_du], the gradient of the loss with respect to www and with respect to uuu, in that order, rounded to 4 decimal places.

You will need the derivative of the activation,

ddatanh⁡(a)=1−tanh⁡2(a),\frac{d}{da}\tanh(a) = 1 - \tanh^2(a),dad​tanh(a)=1−tanh2(a),

which, because ht=tanh⁡(at)h_t = \tanh(a_t)ht​=tanh(at​), is simply 1−ht21 - h_t^21−ht2​ at step ttt.

  • The loss exists only at the last step. There is no loss term at any earlier step.
  • tokens is a list of TTT numbers, with T≥1T \ge 1T≥1.
  • Nothing before the first token is learnable, so the backward pass has somewhere to stop.
  • Round only the two numbers you return; keep full precision everywhere in between.

Nothing in this is a new algorithm. It is the chain rule, run along the unrolled chain instead of down a stack of layers. What it buys you is a direct look at the chapter's central claim: feed it a long sequence with ∣w∣|w|∣w∣ well below 111 and watch how little of the loss's influence is left by the time it reaches the first token.

t=0
W
→
t=1
W
→
t=2
W
→
t=3
W
→
t=4
W
error measured here

The prediction — and therefore the loss — usually appears only at the end. But every earlier step contributed to it through the memory it passed along.

Examples

tokens = [1.0, 2.0]
w = 0.5
u = 1.0
b = 0.0
h0 = 0.0
target = 0.0
returns [0.0504, 0.1461]
tokens = [1.0, -1.0, 0.5]
w = 0.8
u = 0.6
b = 0.1
h0 = 0.2
target = 1.0
returns [-0.6508, -0.03]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run