training

Losses and Objectives

First choose what to estimate. Then choose how the model receives the error.

Published 2026-04-20 · Updated 2026-10-25
On this page

A loss is not just a number to minimize. It defines which prediction is preferred, how errors are weighted, and which gradients reach the model. Two losses can prefer the same population prediction while producing very different training behavior.

Start with the output you need: a numerical estimate, a probability distribution, or a decision boundary. Then distinguish the loss from parameter penalties and implementation details. These distinctions explain why replacing cross-entropy with a bounded score is not a neutral change.

What the objective asks for

The target quantity matters before the optimizer
PredictionCommon objectivePopulation target / behavior
Scalar regressionSquared errorConditional mean
Scalar regressionAbsolute errorConditional median
Class probabilitiesLog score or Brier scoreTrue conditional distribution, with sufficient capacity
Binary decisionsHinge loss with a margin penaltyA decision boundary; not calibrated probabilities by itself

These are population statements. A finite dataset, restricted model family and imperfect optimizer can produce a different result. A low training loss also does not establish good calibration or out-of-distribution performance.

Magnitude, direction and the unit sphere

Before using a norm in an objective, separate magnitude from direction. The Euclidean norm is distance from the origin: ∥x∥2=x⊤x\|x\|_2=\sqrt{x^\top x}. For x = [3,4], the norm is 5, the squared norm is 25, and the normalized vector is [0.6,0.8].

Equal magnitudeL2L1L2 = 1 · L1 = 1, respectively.

L2 level sets are circles in two dimensions. L1 level sets are diamonds. In more dimensions, they become a sphere and a cross-polytope.

Keep direction, change length[0.6,0.8]Original length 5 → unit length 1

The dashed extension shows direction, not the original vector drawn to scale. Normalization discards length; it does not change a nonzero vector’s direction.

Exact conceptual geometry, not measured embedding data. In the first panel, the solid burgundy circle has L2 norm 1. The dashed blue diamond has L1 norm 1. Each plot uses equal horizontal and vertical scale.

An orthogonal transformation R satisfies R⊤R=IR^\top R=I. Therefore ∥Rx∥22=x⊤R⊤Rx=∥x∥22\|Rx\|_2^2=x^\top R^\top Rx=\|x\|_2^2. A rotation or reflection preserves Euclidean length. This symmetry is why spherical geometry fits isotropic Gaussian models. It does not imply that learned embeddings are isotropic.

u=x∥x∥2,u⊤v=cos⁡θfor unit vectors u,vu=\frac{x}{\|x\|_2},\qquad u^\top v=\cos\theta\quad\text{for unit vectors }u,v
The normalization formula requires x ≠ 0. Both vectors must be normalized for their dot product to equal cosine similarity.

The zero vector has no direction. Numerical implementations need a policy. PyTorch uses xmax⁡(∥x∥2,ε)\frac{x}{\max(\|x\|_2,\varepsilon)}: zero stays zero, and vectors with norm below ε are not unit length. Choose the embedding axis explicitly. PyTorch normalization contract ↗.

Unit length alone cannot prevent collapse. If every example maps to the same unit vector, the representation is still collapsed. Whether a self-supervised method normalizes embeddings and how it prevents collapse are separate questions. Self-Supervised Vision Learning →

A strictly convex squared norm is not a strictly convex norm function

Let x = [1,0] and y = [2,0]. The norm of their midpoint is 1.5, equal to the average of their norms. This equality on a positive ray disproves global strict convexity of x↦∥x∥2x\mapsto\|x\|_2.

The Euclidean unit ball has a strictly convex boundary geometry. The squared norm, as a function, is also strictly convex. These are different statements. A unique optimum still requires the actual objective, domain and parameterization to satisfy the relevant conditions.

The next section applies norms to residuals. Later, parameter penalties apply the same geometry to weights. Vectors and Geometry →

L1, L2 and regression

For a vector x, the L2 norm is ∥x∥2=∑ixi2\|x\|_2=\sqrt{\sum_i x_i^2}. Its squared norm is ∥x∥22=∑ixi2\|x\|_2^2=\sum_i x_i^2. For residuals ri=y^i−yir_i=\hat y_i-y_i, mean squared error divides the squared sum by the number of included elements.

MSE⁡=1N∑i=1N(y^i−yi)2MAE⁡=1N∑i=1N∣y^i−yi∣\begin{aligned}\operatorname{MSE}&=\frac1N\sum_{i=1}^N(\hat y_i-y_i)^2\\\operatorname{MAE}&=\frac1N\sum_{i=1}^N|\hat y_i-y_i|\end{aligned}
A sum and a mean differ by a scale factor. This changes gradients and the relative strength of other objective terms.

