Unit 2 of 7 · about 5 hours · derive, implement
Stable softmax, cross-entropy and loss reductions
Classification and contrastive objectives call softmax and cross-entropy on raw logits. The naive form overflows on ordinary inputs, and the wrong reduction silently rescales every gradient.
You'll be able to
- Derive the per-example cross-entropy with logits as , and its gradient minus one-hot().
- Implement max-subtracted softmax and log-softmax that never overflow, and binary cross-entropy with logits that never takes log of a rounded sigmoid.
- State sum, mean and masked-mean reductions exactly: divisor used, and which positions get zero gradient.
Covers
Read
In this order, only the parts listed
0 of 4 done
- Losses from maximum likelihoodUnderstanding Deep Learning - Chapters 3 to 7
Chapter 5, Sections 5.1 to 5.2 (Eq 5.1 to 5.6, printed pp. 56 to 60) for likelihood to negative log-likelihood; Section 5.3 (Eq 5.7 to 5.15, pp. 61 to 64) for least squares; Section 5.4 (Eq 5.16 to 5.20, pp. 64 to 66) for sigmoid plus binary cross-entropy; Section 5.5 (Eq 5.21 to 5.24, pp. 67 to 69) and Section 5.7 (Eq 5.27 to 5.31, pp. 71 to 72) for softmax plus multiclass cross-entropy
- Naive softmax and the spelled-out cross-entropyD2L - tensors, autograd, MLP and backpropagation
The Softmax: the three-step naive code plus the warning that it is not robust and not for serious use; The Cross-Entropy Loss:
y_hat[[0, 1], y]indexing and thereduce_meanof negative logsDo not copy the naive softmax or the log-of-probability loss into your own code. Use them only to see what the stable versions below replace.
- The max-subtraction trickCS231n Linear Classification - Softmax classifier and numeric stability
Softmax classifier: ; Practical issues: Numeric stability: the
f -= np.max(f)code turning[123, 456, 789]into[-666, -333, 0] - Masked reductions in
cross_entropy`torch.nn.functional.cross_entropy` - `reduction` and `ignore_index`ignore_indexandreductionparameters: ignored targets contribute no gradient, and mean averages over the non-ignored targets only
Focus on
- Max subtraction is exact, not approximate: shifting every logit by multiplies numerator and denominator by , which cancels. The largest shifted logit is 0, so every input is at most 0 and no term overflows.
- The fused per-example loss is , and its logit gradient is minus one-hot(). This matches centered differences to about 1e-9 in
float64. - Binary cross-entropy with logits must use the log-sigmoid form, never sigmoid followed by log: a confident sigmoid rounds to exactly 0 or 1 and the log is then infinite. Its logit gradient is .
- Mean divides every gradient by ; a masked mean divides by the valid count and gives masked positions exactly zero gradient. D2L
cross_entropyusesreduce_mean; UDL least squares (Eq 5.11) sums.
Common mistakes · 3
- Taking in two steps. Even with max subtraction, a very small probability can underflow to 0 and its log becomes
-inf.log_softmax(z)= , with the max, never forms the probability. - Clipping probabilities after a naive softmax to fix overflow.
exp(1000)already overflowed toinfand the division already producednan; clipping cannot recover the true distribution. - Expecting the stable answer on
[1000, 1001, 1002]to be[1, 0, 0]. Only logit gaps matter, so the result equalssoftmax([0, 1, 2]): about[0.09, 0.245, 0.665].
Try it yourself
Closed-book, before checking anything
log_softmax with max subtraction and a cross-entropy returning per-example losses plus their mean. Derive minus one-hot(). Show softmax([1000, 1001, 1002]) = [0.0900, 0.2447, 0.6652], and explain why the naive form returns [nan, nan, nan].Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why does subtracting the maximum logit prevent overflow without changing softmax?Answer
Softmax depends only on logit differences: shifting all logits by scales numerator and denominator by the same . After subtracting the max, the largest input is 0, so every term is at most 1.
2.What is the gradient of the per-example cross-entropy with respect to the logits?Answer
minus one-hot(): at the true class, elsewhere. It matches centered finite differences to about 1e-9 in
float64.3.A batch of 5 has 2 masked positions under a masked mean. What is the divisor, and what gradient do masked positions get?Answer
The divisor is the valid count, 3. Masked positions get exactly zero gradient, matching
ignore_indexsemantics.4.Why must binary cross-entropy with logits avoid sigmoid-then-log?Answer
A confident logit makes sigmoid round to exactly 0 or 1 in floating point, and is infinite. The fused log-sigmoid form stays finite, with gradient .
Practice
- Deep-ML 1227: Numerically Stable Softmax
Implement
softmax(t, dim)by subtracting the max alongdim. The two platform tests use a small tensor along rows and along columns, so they do not exercise overflow.After it passes, add your own large-logit test:
[1000, 1001, 1002]must give[0.0900, 0.2447, 0.6652], and your log-softmax plus mean cross-entropy must stay finite. - TensorTonic: Calculate Squared-Error Loss Gradients (autograd-l08-squared-error-loss-gradients)
Losses, Training, and Zeroing Gradients section: Calculate Squared-Error Loss Gradients
State whether your derivation sums or means over examples, and how that choice scales the gradient.
You're done when
Your fused loss matches centered differences, survives logits of magnitude 1000, and you can state the divisor and the masked-position gradient for sum, mean and masked mean without notes.
Only when you can do this without notes.
Leads to
Notes
Resources · 4 for this unit, 9 more in the section
- Understanding Deep Learning - Chapters 3 to 7Simon J. D. Prince · primary
Read Chapters 3-7, emphasizing Chapter 5 for likelihood-derived losses and Chapter 7 for backpropagation and initialization. Use notebooks 3.1, 4.1, 5.1, 6.1 and 7.1 only as equation and plot companions.
- D2L - tensors, autograd, MLP and backpropagationD2L authors · required
Use chapter_preliminaries ndarray and autograd, then MLP, backpropagation, and numerical stability and initialization. Recreate scalar operations, affine maps, activation, reduction, stable cross-entropy, topological backward and unbroadcast in a blank file.
- CS231n Linear Classification - Softmax classifier and numeric stabilityStanford CS231n · reference
Read the Softmax classifier section for the cross-entropy form , then the Practical issues: Numeric stability part for the max-subtraction code
f -= np.max(f). - `torch.nn.functional.cross_entropy` - `reduction` and `ignore_index`PyTorch · reference
Read the
ignore_indexandreductionparameters: ignored targets contribute no gradient, and mean reduction averages over the non-ignored targets only.
Also in this section
- TensorTonic - Build Micrograd from ScratchTensorTonic · required
Use the 25-problem Micrograd study plan in order for derivatives, gradient checks, value graphs, reverse mode, accumulation, operators, modules, losses and training. Preserve local tests as the evidence instead of a platform score.
- Deep-ML candidate - autograd and loss problemsDeep-ML · optional
After the five-sample platform check passes, use at most one of 26 Basic Autograd Operations, 997 Manual Cross-Entropy Backprop or 1227 Stable Softmax as a changed-prompt drill.
- CS231n Neural Networks 3 - Gradient checksStanford CS231n · reference
Read the Gradient Checks section only: centered formula with error, relative error with thresholds, double precision, step size near 1e-5, kinks, few datapoints, burn-in, regularization and dropout discipline, and checking a few dimensions per parameter.
- PyTorch Broadcasting semanticsPyTorch · reference
Read General semantics for the trailing-dimension rules, prepend-1 alignment and max-size result, with the
(5, 1, 4, 1)plus(3, 1, 1)examples; read In-place semantics for why an in-place tensor may not change shape. - `torch.autograd.gradcheck` API and tolerancesPyTorch · reference
Read the
gradchecksignature defaults (eps1e-6,atol1e-5,rtol1e-3) and the note that inputs with overlapping memory, such asexpandoutputs, will likely fail the check. - PyTorch Tensor ViewsPyTorch · reference
Read the view and storage sharing example (
data_ptr, mutating the view changes the base), the transpose non-contiguous example, the full view-ops list, and the special notes:reshapemay copy,contiguouscopies only when needed, basic indexing returns views while advanced indexing copies. - `torch.Tensor.stride` - stride and storage offsetPyTorch · reference
Read the stride definition: strides are per-dimension element steps, and with
storage_offsetthey locate every element. Combine with the Tensor Views page for transposed and expanded layouts. - PyTorch Autograd mechanics - in-place operationsPyTorch · reference
Read In-place operations with autograd (why in-place rewrites the graph and is discouraged) and In-place correctness checks (the version counter and the error on accessing a modified saved tensor).
- `torch.nn.Module` - parameters, buffers and statePyTorch · reference
Read the parameters and buffers documentation: modules collect parameters recursively for the optimizer, while
register_bufferholds persistent non-parameter tensors saved alongside them.