Topic: ml-fundamentals · deep dive

Loss functions

Reading: 31 min, plus 5 in closed details. What a loss makes a model estimate and what it does to the gradient: regression losses as noise models, outliers and leverage, cross entropy and its gradient on the logits, focal loss and label smoothing, margins, ranking losses, and the adversarial loss. Every curve and fit is computed in your browser and checked against PyTorch. Data as of October 2026.

The idea in one sentence. A loss decides two things at once: what the model learns to predict (a mean, a median, a quantile, a probability, a ranking or only a decision) and which examples drive the gradient; read the first from the noise model the loss assumes, and the second from its pull, minus the gradient one example puts on the prediction.

You need

Maximum likelihood (Probability for ML), entropy, cross-entropy and KL as quantities (Information theory for ML), and where the loss sits in one training step (step 3 of Topic: ml-fundamentals).

New terms
  • Error u = y − ŷ, target minus prediction; margin m = y·f(x) with y ∈ {−1, +1}, positive when right.
  • Pull ψ(u) = ρ′(u): minus the gradient of one example's loss with respect to the prediction (or the score).
  • Consistent for a statistic: the loss's expected value is lowest at that statistic (MSE at the mean, MAE at the median). Strictly proper: a loss on probabilities lowest only at the true probability.
  • Leverage point: an input far from the others along x, as opposed to an outlying target.
  • Logit: a score before the softmax; log Z: the log of the softmax's normaliser.
Read a loss by its pull: who drags the model, and how hard
Regression pull against the error u = y − ŷ
Classification pull against the margin m = y·f(x)

Regression: under MSE a point twice as far off pulls twice as hard, so the largest errors steer the fit; Huber caps the pull at δ (here 1) and MAE gives every point the same pull of 1, which is why both resist bad targets. Classification: every classification loss pulls hardest on wrong examples (m < 0) and lets go of right ones, but at different rates: the exponential loss's pull explodes on a mislabelled point, hinge drops to exactly 0 once m ≥ 1, and focal loss (γ = 2) silences easy examples far sooner than cross entropy. Every curve is the exact derivative, drawn from the page's checked formulas derived.

In one screen: target, belief, loss

Read most losses as the negative log-likelihood of a noise model, and the choice follows from what you believe about the target and its noise.

Target, and what you believe about its noiseLossWhat the model learns to predictWatch out for
A number, errors roughly GaussianMSE (squared error)the conditional meana few large errors dominate the fit (below)
A number, some targets wildly wrongHuber (threshold δ), MAEbetween mean and median; the medianprotects against bad targets, not against unusual inputs (leverage)
A number, and you need a range or asymmetric costspinball (quantile) loss at level τthe τ-quantile (Koenker and Bassett 1978)one fit per τ; separately fitted quantile lines can cross
A positive number, relative error is what mattersMSE on log(y), or MAPEMAPE: a value below the median (Gneiting 2011)MAPE has no value at y = 0 and charges over-forecasts more
A countPoisson negative log-likelihoodthe mean ratepredict log(rate) and exponentiate, or the rate can go negative
A number with its own uncertaintyGaussian negative log-likelihood (mean and variance)mean and variancethe variance can collapse; PyTorch clamps it at eps
One class out of Ksoftmax cross entropyclass probabilitiesoverconfidence (label smoothing), rare classes (weights, focal)
Several yes/no labels at oncebinary cross entropy per label, on logitsone probability per labeluse the logits version for numerical stability
Rare positives among many easy negativesfocal loss (γ, α)probabilities pulled towards 0.5 (computed below)recalibrate before reading scores as probabilities
Only the decision mattershinge (SVM)the sign only, no probabilityscores are not probabilities
An order of items for a querypairwise (RankNet), listwise, LambdaRankscores whose order is rightpairwise counts every swap alike; the top of the list matters more (below)
A distribution: a teacher, a prior, a reference modelKL divergencethe other distributionwhich direction (below)
Which of a batch belongs togetherInfoNCE, triplet, contrastive lossesa similarityContrastive and self-supervised learning
Which of two answers people preferBradley-Terry, DPO and its familya reward, or a policyAlignment: SFT, RLHF, DPO Family, RLVR
New samples that look realadversarial (GAN) lossa generatorthe original form stalls early (below)

"What the model learns to predict" is what minimises the expected loss for each input; scikit-learn's guide lists the same pairs as "strictly consistent scoring functions" (scikit-learn, model evaluation). The rule when the loss is also the metric: train with a loss consistent for the quantity you will be scored on.

How a batch becomes one number

Strictly, the loss is one example's error and the cost its aggregate, usually the mean; in practice the words are used interchangeably. The aggregate hides two traps.

  • Reduction. PyTorch losses return one value per element with reduction='none', their sum with 'sum', and by default their mean. With class weights, cross entropy's "mean" divides by the sum of the weights of the examples, not by their number; and targets equal to ignore_index (default −100) are left out of both the sum and the count (PyTorch, CrossEntropyLoss).
  • Token-level means in language models. A language model's loss is the mean over all non-padding tokens. Averaging per micro-batch and then over micro-batches is not the same number when micro-batches hold different numbers of tokens; Hugging Face fixed exactly this in its Trainer's gradient accumulation on 16 October 2024 by summing and dividing by the total token count (Hugging Face). Which tokens count at all (prompt, padding, packed neighbours) is in "Padding, packing, and how tokens are weighted" on Alignment: SFT, RLHF, DPO Family, RLVR.

