Cross-entropy: loss, likelihood and betting
Define cross-entropy as the expected code length under q and relate it to maximum likelihood and forward KL. Derive the stable softmax cross-entropy loss and its gradient, then interpret log loss as a strictly proper score and through the KL growth difference in Kelly betting.
After this lesson you can
- Prove H(p,q) = H(p) + D(p‖q) and that minimizing empirical cross-entropy gives the maximum-likelihood estimate.
- Derive the gradients of softmax cross-entropy and binary cross-entropy with logits.
- Implement stable cross-entropy with log-sum-exp and check it against PyTorch.
- Prove that the logarithmic score is strictly proper and connect it to calibration.
- Derive the horse-race Kelly strategy, show that growth is D(p‖r) − D(p‖b), and show that side information is worth I(X;Y).
- Analyze label smoothing as cross-entropy with a mixture target.
Before you start
Motivation: the loss that trains almost everything
An image classifier receives three photos and assigns their correct classes probabilities , and . How wrong was it? The answer used by almost all modern AI is the mean of : , and , with mean . Notice the penalty’s shape: going from to costs , but going from to costs , and reaching costs infinity. That loss is cross entropy, and it trains image classifiers, language models, policies that imitate an expert, and much of what you will see in later modules. A language model with a vocabulary of tokens (GPT-2’s) that initially distributes probability nearly uniformly has initial loss nats: if training starts with a very different number, something is miswired before the model has learned anything.
Why the logarithm? The previous lesson gave three reasons that become theorems here:
- It is code length. is the bits required to describe with a code fitted to model (surprise). Averaged over the data, it is what one pays to encode with the wrong model, and the excess over entropy is Kullback–Leibler divergence.
- It is likelihood. The logarithm converts a product of probabilities into a sum, and training by maximum likelihood is exactly minimizing this loss.
- It is the only honest way to score a prediction. If paid according to , your best move is to report the probability you truly believe. In another context, betting on a horse race, wealth grows at a rate given by a difference of divergences.
This lesson starts with the definition and decomposition , proves minimizing loss is equivalent to maximum likelihood and minimizing forward KL (and the implications when the model cannot represent the data), derives softmax cross-entropy loss and its gradient, explains why it requires careful computation, studies logarithmic scoring and calibration, covers soft targets (label smoothing and distillation), and ends with Kelly betting. Conventions: in training sections is the natural logarithm and losses are in nats, as in PyTorch; coding and betting use bits. Convert nats to bits by multiplying by ; all identities hold in any base.
Definition and decomposition
Let be distributions over a finite alphabet (lesson 11 extends this to continuous variables). Think of as the data distribution and as the model.
Proof
If (that is, whenever ), sum over the support of :
If an exists with , both sides equal . The inequality and equality case are Gibbs’ inequality: , with equality only if .
∎Two immediate interpretations. First: the floor does not depend on , so minimizing over is equivalent to minimizing ; the model controls excess, and minimum possible cross entropy is not but , irreducible data noise. Second: it is a code length. With lengths , which satisfy Kraft’s inequality with equality, mean bits per symbol of a source is (integer lengths cost less than one extra bit, cost of coding with the wrong model).
The first figure lets you explore this identity. A four-class classifier produces logits , and its prediction is (defined rigorously below). Drag the logits and loss is divided into a stacked bar.
Three things the figure shows and the rest of the lesson proves.
- The floor exists. With an ambiguous target, such as the -bit source or two equally likely classes, no logit reduces loss below . If training loss stalls at on a balanced two-class task, the model predicts the same as an indifferent one: either data contain no signal (floor ) or training is failing, and loss alone cannot distinguish them.
- With a hard label the floor is zero, reached only at infinity. Target (all mass on one class) has , so vanishes only if , i.e. with the correct logit infinitely above the others. However well training goes, gradient descent keeps pushing logits: with four classes and step , margin is after 10 steps, after 100 and after 1000, growing like while loss decreases like . This is the origin of overconfidence in networks trained with hard labels.
- A smoothed target has a finite optimum. With and the target is , its entropy is nats, and the optimum has margin . This is label smoothing, studied below.
Likelihood, cross entropy and forward KL
Data are , independent and identically distributed according to unknown distribution , and the model is a family . Let be the empirical distribution.
Proof
Group terms by value: . The second equality is the decomposition theorem applied to . Since is strictly increasing, maximizing the product is equivalent to minimizing the average of its negated logarithms, and does not depend on .
∎This is what happens in a classifier, where the model is conditional, . Training loss is , the mean cross entropy between each example’s label, viewed as a concentrated distribution , and the model prediction. If every input appears once, and floor is : the first figure’s “hard label”.
When the model cannot represent the data
If for some in the family, the strong law of large numbers gives for each and, under usual regularity conditions (identifiable parameter and uniform convergence in ), the estimator converges to true , where divergence is . But a real model almost never contains the data. Maximum likelihood still converges, to a well-defined quantity: the pseudo-true parameter , the “projection” of onto the family in forward-KL terms. The projection is a question of geometry, and for exponential families has a closed form.
Proof
. Taking and differentiating with respect to gives , and for an exponential family (the derivative of the log-partition is the statistic’s mean). Since is convex, is convex in and stationary points are global minima.
∎For the Gaussian family, : the best Gaussian in cross-entropy terms has the data’s mean and variance, whatever their shape (finite variance suffices). If data are a mixture of two separated bells, the result is a wide bell centered between them. The other direction, , encountered in variational inference, asks the opposite: that have no mass where has none.
With initial values (, two equally weighted modes with standard deviation ), maximum-likelihood fit is and , with nats and . Reverse KL stays with one mode (, ) and has : covering one of two equal modes costs . But for that exceeds nats (on the interactive’s 241-cell grid; in the continuum it grows without bound with separation), because the other mode is uncovered. Each fit most fears its divergence: cross entropy cannot tolerate leaving a data region uncovered and prefers “overcoverage”; reverse KL cannot tolerate placing mass where there are no data and prefers “choosing a mode”. Lesson 15 develops this. For a generative model trained with cross entropy, the drive to cover everything is one reason sampling at temperature can yield low-quality results in low-probability regions.
Classification: softmax cross-entropy loss
A classifier with classes produces logits , unconstrained real numbers converted into probabilities by softmax.
The second form matters: is a smoothed maximum, , so is a smooth version of margin between the highest-scored and correct class. It is convex in because is.
Proof
By the chain rule, and . Subtracting gives the gradient; for a soft target, . For the Hessian, , which is ; and for any , .
∎The result is surprisingly simple: error is predicted probability minus target probability. Its practical consequences:
- It is bounded: each component is in and . It never explodes.
- It does not vanish when the model is confidently wrong. If , gradient component is almost : loss pushes at full strength just where most needed. It vanishes only when .
- It sums to zero, , the function’s shift invariance.
- In a network, the signal reaching the last layer is for a batch of examples, and the gradient with respect to weight matrix with is : residual times input, as in linear regression. This is a property of generalized linear models with their canonical link.
The second figure makes this visible. Three logits have fixed (without loss of generality by invariance), so logit space is a plane. The arrow field is .
At the starting point , the model assigns to the correct class and the cross-entropy gradient norm is . For squared error on probabilities, , whose gradient is , the norm is , times smaller, and worse the more confidently wrong the model is: it is the gradient of a function that flattens when softmax saturates. With , cross entropy takes correct-class probability above in steps; squared error barely moves the ball in the first steps, spends the next hundred lowering the wrong logit while remains below , and needs about . This is the practical reason classification is trained with cross entropy rather than least squares on probabilities: only cross entropy’s signal stays alive when most needed.
The binary version with logits
For two classes a single logit suffices. Let , be the logit and the class-1 probability. Since and , with ,
This is the case of softmax loss with and the loss of logistic regression, where : the likelihood of a Bernoulli model with probability . For example, with and , and gradient . The function is convex in (Hessian ) and is minimized with optimization-module methods. If data are linearly separable, no finite minimum exists: weights grow without bound, the same overconfidence as in the first figure.
Numerical stability: never compute
Definition is mathematically impeccable but numerically dangerous, because in floating point (floating-point representation) the range of is narrow: overflows to at in float32 and at in float64 (special values and subnormals). Two distinct failures occur.
- Overflow. With logits , and naive softmax computes for the first class and for the rest: loss becomes
NaNor depending on the correct class, and gradientNaN. - Underflow and logarithm of zero. With logits in
float32, is smaller than the smallest subnormal and becomes exactly ; correct-class softmax is and , although the true value is . Infinite loss and aNaNgradient propagating to all weights.
The solution is the log-sum-exp trick. For any constant , , and hence with ,
The largest exponent is now , the sum lies between and , and neither overflows nor gives ; terms that vanish through underflow were already irrelevant (the sum is already at least ). This is what log_softmax and F.cross_entropy do, and why loss is calculated directly from logits, in a single fused operation, never by chaining softmax, logarithm and selection. The same principle explains binary_cross_entropy_with_logits: does not overflow for any .
Implementation from scratch
We start with loss, its analytic gradient and a finite-difference check, and the two failures of the naive version.
import numpy as np
def logsumexp(z):
m = z.max(axis=-1, keepdims=True)
return (m + np.log(np.exp(z - m).sum(axis=-1, keepdims=True)))[..., 0]
def log_softmax(z):
return z - logsumexp(z)[..., None]
def perdida(z, y):
"""Entropía cruzada media (en nats) de logits z (B, K) y etiquetas enteras y (B,)."""
return -log_softmax(z)[np.arange(len(y)), y].mean()
def gradiente(z, y):
"""dL/dz = (softmax(z) - one_hot(y)) / B."""
q = np.exp(log_softmax(z))
q[np.arange(len(y)), y] -= 1.0
return q / len(y)
# 1) el ejemplo del texto: logits (2, 1, 0) y clase correcta la primera
z = np.array([[2.0, 1.0, 0.0]]); y = np.array([0])
print("pérdida:", round(perdida(z, y), 4), " gradiente:", np.round(gradiente(z, y)[0], 4))
# 2) el gradiente analítico frente a diferencias finitas centradas
rng = np.random.default_rng(0)
Z = rng.normal(size=(5, 4)) * 2
Y = rng.integers(0, 4, size=5)
G = gradiente(Z, Y)
Gnum = np.zeros_like(Z)
h = 1e-6
for i in range(Z.shape[0]):
for k in range(Z.shape[1]):
Zp, Zm = Z.copy(), Z.copy()
Zp[i, k] += h
Zm[i, k] -= h
Gnum[i, k] = (perdida(Zp, Y) - perdida(Zm, Y)) / (2 * h)
print("error máximo del gradiente analítico:", f"{np.abs(G - Gnum).max():.1e}")
# 3) la versión ingenua: softmax, logaritmo y selección por separado
def perdida_ingenua(z, y):
q = np.exp(z) / np.exp(z).sum(axis=-1, keepdims=True)
return -np.log(q[np.arange(len(y)), y]).mean()
with np.errstate(all="ignore"):
z_grande = np.array([[1000.0, 0.0, -1000.0]])
print("logits (1000, 0, -1000), clase 1: ingenua =", perdida_ingenua(z_grande, np.array([1])), " estable =", perdida(z_grande, np.array([1])))
z32 = np.array([[-120.0, 0.0]], dtype=np.float32)
print("float32, logits (-120, 0), clase 0: ingenua =", perdida_ingenua(z32, np.array([0])), " estable =", perdida(z32.astype(float), np.array([0])))
print("exp desborda en z =", round(float(np.log(np.finfo(np.float32).max)), 2), "(float32) y", round(float(np.log(np.finfo(np.float64).max)), 2), "(float64)")Loss for with the first class correct is nats, and gradient sums to zero and is exactly . The naive version returns inf in both cases, by different routes: in the first, softmax is for the class with logit and for the requested class, whose logarithm is ; in the second, underflows to in float32. The stable version returns and , the correct values. Now a real model: softmax regression on scikit-learn digits ( images of , ten classes), using the loss and gradient just written. To give the problem a unique minimum we add penalty on weights (not bias), the same used by LogisticRegression with .
import numpy as np
from sklearn.datasets import load_digits
d = load_digits()
X, y = d.data / 16.0, d.target
Xtr, ytr, Xte, yte = X[:1200], y[:1200], X[1200:], y[1200:]
n, K = len(ytr), 10
lam = 1.0 / n # penalización l2 equivalente a C = 1
def fg(theta, X=Xtr, y=ytr):
"""Pérdida penalizada y su gradiente; theta = (W aplanada, b)."""
W, b = theta[:64 * K].reshape(64, K), theta[64 * K:]
lp = log_softmax(X @ W + b)
f = -lp[np.arange(len(y)), y].mean() + 0.5 * lam * (W ** 2).sum()
G = np.exp(lp)
G[np.arange(len(y)), y] -= 1.0
G /= len(y)
return f, np.concatenate([(X.T @ G + lam * W).ravel(), G.sum(axis=0)])
theta = np.zeros(64 * K + K)
for paso in range(301):
f, g = fg(theta)
if paso in (0, 10, 50, 100, 300):
print(f"paso {paso:3d}: pérdida = {f:.4f}")
theta -= 2.0 * g # descenso por gradiente con paso 2
print("el descenso es lento: la pérdida penalizada óptima es menor (ver abajo)")Gradient descent reduces loss rapidly at first ( at step , as predicted by an indifferent model’s initial value) and then drags: the problem is ill-conditioned. To reach the minimum, the same fg (function and its analytic gradient) can be passed to an approximate second-order optimizer, L-BFGS, and compared with LogisticRegression and log_loss.
import numpy as np
from scipy.optimize import minimize
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss
res = minimize(fg, np.zeros(64 * K + K), jac=True, method="L-BFGS-B", options=dict(maxiter=500, ftol=1e-14, gtol=1e-9))
W, b = res.x[:64 * K].reshape(64, K), res.x[64 * K:]
print(f"L-BFGS: {res.nit} iteraciones, pérdida penalizada = {res.fun:.5f}")
clf = LogisticRegression(C=1.0, max_iter=2000, tol=1e-10).fit(Xtr, ytr)
print("scikit-learn: diferencia máxima de pesos =", f"{np.abs(clf.coef_.T - W).max():.1e}", " de sesgos =", f"{np.abs(clf.intercept_ - b).max():.1e}")
Q = np.exp(log_softmax(Xte @ W + b))
print("pérdida en test, la nuestra:", round(float(-np.log(Q[np.arange(len(yte)), yte]).mean()), 5),
" sklearn.metrics.log_loss:", round(float(log_loss(yte, Q)), 5))
print("exactitud en test:", round(float((Q.argmax(axis=1) == yte).mean()), 4), " (sklearn:", round(float(clf.score(Xte, yte)), 4), ")")With the same objective, L-BFGS and scikit-learn reach the same weights up to rounding (differences from to ), and log_loss matches our loss: the library has no magic, it has the same cross entropy. The last cell previews the following sections by simulation: scoring rules, calibration decomposition and the horse race.
import numpy as np
rng = np.random.default_rng(0)
# 1) pérdida esperada de declarar q cuando la verdad es p = 0.7, para tres reglas
p = 0.7
q = np.linspace(0.001, 0.999, 999)
reglas = {
"logarítmica": -(p * np.log(q) + (1 - p) * np.log(1 - q)),
"Brier": p * (1 - q) ** 2 + (1 - p) * q ** 2,
"lineal": 1 - (p * q + (1 - p) * (1 - q)),
}
for nombre, L in reglas.items():
print(f"{nombre:12s} mínimo en q = {q[L.argmin()]:.3f} pérdida con q = p: {L[np.argmin(np.abs(q - p))]:.4f} con q = 0.999: {L[-1]:.4f}")
# 2) calibración: el pronosticador declara siempre 0.9, pero el suceso ocurre el 70 % de las veces
F, tasa = 0.9, 0.7
Y = rng.random(200_000) < tasa
total = -(Y * np.log(F) + (~Y) * np.log(1 - F)).mean()
klb = lambda a, b: a * np.log(a / b) + (1 - a) * np.log((1 - a) / (1 - b))
refin = -(tasa * np.log(tasa) + (1 - tasa) * np.log(1 - tasa))
print(f"pérdida medida = {total:.4f}; calibración + refinamiento = {klb(tasa, F):.4f} + {refin:.4f} = {klb(tasa, F) + refin:.4f}")
# 3) Kelly: cuotas 4 por 1, p = (1/2, 1/4, 1/8, 1/8); crecimiento medio en bits por carrera
pk = np.array([1 / 2, 1 / 4, 1 / 8, 1 / 8])
carreras = rng.choice(4, size=400_000, p=pk)
def crecimiento(b):
with np.errstate(divide="ignore"):
return np.mean(np.log2(b[carreras] * 4))
b18 = pk ** 1.8 / np.sum(pk ** 1.8)
print("Kelly b = p: medido", round(crecimiento(pk), 4), " teoría", 0.25)
print("creencia b ∝ p^1.8: medido", round(crecimiento(b18), 4), " teoría", round(float(np.sum(pk * np.log2(pk / 0.25)) - np.sum(pk * np.log2(pk / b18))), 4))
print("b = mercado (uniforme): medido", round(crecimiento(np.full(4, 0.25)), 4))
print("todo al favorito: medido", crecimiento(np.array([1.0, 0, 0, 0])), " (probabilidad de sobrevivir 20 carreras: 2^-20 =", 2.0 ** -20, ")")
# 4) información lateral: un soplo Y que acierta el ganador con probabilidad 0.7 (y falla repartido en 0.1 por caballo)
Pxy = np.array([[pk[x] * (0.7 if x == yv else 0.1) for yv in range(4)] for x in range(4)])
py = Pxy.sum(axis=0)
info = float(np.sum(Pxy * np.log2(Pxy / np.outer(pk, py))))
x = rng.choice(4, size=400_000, p=pk)
yv = np.array([rng.choice(4, p=[0.7 if k == xi else 0.1 for k in range(4)]) for xi in x[:20_000]])
b_dado_y = Pxy / py # b(x | y) = p(x | y), columnas indexadas por y
print("I(X;Y) =", round(info, 4), "bits; crecimiento sin soplo 0.25, con soplo", round(0.25 + info, 4),
" medido en 20 000 carreras:", round(float(np.mean(np.log2(4 * b_dado_y[x[:20_000], yv]))), 4))Two observations. In (1), logarithmic and Brier rules attain their minimum at , while the linear rule’s minimum is : it rewards exaggeration. In (3), simulation recovers Kelly’s slope and the biased-belief slope , and shows that betting like the market itself () gains nothing.
Logarithmic scoring and calibration
So far loss has trained models. Another use is evaluating probabilistic predictions from a model, meteorologist or prediction market. A scoring rule assigns a penalty to prediction and outcome (lower is better). If reality has distribution , expected penalty is . The rule is proper if telling the truth is optimal, for all , and strictly proper if its only optimum is . This ensures no one profits by lying.
Proof
by definition, and by the decomposition theorem , nonnegative and zero only if (Gibbs). If gives zero probability to a possible outcome, expected loss is .
∎It is not the only one. The Brier score is also strictly proper, and its excess is a squared distance: since , expected loss is , with unique minimum at . By contrast, the linear rule is not proper: expected loss is linear in and minimized at vertex . It pays to exaggerate to the extreme. Nor, strictly speaking, is a rule rewarding only correct prediction of the most likely class: any putting the majority class on the correct side gives the same expected loss.
The figure uses binary Brier score , half the sum over two classes. With , telling the truth costs nats under the logarithmic rule, under Brier and under the linear rule. Reporting costs under the first (the opposite event occurs with probability ), under the second and under the third: only the linear rule rewards the lie. And reporting costs extra under logarithmic scoring, , and extra under Brier, .
Calibration: what loss actually measures
A forecaster is calibrated if it rains on 70% of days they say “70%”. Log loss mixes two things that can be separated.
Proof
Condition on . Expected loss is by the decomposition theorem. Averaging over gives first summand and second the calibration error. It is zero if and only if for almost every (Gibbs).
∎In words: log loss is calibration error plus residual uncertainty. The first is fixed by recalibration (replacing by reduces loss by exactly that term); the second measures how informative predictions are and cannot improve without new information. For a forecaster always reporting when the true rate is , expected loss is nats, decomposed into calibration () and refinement (entropy of a coin with bias , since is constant). Low loss does not imply good calibration: two models with equal loss can split it very differently, and a highly accurate network can be systematically overconfident, as seen with hard labels.
Soft targets: label smoothing and distillation
Loss is linear in its first argument, so mixing targets equals mixing losses. Label smoothing uses target , with uniform over classes (PyTorch’s convention). By linearity,
with the mean logit. Gradient is . The minimum is no longer at infinity: it occurs at , with finite margin between the correct class and each other class
and floor nats. This is what the first figure shows when is increased and training repeated: the margin stops growing and stabilizes. Müller, Kornblith and Hinton (2019) study its effects: it often improves calibration and groups each class’s representations into compact clusters; but it erases information about which classes resemble each other still carried by logits of a hard-label-trained model.
This leads to distillation. A student is trained on the teacher’s soft distribution , with temperature enhancing small probabilities, by minimizing
(Hinton et al., 2015). Factor maintains gradient scale: with respect to student logits, that of is , and for large the difference itself is order , so without the factor the gradient would decay like . This loss is often mixed with hard-label loss. The teacher’s soft distribution carries exactly the class-similarity information label smoothing erases, so training the teacher with label smoothing harms the student (Müller et al., 2019). For any soft target, F.cross_entropy also accepts target probabilities.
Log-optimal betting: Kelly and the value of information
There is a third, economic reading of the same loss. A race has horses; winner has distribution and races are independent. A bookmaker pays for each unit bet on horse if it wins (“ to 1”). You have wealth and distribute it all, betting fraction on horse with . If wins, wealth is multiplied by . Odds are summarized by implied probabilities ; with fair odds, and is a distribution: the market’s belief. After races, wealth is , and what matters is its growth rate in bits per race, because by the strong law of large numbers almost surely: .
Proof
Write and distribute the logarithm: . Since , , and substitution gives . The first term does not depend on and with equality only at (Gibbs). For the ratio, almost surely.
∎Four consequences that are surprising at first.
- The optimal bet does not depend on odds. If you must distribute all your wealth, regardless of what each horse pays; odds only determine how much wealth grows, .
- No advantage means no growth. If the market knows the truth (), . And betting like the market, , leaves wealth unchanged in every race, whatever happens.
- Maximizing expected wealth is a bad idea. With odds to 1 and , betting everything on the favorite multiplies expected wealth by each race (), versus Kelly’s . But the probability of surviving races is : its growth rate is . Kelly has lower expected wealth but almost surely much greater actual wealth: extremely rare events dominate the arithmetic mean, and real growth is the geometric mean, the logarithm.
- The calculation is the same as compression. With uniform odds , optimal rate is : the bet wins exactly what a compressor would save. With and , that is bits per race, and after races wealth is of order .
With initial values Kelly grows at bits per race, and belief with at : the difference is , the cost of believing something other than truth. At the slope is already negative (): a belief too confident in what it knows loses wealth even while “favoring” good horses, because exceeds advantage . With and (uniform belief, matching a uniform market) slope is exactly .
The value of information
Before betting, you receive a tip correlated with the winner. What is it worth?
Proof
For each value this is the race problem with , whose solution is and growth, by the previous theorem, is . Averaging over , , and subtracting leaves .
∎This gives mutual information an economic interpretation: each bit of mutual information is worth one more bit of growth rate. A tip identifying the winner with probability (splitting remaining as per horse) has bits in the preceding race and raises rate from to bits per race (the simulation above confirms it).
A practical caution. All this assumes you know . Betting with an estimate loses per race, and moderate error can exceed your advantage, as with . Hence practice uses a fraction of Kelly: split between the Kelly and market bets (the latter leaves wealth unchanged), with . Some growth is sacrificed for much lower variance and robustness to estimation error. The same criterion sizes financial positions (quantitative finance module), and the betting–compression equivalence returns in lesson 8, where bets help estimate English entropy.
The library version
PyTorch implements all this in a fused, stable function.
| Function | Expects | Notes |
|---|---|---|
F.cross_entropy(input, target, weight=None, ignore_index=-100, reduction='mean', label_smoothing=0.0) | logits (B, K) or (B, K, d1, ...); target: int64 indices (B) or float probabilities shaped like input | mean loss across nonignored examples; with weight, the mean divides by the sum of weights, not |
nn.CrossEntropyLoss | same, as a module | |
F.nll_loss(log_probs, target) | log probabilities (output of log_softmax) | F.cross_entropy = log_softmax + nll_loss |
F.binary_cross_entropy_with_logits(input, target, pos_weight=None) | logit and target in | stable |
F.binary_cross_entropy(prob, target) | probabilities | clips to and is unstable; avoid it |
sklearn.metrics.log_loss(y_true, y_pred, labels=None) | probabilities (n, K) | in nats; clips probabilities to an to avoid returning (its value has changed across versions: fix it if relevant) |
In a language model, logits have shape and per-token loss is cross entropy: flatten to (B*T, V) or move the class dimension to position 1 (logits.transpose(1, 2)). Its exponential, with in nats, is perplexity, the effective number of choices between which the model hesitates: for a uniform model over classes. The next cell reproduces F.cross_entropy with label_smoothing and ignore_index, and binary loss with logits, using the implementations above, and measures discrepancy in float32 and bfloat16. It runs on CPU with tiny tensors.
import torch
import torch.nn.functional as F
torch.manual_seed(0)
B, K = 8, 5
z = torch.randn(B, K) * 3
y = torch.randint(0, K, (B,))
y[2] = -100 # una posición de relleno, que se ignora
def log_softmax(z):
s = z - z.max(-1, keepdim=True).values
return s - s.exp().sum(-1, keepdim=True).log()
def ce_propia(z, y, label_smoothing=0.0, ignore_index=-100):
lp = log_softmax(z)
valido = y != ignore_index
nll = -lp.gather(-1, torch.where(valido, y, torch.zeros_like(y))[:, None])[:, 0]
unif = -lp.mean(-1) # entropía cruzada contra la uniforme
por_ejemplo = (1 - label_smoothing) * nll + label_smoothing * unif
return (por_ejemplo * valido).sum() / valido.sum()
for eps in (0.0, 0.1):
ref, mia = F.cross_entropy(z, y, label_smoothing=eps), ce_propia(z, y, eps)
print(f"label_smoothing = {eps}: torch = {ref.item():.6f}, la nuestra = {mia.item():.6f}, diferencia = {abs(ref - mia).item():.1e}")
def bce_propia(z, t):
return (z.clamp(min=0) - z * t + torch.log1p(torch.exp(-z.abs()))).mean()
zb = torch.randn(16) * 4
t = (torch.rand(16) < 0.5).float()
print("binaria con logits: diferencia =", f"{abs(F.binary_cross_entropy_with_logits(zb, t) - bce_propia(zb, t)).item():.1e}")
print("con logits x30: con logits =", round(F.binary_cross_entropy_with_logits(zb * 30, t).item(), 3), " sigmoide + binary_cross_entropy =", round(F.binary_cross_entropy(torch.sigmoid(zb * 30), t).item(), 3))
# el gradiente de autograd es (softmax - one_hot) en las posiciones válidas
zl = z.clone().requires_grad_(True)
F.cross_entropy(zl, y, reduction="sum").backward()
v = (y != -100)[:, None]
teorico = (F.softmax(z, -1) - F.one_hot(y.clamp(min=0), K).float()) * v
print("gradiente de autograd frente a softmax - one_hot: diferencia =", f"{(zl.grad - teorico).abs().max().item():.1e}")
# precisión: logits en bfloat16 frente a una referencia en float64
ref64 = ce_propia(z.double(), y)
print("float32 frente a float64:", f"{abs(F.cross_entropy(z, y).double() - ref64).item():.1e}",
" bfloat16 frente a float64:", f"{abs(F.cross_entropy(z.bfloat16(), y).double() - ref64).item():.1e}")npm run lab and open the connection link.In float32 discrepancy is of rounding order (), and handling of label_smoothing and ignore_index matches ours. With bfloat16 logits (eight precision bits, seven explicit in the mantissa, floating-point representation) loss differs from the reference by about : that is why in mixed-precision training cross entropy is computed in float32 even if logits arrive in bfloat16. The last comparison reminds us why the logits version is used: going through sigmoid and binary_cross_entropy, which clips the logarithm, gives an incorrect value for a very confident prediction.
Common mistakes
Exercises
Step 1 of 3. How do you rewrite loss to differentiate without quotients?
Step 1 of 3. What is ?
ce_suavizada(z, y, eps), receiving logits z of shape (B, K), integer labels y of shape (B,) and , and returning mean loss with label smoothing , where is uniform over classes (the F.cross_entropy(..., label_smoothing=eps) convention), in nats. It must be numerically stable: logits of magnitude 1000 must not give nan or inf.import numpy as np
def ce_suavizada(z, y, eps):
"""Pérdida media con suavizado de etiquetas, en nats."""
z = np.asarray(z, dtype=float)
y = np.asarray(y)
# tu código: logsumexp estable, entropía cruzada con la etiqueta dura y con la uniforme
return 0.0More than one answer may be correct.
Summary
- Decomposition. , equality only if . With hard labels the floor is and reached only with infinite logits (overconfidence); a smoothed target has a finite optimum.
- Likelihood. : maximum likelihood, minimum cross entropy and minimum are the same. When the model cannot represent data, cross entropy “covers” (in exponential families, matches moments); reverse KL “selects a mode”.
- Softmax and gradient. , with : bounded, summing to zero, and not vanishing when the model is confidently wrong, unlike squared error on probabilities. The binary version is , with gradient .
- Stability. Never calculate : subtract the maximum (log-sum-exp) and use
log_softmaxorF.cross_entropy, which accept logits. Double softmax is a silent error. - Scoring and calibration. is strictly proper with excess and is the only local rule for ; log loss is calibration error plus refinement. Brier is also proper; linear is not.
- Soft targets. is linear in its first argument: smoothing , optimal margin ; distillation with ; smoothing the teacher harms the student.
- Kelly. With fair odds, , maximized at ; side information adds exactly bits per race; with estimated bet a fraction.