Squared error penalizes a large residual quadratically. Its derivative is proportional to that residual. Absolute error penalizes it linearly, with a bounded subgradient away from zero. Nondifferentiability at zero does not make L1 optimization inherently unstable.

Why the mean and median appear

Differentiate E[(Y−a)2]\mathbb{E}[(Y-a)^2] with respect to a. The stationary point is a=E[Y]a=\mathbb{E}[Y], provided the second moment is finite. For E[∣Y−a∣]\mathbb{E}[|Y-a|], the subgradient balances probability mass below and above a. Any median achieves that balance.

The squared objective is strictly convex in the scalar prediction a. This does not make a neural network’s objective convex in its parameters. The L2 norm itself is not strictly convex as a function on all vectors: it is linear along a positive ray.

A Gaussian observation model with fixed variance gives a negative log-likelihood proportional to squared error. A Laplace observation model with fixed scale gives absolute error. If the model learns the Gaussian variance, its log-likelihood must also include the log-variance term; it cannot simply inflate variance to erase residuals.

−log⁡p(y∣μ,σ)=(y−μ)22σ2+log⁡σ+12log⁡(2π),σ>0-\log p(y\mid\mu,\sigma)=\frac{(y-\mu)^2}{2\sigma^2}+\log\sigma+\tfrac12\log(2\pi),\qquad\sigma>0
The constant is independent of μ and σ. Discarding log σ is invalid when σ is learned.

Four ordinary observations, one movable observation

Fit a single constant to [0, 0, 0, 0, a]. Squared error selects the mean. Absolute error selects the median.

mean 2.00median 012
MSE at mean 16.00MSE at median 20.00MAE at mean 3.20MAE at median 2.00

Exact synthetic dataset, not a robustness benchmark. Moving the outlier changes the fitted mean even though four points stay fixed.

Cross-entropy from logits

Let p be the target distribution and z the model logits. Softmax gives qi=ezi∑jezjq_i=\frac{e^{z_i}}{\sum_j e^{z_j}}. Cross-entropy evaluates the predicted probabilities under the target.

L(p,q)=−∑ipilog⁡qi=log⁡∑jezj−∑ipizi∂L∂zi=qi−pi\begin{aligned}L(p,q)&=-\sum_i p_i\log q_i\\&=\log\sum_j e^{z_j}-\sum_i p_i z_i\\\frac{\partial L}{\partial z_i}&=q_i-p_i\end{aligned}
Natural logarithms give nats. The logit expression assumes ∑ipi=1\sum_i p_i=1. Evaluate log-sum-exp stably.

For a hard label y, p is one-hot and L=−log⁡qyL=-\log q_y. In a dataset, that observed label is a sample from a conditional distribution. The expected score over repeated observations is minimized by the underlying distribution, not necessarily a one-hot prediction.

Cross-entropy equals H(p)+DKL(p∥q)H(p)+D_{\mathrm{KL}}(p\|q). The first term is fixed when the target is fixed. This is why forward teacher-to-student KL and teacher cross-entropy have identical student gradients at the same temperature. Reverse KL is a different objective. See Information Theory and Compression → for the coding derivation.

Use a fused logits-based loss. Computing softmax, then taking log of a rounded probability, can underflow. Finite forward values still do not guarantee accurate gradients; the next section separates those requirements. Label smoothing changes p itself. Temperature changes q and gradient scaling. Treat both as objective choices, not harmless numerical fixes.

Avoiding overflow is not enough

Subtracting the largest logit prevents exponential overflow. It does not protect every small quantity used by the backward pass. A model can have finite logits and loss while receiving an inaccurate gradient. Barron, Gnanapragasam and Tschannen (2026) examine this failure in A Fix for Softmax and Cross-Entropy ↗.

Why a correct confident prediction can lose its gradient

Consider a hard target t that already has the largest logit. Combine all other classes into one residual mass r. Define the margin against their log-sum-exp, not only against the runner-up:

m=zt−log⁡∑j≠tezj,r=e−m=∑j≠tezj−ztm=z_t-\log\sum_{j\ne t}e^{z_j},\qquad r=e^{-m}=\sum_{j\ne t}e^{z_j-z_t}
Finite logits, at least two classes and a valid hard target. Larger m means greater confidence in the correct class.

The exact target probability is qt=1/(1+r)q_t=1/(1+r). When r is small enough, floating-point addition rounds 1+r to 1. A standard backward path can then evaluate the target gradient as 1−1=0. The other gradients still have small positive numerators. They need not vanish at the same point.

gt=qt−1=−r1+rgj=ezj−zt1+r,j≠t∑igi=0\begin{aligned}g_t&=q_t-1=-\frac{r}{1+r}\\g_j&=\frac{e^{z_j-z_t}}{1+r},\qquad j\ne t\\\sum_i g_i&=0\end{aligned}
These are exact-arithmetic identities. A rounded target gradient of zero with positive non-target entries violates the zero-sum identity implied by invariance to a common logit shift.

