---
title: Derive the gradient of cross-entropy loss with respect to the logits when predictions come from a softmax. How do you…
url: https://gurkanozkan.ai/learn/questions/research-softmax-cross-entropy-gradient-025/
markdown: https://gurkanozkan.ai/learn/questions/research-softmax-cross-entropy-gradient-025.md
kind: question
role: Research
stage: Technical
difficulty: Medium
json: https://gurkanozkan.ai/api/learn/questions/research-softmax-cross-entropy-gradient-025.json
robots: noindex
---

# Derive the gradient of cross-entropy loss with respect to the logits when predictions come from a softmax. How do you implement the loss so it never overflows or underflows?

Research · Technical · Medium

## Answer

*Model answer, written in a candidate's voice*

### In short

- ∂L/∂z = softmax(z) − onehot(y), via the softmax Jacobian ∂p_i/∂z_k = p_i(δ_ik − p_k).
- Use log-softmax: log p_i = z_i − logsumexp(z), with max subtraction before exponentiating.
- Fuse log-softmax and NLL into one cross-entropy operation and use the fused backward p − y; feed it logits, not probabilities.
- Label smoothing replaces the one-hot target with q, so ∂L/∂z = p − q.

### In full

The core result is ∂L/∂z = p − y, where p = softmax(z) and y is the one-hot target. Deriving it: p_i = exp(z_i)/Σ_j exp(z_j), so ∂p_i/∂z_k = p_i(δ_ik − p_k); with L = −log p_y, ∂L/∂p_i = −y_i/p_i, and substituting gives ∂L/∂z_k = Σ_i (−y_i/p_i) p_i(δ_ik − p_k) = p_k − y_k. Numerically I never form exp(z) directly: I compute m = max(z), logsumexp = m + log(Σ_j exp(z_j − m)), and log p_i = z_i − logsumexp, so the exponentials are ≤ 1 and the denominator is at least 1. I fuse log-softmax and NLL into one cross-entropy op, or use the fused backward, so the gradient is p − y rather than a chain through a separately materialised softmax and log; such fused losses (for example PyTorch's cross_entropy) expect raw logits, so passing probabilities would apply softmax twice. With label smoothing the target becomes q = (1−ε) onehot(y) + ε/K, or ε spread over the non-target classes, and the same derivation gives ∂L/∂z = p − q with loss −Σ_i q_i log p_i.

*Corrected by an independent AI reviewer.*

## What a strong answer covers

- ∂L/∂z = softmax(z) − onehot(y), derived via the softmax Jacobian.
- log-softmax = z − logsumexp(z), subtracting the max before exponentiating.
- Fuse softmax and NLL into one operation.
- How label smoothing changes the target.

## Common mistakes

- Passing probabilities to a loss that expects logits.
- Exponentiating without the max shift.

## Topic guides

- [Deep learning fundamentals](https://gurkanozkan.ai/learn/topics/deep-learning.md)
- [Maths and statistics for ML interviews](https://gurkanozkan.ai/learn/topics/maths-statistics.md)
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
