Simple Algorithm
Deep Learning · Emergence · 26 min

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 (1−pt)γ(1-p_t)^\gamma, 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: ℓ=log⁡(1+∑j≠yezj−zy)\ell=\log\big(1+\sum_{j\ne y}e^{z_j-z_y}\big). It is positive for every finite z\mathbf z and tends to zero only as every gap zy−zj→∞z_y-z_j\to\infty. 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 00 or 11 (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 KK classes and smoothing ε\varepsilon, the one-hot vector y\mathbf y is replaced by q=(1−ε)y+ε u\mathbf q=(1-\varepsilon)\mathbf y+\varepsilon\,\mathbf u, where u=(1/K,…,1/K)\mathbf u=(1/K,\dots,1/K). The value ε=0.1\varepsilon=0.1 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).

DerivationWhat label smoothing adds, exactly
  1. H(q,p)=(1−ε) H(y,p)+ε H(u,p)H(\mathbf q,\mathbf p)=(1-\varepsilon)\,H(\mathbf y,\mathbf p)+\varepsilon\,H(\mathbf u,\mathbf p)

    Cross-entropy is linear in the target, so the smoothed loss splits into the original loss and a loss against the uniform distribution:

  2. H(u,p)=H(u)+DKL(u ∥ p)=log⁡K+DKL(u ∥ p)H(\mathbf u,\mathbf p)=H(\mathbf u)+\KL(\mathbf u\,\|\,\mathbf p)=\log K+\KL(\mathbf u\,\|\,\mathbf p)

    Decompose the second term as entropy plus KL divergence; the entropy of the uniform distribution is log⁡K\log K:

  3. ℓLS=(1−ε) ℓCE+ε DKL(u ∥ p)+εlog⁡K\ell_{\text{LS}}=(1-\varepsilon)\,\ell_{\text{CE}}+\varepsilon\,\KL(\mathbf u\,\|\,\mathbf p)+\varepsilon\log K

    So label smoothing is down-weighted cross-entropy plus a penalty ε DKL(u ∥ p)\varepsilon\,\KL(\mathbf u\,\|\,\mathbf p) that grows as p\mathbf p concentrates, plus a constant. The penalty goes to infinity as any pj→0p_j\to0, which is what stops the logits from running away.

  4. zy−zj=log⁡1−ε+ε/Kε/K=log⁡(1+K(1−ε)ε)z_y-z_j=\log\frac{1-\varepsilon+\varepsilon/K}{\varepsilon/K}=\log\Big(1+\frac{K(1-\varepsilon)}{\varepsilon}\Big)

    The minimizer over p\mathbf p is p=q\mathbf p=\mathbf q (Gibbs' inequality): probability 1−ε+ε/K1-\varepsilon+\varepsilon/K on the labeled class and ε/K\varepsilon/K on each other. The optimal logit gap is therefore finite:

Predict before you look

With K=10K=10 classes and ε=0.1\varepsilon=0.1, what logit gap between the labeled class and each other class minimizes the label-smoothed loss?

Show the answer

4.51

log⁡(1+10⋅0.9/0.1)=log⁡91≈4.51\log(1+10\cdot0.9/0.1)=\log91\approx4.51, so the model aims for py=0.91p_y=0.91 and 0.010.01 elsewhere. For ImageNet's K=1000K=1000 the gap is log⁡9001≈9.1\log9001\approx9.1: 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 ptp_t is the predicted probability of the true class:

FL⁡(pt)=−αt (1−pt)γlog⁡pt,γ≥0\operatorname{FL}(p_t)=-\alpha_t\,(1-p_t)^\gamma\log p_t,\qquad\gamma\ge0
γ=0\gamma=0 is cross-entropy (with class weights αt\alpha_t). With γ=2\gamma=2, the value Lin et al. found best (with α=0.25\alpha=0.25 for the rare foreground class), an example with pt=0.9p_t=0.9 contributes 100×100\times less than under cross-entropy, and one with pt≈0.968p_t\approx0.968 about 1000×1000\times less. Hard, misclassified examples (ptp_t small) keep almost their full loss.
Check your understanding

With γ=2\gamma=2, an example is already classified with pt=0.8p_t=0.8. By what factor is its loss reduced relative to plain cross-entropy (ignoring αt\alpha_t)?

  1. 5×5\times
  2. 25×25\times
  3. 4×4\times
  4. 64×64\times
Show the answer

B. 25×25\times

The modulating factor is (1−pt)γ=0.22=0.04(1-p_t)^\gamma=0.2^2=0.04, a reduction by 25×25\times. The better an example is already classified, the faster its weight falls.

DerivationFocal loss hides an entropy bonus
  1. DKL(y ∥ p)−FL⁡=(1−(1−py)γ) (−log⁡py)≤γ py(−log⁡py)≤γ H(p)\KL(\mathbf y\,\|\,\mathbf p)-\operatorname{FL}=\big(1-(1-p_y)^\gamma\big)\,(-\log p_y)\le\gamma\,p_y(-\log p_y)\le\gamma\,H(\mathbf p)

    For a one-hot target, DKL(y ∥ p)=−log⁡py\KL(\mathbf y\,\|\,\mathbf p)=-\log p_y, and the prediction's entropy H(p)=−∑jpjlog⁡pjH(\mathbf p)=-\sum_jp_j\log p_j is at least its own term −pylog⁡py-p_y\log p_y. For γ≥1\gamma\ge1, Bernoulli's inequality gives 1−(1−py)γ≤γpy1-(1-p_y)^\gamma\le\gamma p_y. Hence

  2. FL⁡ ≥ DKL(y ∥ p)−γ H(p)\operatorname{FL}\ \ge\ \KL(\mathbf y\,\|\,\mathbf p)-\gamma\,H(\mathbf p)

    Rearranged, the focal loss upper-bounds cross-entropy minus γ\gamma times the prediction's entropy, the bound Mukhoti et al. (2020) use to explain the focal loss's calibration:

  3. 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 γ\gamma 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 0.90.9, the expected focal loss at γ=2\gamma=2 is minimized by predicting about 0.690.69: the right side of 12\tfrac12, but far from 0.90.9. 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 πy\pi_y 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, 1K∑yP(y^≠y∣y)\frac1K\sum_yP(\hat y\ne y\mid y), not the overall error.

DerivationThe balanced Bayes classifier, and a loss that learns it
  1. y^bal(x)=arg max⁡y p(y∣x)πy=arg max⁡y p(x∣y)\hat y_{\text{bal}}(\mathbf x)=\argmax_y\,\frac{p(y\mid\mathbf x)}{\pi_y}=\argmax_y\,p(\mathbf x\mid y)

    Balanced error weights class yy by 1/K1/K instead of πy\pi_y, 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 p(y∣x)∝p(x∣y) πyp(y\mid\mathbf x)\propto p(\mathbf x\mid y)\,\pi_y:

  2. Post-hoc adjustment. If a network trained with plain cross-entropy outputs logits fy(x)≈log⁡p(y∣x)+c(x)f_y(\mathbf x)\approx\log p(y\mid\mathbf x)+c(\mathbf x), subtract the log-prior at test time: predict arg max⁡y fy(x)−τlog⁡πy\argmax_y\,f_y(\mathbf x)-\tau\log\pi_y, with τ=1\tau=1 in theory.

  3. ℓLA(y,f(x))=−log⁡efy(x)+τlog⁡πy∑y′efy′(x)+τlog⁡πy′\ell_{\text{LA}}\big(y,f(\mathbf x)\big)=-\log\frac{e^{f_y(\mathbf x)+\tau\log\pi_y}}{\sum_{y'}e^{f_{y'}(\mathbf x)+\tau\log\pi_{y'}}}

    Logit-adjusted loss. Alternatively, add the log-prior inside the softmax during training (Menon et al., 2021):

  4. fy(x)=log⁡p(x∣y)+c′(x)⟹arg max⁡yfy(x)=y^bal(x)f_y(\mathbf x)=\log p(\mathbf x\mid y)+c'(\mathbf x)\quad\Longrightarrow\quad \argmax_yf_y(\mathbf x)=\hat y_{\text{bal}}(\mathbf x)

    Its population minimizer makes the adjusted logits match the true posterior, fy+log⁡πy=log⁡p(y∣x)+c(x)f_y+\log\pi_y=\log p(y\mid\mathbf x)+c(\mathbf x). So the raw logits are fy=log⁡p(x∣y)+c′(x)f_y=\log p(\mathbf x\mid y)+c'(\mathbf x), and arg max⁡yfy\argmax_yf_y is exactly the balanced Bayes classifier: with τ=1\tau=1 the loss is Fisher-consistent for balanced error. Equivalently, it demands a larger margin log⁡(πy′/πy)\log(\pi_{y'}/\pi_y) in favor of a rare class yy over a frequent class y′y'.

Reweighting and margins. The obvious alternative is to weight each example's loss by 1/πy1/\pi_y. 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 (Δy∝ny−1/4\Delta_y\propto n_y^{-1/4} 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, log⁡(πy′/πy)\log(\pi_{y'}/\pi_y) 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 log⁡Z=log⁡∑jezj\log Z=\log\sum_je^{z_j}, 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):