The paper calls this softmax collapse. Its approximate round-to-nearest cliffs are m≈5.5 in BF16, 16.6 in FP32 and 36.7 in FP64. Actual kernels may upcast intermediate operations; record that arithmetic contract instead of inferring it from model-weight dtype.

Follow a correction through the computation

  1. 1Keep the small correction
  2. 2Add it to one
  3. 3Inspect the gradient
  4. 4Keep the correction separate
Represent the correctionr = 1.5230e-8
Standard scalar pathg = [0, 7.6150e-9, 7.6150e-9]Gradient sum: 1.5230e-8Loss: 0 nats
Rewritten scalar pathg = [-1.5230e-8, 7.6150e-9, 7.6150e-9]Gradient sum: 0Loss: 1.5230e-8 nats

Step 1 of 4. The target is the largest logit. The two other classes contribute a small positive total r. Their individual gradients can still be represented.

FP32; margin m=18.00. Each non-target class gets half the residual mass. Approximate cliff: m=16.64. Scalar intermediate values are rounded to the selected format; gradients are added in browser double precision for the diagnostic. This is a controlled arithmetic example, not a JAX/PyTorch kernel or measured training curve.

Rewrite the computation, not the objective

Keep the hard-target term out of the exponential sum and apply a stable softplus to the log-sum of the remaining terms. This is still ordinary cross-entropy. Unlike replacing softmax with StableMax, it does not introduce a different prediction map.

L=softplus⁡ ⁣(log⁡∑j≠tezj−zt)=log⁡(1+r)gt=−∑j≠tgj\begin{aligned}L&=\operatorname{softplus}\!\left(\log\sum_{j\ne t}e^{z_j-z_t}\right)=\log(1+r)\\g_t&=-\sum_{j\ne t}g_j\end{aligned}
Use a numerically stable softplus/log1p implementation. Keeping the dependence on zₜ through the non-target differences makes autodiff recover its small negative gradient without subtracting one from a rounded probability.

For the paper's FP32 example z=[9,−9,−9], t=0, its tested standard JAX/Optax path returns zero loss and zero target gradient. The rewritten path returns loss ≈3.046×10⁻⁸ and gradient ≈[−3.046×10⁻⁸,1.523×10⁻⁸,1.523×10⁻⁸]. These are reported implementation results, distinct from the scalar demonstration above.

A small hard-target implementation sketch
# PyTorch sketch; z: [..., classes], t: [...] valid integer IDs.
# Require finite logits and at least two classes. No reduction here.
def hard_target_ce(z, t):
    z_t = z.gather(-1, t[..., None])
    target = F.one_hot(t, z.shape[-1]).bool()
    others = (z - z_t).masked_fill(target, -torch.inf)
    return F.softplus(torch.logsumexp(others, dim=-1))

This pedagogical form allocates a mask; it is not a benchmarked fused-kernel replacement. Apply the note's existing token masks, ignored-label policy and global sum/count reduction. Check both forward values and autodiff gradients in the actual framework, compiler and dtype. A familiar-looking API or a finite scalar loss is not enough.

For finite normal logits, useful checks include a high-precision reference, common-shift invariance and a near-zero sum of logit gradients. Inspect the target gradient separately. A uniform zero-sum projection is not the same as reconstructing the missing target derivative; it redistributes the error across classes.

The evidence concerns small modular-arithmetic grokking tasks and controlled distillation experiments, not a demonstrated large-LLM speedup. The paper's FP32 modular-addition comparison reports 94.3±5.4% versus 100±0% test accuracy across five seeds, with AdamW, weight decay 1 and ε=10⁻⁸. Do not generalize that gain to another training recipe.

A different error appears when teacher and student already agree: see distillation near an exact match. For the optimizer consequence, see Slingshot and precision cliffs.

Hard labels, empirical averages and teachers

A hard label is one observation, not the complete conditional distribution. Fix an input x, draw y from p(·|x), and average its loss:

Ey∼p(⋅∣x)[−log⁡q(y∣x)]=−∑ip(i∣x)log⁡q(i∣x)\mathbb{E}_{y\sim p(\cdot\mid x)}[-\log q(y\mid x)]=-\sum_i p(i\mid x)\log q(i\mid x)
A dataset average estimates this expectation under its sampling distribution. It does not reveal the true conditional probabilities from a single label.

For eight illustrative observations with class counts [3,2,3], the empirical target is [3/8,2/8,3/8]. Averaging eight one-hot log losses equals cross-entropy against that empirical distribution. It need not equal the population risk.

