The Softmax and Cross-Entropy Gradient
The single most-used gradient in deep learning is that of softmax followed by cross-entropy: every classifier and every language model starts its backward pass with it. The result is remarkably simple, predicted probabilities minus the one-hot target, and deriving it carefully, through the softmax Jacobian, is a good workout in matrix calculus (Jacobians).
The softmax Jacobian
With , differentiate with respect to using the quotient rule:
is symmetric, and its rows sum to zero (adding a constant to all logits does not change ), so : it is singular.
Chaining with the cross-entropy
The loss for true class is , so . By the chain rule,
Even quicker: , and the gradient of log-sum-exp is the softmax.
import numpy as np
z = np.array([2.0, 1.0, 0.1]); y = 0
p = np.exp(z - z.max()); p /= p.sum()
J = np.diag(p) - np.outer(p, p)
print("p =", np.round(p, 4))
print("Jacobian:\n", np.round(J, 4))
print("rows sum to 0:", np.allclose(J.sum(1), 0))
dl_dp = -np.eye(3)[y] / p[y]
print("chain rule J^T dl/dp:", np.round(J.T @ dl_dp, 4))
print("shortcut p - e_y: ", np.round(p - np.eye(3)[y], 4))p = [0.659 0.2424 0.0986]
Jacobian:
[[ 0.2247 -0.1598 -0.065 ]
[-0.1598 0.1837 -0.0239]
[-0.065 -0.0239 0.0889]]
rows sum to 0: True
chain rule J^T dl/dp: [-0.341 0.2424 0.0986]
shortcut p - e_y: [-0.341 0.2424 0.0986]
What the gradient means
- Each wrong class is pushed down in proportion to the probability the model gave it.
- The true class is pushed up by , its missing probability.
- The components sum to zero: probability mass is moved, not created.
- The gradient never exceeds 1 in size per component, so the loss cannot produce exploding gradients by itself, even when is tiny.
Batches and soft targets
For a batch with mean reduction, . With a soft target distribution (label smoothing, distillation), and the gradient becomes , the same form.
With a softmax temperature , and the gradient with respect to is ; distillation multiplies the loss by to keep gradient sizes comparable across temperatures.
import numpy as np
rng = np.random.default_rng(0)
B, K = 4, 5
Z = rng.normal(size=(B, K)); y = np.array([1, 0, 4, 2])
def loss(Z):
Zs = Z - Z.max(1, keepdims=True)
return np.mean(np.log(np.exp(Zs).sum(1)) - Zs[np.arange(B), y])
P = np.exp(Z - Z.max(1, keepdims=True)); P /= P.sum(1, keepdims=True)
G = (P - np.eye(K)[y]) / B
num = np.zeros_like(Z)
for idx in np.ndindex(Z.shape):
E = np.zeros_like(Z); E[idx] = 1e-6
num[idx] = (loss(Z + E) - loss(Z - E)) / 2e-6
print("max |analytic - numeric|:", f"{np.abs(G - num).max():.1e}")
print("each row of G sums to 0:", np.allclose(G.sum(1), 0))max |analytic - numeric|: 2.3e-10
each row of G sums to 0: True
In software
F.cross_entropyfuses log-softmax and NLL and backpropagates directly, never forming the Jacobian (which would be , about entries for a 100k-token vocabulary).- For huge vocabularies, chunked or "cut" cross-entropy kernels avoid materializing all logits at once.
ignore_indexzeroes the gradient for padding tokens.
Exercises
Exercise 1: By hand
, true class 2. Find and .
Answer
, gradient .
Solution
, sum 4. Subtract the one-hot .
Exercise 2: Perfect prediction
What is the gradient when exactly?
Answer
Zero.
Solution
Then and . In practice logits are finite, so and the gradient keeps (slowly) growing the logit gap, which is what label smoothing prevents.
Exercise 3: Soft targets (code)
Verify numerically that the gradient of is for .
Answer
The two vectors agree.
Solution
import numpy as np
z, q = np.array([0.3, -1.0, 2.0]), np.array([0.1, 0.8, 0.1])
L = lambda z: -np.sum(q * (z - np.log(np.sum(np.exp(z)))))
p = np.exp(z) / np.exp(z).sum()
num = np.array([(L(z + e) - L(z - e)) / 2e-6 for e in np.eye(3) * 1e-6])
print(np.allclose(p - q, num, atol=1e-8))True
Test yourself
The gradient of softmax cross-entropy with respect to the logits is…
Why do the rows of the softmax Jacobian sum to zero?
- Because probabilities are positive
- Adding a constant to all logits leaves the softmax unchanged
- Because it is diagonal
- They do not
With soft targets , the gradient becomes…