PigeonColumba compressa

Lesson 2 of 10

A dense layer: forward and backward

A dense (fully connected) layer with a ReLU computes a = relu(h @ W + b) for a batch h of shape (N, in), weights W of shape (in, out) and bias b of shape (out,).

Backpropagation runs the chain rule backwards. Given g = dL/da (same shape as a), you need three things:

  1. gz = g * (z > 0), where z = h @ W + b. ReLU passes gradient only where it was active.
  2. dW = h.T @ gz and db = gz.sum(axis=0): how the loss changes with each parameter.
  3. dh = gz @ W.T: the gradient to hand to the layer below.

Every network in lab/nn.py is a stack of these. MLP.backward is this function in a loop.

Your code

Where this is used