A teacher supplies a soft target directly. Its probabilities express relative plausibility beyond the observed hard label. For a fixed teacher, forward KL subtracts only the teacher entropy, so it has the same student gradients at the same temperature. Distillation →

Changing from natural logs to base-two logs multiplies loss and gradients by 1/ln 2. The optimum stays the same, but the new scale can interact with learning rates and gradient clipping.

The coding interpretation and the exact 2.625 = 1.75 + 0.875 bit example have one owner: Information Theory, cross-entropy and KL →. The implementation section below connects sequence likelihood to masked token loss.

Binary and multilabel targets

A Bernoulli target y ∈ [0,1] has a single positive-class probability q = sigmoid(z). Its binary cross-entropy is the two-outcome log score.

BCE⁡(y,q)=−ylog⁡q−(1−y)log⁡(1−q)BCEWithLogits⁡(y,z)=max⁡(z,0)−yz+log⁡(1+e−∣z∣)\begin{aligned}\operatorname{BCE}(y,q)&=-y\log q-(1-y)\log(1-q)\\\operatorname{BCEWithLogits}(y,z)&=\max(z,0)-yz+\log(1+e^{-|z|})\end{aligned}
The stable expression avoids overflow in exp(z). The derivative is sigmoid(z) − y.

For a hard positive target, −log q diverges logarithmically as q approaches zero. It does not grow exponentially in 1/q. The derivative with respect to q diverges, but the sigmoid-composed logit derivative approaches −1.

For finite logits and hard targets, the loss approaches zero without reaching it. With a soft target, its minimum is the target’s Bernoulli entropy. This is a useful reminder that a correct distribution need not produce zero log loss.

For multilabel tasks, apply one Bernoulli loss per label. This estimates marginal label probabilities. The use of separate losses does not prove that the real labels are independent. Positive-class weights alter the optimal probability under the weighted objective, so calibration needs separate evaluation.

PyTorch: stable BCE with logits ↗

Weighting, calibration and numerical limits

Binary classification uses one Bernoulli output. Multilabel classification uses one per label; single-label multiclass prediction instead uses a normalized categorical distribution. A batch mean averages included elements, not necessarily one loss per example.

Giving positive examples more weight changes the population optimum. Let p be the true positive probability at a fixed input and w > 0 multiply only the positive term. The expected weighted loss is:

R(q)=−wplog⁡q−(1−p)log⁡(1−q)q∗=wpwp+1−p\begin{aligned}R(q)&=-wp\log q-(1-p)\log(1-q)\\q^*&=\frac{wp}{wp+1-p}\end{aligned}
Setting −wpq+1−p1−q=0-\frac{wp}{q}+\frac{1-p}{1-q}=0 gives q*. This is the optimum over unconstrained Bernoulli probabilities, not a guarantee for a fitted network.

Weight the examples, move the learned probability

Hold true p = 0.20 fixed. Change only the positive-class weight. These are analytical optima, not training measurements.

True probability p = 20%

Weighted optimum q* = 20.00%

With w = 1, the proper Bernoulli log score is minimized at the true probability.

For p = 0.20 and w = 4, q* = 0.50. The new output is not calibrated to the original p. At the population optimum, thresholding q* at 0.5 corresponds to thresholding p at 1w+1\frac{1}{w+1}. A larger positive weight lowers that threshold. Actual precision and recall still depend on the fitted model, data and decision rule.

Multiplying every element by one common positive constant only rescales the risk; it does not produce this class-specific shift. PyTorch distinguishes element weights from positive-class weights. Use the intended broadcasting shape and an explicit reduction. BCEWithLogitsLoss contract ↗.

Keep the loss finite without clipping away the error

When q rounds to zero, −log q is infinite. Clipping q to ε caps that penalty. Differentiating through a hard clip also gives zero gradient outside the allowed interval. This changes the training objective; it is not equivalent to stable evaluation from logits.

Hard positive target y = 1; natural logs
InputStable logits BCEGradient with respect to z
z = 0log 2 ≈ 0.693−0.5
z = −1000Approximately 1000Approximately −1
z = +1000Approximately 0Approximately 0

A wrong extreme logit can still receive a corrective gradient. The logarithm diverges as q approaches zero, while the sigmoid-composed logit gradient stays bounded. Do not describe the probability-space penalty as exponential.

The same score inside an adversarial game

The original GAN discriminator assigns real samples target 1 and generated samples target 0. It maximizes log D(real) + log(1−D(fake)), equivalent to minimizing the corresponding BCE. The minimax generator instead minimizes log(1−D(fake)).

The paper also proposes maximizing log D(fake), or minimizing −log D(fake), to reduce early saturation. These generator objectives are not interchangeable labels for ordinary supervised BCE training. Generative Adversarial Nets, §3 ↗.