Lz=10−4⋅(log⁡Z)2,∂Lz∂zk=2⋅10−4 log⁡Z  pk\loss_z=10^{-4}\cdot\big(\log Z\big)^2,\qquad \frac{\partial\loss_z}{\partial z_k}=2\cdot10^{-4}\,\log Z\;p_k
In the paper's words, it encourages "the softmax normalizer log(Z) to be close to 0", which the authors found increases training stability. Its gradient moves every logit down (if log⁡Z>0\log Z>0) in proportion to its probability.

Because any logit vector can be shifted to have log⁡Z=0\log Z=0 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 (1−ε) ℓCE+ε DKL(u ∥ p)(1-\varepsilon)\,\ell_{\text{CE}}+\varepsilon\,\KL(\mathbf u\,\|\,\mathbf p) plus a constant; it yields a finite logit gap log⁡(1+K(1−ε)/ε)\log(1+K(1-\varepsilon)/\varepsilon), tighter class clusters and better calibration, but poorer distillation teachers.
  • The focal loss −(1−pt)γlog⁡pt-(1-p_t)^\gamma\log p_t down-weights easy examples (100×100\times at pt=0.9p_t=0.9 for γ=2\gamma=2) and satisfies FL⁡≥DKL(y ∥ p)−γH(p)\operatorname{FL}\ge\KL(\mathbf y\,\|\,\mathbf p)-\gamma H(\mathbf p), an implicit entropy bonus that helps calibration.
  • For balanced error the Bayes rule is arg max⁡yp(y∣x)/πy\argmax_yp(y\mid\mathbf x)/\pi_y; subtracting log⁡πy\log\pi_y post hoc, or adding it inside the softmax during training, is Fisher-consistent, unlike plain cross-entropy.
  • The z-loss 10−4(log⁡Z)210^{-4}(\log Z)^2 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.

