Where the Backward Pass Begins

BackpropagationHard+30 XP+30

Where the Backward Pass Begins

A classifier sorts photos into KKK classes. For one photo, its last layer emits KKK raw scores, the logits z1,…,zKz_1, \dots, z_Kz1​,…,zK​. Softmax turns them into probabilities, and categorical cross-entropy grades the probability given to the true class yyy:

pk=ezk∑jezj,L=−ln⁡pyp_k = \frac{e^{z_k}}{\sum_{j} e^{z_j}}, \qquad L = -\ln p_ypk​=∑j​ezj​ezk​​,L=−lnpy​

Every backward pass through this network starts with the same question: how fast does the loss change when each logit is nudged? The chain from a logit zkz_kzk​ to the loss LLL has two links, and here are both of their rates.

  • The loss link. The loss reads only the true class's probability, so ∂L∂py=−1py\dfrac{\partial L}{\partial p_y} = -\dfrac{1}{p_y}∂py​∂L​=−py​1​. The other probabilities do not appear in LLL at all.
  • The softmax link. Nudging any logit moves pyp_ypy​, because every logit sits in the shared denominator: ∂py∂zk=py ([k=y]−pk)\dfrac{\partial p_y}{\partial z_k} = p_y\,\big([k = y] - p_k\big)∂zk​∂py​​=py​([k=y]−pk​), where [k=y][k = y][k=y] is 111 when kkk is the true class and 000 otherwise.

A training batch holds NNN photos, and the batch's loss is the mean of the NNN per-photo losses.

Task: write logit_gradients(logits, labels).

  • logits is a list of NNN rows, each holding KKK logits.
  • labels is a list of NNN class indices, counting from 0.

Return an N×KN \times KN×K list of lists whose entry [i][k] is the rate of change of the batch loss with respect to logit kkk of photo iii, rounded to 4 decimal places.

A confident model can produce logits in the hundreds. Your function must still return correct, finite numbers for them.

Examples

logits = [[2.0, 1.0, 0.1]]
labels = [0]
returns [[-0.341, 0.2424, 0.0986]]
logits = [[1.0, 3.0], [0.5, -0.5]]
labels = [1, 0]
returns [[0.0596, -0.0596], [-0.1345, 0.1345]]

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