257. 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).
def dense_backward(x, W, dy)Example 1
Input: dense_backward([[1.0, 2.0]], [[1.0], [0.5]], [[1.0]])
Output: ([[1.0, 0.5]], [[1.0], [2.0]], [1.0])
Constraints
xhas shape(n, d_in)Whas shape(d_in, d_out)dyhas shape(n, d_out)- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
Each gradient must have the same shape as the thing it is a gradient of, and that alone tells you which matrices to multiply and transpose.
Hint 2
Push dy back through the matrix product for dx and dW, and sum dy over the batch for db, because the bias was added to every row.
Hint 3
dx is (n, d_in), so it is dy @ W.T; dW is (d_in, d_out), so it is x.T @ dy; db is dy.sum(axis=0).
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.
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.
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.
Topics
Companies3
- Anthropic a candidate reported this question ML Coding at Each Company (CircleCoder)
- NVIDIA the topic appears in interview reports NVIDIA Interview Prep: Questions, Process & Study Plan
- OpenAI a candidate reported this question Coding Exercises & ML System Design: Real AI Interview Questions (landedjobs)
From public interview reports and guides. Not affiliated with or endorsed by these companies.