Fig. 1 runs a real batch through both averages: four public-domain opening sentences, every token's cross entropy under SmolLM2-135M (src/real_tokens.py) measured.

  1. One loss per token. Four sentences padded to the longest, 26 tokens; each column is the cross entropy of predicting that token from the ones before it. The tallest is "Ishmael" after "Call me", 11.68 nats. Grey tiles are padding.
  2. Padding is masked. Padding positions get the label −100, PyTorch's default ignore_index, so they leave both the sum and the count: 3, 13, 15 and 25 predicted tokens, 56 in all.
  3. Mean per token. Every token counts once: the sum divided by 56 is 2.38 nats, what cross_entropy returns on the padded batch; each token weighs 1.8%.
  4. Mean per sentence. Average each row first: 7.44 for "Call me Ishmael.", 1.09 for Dickens, 2.38 for Tolstoy and 2.44 for Austen.
  5. Then the mean of the means. 3.34 nats, 40% higher, because the short sentence now counts as much as the long one: each of Melville's tokens weighs 8.3%, each of Austen's 1.0%.
  6. Gradient accumulation. With one sentence per micro-batch, averaging each micro-batch and then over micro-batches gives the mean of the means; the October 2024 fix above gives the per-token mean.

Regression: each loss is a noise model, and picks a statistic

Every regression loss is a function ρ(u) of the error, and its derivative ψ(u) is the pull. MSE is maximum likelihood for Gaussian noise of fixed variance and MAE for Laplace noise (the recipe that turns a noise distribution into its loss, with each derivation: Probability for ML, section 7).

LossPer example, ρ(u)Pull ψ(u)ForAgainst
MSEu22u: grows with the errorsmooth, and the gradient shrinks near the minimum, so convergence is clean for small errorssquaring lets huge errors dominate: drastic update jumps, very sensitive to outliers
RMSE√MSE, over the batchui / (N·RMSE)in the target's units, so it reads well as a reported numbersame minimiser as MSE, so exactly as outlier-sensitive when trained on; and its gradient does not shrink as all errors shrink together (it is the error divided by the RMSE) derived
MAE|u|sign(u): every point pulls with the same forceoutliers that are real data (or bad labels) cannot dominate; estimates the medianthe gradient does not soften near the minimum, so a fixed step size oscillates; no gradient at 0 (a subgradient is used)
Huber (δ)½u2 for |u| ≤ δ, δ(|u| − ½δ) beyond (Huber 1964)u clipped to [−δ, δ]MSE near the target, MAE far from itδ is in the target's units and must be tuned (or a scale estimated alongside, as scikit-learn's HuberRegressor does, default 1.35 in units of that scale: scikit-learn); second derivative 0 beyond δ
Log-coshlog cosh(u)tanh(u)Huber-shaped, smooth and twice differentiable everywherea fixed scale: it behaves like Huber with δ about 1 in the target's units, so on a target measured in miles it is MAE in all but name (see the picker below)
Pinball, level ττu if u ≥ 0, (τ − 1)u if notτ or τ − 1predicts a quantile: τ = 0.9 under-predicts only 10% of the time; τ = 0.5 is MAE / 2one model per τ
MAPE|u| / |y|sign(u) / |y|scale-free, so errors on small and large targets count alikeno value at y = 0 and huge near it; biased low (below)

