Blame on Every Wire

BackpropagationMedium+20 XP+20

Blame on Every Wire

During the backward pass every layer is handed an error signal: one number per neuron, saying how fast the loss changes as that neuron's weighted sum zzz changes. Receiving it is only half of the layer's job. The layer still has to turn it into a gradient for each of its own weights and biases, one per connection, so that every one of them can be updated.

The layer is dense and its weights are stored as a connection table, with one row per input and one column per neuron: weights[i][j] is the weight on the wire from input i to neuron j. With ddd inputs and kkk neurons the table is d×kd \times kd×k. On one example, neuron jjj computes

zj=∑ixi⋅weights[i][j]+biases[j]z_j = \sum_i x_i \cdot \text{weights}[i][j] + \text{biases}[j]zj​=∑i​xi​⋅weights[i][j]+biases[j]

The training step runs a batch of nnn examples, and the loss it minimises is the average of the examples' own losses:

L=1n∑e=1nLeL = \frac{1}{n}\sum_{e=1}^{n} L_eL=n1​∑e=1n​Le​

For each example eee you are given two lists:

  • inputs[e]: the ddd values xix_ixi​ that arrived at the layer on that example. The forward pass stored them.
  • errors[e]: the kkk error signals the backward pass delivered for that example alone. Entry jjj is ∂Le∂zj\dfrac{\partial L_e}{\partial z_j}∂zj​∂Le​​, how fast example eee's own loss changes as neuron jjj's weighted sum on that example changes.

Task: write layer_gradients(inputs, errors), returning [weight_grads, bias_grads]:

  • weight_grads: a d×kd \times kd×k table in the same layout as weights. Entry [i][j] is ∂L∂ weights[i][j]\dfrac{\partial L}{\partial\, \text{weights}[i][j]}∂weights[i][j]∂L​, the gradient of the batch loss LLL.
  • bias_grads: kkk entries, where entry jjj is ∂L∂ biases[j]\dfrac{\partial L}{\partial\, \text{biases}[j]}∂biases[j]∂L​.

Round every value to 4 decimal places. inputs has n≥1n \ge 1n≥1 rows of ddd numbers, and errors has the same nnn rows, each of kkk numbers. A table with a single row or a single column is still a list of lists.

Notice what this function was never given: the layer's weights. Everything it needed was either stored on the way forward or delivered on the way back. That is why a training framework keeps every layer's input in memory until the backward pass has come through. The forward pass cannot throw them away as soon as the next layer has used them.

Examples

inputs = [[1.0, 2.0, 0.5], [0.0, -1.0, 2.0]]
errors = [[0.5, -1.0], [2.0, 0.25]]
returns [[[0.25, -0.5], [-0.5, -1.125], [2.125, 0.0]], [1.25, -0.375]]
inputs = [[1.0, -2.0], [0.5, 1.0], [3.0, 0.0]]
errors = [[0.2, 0.4], [-1.0, 0.6], [0.1, -0.3]]
returns [[[0.0, -0.0667], [-0.4667, -0.0667]], [-0.2333, 0.2333]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run