Proper scores and Bayes risk

A score S(q,i) evaluates a proposed distribution q when outcome i occurs. Its population risk under p is L(p,q)=∑ipiS(q,i)L(p,q)=\sum_i p_iS(q,i). A proper score makes q = p a minimizer. A strictly proper score makes it the unique minimizer over distributions.

L(p,p)≤L(p,q),HS(p)=L(p,p)L(p,p)\le L(p,q),\qquad H_S(p)=L(p,p)
Hₛ is the score’s Bayes risk. It need not be Shannon entropy.

The log score is strictly proper. So is the full multiclass Brier score S(q,i)=∑j(qj−1[j=i])2S(q,i)=\sum_j(q_j-\mathbf{1}[j=i])^2. Its Bayes risk is 1−∑jpj21-\sum_j p_j^2.

LBrier(p,q)=1−∥p∥22+∥q−p∥22L_{\mathrm{Brier}}(p,q)=1-\|p\|_2^2+\|q-p\|_2^2
The nonnegative final term proves strict propriety. The score for one observation lies between 0 and 2 under this full-vector convention.
The tangent-plane construction

A differentiable concave Bayes risk H defines a proper population risk through its supporting tangent plane:

L(p,q)=H(q)+(p−q)⊤∇H(q)S(q,i)=H(q)+(ei−q)⊤∇H(q)\begin{aligned}L(p,q)&=H(q)+(p-q)^\top\nabla H(q)\\S(q,i)&=H(q)+(e_i-q)^\top\nabla H(q)\end{aligned}
Concavity places this tangent at or above H(p). Strict concavity gives uniqueness under the corresponding conditions. Boundary points require limits or supporting subgradients.

Shannon H gives the log score. Quadratic H gives Brier. This is why more than one proper score exists. The log score has a special locality property: the observed score depends only on qᵢ.

For alphabets with at least three outcomes, standard regularity conditions severely restrict strictly proper local scores to the log-score form. The binary case has exceptions. Do not turn this qualified result into “cross-entropy is the only proper loss.”

Properness concerns the expected score over probability distributions. It does not guarantee that gradient descent on a deep network finds those probabilities.

The Bayes risk is concave because it is the pointwise minimum of risks that are linear in the target distribution. At a nondifferentiable point, use a supporting supergradient of the concave risk. A subgradient instead belongs to its negative convex regularizer.

Tsallis, spherical and some Rényi-related constructions give other scoring families. Check the exact sign and parameter range. A family name alone does not establish strict propriety, robustness or good finite-data behavior.

Why a local proper score becomes logarithmic

The log score is not the only proper score. A narrower requirement makes it special: the observed loss uses only the probability assigned to the outcome that occurred.

Derive the logarithm under the local-loss assumptions

Use a finite alphabet with at least three outcomes. Assume one differentiable function F gives S(q,i)=F(qi)S(q,i)=F(q_i). Require q = p to minimize ∑ipiF(qi)\sum_i p_iF(q_i) for every interior distribution p, subject to ∑iqi=1\sum_i q_i=1.

q=p⟹piF′(pi)+λ=0for each iq=p\quad\Longrightarrow\quad p_iF'(p_i)+\lambda=0\quad\text{for each }i
The same Lagrange multiplier λ applies to every component of this constrained optimization.

Define g(t) = tF′(t). Any two probabilities that coexist in an interior distribution must have the same g value. A third positive probability can connect values whose sum exceeds one. Thus g is constant on (0,1).

F′(t)=−kt⟹F(t)=−klog⁡t+CF'(t)=-\frac{k}{t}\quad\Longrightarrow\quad F(t)=-k\log t+C
Strict propriety requires k > 0. Zero k gives a constant score; negative k rewards moving away from the truthful distribution.

This derivation assumes the same F for each outcome. The more general local-score characterization permits an outcome-dependent additive constant. Such a constant does not change the minimizing q. Dawid, Lauritzen and Parry, §3.2 ↗.

With two outcomes, the other probability is already determined by the observed probability. Full-vector Brier becomes F(qi)=2(1−qi)2F(q_i)=2(1-q_i)^2. It is a strictly proper, non-logarithmic binary counterexample. With three outcomes, the unobserved mass can be split in different ways, so multiclass Brier is not local in this sense.

Locality changes when the alphabet changes
Observed A, q(A)=0.2Unobserved probabilitiesFull Brier for A
Three outcomes, forecast 10.4, 0.40.64 + 0.16 + 0.16 = 0.96
Three outcomes, forecast 20.7, 0.10.64 + 0.49 + 0.01 = 1.14
Two outcomes0.8, fixed by normalization0.64 + 0.64 = 1.28

