Neural networks
Loss Functions as Learning Contracts
Connect neural outputs to differentiable objectives, compare major loss families, and diagnose mismatch between training signals and real goals.
By the end you can
- Explain how a loss converts outputs and targets into a scalar learning signal
- Match regression and classification tasks to common loss families
- Distinguish per-example reduction from dataset-level evaluation
- Identify proxy mismatch, class weighting, and numerical-stability concerns
A loss specifies what counts as improvement during training
Training needs a scalar objective whose local changes can be differentiated. The loss compares model outputs with targets or other training signals, and then assigns a penalty.
A lower loss means the model better satisfies that mathematical contract. The contract covers the measured data. It does not automatically mean the product became more useful, fair, or safe.
Satisfying the contract well does not make the outputs mean what they look like they mean. A 2017 ICML paper on calibration put it flatly: “modern neural networks, unlike those from a decade ago, are poorly calibrated”. Its Figure 1 sets the two failures side by side on CIFAR-100. A 5-layer LeNet makes 44.9% error and is nearly calibrated. A 110-layer ResNet makes 30.6% error and is badly over-confident. The more accurate model is the one whose confidence is worth less. The same paper names what drives it: “depth, width, weight decay, and Batch Normalization are important factors influencing calibration”. Cross-entropy rewards putting probability mass on the correct class. It does not promise that an output of 0.9 is right nine times in ten.
The remedy was a separate step, fitted after training: “on most datasets, temperature scaling — a single-parameter variant of Platt Scaling — is surprisingly effective at calibrating predictions.” That repair has a domain of validity, and the domain ends where the training distribution does. A NeurIPS 2019 benchmark measured temperature scaling under corrupted data. Its expected calibration error rises sharply as corruption intensity increases, and under shift nearly every other method beats it on Brier score. The benchmark states the limit in one sentence: “An important observation is that while calibrating on the validation set leads to well-calibrated predictions on the test set, it does not guarantee calibration on shifted data.” A fix fitted on the validation set is another contract. It too covers only the data it was measured on.
The loss is the model’s immediate teacher, not a complete statement of human intent.
Visual
From an example to one batch loss
Most training objectives pass through several distinct decisions. Each one is a place where the number the optimizer sees can stop describing the outcome anyone wanted: the head's output format, the target encoding, the per-element scoring rule, the treatment of masked or reweighted entries, and the aggregation that collapses everything into a single scalar.
- 1
Model output
The head emits logits, numeric values, embeddings, or distribution parameters.
- 2
Target encoding
Labels, values, pairs, masks, or sequences define the training comparison.
- 3
Per-element penalty
A scoring rule measures mismatch for each relevant component.
- 4
Mask and weight
Missing targets, classes, tokens, or examples receive chosen treatment.
- 5
Reduction
Sum, mean, or another aggregation produces the scalar used for gradients.
Comparison
Loss families encode different error geometry
Similar-looking predictions can imply different penalties and therefore different parameter updates.
The robust middle option is not a modern patch on squared error. Peter J. Huber published it in 1964, in The Annals of Mathematical Statistics. scikit-learn implements the idea as H_epsilon(z) = z² for |z| < epsilon and 2·epsilon·|z| − epsilon² otherwise. Epsilon is the exact point where the penalty stops squaring and starts growing linearly — the point past which one outlier can no longer buy unlimited influence over the fit.
That is why the phrase “different derivative near zero or threshold” is worth a number rather than a warning. The scikit-learn user guide gives the setting practitioners should use: “It is advised to set the parameter epsilon to 1.35 to achieve 95% statistical efficiency.” The trade is legible in one line. On clean Gaussian data the Huber fit retains 95% of the efficiency of least squares, and in exchange the tail of the residual distribution stops dictating the answer. Squared error, absolute and Huber losses, and cross-entropy are not three styles of the same statement. They estimate different target statistics, and they hand the optimizer different gradients for the same visible error.
Squared error
Penalizes the square of numeric residuals.
- Smooth and familiar
- Large errors receive strong weight
- Sensitive to outliers
- Fits Gaussian-likelihood assumptions in common settings
Absolute or Huber loss
Reduces the dominance of large numeric residuals.
- More robust to outliers
- Different derivative near zero or threshold
- May optimize a different target statistic
- Useful when noise has heavy tails
Cross-entropy
Scores probability assigned to the observed class or label.
- Pairs naturally with logits
- Strong penalty for confident wrong outputs
- Supports binary or categorical forms
- Does not ensure calibration by itself
Mean and sum are not innocent formatting choices
Summing per-example losses makes gradient magnitude grow with the batch or sequence length. Averaging stabilizes that scale across batch sizes, but it leaves masking and variable-length data to complicate the denominator.
A token-level mean weights long documents more heavily than a document-level mean. State the unit being averaged before comparing experiments.
This is not a classroom caveat, and it is recent. In October 2024 the mean-reduced cross-entropy default in Hugging Face Transformers meant that gradient accumulation was not mathematically equivalent to full-batch training for causal LM. Averaging per-micro-batch means whose non-padding token counts differ is not the same as one mean over all the tokens. Hugging Face published the diagnosis and the repair on 16 October 2024: “To be precise, for gradient accumulation across token-level tasks like causal LM training, the correct loss should be computed by the total loss across all batches in a gradient accumulation step divided by the total number of all non padding tokens in those batches. This is not the same as the average of the per-batch loss values.” Sum the token losses; divide by the total number of non-padding tokens. PyTorch's torchtune landed the identical normalization in PR #1875, “Normalize CE loss by total number of (non-padding) tokens”, merged 25 October 2024. Two of the most-used training stacks shipped the wrong denominator. The mistake was in the reduction, not in the model or the optimizer.
Reduction defines which units of experience receive equal influence.
Example
Class weights and focal emphasis change the training population
Reweighting can address priorities, but it also changes the objective being estimated. The frameworks state the mechanism in their own reference pages rather than leaving it to intuition. PyTorch's BCEWithLogitsLoss works the arithmetic. For a dataset with 100 positive and 300 negative examples, set pos_weight to 300/100 = 3, and the loss then “would act as if the dataset contains 3×100 = 300 positive examples”. Nothing on disk changed. The population the gradient sees did. PyTorch also states the direction of the lever: pos_weight above 1 increases recall, below 1 increases precision. TensorFlow documents the same lever as an explicit trade: “This is like sigmoid_cross_entropy_with_logits() except that pos_weight, allows one to trade off recall and precision by up- or down-weighting the cost of a positive error relative to a negative error.”
- Inverse-frequency weights give rare classes more gradient influence than their raw prevalence — PyTorch's worked case turns 100 positives into an effective 300 by setting pos_weight to 3.
- Cost-sensitive weights encode different penalties for false negatives and false positives; in TensorFlow's weighted cross-entropy, pos_weight enters as a multiplicative coefficient on the positive-label term only.
- Focal-style terms reduce emphasis on already easy examples and concentrate on harder ones.
- Per-token weights can ignore padding or emphasize important spans.
- Example weights may correct a sampling design only when the intended target distribution is known.
Case
Down-weighting easy examples closed the one-stage detector gap
Reweighting is not a marginal knob. One-stage object detectors trailed two-stage ones in accuracy, and the paper that introduced the focal loss, at ICCV 2017, named the reason: “the extreme foreground-background class imbalance encountered during training of dense detectors is the central cause”. Section 3 puts the ratio on the page: “The Focal Loss is designed to address the one-stage object detection scenario in which there is an extreme imbalance between foreground and background classes during training (e.g., 1:1000).” The loss is applied to all of the roughly 100k anchors in every image. The population the gradient averages over is about one useful example per thousand.
The fix reshapes cross-entropy “such that it down-weights the loss assigned to well-classified examples”. At the focusing parameter gamma = 2 that the authors chose, an example already classified at p_t = 0.9 contributes 100× less loss than it would under plain cross-entropy, and one at p_t ≈ 0.968 contributes 1000× less. The easy background is still there. It simply stops setting the agenda.
The payoff was measured on COCO test-dev. RetinaNet with a ResNet-101-FPN backbone reached 39.1 AP at 5 fps, above the 36.2 AP of the best two-stage FPN Faster R-CNN and the 33.2 AP of DSSD513. A 2019 survey in IEEE Access tabulates the same comparison independently. In the authors' own summary, RetinaNet “is able to match the speed of previous one-stage detectors while surpassing the accuracy of all existing state-of-the-art two-stage detectors”. The obstacle they identified was not the architecture. It was which examples dominated the gradient.
Key idea
Stable implementations work with logits
Computing probabilities and then taking logarithms can underflow or produce infinities. Standard libraries combine the transformations with log-sum-exp identities to keep the calculation stable. PyTorch documents this on the page you will import from, saying of BCEWithLogitsLoss that “This version is more numerically stable than using a plain Sigmoid followed by a BCELoss as, by combining the operations into one layer, we take advantage of the log-sum-exp trick for numerical stability.” The fused loss is not a convenience wrapper. The fusion is the numerical method.
Follow the loss interface exactly. Passing probabilities into a logits-based function applies the wrong mathematics even if tensor shapes match, and nothing will raise. TensorFlow states the consequence in the reference page for softmax_cross_entropy_with_logits: “Warning: This op expects unscaled logits, since it performs a softmax on logits internally for efficiency. Do not call this op with the output of softmax, as it will produce incorrect results.” That is a silent correctness bug rather than a shape error. Training proceeds, the curve descends, and the objective being minimized is not the one you named.
Use numerically stable combined losses instead of rebuilding them from naive probability operations.
Analogy
A rubric that scored cost while the goal was need
A model optimizes the quantity it is scored on, and the scored quantity is usually a stand-in for the one people care about. A commercial risk-prediction algorithm affecting millions of patients had that substitution sitting at its centre. It was trained to predict health-care costs as a proxy for health need. Because less is spent on Black patients at equal sickness, the proxy was wrong in a consistent direction. Remedying the resulting bias would have raised the share of Black patients flagged for extra help from 17.7% to 46.5%.
By its own scoring rule, the system was performing. The four researchers who took it apart stated the general lesson in Science on 25 October 2019: “Thus, despite health care cost appearing to be an effective proxy for health by some measures of predictive accuracy, large racial biases arise. We suggest that the choice of convenient, seemingly effective proxies for ground truth can be an important source of algorithmic bias in many contexts.”
The consequence arrived the same day. The New York State Department of Financial Services and Department of Health wrote jointly to UnitedHealth Group's CEO about Optum's Impact Pro, demanding that the company prove the algorithm is not discriminatory or stop using it: “These discriminatory results, whether intentional or not, are unacceptable and are unlawful in New York.” No line of the objective was miswritten. The objective was cost, cost is not need, and the model had no way to learn the difference.
A model cannot optimize a goal that appears nowhere in its feedback.
Steps
Audit the loss before tuning the optimizer
Many training failures are objective failures in disguise.
A change to the objective can pay in one currency and charge in another. Label smoothing has both sides of its ledger measured. It arrived at CVPR 2016 with epsilon = 0.1 over the K = 1000 ImageNet classes, training against a weighted average of the hard targets and the uniform distribution over labels. What that bought is stated plainly: “For ILSVRC 2012, we have found a consistent improvement of about 0.2% absolute both for top-1 error and the top-5 error (cf. Table 3).” Table 3 carries the numbers behind the sentence — top-1 error of 23.1% without smoothing against 22.8% with it, and top-5 error of 6.1%.
A NeurIPS 2019 paper by Hinton and two colleagues returned to the method and confirmed a second benefit, since “in addition to improving generalization, label smoothing improves model calibration”. Then they measured the charge. They found that “if a teacher network is trained with label smoothing, knowledge distillation into a student network is much less effective”. Smoothing “encourages the representations of training examples from the same class to group in tight clusters”, and so loses “information in the logits about resemblances between instances of different classes”. Two tenths of a point of top-1 error bought, and a model that has become a worse teacher. The loss curve reports the purchase. It has no column for the bill.
So audit the objective before the optimizer. Name the behavior you want and the unit it applies to. Inspect the targets for delay, missingness and ambiguity. Check that the output format matches what the loss expects. Recompute the reduction across examples, classes and tokens. Then confirm on held-out data that the lower loss corresponds to better decisions.
1. Name the desired behavior
Describe the real outcome and affected unit.
2. Inspect target quality
Check labels, masks, missingness, delay, and ambiguity.
3. Match output and loss
Verify logits, ranges, units, and distributional assumptions.
4. Recalculate reductions
Confirm weighting across examples, classes, tokens, and batches.
5. Compare external metrics
Test whether lower loss corresponds to better decisions on held-out data.
Key takeaways
- A loss turns outputs and targets into the scalar signal used for gradient-based learning.
- Different losses encode different assumptions about errors, distributions, and target statistics — Huber's 1964 threshold, set at epsilon = 1.35, keeps 95% of least-squares efficiency while capping how far one outlier can pull the fit.
- Reduction choices determine whether examples, tokens, sequences, or classes receive equal influence; Hugging Face and torchtune both corrected the same wrong denominator in October 2024.
- Weighting and focal terms change the effective objective rather than merely “fixing” imbalance: pos_weight = 3 makes 100 positives behave like 300, and gamma = 2 makes a p_t = 0.9 example count 100× less.
- Stable library losses should receive the expected logits or parameters directly, because feeding them probabilities is a silent correctness bug rather than a shape error.
- Loss curves must be connected to held-out metrics and real decisions before they justify a model change. A cost-predicting health algorithm scored well by its own accuracy measure while flagging 17.7% of Black patients for extra help instead of the 46.5% that removing the bias implied.