Push a gradient through tanh by the chain rule

Backpropagation is the chain rule applied layer by layer. Here is a tiny network with one hidden layer:

h = tanh(x @ W1 + b1)
y = h @ W2 + b2
loss = mean((y - t) ** 2) over every entry of y

Write mlp_grads(x, t, W1, b1, W2, b2) that returns a dict with the gradients of loss for "W1", "b1", "W2", "b2", each the same shape as the parameter.

x is (n, d_in), t is (n, d_out). Check yourself: the derivative of tanh(a) is 1 - tanh(a) ** 2.

Signaturedef mlp_grads(x, t, W1, b1, W2, b2)

Understand the idea

Backpropagation is the chain rule run backwards: start from the loss and pass the gradient through each layer, multiplying by that layer's local slope. Like tracing a mistake back through each step of a recipe. Worked example with scalars: x = 1, W1 = 0.5, b1 = 0, W2 = 2, b2 = 0, t = 1. Forward: h = tanh(0.5) = 0.4621, y = 0.9242, loss = (y - t)^2 = 0.0057. Backward: dy = 2(y - t) / 1 = -0.1515. dW2 = h * dy = -0.0700, db2 = -0.1515. dh = dy * W2 = -0.3031. Through tanh: da = dh * (1 - h^2) = -0.3031 * 0.7865 = -0.2383. dW1 = x * da = -0.2383, db1 = -0.2383. With matrices: dy = 2(y - t) / y.size; for a linear layer dW = input^T dout, db = sum of dout over rows, dinput = dout W^T; tanh multiplies by 1 - h^2. Every deep learning framework automates exactly these steps.

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

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

  • Sample 1: dW1mlp_grads(_x, _t, _W1, _b1, _W2, _b2)['W1']
  • Sample 2: db1mlp_grads(_x, _t, _W1, _b1, _W2, _b2)['b1']