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.
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).
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.
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 noise | Loss | What the model learns to predict | Watch out for |
|---|---|---|---|
| A number, errors roughly Gaussian | MSE (squared error) | the conditional mean | a few large errors dominate the fit (below) |
| A number, some targets wildly wrong | Huber (threshold δ), MAE | between mean and median; the median | protects against bad targets, not against unusual inputs (leverage) |
| A number, and you need a range or asymmetric costs | pinball (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 matters | MSE on log(y), or MAPE | MAPE: a value below the median (Gneiting 2011) | MAPE has no value at y = 0 and charges over-forecasts more |
| A count | Poisson negative log-likelihood | the mean rate | predict log(rate) and exponentiate, or the rate can go negative |
| A number with its own uncertainty | Gaussian negative log-likelihood (mean and variance) | mean and variance | the variance can collapse; PyTorch clamps it at eps |
| One class out of K | softmax cross entropy | class probabilities | overconfidence (label smoothing), rare classes (weights, focal) |
| Several yes/no labels at once | binary cross entropy per label, on logits | one probability per label | use the logits version for numerical stability |
| Rare positives among many easy negatives | focal loss (γ, α) | probabilities pulled towards 0.5 (computed below) | recalibrate before reading scores as probabilities |
| Only the decision matters | hinge (SVM) | the sign only, no probability | scores are not probabilities |
| An order of items for a query | pairwise (RankNet), listwise, LambdaRank | scores whose order is right | pairwise counts every swap alike; the top of the list matters more (below) |
| A distribution: a teacher, a prior, a reference model | KL divergence | the other distribution | which direction (below) |
| Which of a batch belongs together | InfoNCE, triplet, contrastive losses | a similarity | Contrastive and self-supervised learning |
| Which of two answers people prefer | Bradley-Terry, DPO and its family | a reward, or a policy | Alignment: SFT, RLHF, DPO Family, RLVR |
| New samples that look real | adversarial (GAN) loss | a generator | the 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.
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='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).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.
ignore_index, so they leave both the sum and the count: 3, 13, 15 and 25 predicted tokens, 56 in all.cross_entropy returns on the padded batch; each token weighs 1.8%.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).
| Loss | Per example, ρ(u) | Pull ψ(u) | For | Against |
|---|---|---|---|---|
| MSE | u2 | 2u: grows with the error | smooth, and the gradient shrinks near the minimum, so convergence is clean for small errors | squaring lets huge errors dominate: drastic update jumps, very sensitive to outliers |
| RMSE | √MSE, over the batch | ui / (N·RMSE) | in the target's units, so it reads well as a reported number | same 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 force | outliers that are real data (or bad labels) cannot dominate; estimates the median | the 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-cosh | log cosh(u) | tanh(u) | Huber-shaped, smooth and twice differentiable everywhere | a 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 τ − 1 | predicts a quantile: τ = 0.9 under-predicts only 10% of the time; τ = 0.5 is MAE / 2 | one model per τ |
| MAPE | |u| / |y| | sign(u) / |y| | scale-free, so errors on small and large targets count alike | no 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.
"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.
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.
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.
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.
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.
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.
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.
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 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 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).
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.
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.
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:
| Output | Activation, loss | ∂L/∂z |
|---|---|---|
| a real number | identity, ½(ŷ − y)2 | ŷ − y |
| yes or no | sigmoid p = σ(z), binary cross entropy | p − y |
| one of K classes | softmax, cross entropy −log pt | p − et (one-hot et); p − q with soft targets q |
| a count | rate μ = ez, Poisson negative log-likelihood | ez − 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:
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).
| Loss | Use | Per example | Notes |
|---|---|---|---|
| Binary cross entropy | binary, 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 entropy | one class out of K (softmax) | −Σc yc log p̂c | PyTorch's CrossEntropyLoss takes unnormalised logits and equals LogSoftmax then NLLLoss (PyTorch) |
| Sparse categorical CE | the same, integer labels | −log p̂y | identical maths; takes the class index instead of a one-hot vector (Keras's name; PyTorch's CrossEntropyLoss accepts either) |
| Label smoothing | overconfident models, calibration | cross entropy against a softened target | two 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 CE | class imbalance | wy times the CE | up-weight the minority class; PyTorch's mean then divides by the summed weights, not the count |
| Focal loss | extreme imbalance (dense detection) | −αt(1 − pt)γ log pt | down-weights easy examples so the hard ones dominate the gradient (Lin et al. 2017) |
| Hinge | SVMs, maximum margin | max(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).
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.
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).
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.
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.
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.
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:
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).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.
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).
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.
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).
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).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.
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.
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).SmoothL1Loss(beta) is HuberLoss(delta) divided by β; with β ≠ 1 the gradients differ by that factor.'mean' averages over every element, not over examples; 'batchmean' gives the KL.Every regression loss on this page fitting the same straight line, exactly, on real data or on points you place: the workbench for the outlier and leverage sections of the Reading tab.
Try: on Anscombe III, slide δ from 10 down to 0.1 and watch Huber move from MSE's line to MAE's. Switch to the stars and see every loss lose the main sequence. Choose "your points", tap to add points and tap a point to remove it; build a bad target, then a leverage point, and compare.
Defaults reproduce Anscombe's y = 3.00 + 0.500x for set III (Anscombe 1973), independently. Fits are exact minimisers of the mean loss: closed form (MSE), iteratively reweighted least squares to convergence (Huber, log-cosh), and the best line through two data points (MAE, pinball, MAPE), which is where a linear programme's optimum lies. Checked against PyTorch's MSELoss, L1Loss and HuberLoss with autograd, and SciPy's linprog and BFGS (src/recompute.py: objectives agree to 10−15, parameters to 10−6). Data: Anscombe's set III (R datasets::anscombe); robustbase starsCYG, giants are observations 11, 20, 30, 34.
The regression losses walked through one by one. (20 min)
The canonical reference for exact formulas and reduction semantics; the definitions this page's checks use. (20 min)
The original derivation and the class-imbalance argument; α and γ ablations. (45 min)
What smoothing does to representations and calibration, and why it hurts distillation. (45 min)
Which statistic each loss is consistent for, including MAPE's "median of order −1"; the theory behind "Which number each loss picks". (60 min)
Why hinge, logistic and exponential losses all give the right decisions, and what each score estimates; Examples 1 to 3 are the margin charts in the Reading tab. (60 min)
A practical guide to strictly consistent scoring functions: pick the functional first, then the loss. (20 min)
Pairwise ranking as cross entropy, the lambdas as forces on each document, and why multiplying by |ΔNDCG| works; the source of the ranking section. (40 min)
Output-logit divergence reproduced in small models, and z-loss as the fix. (40 min)
Reading tab, step 3: the loss explorer (cross entropy, label smoothing, focal, the push on the right logit) and the starting-loss check; thread 1: cross entropy = entropy + KL with four targets. Training lab tab: swap cross entropy, MSE, label smoothing and focal loss in a network that trains live. When training goes wrong tab: focal loss with α against re-weighting and oversampling on imbalanced data. Defaults across models tab: which models used z-loss and label smoothing.
Entropy, cross-entropy and KL from first principles, and the cross entropy = entropy + KL derivation.
Maximum likelihood, and how distributions lead to losses.
z-loss and soft-capping on the logits, with measured runs: the owner of the logit-level fixes.
L1, L2 and elastic-net penalties added to the loss; label smoothing as a regulariser.
Entropy against cross entropy against KL as measurements; metrics for imbalanced classes.
InfoNCE and the other batch-level losses.
SVMs and the hinge loss, boosting and its losses.
Soft targets, temperature, forward against reverse KL.
Token weighting in SFT; Bradley-Terry reward models; one preference pair through eight preference losses.
GANs and the other generative objectives.
A tiny CLIP trained live, with its symmetric contrastive loss.
Built from the repository's src/ for this page: every curve, fit and minimum is computed in the page and checked offline against PyTorch 2.14 and SciPy (check_core.mjs, recompute.py); the real logits come from real_logits.py. Checked 3 October 2026; rebuilt to the teaching contract, with the ranking section and the gradient-on-logits widget added, on 24 October 2026.