Backward pass of a dense layer

A dense layer computes y = x @ W + b. Given the gradient of the loss with respect to y, backprop needs three gradients.

Write dense_backward(x, W, dy) for x of shape (n, d_in), W of shape (d_in, d_out) and dy of shape (n, d_out). Return (dx, dW, db).

Signaturedef dense_backward(x, W, dy)

Understand the idea

A dense layer computes y = x W + b. In backprop you receive dy, how the loss changes with each output, and must pass back three things: the gradient for the inputs, for the weights and for the bias. Each comes from the chain rule and the shapes guide you. Worked example: x = [[1, 2]], W = [[1], [3]], dy = [[2]]. dx = dy W^T = [[2 x 1, 2 x 3]] = [[2, 6]]. dW = x^T dy = [[1 x 2], [2 x 2]] = [[2], [4]]. db = sum of dy over rows = [2]. With a batch of rows, dW adds up every row's contribution through the matrix product, and db sums dy over rows because the same bias was added to every row. Taking the mean instead of the sum is a common bug. Rule: dx = dy W^T (shape n by d_in); dW = x^T dy (d_in by d_out); db = sum(dy, axis 0) (d_out). Every MLP and transformer projection uses this backward pass.

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

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: dxdense_backward(_x, _W, _dy)[0]
  • Sample 2: dWdense_backward(_x, _W, _dy)[1]
  • Test 3: dbdense_backward(_x, _W, _dy)[2]