Overview
Ordinary cross-entropy tells the model the right class has probability 1 and the others 0. The only way to match that is to make the true logit infinitely larger than the rest, so the model is pushed to be ever more confident. Label smoothing changes the target slightly. The true class gets a probability a little below 1, and the remainder is divided evenly among all classes. Now the best prediction is confident but finite. The model stops inflating its logits, tends to be better calibrated, and is less damaged by an occasional wrong label.
A short history
Christian Szegedy and colleagues introduced label smoothing in the 2015 paper 'Rethinking the Inception Architecture for Computer Vision'. One-hot targets push a classifier to make its winning score ever larger, which leads to overconfidence. Moving a small share of the target probability to the other classes removes that pressure. The original Transformer used it in 2017, and Müller, Kornblith and Hinton analysed in 2019 why it improves calibration.
How it works
- Take the logits, shape (N, C), and the target class index for each row.
- Build the smoothed target : every class gets , and the true class gets an extra .
smoothed_targetsreturns this. - Compute the log-softmax of the logits.
- The loss for a row is the cross-entropy between and the prediction: minus the sum of times the log-probabilities.
- Reduce over rows with
reduction. - In
backward, each row's gradient is softmax minus , divided by for the mean.
Watch out for
- The loss can no longer reach zero. Its floor is the entropy of the smoothed target, so loss values are not comparable with unsmoothed runs.
- Smoothing makes the outputs for wrong classes more uniform. That removes information a student model would learn from, so smoothed teachers can distil worse.
- Conventions differ. Here the true class gets . Some libraries spread over the other classes only, which gives slightly different numbers.
- Too much smoothing makes the model underconfident and can lower accuracy. Values much above 0.2 are rarely helpful.
Use cases
When to use it
Classification with many classes or somewhat noisy labels, where overconfidence hurts: image classifiers and sequence models commonly use a smoothing of 0.1.
In industry
- Machine translation
- The original Transformer was trained with label smoothing of 0.1, and it has remained a common setting for translation models.
- Image classification
- ImageNet training recipes for convolutional networks and vision transformers routinely include label smoothing.
- Speech recognition
- Attention-based speech recognisers use label smoothing to stop the decoder becoming overconfident in its next token.
Choosing it: what must hold
- A multi-class problem trained with softmax cross-entropy.
- A model that is overconfident, or labels with some noise in them.
- No plan to use the model as a teacher for distillation, since smoothing removes information the student would learn from.
When to choose something else
| If | Use instead |
|---|---|
| Labels are clean and you need the sharpest possible probabilities | Plain softmax cross-entropy |
| The model will be distilled into a smaller one | Plain cross-entropy for the teacher, then KL divergence for the student |
| The main problem is class imbalance, not overconfidence | Focal loss |
Math foundations
The smoothed target
A mix of the one-hot label and the uniform distribution. The true class gets , every other class gets , and the total is 1.
The loss
Cross-entropy between the smoothed target and the predicted distribution . With it is ordinary cross-entropy.
Split into two familiar parts
Ordinary cross-entropy, scaled down, plus a term that is the cross-entropy against a uniform target. The second term punishes giving any class a very low probability.
Gradient with respect to the logits
Predicted minus smoothed target. It is zero when , which happens at finite logits.
Where the optimum sits
At the minimum the true logit exceeds each other logit by this fixed, finite gap. Without smoothing the gap would be pushed toward infinity.
Symbols
- the smoothing share,
smoothingin the config, default 0.1 - the number of classes
- the index of the true class
- the smoothed target probability of class c
- the predicted probability of class c, softmax of the logits
- the logit of class c
- the loss for one example
- 1 when c is the true class, otherwise 0
Worked by hand
Four classes, smoothing , true class 0. Suppose the softmax output is . Use and .
The loss is 0.5026, against 0.3567 for plain cross-entropy. The gradient on the true class is instead of , so the push toward more confidence is weaker.
Visual example
Loading the example.
Try this
- Move across the curve: the height is what the model is charged.
- Move each control and watch which part of the curve it changes.
Code sample
import numpy as np
from impl import LabelSmoothingCrossEntropy
from config import LabelSmoothingCrossEntropyConfig
loss = LabelSmoothingCrossEntropy(LabelSmoothingCrossEntropyConfig(smoothing=0.1))
logits = np.array([[2.0, 1.0, 0.1], [0.5, 2.5, 0.3]]) # (N=2, C=3)
target = np.array([0, 1])
print(loss.smoothed_targets(target, 3)) # rows like [0.9333, 0.0333, 0.0333]
print(loss.forward(logits, target)) # a little above the plain cross-entropy 0.3185
print(loss.backward(logits, target)) # (softmax - smoothed targets) / 2Read the implementation (63 lines)
"""Label-smoothed cross-entropy: cross-entropy against q = (1 - s) * one_hot + s / C.
NumPy only. `forward` returns the loss, `backward` its gradient with respect to the logits.
"""
from __future__ import annotations
import numpy as np
try:
from .config import LabelSmoothingCrossEntropyConfig
except ImportError: # run from the template's own folder
from config import LabelSmoothingCrossEntropyConfig
def _log_softmax(z: np.ndarray, axis: int = -1) -> np.ndarray:
"""log(softmax(z)) along `axis`, with the maximum subtracted first so exp cannot overflow."""
shifted = z - z.max(axis=axis, keepdims=True)
return shifted - np.log(np.exp(shifted).sum(axis=axis, keepdims=True))
def _check(logits, target) -> tuple[np.ndarray, np.ndarray]:
"""Logits as a float array (N, C) and class indices as an int array (N,). Raises ValueError otherwise."""
logits, target = np.asarray(logits, dtype=float), np.asarray(target)
if logits.ndim != 2 or target.shape != (logits.shape[0],):
raise ValueError(f"expected logits (N, C) and target (N,), got {logits.shape} and {target.shape}")
return logits, target.astype(int)
class LabelSmoothingCrossEntropy:
"""Softmax cross-entropy against targets softened by the smoothing share."""
def __init__(self, config: LabelSmoothingCrossEntropyConfig | None = None) -> None:
self.config = config or LabelSmoothingCrossEntropyConfig()
def smoothed_targets(self, target: np.ndarray, num_classes: int) -> np.ndarray:
"""Target distribution q. target: (N,) class indices. Returns (N, num_classes), rows summing to 1."""
target = np.asarray(target).astype(int)
if target.size and (target.min() < 0 or target.max() >= num_classes):
raise ValueError(f"target classes must lie in [0, {num_classes})")
s = self.config.smoothing
q = np.full((len(target), num_classes), s / num_classes)
q[np.arange(len(target)), target] += 1.0 - s
return q
def forward(self, logits: np.ndarray, target: np.ndarray):
"""logits: (N, C) raw scores. target: (N,) class indices. Returns a float, or (N,) for "none"."""
logits, target = _check(logits, target)
q = self.smoothed_targets(target, logits.shape[1])
per_row = -(q * _log_softmax(logits)).sum(axis=1)
if self.config.reduction == "none":
return per_row
return float(per_row.mean()) if self.config.reduction == "mean" else float(per_row.sum())
def backward(self, logits: np.ndarray, target: np.ndarray) -> np.ndarray:
"""Gradient of the reduced loss with respect to the logits, shape (N, C).
Per row it is softmax(logits) - q, divided by N for "mean". For "none" the per-row gradient is
returned unscaled.
"""
logits, target = _check(logits, target)
grad = np.exp(_log_softmax(logits)) - self.smoothed_targets(target, logits.shape[1])
return grad / len(target) if self.config.reduction == "mean" else grad
__call__ = forward- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build LabelSmoothingCrossEntropy(LabelSmoothingCrossEntropyConfig(smoothing=0.1)) and print smoothed_targets for target 0 with 4 classes. Then evaluate forward on logits for from 0 to 12, find the with the lowest loss, and compare it with the formula for the optimal gap.
Check on learning
- With hard targets the loss keeps falling as the true logit grows. With smoothed targets it eventually rises again. Why?
A way to think about it
Use the two-part form. As the model grows more confident, the probabilities of the other classes shrink, and the uniform term charges for their logs.
- For 1000 classes and a smoothing of 0.1, what logit gap does the optimum ask for, and what probability does the true class then receive?
A way to think about it
Plug into the gap formula, then note that at the optimum , so the true-class probability is simply .
- About 5 percent of your training labels are wrong. Why might smoothing help more than it would on clean data?
A way to think about it
A mislabelled example with a hard target produces a strong, persistent push in the wrong direction. Compare the size of the gradient once the target admits some doubt.
- A teacher trained with smoothing gives worse distillation results than one trained without. What information did smoothing remove?
A way to think about it
Distillation relies on the relative sizes of the wrong-class probabilities, which encode which classes resemble each other. Smoothing pulls those toward one common value.