PigeonColumba compressa

Lesson 1 of 10

Softmax, cross-entropy and its gradient

Every classifier in this lab ends the same way: a vector of logits z (one number per class) becomes probabilities with softmax, and the loss is cross-entropy against the true class.

softmax(z)_i = exp(z_i) / sum_j exp(z_j)

Dividing the logits by a temperature T before the softmax flattens the distribution when T > 1. Distillation depends on that knob.

Two things to get right:

  1. Numerical stability. exp(1000) overflows. Subtracting the row's maximum first changes nothing mathematically (it cancels in the ratio) and keeps every exponent at or below 0.
  2. The gradient. For L = -log softmax(z)[y], the derivative with respect to the logits is beautifully simple: p - onehot(y). Averaged over a batch of N rows, divide by N.

Implement the three functions. All inputs are 2-D: one row per example.

Your code

Where this is used