Predict, then look: which of these losses gives a Newton step (XGBoost's leaf weight, which divides by the summed second derivative) nothing to divide by for large errors? Switch to "second derivative".

PyTorch's HuberLoss(delta) is the formula above; SmoothL1Loss(beta) is the same curve divided by β, so the two differ by a factor of δ and agree only at δ = 1 (PyTorch, SmoothL1Loss). The rule of thumb: MSE by default, MAE or Huber when outliers are real data, log-cosh (or pseudo-Huber) when a smooth second derivative is needed.

Two claims about log-cosh, checked

"Cheaper than Huber": not in arithmetic. Huber is one comparison and a multiply; log-cosh needs an exponential and a logarithm (computed stably as |u| + log(1 + e−2|u|) − log 2). "Second-order methods want it": half right. Huber's second derivative is exactly 0 beyond δ, so a leaf of large errors has nothing to divide by; XGBoost ships pseudo-Huber for this reason, "a twice differentiable alternative to absolute loss" (XGBoost parameters). But log-cosh's second derivative, 1/cosh2(u), also falls towards 0 for large errors (about 4e−2|u|), so it softens the problem rather than removing it derived.

The pull separates the losses; the second derivative is what a Newton step needs

MAPE is drawn for a target y = 1, where it equals MAE; for other targets divide by |y|. Huber's second derivative is 0 beyond δ, log-cosh's decays as 4e−2|u|, MAE's and pinball's are 0 everywhere except a kink. Values and pulls checked against PyTorch autograd.

Which number each loss picks

Before any model, ask what single number each loss would predict for a whole sample: that is the statistic the loss estimates, and where a model trained on it will sit for every input. The sample is real and skewed: the lengths of 141 major North American rivers, in miles (R's rivers, from the USGS via the World Almanac 1975).

Predict, then look: add one 0.5-mile river. Which loss's choice collapses? Tick "add a 0.5-mile river", then move τ and δ.

On the rivers the mean is 591 miles and the median 425. MAPE picks 336, below the median, because dividing by y makes short rivers count for more; Gneiting proved this in general: MAPE is consistent for the "median of order −1", the median of a distribution reweighted by 1/y, which "tends to support severe underforecasts" (Gneiting 2011). Log-cosh lands on 425.2, the median to a fraction of a mile, because every river is hundreds of units away from any reasonable c, deep in its linear part.

The long rivers drag the mean up; MAPE lands below the median

Each curve is the mean loss for a constant forecast c, scaled to its own range; the dot is its minimum; log-cosh's curve lies on top of MAE's. Exact minimisers: the mean; the median; the τ-quantile and MAPE's weighted median (weights 1/y) by sorting; Huber and log-cosh by solving Σψ(y − c) = 0. All checked against PyTorch losses evaluated on a 40,000-point grid (src/recompute.py). The 0.5-mile river is illustrative.

What an outlier does to a fit, step by step

Anscombe built four small datasets with the same means, variances, correlation and least-squares line, y = 3.00 + 0.500x (Anscombe 1973). His third set is ten points on an almost perfect line plus one point far above it. Fig. 2 puts the points on the floor with the fitted line; each point's loss stands on it as a column, and green dots run from the line towards each point, as long as that point's pull on the line.

Predict, then watch: how far will one bad point move the MSE slope from the clean 0.345? Then press "Unusual inputs", where the outliers sit at unusual inputs instead.

  1. Ten clean points. Anscombe's set III without its outlier: MSE's line is y = 4.01 + 0.345x, and every column is nearly flat. The side column is the total loss, the number the fit minimises.
  2. One bad target arrives. On Anscombe III the outlier at (13, 12.74) is a bad target, u = 4.24 above the line. Under MSE its loss is u2 = 18.0, the one tall column, and its pull 2u is the only one long enough to see.
  3. MSE gives way. Under MSE its pull is 2u, so the line moves to the minimum of the total, slope 0.500 (Anscombe's line): the total falls from 18.01 to 13.76, of which the outlier still holds 76%. To shrink one big square, MSE puts every other point off the line: their columns rise from the floor.
  4. Huber caps the pull. Under Huber with δ = 1 its pull is capped at 1 and its loss grows only linearly (3.74 at the clean line), so the slope only moves to 0.393; the dashed line is MSE's.
  5. MAE ignores it. |u| gives every point a pull of exactly 1, so the ten clean points outvote the outlier: the slope stays at 0.345, through the ten clean points. The outlier keeps its whole error, 4.24 of a total of 4.26.
  6. Three minima. MSE 0.500, Huber 0.393, MAE 0.345: the faster a loss's pull grows with the error, the further one bad target drags the line. Log-cosh behaves like Huber (0.394), because the residuals here are in the units where its bend sits.

Defaults reproduce Anscombe's line, y = 3.00 + 0.500x for set III, independently (MSE fit here: 3.0025 + 0.4997x). Every fit is the exact minimiser (closed form for MSE, IRLS for Huber and log-cosh, a line through two data points for MAE), checked against PyTorch's MSELoss, L1Loss and HuberLoss with autograd and SciPy (src/recompute.py). Columns share one scale per dataset; pulls are scaled to the largest in each step.

Robust to bad targets is not robust to unusual inputs

The star cluster CYG OB1 (47 stars, log surface temperature against log light intensity; robustbase starsCYG, from Rousseeuw and Leroy 1987) is the classic counter-example: press "Unusual inputs" in Fig. 2. 43 stars lie on the main sequence, where light rises with temperature; 4 red giants (observations 11, 20, 30, 34) are cool and bright, far out on the x axis. They are leverage points: unusual inputs, not unusual targets.

Correction: "Huber and MAE make a fit robust to outliers"

Only to outliers in y: the 4 giants turn every loss's line over (Fig. 2, steps 3 to 5). Capping each point's pull does nothing about its lever: a point's effect on the slope is its pull times its distance along x, and the giants' distance is the largest in the set. Fixing this needs a method that down-weights by position as well (least trimmed squares, RANSAC, Theil-Sen); scikit-learn's guide separates "outliers in the y direction" from "outliers in the X direction" for this reason (scikit-learn, robustness regression; Rousseeuw and Leroy 1987). In a neural network the same holds: a robust loss protects against bad labels, not against inputs unlike the rest of the training set.

Every loss, any δ or τ, on these datasets or on points you place yourself, with each point's pull and lever: Fit a line.

MAPE and quantiles

MAPE is asymmetric. For a positive target and a non-negative forecast, under-forecasting can cost at most 100% (forecast 0), while over-forecasting has no ceiling: forecasting 2y costs 100%, 3y costs 200% derived. That, and the 1/y weighting above, is why a MAPE-trained model under-forecasts. At y = 0 it has no value at all: scikit-learn divides by machine epsilon instead and documents an example returning 1.1 × 1014 from a single zero target, "arbitrarily large MAPE values, especially if some y_true values are very close to zero" (scikit-learn, MAPE); it also returns a fraction, not a percentage (0.5 means 50%). When relative error is what matters, training MSE on log(y) is the usual alternative; it estimates the mean of log y, a geometric mean, and it too needs y > 0.

Quantile (pinball) loss gives a prediction interval from two fits: τ = 0.05 and 0.95 bracket 90% of targets if the model is right. Tree libraries ship it (XGBoost's reg:quantileerror since 2.0 with quantile_alpha, which accepts a list of quantiles: XGBoost; scikit-learn's HistGradientBoostingRegressor(loss="quantile"): scikit-learn).

Counts and predicted variances: Poisson and Gaussian negative log-likelihood

Counts take the Poisson negative log-likelihood, ŷ − y log ŷ (+ log y!, a constant), with the network predicting log ŷ so the rate stays positive; that is PyTorch's PoissonNLLLoss with its default log_input=True (PyTorch). Its minimiser is the mean, like MSE's, but it charges errors relative to the rate.

A prediction with its own variance takes the Gaussian negative log-likelihood, ½(log σ2 + (y − ŷ)2/σ2), with the network predicting σ2 too; the model can lower the loss on hard examples by raising their σ2 instead of fitting them, and PyTorch clamps σ2 at eps (default 10−6) so it cannot collapse to zero (PyTorch, GaussianNLLLoss).

Cross entropy: likelihood, KL, and the gradient p − y

A five-class image classifier outputs logits z = (3.0, 1.5, 0.5, −0.5, −1.5) for cat, dog, fox, owl and car; the softmax turns them into p = (0.743, 0.166, 0.061, 0.022, 0.008) illustrative. If the image is a cat, cross entropy is −log 0.743 = 0.30 nats; if it is a car, −log 0.008 = 4.80.

  • It is maximum likelihood. With a one-hot label, cross entropy is the negative log-likelihood of the right class, so minimising its mean is maximum likelihood estimation (Probability for ML).
  • It is entropy plus KL. Against any target distribution P, cross entropy H(P, Q) = H(P) + DKL(P‖Q). With a one-hot P, H(P) = 0 and the loss is the KL; with a soft target (label smoothing, a teacher) H(P) > 0 is a floor no model goes below. The derivation is on Information theory for ML.
  • Its gradient on the logits is just ∂L/∂zk = pk − yk. Every wrong class is pushed down by its probability, the right class up by what it lacks, and the pushes sum to zero derived. For the cat that is −0.257 on the cat logit; for the car, −0.992 on the car logit: a confidently wrong example gets almost the largest push possible (1).

Fig. 3 runs one real prediction through the loss: SmolLM2-135M on the Dickens sentence, at the token after "it was the spring of hope, it was the" (src/real_tokens.py) measured.

  1. The logits. The model's nine most likely next tokens of 49,152, all close: "winter" 20.0, "summer" 19.9, "fall" 19.8, "autumn" 19.5.
  2. The softmax. p = ez − log Z, with log Z = 21.6 over the whole vocabulary: winter gets 19.5%, summer 17.9%, fall 16.3%, and 24.7% is spread over the other 49,145 tokens.
  3. The target. Dickens wrote "winter": y is 1 there and 0 everywhere else, and the loss is −ln p = log Z − z = 1.63 nats.
  4. The gradient, p − y. Gradient descent moves each logit by −(p − y): winter is pulled up by 1 − p = 0.805, every other token is pushed down by its own probability (summer 0.179, fall 0.163), and the rest of the vocabulary by 0.247 together. The tokens that took the probability are pushed hardest.
  5. The pushes add up to the pull. p and y both sum to 1, so the gradient sums to zero: a step reshapes the logits but never moves their overall level, which is why that level is free (Fig. 4).

The same gradient for every standard pairing. Pair each output with its matching activation and loss and the gradient in the logit z (the raw score before any squashing, what backprop starts from) is always prediction minus target derived:

OutputActivation, loss∂L/∂z
a real numberidentity, ½(ŷ − y)2ŷ − y
yes or nosigmoid p = σ(z), binary cross entropyp − y
one of K classessoftmax, cross entropy −log ptp − et (one-hot et); p − q with soft targets q
a countrate μ = ez, Poisson negative log-likelihoodez − y

Each pairing is a generalised linear model: the target's distribution is in the exponential family, the logit is its natural parameter, and the negative log-likelihood has gradient mean minus target (why, from the distribution: Probability for ML, section 7; every derivation step: Calculus and optimisation for ML, section 2). What it means in practice: the push on a logit is bounded by 1 and is largest exactly when the model is most wrong. A squashing activation paired with the wrong loss keeps the activation's slope, which vanishes there: squared error on a sigmoid has gradient 2(p − y)p(1 − p), and at z = −6 with y = 1 that is −0.0049 against cross entropy's −0.9975, about 203 times smaller; the softmax case is the 38 times below.

Every other classification loss is this gradient reshaped: a softer target, a weight per example, or a different function of p. The widget puts each beside cross entropy on the same logits.

Predict, then look: on the car (confidently wrong), which loss pushes the car logit hardest, and which barely at all? Pick "confidently wrong", then each loss on the right.

What the widget shows, in numbers computed here:

  • MSE on probabilities lets the worst examples off. On the car it pushes the car logit by 0.026 against cross entropy's 0.992, 38 times less, because the softmax's slope pk(1 − pk) is nearly 0 at p = 0.008 and squared error has no log to cancel it. Cross entropy's log exactly cancels that slope, which is why classifiers train on it; the parent's Training lab trains the same network both ways.
  • Focal loss silences the easy example, not the hard one. On the cat it pushes 0.046, 5.6 times less than cross entropy; on the car it pushes 1.053, about the same. That is the point of focal loss: the gradient budget moves to the hard examples.
  • Label smoothing stops short of certainty and lifts the tail. On the cat it pushes the cat logit 0.177 instead of 0.257, and it pushes the car logit up (0.012), because p = 0.008 is below its target of 0.02 for every wrong class.
Same logits, four losses: the gradient each one puts on every logit
Cross entropy the reference, p − y
Label smoothing

Bars are −∂L/∂zk, the direction gradient descent moves each logit (up is towards the class), on one scale across both panels; the right class is outlined. Label smoothing uses PyTorch's convention (target 1 − ε + ε/K on the right class, ε/K = 0.02 on each other); focal is −(1 − pt)γ log pt with α = 1; MSE on probabilities is the Brier score Σk(pk − yk)2. Gradients checked against PyTorch autograd (src/recompute.py).

The cross-entropy family

LossUsePer exampleNotes
Binary cross entropybinary, and multilabel (one sigmoid per output)−[y log p̂ + (1 − y) log(1 − p̂)]feed logits to BCEWithLogitsLoss, which folds in the sigmoid and is "more numerically stable" via the log-sum-exp trick; pos_weight up-weights positives (PyTorch)
Categorical cross entropyone class out of K (softmax)−Σc yc log p̂cPyTorch's CrossEntropyLoss takes unnormalised logits and equals LogSoftmax then NLLLoss (PyTorch)
Sparse categorical CEthe same, integer labels−log p̂yidentical maths; takes the class index instead of a one-hot vector (Keras's name; PyTorch's CrossEntropyLoss accepts either)
Label smoothingoverconfident models, calibrationcross entropy against a softened targettwo conventions: 1 − ε on the true class and ε/(K − 1) on each other, or (PyTorch and Szegedy et al. 2016) a mix with the uniform distribution, 1 − ε + ε/K and ε/K; the same ε gives different targets
Weighted CEclass imbalancewy times the CEup-weight the minority class; PyTorch's mean then divides by the summed weights, not the count
Focal lossextreme imbalance (dense detection)−αt(1 − pt)γ log ptdown-weights easy examples so the hard ones dominate the gradient (Lin et al. 2017)
HingeSVMs, maximum marginmax(0, 1 − y·f(x)), y ∈ {−1, 1}zero once the margin is met; the decision, not a probability (below)

Focal loss, exactly as published. In a dense detector most of the roughly 100,000 anchor boxes per image are easy background, and "easily classified negatives comprise the majority of the loss and dominate the gradient". The factor (1 − pt)γ removes them: "with γ = 2, an example classified with pt = 0.9 would have 100× lower loss compared with CE and with pt ≈ 0.968 it would have 1000× lower loss" (1/0.12 = 100 and 1/0.0322 = 977 derived; reproduced live in the margin chart below).

Focal loss: α, the prior bias and the paper's ablations

The paper found γ = 2 best and, with it, α = 0.25, noting that "lower α's are selected for higher γ's": α weights the rare foreground class down, because γ already removed most of the easy background. It also initialises the output bias so the model starts by predicting 0.01 for the rare class, and shows that "the exact form of the focal loss is not crucial" (Lin et al. 2017). The parent's When training goes wrong tab runs focal loss with α = 0.25 against re-weighting, oversampling and the prior bias on an imbalanced task.

Label smoothing improves calibration: on ImageNet Müller et al. report an expected calibration error of 0.071 with hard targets, 0.022 after temperature scaling, and 0.035 with label smoothing of 0.1 and no scaling. It also harms distillation: a teacher trained with label smoothing was more accurate than one trained with hard targets and dropout (0.59% error against 0.67% on MNIST) but taught a much worse student (0.91% against 0.74%) (Müller et al. 2019), because smoothing erases the similarities between wrong classes that a student learns from (Distillation and Small Language Models).

Proper scoring. A loss on probabilities is strictly proper when the expected loss is lowest only at the true probability; the log score (cross entropy) and the Brier score (squared error on probabilities) are (Gneiting and Raftery 2007). Focal loss is not: if 90% of inputs like this one are positive, the focal optimum with γ = 2 is a predicted probability of 0.694, with γ = 3 0.647 computed here (move η and γ in the score chart in the next section). Either way, a focal model's scores are recalibrated before being read as probabilities.

Why focal-trained networks still come out better calibrated

Mukhoti et al. show the same thing from the other side: focal loss is an upper bound on KL minus γ times the entropy of the prediction, so it raises entropy, and that is why networks trained with it come out better calibrated than overconfident cross-entropy networks (Mukhoti et al. 2020).

One axis for every classification loss: the margin

With labels y ∈ {−1, +1} and a score f(x), the margin m = y·f(x) is positive when the example is classified correctly and large when it is classified confidently. The loss we would like is the 0-1 loss (1 if m ≤ 0); it has no gradient, so training minimises a convex surrogate: hinge max(0, 1 − m) for the SVM, logistic log(1 + e−m), which is binary cross entropy on logits, and exponential e−m, which AdaBoost minimises (Friedman, Hastie and Tibshirani 2000). A convex surrogate gives the right decisions in the limit exactly when it is differentiable at 0 with a negative slope there (Bartlett, Jordan and McAuliffe 2006, Theorem 6), which all of these pass.

Who pulls hardest. A misclassified point at m = −5 pulls with 0.99 under the logistic loss, 1 under hinge, and e5 = 148 under the exponential loss derived. A mislabelled example is exactly such a point, which is why exponential-loss boosting suffers under label noise; Long and Servedio prove that for a broad class of convex potentials, any nonzero rate of random label noise can stop a booster from beating 1/2 accuracy on a data set it would learn without noise (Long and Servedio 2010).

Try: switch to "pull" and drag m to −3; then press the two buttons under the chart to land on Lin et al.'s focal numbers.

Every surrogate pulls on wrong examples; they differ in how fast they let go of right ones

Defaults reproduce Lin et al.'s "100× lower loss" at pt = 0.9 and "1000×" at pt ≈ 0.968 for γ = 2: 100× and 977×, independently.

Logistic loss in nats, log(1 + e−m), which is BCEWithLogitsLoss on the score; some texts divide by ln 2 so that it equals 1 at m = 0. Focal is the binary focal loss on the same score, pt = σ(m), α = 1. Values and pulls checked against PyTorch autograd.

What the score estimates. If a fraction η of inputs like x are positive, the logistic loss is minimised at f = log(η/(1 − η)), the log-odds, so σ(f) is the probability; exponential at half the log-odds; squared hinge at 2η − 1; hinge at sign(η − ½), "for all η ∈ (0, 1) other than 1/2" (Bartlett et al. 2006, Example 3): an SVM's score carries the decision and nothing about how sure it is.

Logistic recovers η exactly; hinge keeps only the sign; focal is pulled towards 0.5

The expected loss of a score f is η·φ(f) + (1 − η)·φ(−f). Its minimum f* is what a model trained on that loss learns to output.

Closed forms for logistic (log-odds), exponential (half the log-odds), squared hinge (2η − 1) and hinge (sign; Bartlett et al. 2006, Example 3); focal by a grid then golden-section search, checked against SciPy. Each curve is shifted and scaled to its own range so their minima can be compared.

Ranking losses: only the order counts

A search engine scores each document i for a query, si = f(xi), and shows them sorted. The labels are relevance grades, and the metric only looks at the order, usually NDCG: each document's gain 2l − 1 divided by log(1 + its rank), summed, over the best possible sum (Burges 2010, eq. 5; the log's base cancels in the ratio). Three ways to turn that into a loss:

  • Pairwise. For each pair where i should rank above j, penalise the score difference. PyTorch's MarginRankingLoss is the hinge version, max(0, −y·(x1 − x2) + margin), margin 0 by default (PyTorch 2.14 docstring). RankNet is the logistic version: model P(i above j) = 1/(1 + e−σ(si − sj)) and take cross entropy, which for a known order is C = log(1 + e−σ(si − sj)), the logistic margin loss above with m = si − sj; "when si = sj, the cost is log 2" (Burges 2010, section 2).
  • Listwise. A softmax over the whole list's scores, cross entropy against the target distribution (ListNet, with its top-one probability: Cao et al. 2007). With exactly one relevant item in the list this is InfoNCE, the loss contrastive learning runs over a batch (Contrastive and self-supervised learning).
  • Metric-weighted (LambdaRank). NDCG is "everywhere either discontinuous or flat" in the scores, so it has no useful gradient. LambdaRank keeps RankNet's gradient on each pair, λij = −σ/(1 + eσ(si − sj)), and multiplies it by |ΔNDCG|, the change in NDCG from swapping the two; "experiments have shown" this "gives very good results" (eq. 6). LambdaMART is its boosted-tree version; "an ensemble of LambdaMART rankers won Track 1 of the 2010 Yahoo! Learning To Rank Challenge" (Burges 2010).

Why pairwise is not enough, in numbers. Ten documents, relevant at ranks 2 and 10, the rest irrelevant illustrative: 9 pairs are in the wrong order, NDCG 0.564. Fix A lifts the bottom relevant document to rank 5: 4 wrong pairs, NDCG 0.624. Fix B swaps the top two: 8 wrong pairs, NDCG 0.790. A pairwise loss prefers A; the user, and NDCG, prefer B computed here. Burges's Figure 1 makes the same point (13 pairwise errors reduced to 11 by a move that hurts the top of the list).

Predict, then look: under RankNet, which document gets the largest push? Under LambdaRank? Then move the second relevant document up the list.

With the default list, RankNet pushes the relevant document at rank 2 only 0.30 times as hard as the one at rank 10, because rank 10 is in more wrong pairs; LambdaRank raises that to 0.42. The irrelevant document at rank 1 is pushed down 0.24 times as hard as rank 10 is pushed up under RankNet, 0.75 times under LambdaRank: the swap that fixes the top of the list now carries a far larger share of the gradient computed here.

The triplet loss, max{d(a, p) − d(a, n) + margin, 0}, is the same idea for embeddings: rank the matching pair above the non-matching one for an anchor (PyTorch's TripletMarginLoss: margin 1, p = 2 by default). Its margin, the choice of negatives and the collapse that hard negatives cause are owned by Contrastive and self-supervised learning ("Pairs and triplets: the margin losses"), which runs it on a real batch.

Same scores, same pairs: LambdaRank moves the push to the top of the list
RankNet every wrong pair counts alike
LambdaRank each pair times |ΔNDCG|

Each bar is −λi = −∂C/∂si summed over the document's pairs (Burges 2010, eqs. 3, 4 and 6; σ = 1): right is "push this score up". Each panel is scaled to its own largest bar, because LambdaRank's λ carries NDCG's units. Scores fall by 0.4 per rank from 2.0 illustrative; RankNet's λ checked against PyTorch autograd, LambdaRank's recomputed independently (src/recompute.py).

The level of the logits: what cross entropy ignores

Because the cross-entropy gradient p − y sums to zero over the classes, adding the same constant c to every logit changes neither the softmax nor the loss. The overall level, log Z = log Σj ezj, is free to drift, and in large models it does. Two fixes act on the logits themselves: z-loss adds 10−4·log2 Z to pull the level to log Z = 0 (PaLM), and soft-capping bounds them, soft_cap·tanh(logits / soft_cap) (Gemma 2: 50 in attention, 30 on the final layer). Both, with the instabilities they prevent and measured runs, are owned by Normalisation, residuals and stability (section 5 for z-loss, section 4 for soft-capping).

Fig. 4 takes the same prediction as Fig. 3 and moves only the level.

  1. Where the level sits. SmolLM2's top logit is 20.0 and log Z = 21.6 (the glass plate). Cross entropy, log Z − zwinter = 1.63, sees only differences; z-loss sees the level: 10−4·log2 Z = 0.047.
  2. Shift every logit by c = +8 illustrative. The softmax in front does not move and cross entropy stays 1.63, but log Z becomes 29.6 and z-loss 0.088.
  3. z-loss pushes down. Its gradient on logit i is 2·10−4·log Z·pi, largest on the likeliest token: 1.2×10−3 on winter here (8.4×10−4 at the model's own level), small beside cross entropy's 0.805, and the same sign on every logit, so it moves the level, not the differences.
  4. Down to log Z = 0. Every logit falls together; the softmax and cross entropy never change.
  5. Each logit is its log-probability. At log Z = 0 winter sits at −1.63 and time at −3.46, and z-loss is 0: the level PaLM's z-loss pulls towards.
Real logits from three small models: where the level sits, and what bf16 storage does to it (measured)

PaLM added "an auxiliary loss of z_loss = 10−4 · log2 Z to encourage the softmax normalizer log(Z) to be close to 0, which we found increases the stability of training" (Chowdhery et al. 2022). Its gradient on logit i is 2·10−4·log Z·softmaxi, a push of every logit towards a level where log Z = 0 and each logit is its log-probability. Wortsman et al. reproduced the failure it prevents, output logits diverging late in training, in small models trained without weight decay at high learning rates, and found z-loss resolves it (weight decay also helped in their larger models; Wortsman et al. 2023). Which landmark models used it is in the parent's Defaults across models tab.

Why the level matters at all is number formats: bfloat16 keeps 8 significant bits, so the gap between neighbouring values grows with magnitude (0.0078 near 1, 0.125 near 24, 0.5 near 100) derived. Logits stored in bf16 at a high level lose the small differences the softmax depends on. Slide the shift c added to every logit: cross entropy does not move, z-loss does, and so does the damage bf16 storage does to the probabilities.

The opening sentence of A Tale of Two Cities (public domain), tokenised by each model; 72 or 73 next-token predictions each. Logits computed offline in float32 with PyTorch and Hugging Face transformers (src/real_logits.py); the bf16 column rounds every logit to bfloat16 with torch.bfloat16 before an exact softmax and reports the mean total-variation distance from the float32 probabilities. Cross entropy is low because the sentence is famous. measured

None of the three sits at log Z = 0: GPT-2 averages −42.6 (its logits sit around −61), SmolLM2-135M +25.2 and Qwen2.5-0.5B +22.4, and storing GPT-2's logits in bf16 already moves 2.4% of its probability mass. For SmolLM2 and Qwen2.5 the bf16 error is smallest at shifts of −16 to −24, close to −log Z, which is where z-loss would put them; GPT-2's minimum lies further out because its bulk of very negative logits matters too. This is a demonstration of the mechanism, not of training: mixed-precision training usually computes the softmax and loss in float32. Gemma 3 replaced Gemma 2's soft-capping with QK-norm (Gemma 3 report; soft-capping values from the Gemma 2 report).

Between distributions and between models

  • KL divergence, DKL(P‖Q) = Σ P log(P/Q): asymmetric and not a metric. It is the regulariser in VAEs (keep the code near its prior), the distillation loss (the student matches the teacher) and the RLHF anchor (the policy stays near its reference). Which direction a small student should minimise, forward or reverse, is "Forward or reverse KL" on Distillation and Small Language Models. In PyTorch, KLDivLoss takes the model's log-probabilities first and the target second, and its default reduction='mean' "doesn't return the true KL divergence value"; use 'batchmean' (PyTorch).
  • Penalties (L1 or lasso, L2 or ridge, elastic net) are added to the loss but are not task losses: L1 drives weights to exactly zero (sparsity, feature selection), L2 shrinks them without zeroing any, elastic net combines both. Details on Regularisation.
  • Preference losses (Bradley-Terry reward models, DPO and its family) score a preferred answer against a rejected one, a pairwise ranking loss on two answers; "Direct preference optimisation and its family" on Alignment: SFT, RLHF, DPO Family, RLVR runs one preference pair through eight of them. The CLIP paper page runs a contrastive loss live.

The adversarial loss, and the fix in the same paper

A GAN trains a generator G and a discriminator D against each other in one minimax game, minG maxD E[log D(x)] + E[log(1 − D(G(z)))]. The original paper already warned that this form starves the generator: "Early in learning, when G is poor, D can reject samples with high confidence ... In this case, log(1 − D(G(z))) saturates. Rather than training G to minimize log(1 − D(G(z))) we can train G to maximize log D(G(z))", which has the same fixed point "but provides much stronger gradients early in learning" (Goodfellow et al. 2014, section 3). This is the non-saturating loss most GANs train with.

Predict, then slide: when the discriminator gives a fake 0.01, how many times stronger is the non-saturating gradient? Slide how confidently the discriminator rejects a generated sample.

Later losses change the game itself: least-squares GANs replace the log loss with squared error, because the sigmoid cross-entropy loss "may lead to the vanishing gradients problem", and minimising it amounts to the Pearson χ2 divergence (Mao et al. 2017); Wasserstein GANs minimise the earth mover's distance with a Lipschitz critic, enforced in the first paper by weight clipping, which its authors call "a clearly terrible way to enforce a Lipschitz constraint" (Arjovsky et al. 2017). GANs themselves belong to Topic: generative-and-multimodal.

The minimax gradient vanishes exactly when the generator is worst

Gradients with respect to the discriminator's logit l on the sample, D = σ(l): minimax d/dl log(1 − σ(l)) = −D; non-saturating d/dl (−log σ(l)) = −(1 − D) derived, checked with PyTorch autograd. At D = 0.01 the ratio is (1 − D)/D = 99.

Common mistakes

A softmax (or sigmoid) before a loss that expects logits
CrossEntropyLoss applies log-softmax itself, and BCEWithLogitsLoss the sigmoid; applying them twice squashes the scores and shrinks every gradient. Use the plain BCELoss on probabilities only when you have no logits; the logits version is the numerically stable one (PyTorch).
δ in the wrong units, or SmoothL1 taken for Huber
Huber's δ (and log-cosh's built-in bend at about 1) is measured in the target's units: standardise the target or pick δ from the residual scale. SmoothL1Loss(beta) is HuberLoss(delta) divided by β; with β ≠ 1 the gradients differ by that factor.
MAPE with zeros or tiny targets
Use MAE on a scale that makes sense, MSE on log(y), or a weighted error.
Reading focal or hinge scores as probabilities
Recalibrate (temperature or Platt scaling) on held-out data first.
KLDivLoss with its arguments swapped or its default reduction
The first argument is the model's log-probabilities; 'mean' averages over every element, not over examples; 'batchmean' gives the KL.
Comparing loss values across set-ups
A smoothed target has entropy above 0, so its loss has a floor no model goes below; class weights change what "mean" divides by; per-micro-batch averages differ from a token mean. Compare under the same target, weights and reduction, or compare a metric instead. And check the starting loss: an untrained K-class classifier should score about ln K (step 3 of Topic: ml-fundamentals).