Question 1

With uniform distribution u\mathbf u over KK classes, label smoothing with parameter ε\varepsilon is exactly equivalent to which loss (up to a constant)?

  1. (1−ε) ℓCE+ε DKL(u ∥ p)(1-\varepsilon)\,\ell_{\text{CE}}+\varepsilon\,\KL(\mathbf u\,\|\,\mathbf p)
  2. ℓCE+ε ∥z∥2\ell_{\text{CE}}+\varepsilon\,\norm{\mathbf z}^2
  3. (1−ε) ℓCE+ε DKL(p ∥ u)(1-\varepsilon)\,\ell_{\text{CE}}+\varepsilon\,\KL(\mathbf p\,\|\,\mathbf u)
  4. ℓCE\ell_{\text{CE}} evaluated at temperature 1/ε1/\varepsilon
Show the answer

A. (1−ε) ℓCE+ε DKL(u ∥ p)(1-\varepsilon)\,\ell_{\text{CE}}+\varepsilon\,\KL(\mathbf u\,\|\,\mathbf p)

H(q,p)=(1−ε)H(y,p)+εH(u,p)H(\mathbf q,\mathbf p)=(1-\varepsilon)H(\mathbf y,\mathbf p)+\varepsilon H(\mathbf u,\mathbf p) and H(u,p)=log⁡K+DKL(u ∥ p)H(\mathbf u,\mathbf p)=\log K+\KL(\mathbf u\,\|\,\mathbf p).

Question 2

A 5-class model is trained with label smoothing ε=0.2\varepsilon=0.2. What logit gap between the labeled class and each other class minimizes the loss?

  1. It grows without bound, as with plain cross-entropy
  2. log⁡21≈3.04\log21\approx3.04
  3. log⁡4≈1.39\log4\approx1.39
  4. 0.20.2
Show the answer

B. log⁡21≈3.04\log21\approx3.04

The target is 1−ε+ε/K=0.841-\varepsilon+\varepsilon/K=0.84 on the labeled class and 0.040.04 on the others; log⁡(0.84/0.04)=log⁡21\log(0.84/0.04)=\log21.

Question 3

A classifier trained with plain cross-entropy on long-tailed data, with class priors πy\pi_y, outputs logits fy(x)f_y(\mathbf x). Which test-time rule targets the balanced error?

  1. arg max⁡y fy(x)\argmax_y\,f_y(\mathbf x)
  2. arg max⁡y fy(x)+log⁡πy\argmax_y\,f_y(\mathbf x)+\log\pi_y
  3. arg max⁡y fy(x)/πy\argmax_y\,f_y(\mathbf x)/\pi_y
  4. arg max⁡y fy(x)−log⁡πy\argmax_y\,f_y(\mathbf x)-\log\pi_y
Show the answer

D. arg max⁡y fy(x)−log⁡πy\argmax_y\,f_y(\mathbf x)-\log\pi_y

Logits estimate log⁡p(y∣x)\log p(y\mid\mathbf x) up to a constant, and the balanced Bayes rule maximizes p(y∣x)/πyp(y\mid\mathbf x)/\pi_y: subtract log⁡πy\log\pi_y.

Question 4

Why can the z-loss 10−4(log⁡Z)210^{-4}(\log Z)^2 improve stability without changing what a trained model predicts?

  1. Its weight is too small to matter
  2. It only affects the logit of the correct class
  3. The softmax ignores a common shift of all logits, so any model can satisfy log⁡Z=0\log Z=0 by shifting its logits, leaving every probability unchanged
  4. 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 log⁡Z=0\log Z=0 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).