The first two forecasts give the same log loss, −log 0.2. Their Brier scores differ. The observed-class probability alone is not enough to calculate multiclass Brier.

Same optimum, different gradients

A bounded loss can reduce the influence of extreme errors. It can also weaken a needed corrective signal. For Brier composed with softmax, the gradient contains the softmax Jacobian J=diag⁡(q)−qq⊤J=\operatorname{diag}(q)-qq^\top.

∇zLCE=q−ey∇zLBrier=2J(q−ey),J=diag⁡(q)−qq⊤\begin{aligned}\nabla_z L_{\mathrm{CE}}&=q-e_y\\\nabla_z L_{\mathrm{Brier}}&=2J(q-e_y),\quad J=\operatorname{diag}(q)-qq^\top\end{aligned}
Near a nearly one-hot softmax output, J is small. A confident wrong prediction can receive a small Brier logit gradient.

Why a bounded score can learn slowly from a confident error

Target class A. Vary q(A), produced by two-class softmax. Differentiate with respect to A’s logit while the other logit stays fixed.

Log score · natural logarithm
Loss 4.605Gradient −0.990
Full two-class Brier score
Loss 1.960Gradient −0.039

A small negative gradient raises A’s logit slowly. Log loss retains a large corrective gradient here.

At q(A) = 0.001 and target A, log loss has derivative −0.999. Full two-class Brier has derivative about −0.003992. Their loss scales differ, so compare more than raw gradient magnitude. The extra saturation factor remains a structural distinction.

This explains a common trap: selecting a score from its probability-space properties while ignoring the output map. The next construction chooses the map and loss together.

Fenchel–Young: pair the map with the loss

Choose a concave entropy-like function H on the simplex. Define a regularized prediction map by balancing a logit score against H. Define Φ as the maximum value of that optimization.

Φ(z)=max⁡q∈Δ{q⊤z+H(q)}q(z)∈arg max⁡q∈Δ{q⊤z+H(q)}LFY(z,p)=Φ(z)−p⊤z−H(p)\begin{aligned}\Phi(z)&=\max_{q\in\Delta}\{q^\top z+H(q)\}\\q(z)&\in\operatorname*{arg\,max}_{q\in\Delta}\{q^\top z+H(q)\}\\L_{\mathrm{FY}}(z,p)&=\Phi(z)-p^\top z-H(p)\end{aligned}
Equivalently use the convex regularizer Ω=−H\Omega=-H and its conjugate Ω∗\Omega^*. If the prediction is unique, ∇Φ(z)=q(z)\nabla\Phi(z)=q(z).

The matched loss has gradient q(z) − p when differentiable. This is not the same as choosing an arbitrary score and composing it with softmax. For a one-hot target and H(eᵧ) = 0, the loss reduces to Φ(z) − zᵧ.

Changing the regularizer changes the output map
ChoicePrediction mapConsequence
Shannon entropySoftmaxPositive probabilities; matched log loss
Scaled quadratic/Gini entropySparsemaxProjection onto the simplex; exact zeros
Tsallis familyα-entmaxInterpolates softmax and sparsemax under the standard parameterization

At α = 1, the usual limiting map is softmax. At α = 2, it is sparsemax. α = 1.5 is a useful intermediate case. Constants in the entropy definition affect scale and temperature; do not mix formulas from incompatible conventions.

Sparse predictions can reduce active output support. Exact zero probability creates infinite log loss for a missed target, however. Sampling semantics, rare-token behavior, vocabulary kernels and evaluation all need attention. A sparse-output training loss does not automatically improve throughput or remain comparable to standard perplexity.

Exact zeros make the active support explicit and can reduce the influence of implausible classes. They do not identify noisy labels: rare language tokens can be correct. Forward KL is infinite if the teacher assigns mass where the student assigns zero. Reverse KL has the opposite support requirement.

Sparse outputs also change sampling and vocabulary-wide threshold calculations. A sparse probability vector does not by itself reduce the cost of computing all vocabulary logits. Evaluate fused kernels, memory and distillation under the chosen map rather than assuming softmax implementations transfer unchanged.

Fenchel–Young losses ↗ · Sparsemax ↗ · Sparse sequence-to-sequence models ↗

Margins and support vector machines

Probability estimation is not the only goal. A linear SVM learns a separating function f(x) = w·x + b for labels y ∈ {−1,+1}. Scaling w and b leaves the decision boundary unchanged, so canonical constraints fix their scale.

