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

Stable softmax and log-softmaxCross-entropy and binary cross-entropy with logitsRegression, reconstruction and masked loss reductions
1

Read

In this order, only the parts listed

0 of 4 done

  1. 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

  2. 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 the reduce_mean of negative logs

    Do 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.

  3. 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]

  4. Masked reductions in cross_entropy`torch.nn.functional.cross_entropy` - `reduction` and `ignore_index`

    ignore_index and reduction parameters: ignored targets contribute no gradient, and mean averages over the non-ignored targets only

2

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_entropy uses reduce_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 to inf and the division already produced nan; 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 equals softmax([0, 1, 2]): about [0.09, 0.245, 0.665].
3

Try it yourself

Closed-book, before checking anything

Closed-book, implement 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].
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 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. 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. 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_index semantics.

  4. 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 .

5

Practice

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

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 gradcheck signature defaults (eps 1e-6, atol 1e-5, rtol 1e-3) and the note that inputs with overlapping memory, such as expand outputs, 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: reshape may copy, contiguous copies 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_offset they 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_buffer holds persistent non-parameter tensors saved alongside them.