Reshaping Cross-Entropy
Label smoothing, focal loss and logit adjustment for imbalanced data.
Plain cross-entropy takes every label as certain, weighs every example the same, treats every class as equally common, and rewards logits that grow without bound. Each assumption fails somewhere: labels are noisy, easy examples swamp hard ones, rare classes drown, and runaway logits destabilize training. Small edits to the loss fix each failure, and each edit has an exact mathematical meaning.
What you’ll learn
- Show that cross-entropy on separable data is minimized only by infinite logits, and decompose label smoothing exactly into cross-entropy plus a KL penalty toward the uniform distribution, with the finite logit gap it induces.
- Analyze the focal loss as a per-example reweighting by , and prove the bound linking it to an entropy bonus.
- Derive the Bayes-optimal classifier for balanced error and prove that logit-adjusted cross-entropy is Fisher-consistent for it; contrast it with reweighting and LDAM margins.
- Explain auxiliary losses on the logits, such as the z-loss, as fixes for a free direction of the softmax.
Cross-entropy pushes logits to infinity
Write the loss of one example in terms of logit differences: . It is positive for every finite and tends to zero only as every gap . On training data that the network can separate, which is the usual situation for large networks, gradient descent therefore keeps growing the logits long after every example is classified correctly. In linear models this drives the weights toward the maximum-margin direction while their norm grows without bound (Soudry et al., 2018); in deep networks it shows up as ever more confident outputs.
Three practical failures follow, each addressed by one section of this lesson:
- Overconfidence and noisy labels. A mislabeled example keeps pulling forever, and predicted probabilities saturate at or (label smoothing).
- Easy examples dominate. Millions of correct, confident examples each contribute a small loss that adds up to most of the gradient (focal loss).
- Rare classes drown. With long-tailed labels, the loss is dominated by frequent classes and the decision boundaries drift toward the rare ones (logit adjustment).
A fourth, numerical, failure is the drift of the logits' overall level, which the softmax ignores but floating point does not (the z-loss).
Label smoothing
Label smoothing (Szegedy et al., 2016) trains on a softened target: with classes and smoothing , the one-hot vector is replaced by , where . The value is common: Szegedy et al. used it on ImageNet, and the original transformer used it for translation, where it hurt perplexity but improved accuracy and BLEU (Vaswani et al., 2017). In PyTorch it is F.cross_entropy(logits, y, label_smoothing=0.1).
Cross-entropy is linear in the target, so the smoothed loss splits into the original loss and a loss against the uniform distribution:
Decompose the second term as entropy plus KL divergence; the entropy of the uniform distribution is :
So label smoothing is down-weighted cross-entropy plus a penalty that grows as concentrates, plus a constant. The penalty goes to infinity as any , which is what stops the logits from running away.
The minimizer over is (Gibbs' inequality): probability on the labeled class and on each other. The optimal logit gap is therefore finite:
With classes and , what logit gap between the labeled class and each other class minimizes the label-smoothed loss?
Show the answer
4.51
, so the model aims for and elsewhere. For ImageNet's the gap is : still finite, though larger, because the smoothing mass is spread more thinly.
What it does to the network. Müller, Kornblith and Hinton (2019) found that label smoothing makes penultimate-layer representations of each class gather into tight clusters, improves calibration (often about as much as temperature scaling), and helps beam search. It also makes the network a much worse teacher for knowledge distillation: the clustering erases the information about class resemblances that a student learns from the teacher's wrong-class probabilities (Knowledge Distillation). The penalty treats all wrong classes alike, which is exactly what destroys that "dark knowledge".
Focal loss
A one-stage object detector scores tens of thousands of candidate boxes per image, nearly all of them easy background. Each easy box has a small cross-entropy, but together they dominate the gradient. Lin, Goyal, Girshick, He and Dollár (2017) down-weighted them with the focal loss, where is the predicted probability of the true class:
With , an example is already classified with . By what factor is its loss reduced relative to plain cross-entropy (ignoring )?
Show the answer
B.
The modulating factor is , a reduction by . The better an example is already classified, the faster its weight falls.
For a one-hot target, , and the prediction's entropy is at least its own term . For , Bernoulli's inequality gives . Hence
Rearranged, the focal loss upper-bounds cross-entropy minus times the prediction's entropy, the bound Mukhoti et al. (2020) use to explain the focal loss's calibration:
Minimizing a loss that behaves like "cross-entropy minus an entropy bonus" discourages the near-zero-entropy outputs that make cross-entropy models overconfident. Mukhoti et al. found focal-loss models better calibrated than cross-entropy models across vision and language tasks, and well calibrated after temperature scaling without losing accuracy; they also proposed a rule for choosing per example.
The flip side: unlike cross-entropy, the focal loss is not a proper scoring rule, as Mukhoti et al. point out. If a binary label is 1 with probability , the expected focal loss at is minimized by predicting about : the right side of , but far from . Its outputs are not calibrated probabilities by construction; what it offers in practice is a brake on the overconfidence of networks that fit their training data, which is why it is paired with temperature scaling.
Imbalanced classes: logit adjustment
With imbalanced or long-tailed labels, training priors differ wildly, but we often care about every class equally. The right target is then the balanced error, the average of the per-class error rates, , not the overall error.
Balanced error weights class by instead of , which is the ordinary error under a uniform label prior. Its Bayes-optimal rule replaces the training prior with a uniform one, by Bayes' rule :
Post-hoc adjustment. If a network trained with plain cross-entropy outputs logits , subtract the log-prior at test time: predict , with in theory.
Logit-adjusted loss. Alternatively, add the log-prior inside the softmax during training (Menon et al., 2021):
Its population minimizer makes the adjusted logits match the true posterior, . So the raw logits are , and is exactly the balanced Bayes classifier: with the loss is Fisher-consistent for balanced error. Equivalently, it demands a larger margin in favor of a rare class over a frequent class .
Reweighting and margins. The obvious alternative is to weight each example's loss by . It is also consistent in the population, but in overparameterized networks that fit the training set perfectly its effect fades as training goes on: Byrd and Lipton (2019) found importance weights mattered early in training and much less later, with L2 regularization and batch normalization partly restoring the effect. Cao et al. (2019) instead enforce class-dependent margins in the loss, larger for rare classes ( in their LDAM loss, derived from a margin-based generalization bound), and defer reweighting until after an initial phase of training. Logit adjustment can be read as a principled margin of this kind, between each pair of classes.
The z-loss: pinning a free direction
The softmax ignores adding the same constant to every logit, so cross-entropy has a flat direction: it constrains logit differences only. (This is the translation symmetry of Symmetries & Conservation Laws.) Nothing then stops the overall level, measured by , from drifting, and large logits are bad news in low-precision arithmetic. PaLM added an auxiliary loss that pins the level (Chowdhery et al., 2022):
Because any logit vector can be shifted to have without changing a single probability, the z-loss costs nothing at the optimum: it fixes the gauge, not the predictions. Wortsman et al. (2023) reproduced the divergence of output logits that motivated it in small transformers trained at high learning rates, and found that the mitigations used at large scale work there too. The same idea appears as a router z-loss in mixture-of-experts layers (Mixture of Experts), and the broader story of logit growth and loss spikes is in Normalization & Stability in Transformers.
Key takeaways
- Cross-entropy is minimized on separable data only by infinite logit gaps, which feeds overconfidence, sensitivity to label noise and runaway logits.
- Label smoothing equals plus a constant; it yields a finite logit gap , tighter class clusters and better calibration, but poorer distillation teachers.
- The focal loss down-weights easy examples ( at for ) and satisfies , an implicit entropy bonus that helps calibration.
- For balanced error the Bayes rule is ; subtracting post hoc, or adding it inside the softmax during training, is Fisher-consistent, unlike plain cross-entropy.
- The z-loss pins the logits' overall level, the one direction cross-entropy leaves free, improving stability without changing predictions.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
With uniform distribution over classes, label smoothing with parameter is exactly equivalent to which loss (up to a constant)?
- evaluated at temperature
Show the answer
A.
and .
A 5-class model is trained with label smoothing . What logit gap between the labeled class and each other class minimizes the loss?
- It grows without bound, as with plain cross-entropy
Show the answer
B.
The target is on the labeled class and on the others; .
A classifier trained with plain cross-entropy on long-tailed data, with class priors , outputs logits . Which test-time rule targets the balanced error?
Show the answer
D.
Logits estimate up to a constant, and the balanced Bayes rule maximizes : subtract .
Why can the z-loss improve stability without changing what a trained model predicts?
- Its weight is too small to matter
- It only affects the logit of the correct class
- The softmax ignores a common shift of all logits, so any model can satisfy by shifting its logits, leaving every probability unchanged
- It is applied only at test time
Show the answer
C. The softmax ignores a common shift of all logits, so any model can satisfy by shifting its logits, leaving every probability unchanged
Cross-entropy constrains only logit differences. The z-loss acts on the one direction that cross-entropy leaves free, the overall level, keeping logits in a numerically safe range.
Further reading
- C. Szegedy, V. Vanhoucke, S. Ioffe, J. Shlens & Z. Wojna, "Rethinking the Inception architecture for computer vision," CVPR (2016).
- R. Müller, S. Kornblith & G. Hinton, "When does label smoothing help?," NeurIPS (2019).
- T.-Y. Lin, P. Goyal, R. Girshick, K. He & P. Dollár, "Focal loss for dense object detection," ICCV (2017).
- J. Mukhoti, V. Kulharia, A. Sanyal, S. Golodetz, P. H. S. Torr & P. K. Dokania, "Calibrating deep neural networks using focal loss," NeurIPS (2020).
- A. K. Menon, S. Jayasumana, A. S. Rawat, H. Jain, A. Veit & S. Kumar, "Long-tail learning via logit adjustment," ICLR (2021).
- A. Chowdhery et al., "PaLM: Scaling language modeling with Pathways," arXiv:2204.02311 (2022).