min⁡w,b12∥w∥22subject to yif(xi)≥1  for all iMargin width=2∥w∥2\begin{aligned}&\min_{w,b}\tfrac12\|w\|_2^2\quad\text{subject to }y_i f(x_i)\ge1\;\text{for all }i\\&\text{Margin width}=\frac2{\|w\|_2}\end{aligned}
The two margin planes are f(x)=−1 and f(x)=+1. Distance to f(x)=0 is ∣f(x)∣∥w∥2\frac{|f(x)|}{\|w\|_2}.

When the data are not separable, a soft-margin objective allows violations. Eliminating its nonnegative slack variables gives hinge loss.

min⁡w,b{12∥w∥22+C∑imax⁡(0,1−yif(xi))}\min_{w,b}\left\{\tfrac12\|w\|_2^2+C\sum_i\max(0,1-y_i f(x_i))\right\}
Large C emphasizes violations. Small C relaxes them relative to the weight penalty. Feature scale affects the resulting margin.

Support vectors are examples with active constraints and nonzero dual weights. In the hard-margin case they lie on the margin. In the soft-margin case they can lie inside it or be misclassified. They are not always exactly on its boundary.

The linear convex formulation differs from a neural model with a hinge objective. Its squared weight penalty can give uniqueness in w, but this does not automatically give uniqueness in every parameter, such as b. A large margin is useful under suitable assumptions; it is not a universal guarantee of generalization.

f=−1f=0f=+1Full margin width = 2
Synthetic geometry, not a fitted benchmark. Circles have label −1; squares have label +1. With w=(1,0), b=0, the nearest examples at x=±1 touch the canonical margin. Each boundary is one unit from the decision plane.

Prediction uses the sign of f. At f=0, choose an explicit tie policy. For nonzero w, perpendicular distance is ∣f(x)∣∥w∥2\frac{|f(x)|}{\|w\|_2}. Both margin planes are parallel, so their separation is the sum of their distances from the central plane.

min⁡w,b,ξ≥012∥w∥22+C∑iξisubject toyif(xi)≥1−ξiξimin=max⁡(0,1−yif(xi))(C>0)\begin{aligned}\min_{w,b,\xi\ge0}&\quad\tfrac12\|w\|_2^2+C\sum_i\xi_i\\\text{subject to}&\quad y_if(x_i)\ge1-\xi_i\\\xi_i^{\rm min}&=\max(0,1-y_if(x_i))\quad(C>0)\end{aligned}
Minimal nonnegative slack gives the hinge formulation above. Slack measures margin violation, not geometric distance in input units.
Signed margin identifies three different cases
y f(x)Hinge / minimal slackInterpretation
≥10Correct, outside or on the margin
Between 0 and 11−y f(x)Correct side, inside the margin
<0>1Misclassified

Structural risk minimization balances fit with model complexity. In this formulation, C controls violations relative to squared weight magnitude. Margin-based robustness depends on feature scale, perturbation norm and data assumptions. Convexity alone does not prove uniqueness in every parameter. SVM formulation and implementation conventions ↗.

Loss, normalization and regularization

An L2 residual loss evaluates prediction error. An L2 parameter penalty evaluates the size of model parameters. L2 normalization replaces a nonzero vector with x∥x∥2\frac{x}{\|x\|_2}. They share a norm but perform different operations.

Three distinct uses of the same norm
OperationWhat changes?What it does not establish
Squared residual lossPreferred prediction and error weightingConvexity in neural parameters
λ∥θ∥22\lambda\|\theta\|_2^2 penaltyTradeoff between fit and parameter magnitudeEquivalence to every optimizer’s weight decay
x∥x∥2\frac{x}{\|x\|_2} normalizationVector length; dot products become cosine similarities if both sides normalizedPrevention of collapse: all unit vectors can still become identical

Why ridge stabilizes a linear solve

Assume the features and targets are centered, or handle an unpenalized intercept separately. Minimize ∥Xw−y∥22+λ∥w∥22\|Xw-y\|_2^2+\lambda\|w\|_2^2. Setting its gradient to zero gives (X⊤X+λI)w=X⊤y(X^\top X+\lambda I)w=X^\top y. Use a linear solver rather than explicitly forming an inverse.

v⊤(X⊤X+λI)v=∥Xv∥22+λ∥v∥22>0,v≠0,  λ>0v^\top(X^\top X+\lambda I)v=\|Xv\|_2^2+\lambda\|v\|_2^2>0,\qquad v\ne0,\;\lambda>0
A positive penalty makes the system positive definite even when X has dependent columns. This establishes a unique weight solution in this linear setting.

X⊤XX^\top X is the feature Gram matrix. It is proportional to an empirical covariance only after the appropriate centering and scaling. Ridge does not inherently require an inverse covariance matrix. A Gaussian residual model with covariance Σ instead uses r⊤Σ−1rr^\top\Sigma^{-1}r; Σ−1\Sigma^{-1} is the precision matrix. These are distinct uses of a quadratic form.

