Derive the gradient of softmax plus cross-entropy

The last layer of almost every classifier and language model is softmax followed by cross-entropy. Its gradient with respect to the logits has a famously short form, and every framework hard-codes it.

Write softmax_ce_grad(logits, labels) for logits of shape (n, c) and integer labels of shape (n,). Return (loss, grad):
- loss: the mean cross-entropy over the n rows.
- grad: shape (n, c), the gradient of that mean loss with respect to the logits.

Keep it numerically stable for large logits.

Signaturedef softmax_ce_grad(logits, labels)

Understand the idea

Softmax followed by cross-entropy is the last step of almost every classifier and language model. Its gradient with respect to the logits is beautifully simple: predicted probabilities minus the one-hot label. If the model is already right, the push is small; if it is wrong, the push is large. Worked example, one row, logits [2, 0], label 0. Softmax is [0.881, 0.119]. Loss = -ln(0.881) = 0.127. Gradient = [0.881 - 1, 0.119 - 0] = [-0.119, 0.119]. Because the loss here is the mean over n rows, every row's gradient is then divided by n. For large logits subtract the row max before exp, and compute log-probabilities as z - max - log(sum(exp)) to avoid log of 0. Rule: loss = mean over rows of -log softmax(z)[y]; grad = (softmax(z) - onehot(y)) / n. PyTorch and every other framework hard-code this fused gradient for speed and stability.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: losssoftmax_ce_grad(_z, _y)[0]
  • Sample 2: gradientsoftmax_ce_grad(_z, _y)[1]
  • Test 3: huge logits stay finitesoftmax_ce_grad([[1000.0, 0.0]], [0])
  • Test 4: gradient rows sum to 0softmax_ce_grad(_z, _y)[1].sum(axis=1)