Cross-entropy with label smoothing from raw logits

EasyLosses

Label smoothing stops a classifier from pushing its logits to extreme values. The one-hot target is mixed with a uniform distribution, so the model is never asked for probability exactly 1.

Write label_smoothed_ce(logits, targets, eps) where logits is (n, C), targets is a length-n list of class ids and 0 <= eps < 1.
- The smoothed target for row i is q = (1 - eps) * one_hot(targets[i]) + eps / C on every class (including the true class).
- Loss for a row is -sum_c q[c] * log_softmax(logits[i])[c].
- Return the mean over rows as a float.
Use a stable log-softmax so logits like 1000 work.

Signaturedef label_smoothed_ce(logits, targets, eps)

Example

logits [[0, 0]], targets [0], eps 0.2 gives log 2 = 0.693147..., because the prediction is already uniform.

Understand the idea

Label smoothing tells the model the right answer is very likely, not certain. The one-hot target is blended with a uniform spread, so the model stops pushing logits to extreme values. In this problem eps is spread over all C classes, including the true one. Worked example: C = 2, eps = 0.2, true class 0. q = (1 - 0.2) * [1, 0] + 0.2 / 2 = [0.9, 0.1]. Logits [2, 0]: logsumexp = log(e^2 + 1) = 2.1269, so log-probs are [-0.1269, -2.1269]. Loss = 0.9 * 0.1269 + 0.1 * 2.1269 = 0.1142 + 0.2127 = 0.3269. Rule: q = (1 - eps) * one_hot + eps / C, row loss = -sum over classes of q times log_softmax(logits), then average rows. Compute log_softmax as logits minus their max, minus log of the summed exps, so logits like 1000 stay finite. Used when training image classifiers and many transformer models, often with eps = 0.1.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplelabel_smoothed_ce([[0.0, 0.0]], [0], 0.2)
  • Sample 2: eps 0 is plain CElabel_smoothed_ce(_z, _t, 0.0)
  • Test 3: eps 0.1label_smoothed_ce(_z, _t, 0.1)
  • Test 4: large logitslabel_smoothed_ce([[1000.0, 0.0, -1000.0]], [0], 0.3)