Penalty geometry is not residual robustness
Weight penaltyEffectCondition or limit
λ∥w∥1\lambda\|w\|_1Can select exactly zero coordinatesLasso-type objective; scaling and correlated features affect selection
λ∥w∥22\lambda\|w\|_2^2Shrinks weights without a corner at zeroDoes not enforce sparsity; zeros can still occur
L1 residual lossTargets a conditional medianNot the same operation as sparse weight selection

L1 and L2 are not inverse operations. A smooth squared residual is also not universally more stable to optimize than an absolute residual. Compare the model, solver and data, not just the derivative at zero. Ridge objective and solver conventions ↗.

Negative log-likelihood is not the reciprocal of likelihood. Self-supervised learning needs additional mechanisms to avoid representational collapse. Normalization alone is insufficient. For MoE, an auxiliary balance loss is a separate routing objective; changing it changes how capacity is used. Mixture of Experts →

Language-model implementation

A causal language model predicts the next token, not the current token. Shift logits and labels consistently. Padding, prompt-only regions and packed-sequence boundaries need an explicit supervision mask.

# logits: [batch, time, vocabulary]; tokens: [batch, time]
pred = logits[:, :-1].float()
target = tokens[:, 1:]
valid = supervision[:, 1:].bool()
per_token = F.cross_entropy(
    pred.transpose(1, 2), target, reduction="none")
loss = per_token[valid].mean()  # reject/skip an empty valid set

If ignored labels contain −100, use the loss’s ignore-index handling and build a matching valid mask. For operations that gather target entries manually, replace ignored indices before gathering. Do not let −100 select an unintended vocabulary entry.

# Full-vector Brier without allocating a one-hot target array.
q = pred.softmax(-1)
safe_target = target.masked_fill(~valid, 0)
q_true = q.gather(-1, safe_target[..., None]).squeeze(-1)
per_token = q.square().sum(-1) - 2 * q_true + 1
loss = per_token[valid].mean()  # same empty-set policy
Callable Brier reference: per-token, sum or mean
import torch

def brier_from_logits(logits, targets, reduction="mean"):
    q = logits.softmax(dim=-1)
    q_true = q.gather(-1, targets.unsqueeze(-1)).squeeze(-1)
    per_token = q.square().sum(-1) - 2 * q_true + 1
    if reduction == "none":
        return per_token
    if reduction == "sum":
        return per_token.sum()
    if reduction == "mean":
        return per_token.mean()
    raise ValueError(f"Unknown reduction: {reduction}")

Logits have shape [batch,time,vocabulary]; targets have shape [batch,time] and valid integer vocabulary IDs. This function preserves the original three reduction modes. It avoids one-hot allocation, not full softmax storage or vocabulary summation. For causal batches, shift first and use safe temporary IDs for ignored labels, as above. The caller must reject or skip an empty supervision mask.

A token mean gives longer examples more weight. A mean of sequence means weights each sequence equally. In distributed training, averaging rank-local means is incorrect for a global token mean when valid counts differ. Reduce sums and counts consistently.

For a mean natural-log loss L, perplexity is exp(L). Bits per token are L/ln 2. Comparing perplexity across different tokenizers or evaluation distributions is not a controlled comparison. Track the precise mask, denominator and corpus.

Changing the loss is an experiment

A positive mixture of proper scores remains proper over distributions. This does not make a CE–Brier mixture or a late-training switch automatically beneficial. The gradient scale, saturation behavior and optimizer state still change.

Treat such changes as hypotheses. Compare held-out log loss, calibration, rare-token quality, corruption sensitivity and throughput. Separate clean-data and noisy-data effects. Keep reductions, batch composition and compute budgets controlled.

Measure every term separately when adding regularization. A convenient total loss can conceal a routing penalty dominating language modeling, or a changing token denominator. Inspect gradients as well as scalar values.

Sλ=(1−λ)Slog⁡+λSBrier,0≤λ≤1S_\lambda=(1-\lambda)S_{\log}+\lambda S_{\rm Brier},\qquad0\le\lambda\le1
A nonnegative mixture is proper; it remains strictly proper when a strictly proper component has positive weight. This population fact does not establish a useful training schedule.

The motivating blog proposes strong CE correction early and Brier later to reduce suspected-noise influence. That is an unverified language-model research direction. Compare equal-token/equal-compute CE, Brier-plus-softmax, a matched Fenchel–Young map, fixed mixtures and late switches. Separate deliberate corruption from genuinely ambiguous clean language. Measure calibration, rare-token accuracy, downstream quality, memory, throughput and numerical stability at the real vocabulary size.

Sources and connected notes

Gneiting and Raftery: proper scoring rules ↗ · Source discussion of scoring rules and output maps ↗