261. 运行 MLP 前向传播并保留每一层的 activation
重要性 每个框架的 autograd 都会在 forward pass 期间存储这些 per-layer activations,以便 backward pass 可以使用它们。
Backprop 需要每一层的 activation,因此前向传播应该返回所有 activation,而不仅仅是输出。
编写 mlp_forward(x, layers, acts)。x 是一个 (n, d0) 数组。layers 是一个 (W, b) 对组成的列表,其中第 l 层的 W 形状为 (d_{l-1}, d_l),b 的形状为 (d_l,)。acts 是一个长度相同的列表,指定每一层后的 activation 名称:"relu"、"tanh"、"sigmoid" 或 "linear"。计算 z_l = a_{l-1} @ W_l + b_l 和 a_l = act_l(z_l),其中 a_0 = x。以 float 数组形式返回列表 [a_0, a_1, ..., a_L]。
def mlp_forward(x, layers, acts)示例 1
输入: x = [[1, -2]], layers = [([[1, 0], [0, 1]], [0, 1]), ([[1], [1]], [0.5])], acts = ["relu", "linear"]
输出: [[[1, -2]], [[1, 0]], [[1.5]]]
示例 2
输入: x = [[0.5, 1.0], [-1.0, 0.0]], layers = [([[1.0, -1.0, 0.5], [2.0, 0.0, -1.0]], [0.1, 0.0, -0.2]), ([[1.0], [-1.0], [2.0]], [0.0])], acts = ['tanh', 'sigmoid']
输出: [[[0.5, 1.0], [-1.0, 0.0]], [[0.989027, -0.462117, -0.739783], [-0.716298, 0.761594, -0.604368]], [[0.492895], [0.063767]]]
示例 3
输入: x = [[3.0]], layers = [([[2.0]], [-7.0])], acts = ['relu']
输出: [[[3.0]], [[0.0]]]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
遍历每一层,进行矩阵乘法,加上 bias,然后应用 activation,最后将其 append 到列表中。
提示 2
使用 dict 将名称映射到函数。
提示 3
z = a @ W + b 对 b 使用了 broadcasting。
提示 4
将输入本身作为第一个元素包含在内。
常见错误
- 在 nonlinearity 之后才加上 bias。
- 忘记返回
a_0,这会导致 backprop 中的每个索引发生偏移。
理解思路
MLP 是层的堆叠。每一层做两件事:加权求和,然后是一个 squashing 或 clipping 函数。可以把它想象成一场接力赛,每个跑者在传递接力棒之前都会对其进行一点点改变。我们对层进行编号:a_0 是输入,z_l 是第 l 层的加权和,a_l 是经过 activation 后的输出。
x = [1, -2], W1 是 identity 矩阵且 b1 = [0, 1]。那么 z1 = [1, -1] 且 a1 = relu(z1) = [1, 0]。若 W2 = [[1], [1]] 且 b2 = 0.5,则 z2 = 1 + 0 + 0.5 = 1.5。
z_l = a_{l-1} @ W_l + b_l, a_l = act(z_l)。保留每一个 a_l,因为第 l 层的 gradient 需要 a_{l-1}。从小型 MLP 到 transformer feed-forward blocks,每一个神经网络库都会运行完全相同的循环,并缓存 activations 以供 backprop 使用。
Shape 与数据流
x (n, d0) -> a1 (n, d1) -> ... -> aL (n, dL); W_l is (d_{l-1}, d_l)公司3
- Anthropic a candidate reported this question Anthropic: MLP forward and backward by hand (CircleCoder)
- Meta a candidate reported this question Timed ML screen: concept questions then classic models from scratch (Land the Lab)
- NVIDIA the topic appears in interview reports NVIDIA Interview Prep: Questions, Process & Study Plan
来自公开面试报告和指南。与这些公司无隶属关系或背书关系。