Run an MLP forward pass and keep every layer's activation

Why it matters Every framework's autograd stores these per-layer activations during the forward pass so the backward pass can use them.

Backprop needs the activation of every layer, so a forward pass should return all of them, not only the output.

Write mlp_forward(x, layers, acts). x is an (n, d0) array. layers is a list of (W, b) pairs where layer l has W of shape (d_{l-1}, d_l) and b of shape (d_l,). acts is a list of the same length naming the activation after each layer: "relu", "tanh", "sigmoid" or "linear". Compute z_l = a_{l-1} @ W_l + b_l and a_l = act_l(z_l), with a_0 = x. Return the list [a_0, a_1, ..., a_L] as float arrays.

Signaturedef mlp_forward(x, layers, acts)

Example

x = [[1, -2]], layers = [([[1, 0], [0, 1]], [0, 1]), ([[1], [1]], [0.5])], acts = ["relu", "linear"] gives [[[1, -2]], [[1, 0]], [[1.5]]].

Understand the idea

An MLP is a stack of layers. Each layer does two things: a weighted sum, then a squashing or clipping function. Think of a relay race where each runner changes the baton a little before passing it on. We number the layers: a_0 is the input, z_l is layer l's weighted sum and a_l is its output after the activation.

Tiny example: x = [1, -2], W1 is the identity and b1 = [0, 1]. Then z1 = [1, -1] and a1 = relu(z1) = [1, 0]. With W2 = [[1], [1]] and b2 = 0.5, z2 = 1 + 0 + 0.5 = 1.5.

Rule: z_l = a_{l-1} @ W_l + b_l, a_l = act(z_l). Keep every a_l, because the gradient of layer l needs a_{l-1}.

Every neural network library, from small MLPs to transformer feed-forward blocks, runs exactly this loop and caches the activations for backprop.

Shapes and data flow

x (n, d0) -> a1 (n, d1) -> ... -> aL (n, dL); W_l is (d_{l-1}, d_l)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplemlp_forward([[1.0, -2.0]], [([[1.0, 0.0], [0.0, 1.0]], [0.0, 1.0]), ([[1.0], [1.0]], [0.5])], ['relu', 'lin...
  • Sample 2: tanh sigmoidmlp_forward([[0.5, 1.0], [-1.0, 0.0]], [([[1.0, -1.0, 0.5], [2.0, 0.0, -1.0]], [0.1, 0.0, -0.2]), ([[1.0], ...
  • Test 3: single layermlp_forward([[3.0]], [([[2.0]], [-7.0])], ['relu'])