Backprop through softmax without building the Jacobian

HardAutogradPro

The Jacobian of softmax over n classes is an n by n matrix. For a vocabulary of 128k that is far too big to build. Autograd never builds it: it computes the vector-Jacobian product directly.

For s = softmax(z) and an upstream gradient g = dL/ds, the result is dL/dz = s * (g - sum(g * s)).

Write softmax_vjp(z, g) for 2D arrays (one softmax per row). Return dL/dz with the same shape. Do not build any (n, n) matrix.

Signaturedef softmax_vjp(z, g)

Understand the idea

Softmax mixes all its inputs: raising one logit raises its own probability and lowers every other one. Its full Jacobian is an n by n matrix, diag(s) - s s^T, which is far too big for a large vocabulary. Backprop only needs the Jacobian times the upstream gradient g, and that simplifies to s * (g - sum(g * s)), costing O(n). Worked example: z = [0, 0], so s = [0.5, 0.5]. Upstream g = [1, 0]. sum(g * s) = 0.5. Result = [0.5 x (1 - 0.5), 0.5 x (0 - 0.5)] = [0.25, -0.25]. The entries sum to 0, as they always must, since probabilities always add to 1. Using only the diagonal s(1 - s) g would give [0.25, 0], missing the push-down on other classes. Rule: per row, s = softmax(z) with max subtracted, dot = sum(g * s), dz = s * (g - dot). Never build the (n, n) matrix. LLM training needs this over vocabularies of 100k+ tokens.

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

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: randomsoftmax_vjp(_z, _g)
  • Sample 2: constant upstream gives zerosoftmax_vjp(_z, np.ones((3, 5)))