257. 全连接层的反向传播
全连接层计算 y = x @ W + b。给定损失函数对 y 的梯度,反向传播需要三个梯度。
编写 dense_backward(x, W, dy),其中 x 的形状为 (n, d_in),W 的形状为 (d_in, d_out),dy 的形状为 (n, d_out)。返回 (dx, dW, db)。
def dense_backward(x, W, dy)示例 1
输入: dense_backward([[1.0, 2.0]], [[1.0], [0.5]], [[1.0]])
输出: ([[1.0, 0.5]], [[1.0], [2.0]], [1.0])
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 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.
提示 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.
提示 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).
理解思路
全连接层计算 y = x W + b。在反向传播中,你会收到 dy(即损失随每个输出的变化情况),并且必须传回三样东西:输入的梯度、权重的梯度以及偏置的梯度。这些都源于链式法则,且形状可以作为你的指导。
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 = dy 按行求和 = [2]. 对于一个 batch 的行,dW 通过矩阵乘法累加了每一行的贡献,而 db 对 dy 按行求和是因为相同的偏置被加到了每一行。使用均值而不是求和是一个常见的 bug。
dx = dy W^T (形状为 n by d_in); dW = x^T dy (d_in by d_out); db = sum(dy, axis 0) (d_out). 每个 MLP 和 transformer 的 projection 都会用到这个反向传播过程。
公司3
- 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)
来自公开面试报告和指南。与这些公司无隶属关系或背书关系。