TExcelTAD
Home › Math for Deep Learning & LLMs › Softmax and Cross-Entropy Gradient

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 pi=ezi/∑kezkp_i = e^{z_i}/\sum_k e^{z_k}, differentiate with respect to zjz_j using the quotient rule:

∂pi∂zj={pi(1−pi)i=j−pipji≠j⟺J=diag⁡(p)−ppT\frac{\partial p_i}{\partial z_j} = \begin{cases} p_i(1 - p_i) & i = j \\ -p_ip_j & i \ne j \end{cases} \qquad\Longleftrightarrow\qquad J = \operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^T

JJ is symmetric, and its rows sum to zero (adding a constant to all logits does not change p\mathbf{p}), so J1=0J\mathbf{1} = \mathbf{0}: it is singular.

Chaining with the cross-entropy

The loss for true class yy is ℓ=−log⁡py\ell = -\log p_y, so ∂ℓ∂pi=−[i=y]py\frac{\partial\ell}{\partial p_i} = -\frac{[i = y]}{p_y}. By the chain rule,

∂ℓ∂zj=∑i∂ℓ∂pi∂pi∂zj=−1py∂py∂zj=−1py(py[j=y]−pypj)=pj−[j=y]\frac{\partial\ell}{\partial z_j} = \sum_i \frac{\partial\ell}{\partial p_i}\frac{\partial p_i}{\partial z_j} = -\frac{1}{p_y}\frac{\partial p_y}{\partial z_j} = -\frac{1}{p_y}\left(p_y[j = y] - p_yp_j\right) = p_j - [j = y]
∇zℓ=p−ey\nabla_{\mathbf{z}}\ell = \mathbf{p} - \mathbf{e}_y

Even quicker: ℓ=LSE⁡(z)−zy\ell = \operatorname{LSE}(\mathbf{z}) - z_y, and the gradient of log-sum-exp is the softmax.

python · try it yourself
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 1−py1 - p_y, 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 pyp_y is tiny.

Batches and soft targets

For a batch with mean reduction, G=1B(P−Y)G = \frac{1}{B}(P - Y). With a soft target distribution q\mathbf{q} (label smoothing, distillation), ℓ=−∑iqilog⁡pi\ell = -\sum_i q_i\log p_i and the gradient becomes p−q\mathbf{p} - \mathbf{q}, the same form.

With a softmax temperature TT, p=softmax⁡(z/T)\mathbf{p} = \operatorname{softmax}(\mathbf{z}/T) and the gradient with respect to z\mathbf{z} is 1T(p−q)\frac{1}{T}(\mathbf{p} - \mathbf{q}); distillation multiplies the loss by T2T^2 to keep gradient sizes comparable across temperatures.

python · try it yourself
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_entropy fuses log-softmax and NLL and backpropagates p−ey\mathbf{p} - \mathbf{e}_y directly, never forming the Jacobian (which would be K×KK \times K, about 101010^{10} entries for a 100k-token vocabulary).
  • For huge vocabularies, chunked or "cut" cross-entropy kernels avoid materializing all logits at once.
  • ignore_index zeroes the gradient for padding tokens.

Exercises

Exercise 1: By hand

z=(0,0,ln⁡2)\mathbf{z} = (0, 0, \ln 2), true class 2. Find p\mathbf{p} and ∇zℓ\nabla_{\mathbf{z}}\ell.

Answer

p=(0.25,0.25,0.5)\mathbf{p} = (0.25, 0.25, 0.5), gradient (0.25,0.25,−0.5)(0.25, 0.25, -0.5).

Solution

ez=(1,1,2)e^{\mathbf{z}} = (1, 1, 2), sum 4. Subtract the one-hot (0,0,1)(0, 0, 1).

Exercise 2: Perfect prediction

What is the gradient when py=1p_y = 1 exactly?

Answer

Zero.

Solution

Then p=ey\mathbf{p} = \mathbf{e}_y and p−ey=0\mathbf{p} - \mathbf{e}_y = \mathbf{0}. In practice logits are finite, so py<1p_y < 1 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 −∑iqilog⁡softmax⁡(z)i-\sum_i q_i\log\operatorname{softmax}(\mathbf{z})_i is p−q\mathbf{p} - \mathbf{q} for q=(0.1,0.8,0.1)\mathbf{q} = (0.1, 0.8, 0.1).

Answer

The two vectors agree.

Solution
python · try it yourself
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…

  1. ey−p\mathbf{e}_y - \mathbf{p}
  2. p−ey\mathbf{p} - \mathbf{e}_y
  3. −1/py-1/p_y
  4. diag⁡(p)−ppT\operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^T

Why do the rows of the softmax Jacobian sum to zero?

  1. Because probabilities are positive
  2. Adding a constant to all logits leaves the softmax unchanged
  3. Because it is diagonal
  4. They do not

With soft targets q\mathbf{q}, the gradient becomes…

  1. p−q\mathbf{p} - \mathbf{q}
  2. q\mathbf{q}
  3. pqT\mathbf{p}\mathbf{q}^T
  4. log⁡q\log\mathbf{q}