Probability for ML: random variables, distributions to losses, MLE, MAP, Bayes

A child page of Topic: math. A model's output as a distribution: how it is scored (the losses, MLE, proper scoring and calibration measured on three real models), reshaped (temperature, priors, Bayes' rule), averaged (the law of large numbers and the central limit theorem by simulation) and sampled (inverse CDF, Gumbel-max, reparameterisation), on the root's tiny three-word model, with every number recomputed. Data as of October 2026. Reading: 32 min, plus 16 in closed details.

The idea in one screen

A model's output is a probability distribution; training scores it by minus the log-probability it gave the truth, generation draws from it, and the rest of probability says how to reshape it (temperature, priors, evidence), how sure to be about averages of it, and how to compute with it without overflowing.

Fig. 1 is the root page's tiny model, the running example of every section below: one distribution, three things done with it.

  1. Scores. The model's last layer gives any real numbers: z=(2,1,0)z = (2, 1, 0) for cat, dog and sat.
  2. Softmax turns them into a bet. Exponentiate, divide by the total: p=(0.665,0.245,0.090)p = (0.665, 0.245, 0.090), non-negative and adding to 1; the dots carry each word's share (sections 1 and 6).
  3. Score it. The right word was sat, so the loss is −ln⁡0.090=2.408-\ln 0.090 = 2.408: the smaller the bet on the truth, the taller this column (sections 7 and 8).
  4. Draw from it. Lay pp end to end as the CDF strip and drop a uniform number on it; u=0.7u = 0.7 lands in dog's slice, between 0.665 and 0.910 (section 10).
  5. Reshape it. Divide the scores by a temperature: at T=2T = 2 they halve and the bet flattens to (0.506,0.307,0.186)(0.506, 0.307, 0.186). Multiplying by a prior and renormalising reshapes it too (sections 5, 6 and 9).

You need: the running example, from Topic: math (its section 2 shows the tiny model's numbers and their owners). On ground an MSc already covers (axioms, PMF, expectation), this page states only what ML uses differently and puts the rest in closed blocks.

Density
probability per unit of xx; only its areas are probabilities, so it can exceed 1 and its NLL can be negative.
Exponential family
distributions of the form h(y)eηT(y)−A(η)h(y)\,e^{\eta T(y) - A(\eta)}; why every standard loss has a "prediction minus target" gradient.
Proper scoring rule
a score whose expectation is best when you report your true belief (the log loss, Brier).
ECE
expected calibration error: the size-weighted gap between confidence and accuracy over confidence bins.
Conjugate prior
a prior whose posterior has the same form; for a coin, Beta plus counts is Beta.
Gumbel-max
sampling a categorical as arg⁡maxi⁡(zi+gi)\arg\max_i (z_i + g_i) with Gumbel noise gg; Gumbel-softmax is its differentiable relaxation.
Reparameterisation
writing a sample as a function of the parameters and parameter-free noise, x=μ+σεx = \mu + \sigma\varepsilon, so gradients pass through it.
Log-sum-exp
ln⁡∑kezk\ln \sum_k e^{z_k}, the log of the softmax normaliser, computed as m+ln⁡∑kezk−mm + \ln\sum_k e^{z_k - m} with m=maxk⁡zkm = \max_k z_k.

Owned elsewhere and linked, not taught here: estimation, bias, intervals and tests on Statistics for ML; entropy and KL on Information theory for ML; the ELBO, VAEs and diffusion on Variational inference and generative-model maths; decoding strategies for LLMs on Sampling and Decoding; floating point and the stable softmax in depth on Numerical computing for ML.

The page in one table (reference)
IdeaIn one lineOn the tiny modelUsed in ML for
Distribution (1, 2)non-negative numbers, one per outcome, adding to 1p=(0.665,0.245,0.090)p = (0.665, 0.245, 0.090) is a categorical distributionevery output layer
Expectation (3)probability-weighted averageexpected loss under its own bet = entropy, 0.832 natsevery loss is an expectation over data
LLN and CLT (4)averages settle, with Gaussian error shrinking as 1/n1/\sqrt{n}the mean of 100 token losses is within about 0.065 of 0.832minibatches, Monte Carlo, error bars
Conditional probability, Bayes (5)restrict to what you know, renormalisepp is P(next word|"the cat")P(\text{next word} \mid \text{"the cat"})reading classifier scores against base rates
Chain rule (5)a joint is a product of conditionalsa sentence's probability is the product of next-word probabilitieswhy language models predict one token at a time
Softmax and temperature (6)scores to a distribution; z/Tz/T sharpens or flattens itat T=2T = 2, (0.506,0.307,0.186)(0.506, 0.307, 0.186)decoding, calibration, distillation
Exponential family (7)one form covers Bernoulli, categorical, Gaussian, Poissongradient of the loss in the scores = p−one-hotp - \text{one-hot}why every standard loss has "prediction minus target" gradients
Distribution to loss (7)loss = minus the log-probability of the truth−ln⁡psat=2.408-\ln p_{\text{sat}} = 2.408choosing BCE, CE, MSE, L1 or Poisson loss
Proper scoring, calibration (8)the log loss rewards honest probabilitiesa pretrained model's 70% should be right 70% of the timetrusting confidences; temperature scaling
MLE, MAP, Bayesian (7, 9)best single answer; with a prior; keep every answer weightedtraining = MLE; weight decay = MAPregularisation, uncertainty, small data
Sampling (10)turn uniform numbers into drawsa uniform number below 0.665 picks cattext generation, RL, estimating expectations
Reparameterisation (11)write a sample as a function of parameters plus fixed noisex=μ+σεx = \mu + \sigma \varepsilonVAEs, diffusion, low-variance gradients
Log space (12)add log-probabilities; normalise with log-sum-expa 100-token sentence at 0.090 per token: 10−104.610^{-104.6}, log −240.8-240.8every loss and likelihood in practice
The one idea to keep
Pick a distribution for the target, let the network output its parameters, and minus the log of the probability it gives the truth is the loss. Every standard loss falls out of that move (section 7), its gradient is always "prediction minus target" (section 7), and the probabilities it trains are honest because the log loss is a proper scoring rule (section 8).

1. Random variables and the three distributions that matter

A random variable turns each outcome into a number; Y∼pY \sim p reads "YY is drawn from pp". For the tiny model, let YY be the index of the next word (1 cat, 2 dog, 3 sat), so P(Y=3)=0.090P(Y = 3) = 0.090. A discrete variable has a probability mass function (PMF) p(x)=P(X=x)p(x) = P(X = x) that sums to 1; a continuous one has a density (PDF) whose areas are probabilities (any single value has probability 0), P(a≤X≤b)=∫abp(x)dxP(a \le X \le b) = \int_a^b p(x)\,dx; both have a cumulative distribution function (CDF) F(x)=P(X≤x)F(x) = P(X \le x), and p=F′p = F' for a density. The tiny model's CDF steps through 0.665, 0.910, 1; the inverse CDF gives quantiles (the median is F−1(0.5)F^{-1}(0.5)) and is one way to sample (section 10).

For the standard Gaussian, Φ(1)=0.8413\Phi(1) = 0.8413 (Φ\Phi is its CDF), so P(−1≤X≤1)=0.6827P(-1 \le X \le 1) = 0.6827; within 2 standard deviations 0.9545, within 3, 0.9973; within 1.96, exactly 0.95, which is where the 1.96 in 95% error bars comes from.

A density is not a probability: it can be far above 1

𝒩(0,0.12)\mathcal{N}(0, 0.1^2): peak density 1/2π×0.01=3.9891/\sqrt{2\pi \times 0.01} = 3.989, yet the shaded area within one standard deviation is 0.6827. Its NLL at the peak is −ln⁡3.989=−1.384-\ln 3.989 = -1.384: Gaussian NLL losses can be negative, because densities above 1 are normal. A uniform on [0,0.5][0, 0.5] has density 2 everywhere.

Three distributions cover almost every output layer:

DistributionForPMF or PDFMeanVarianceIn ML
Bernoulli(p)(p)one yes or nopy(1−p)1−yp^y (1 - p)^{1 - y}, y∈{0,1}y \in \{0, 1\}ppp(1−p)p(1 - p)binary labels; dropout masks
Categorical(p)(p)one of KK∏kpk[y=k]\prod_k p_k^{[y = k]}, i.e. pyp_ypp (one-hot)diag⁡(p)−pp⊤\operatorname{diag}(p) - pp^\topclassifiers, next token
Gaussian 𝒩(μ,σ2)\mathcal{N}(\mu, \sigma^2)a real number12πσ2e−(y−μ)2/2σ2\frac{1}{\sqrt{2\pi\sigma^2}} e^{-(y - \mu)^2 / 2\sigma^2}μ\muσ2\sigma^2regression noise, initialisation, priors, diffusion noise

Every distribution here, and six more, is live in the Distribution explorer: its PMF or PDF and CDF, seeded samples checked against the mean and variance formulas, and the same distribution read as a loss with its gradient.

Six more distributions, how they relate, and their numbers (depth)
DistributionForPMF or PDFMeanVarianceIn ML
Binomial(n,p)(n, p)successes in nn tries(nk)pk(1−p)n−k\binom{n}{k} p^k (1 - p)^{n - k}npnpnp(1−p)np(1 - p)an accuracy count on nn items
Poisson(λ)(\lambda)a count per intervalλke−λ/k!\lambda^k e^{-\lambda} / k!λ\lambdaλ\lambdaclicks, events, arrivals
Laplace(μ,b)(\mu, b)a real number, heavy tails12be−|y−μ|/b\frac{1}{2b} e^{-|y - \mu| / b}μ\mu2b22b^2L1 loss; L1 prior
Exponential(λ)(\lambda)a waiting timeλe−λx\lambda e^{-\lambda x}, x≥0x \ge 01/λ1/\lambda1/λ21/\lambda^2inter-arrival times; the "exponential race" sampler
Beta(a,b)(a, b)a probability in [0,1][0, 1]pa−1(1−p)b−1B(a,b)\frac{p^{a - 1} (1 - p)^{b - 1}}{B(a, b)}aa+b\frac{a}{a + b}ab(a+b)2(a+b+1)\frac{ab}{(a + b)^2 (a + b + 1)}prior on a rate (section 9)
Dirichlet(α)(\alpha)a probability vector1B(α)∏kpkαk−1\frac{1}{B(\alpha)} \prod_k p_k^{\alpha_k - 1}αk/α0\alpha_k / \alpha_0αk(α0−αk)α02(α0+1)\frac{\alpha_k(\alpha_0 - \alpha_k)}{\alpha_0^2(\alpha_0 + 1)}prior on a categorical; topic models; smoothing

[y=k][y = k] is 1 when y=ky = k and 0 otherwise. (nk)=n!k!(n−k)!\binom{n}{k} = \frac{n!}{k!(n - k)!} counts the ways to choose which kk of the nn tries succeed. B(a,b)=Γ(a)Γ(b)/Γ(a+b)B(a, b) = \Gamma(a)\Gamma(b)/\Gamma(a + b) is the Beta function, the constant that makes the area 1 (Γ\Gamma extends the factorial: Γ(n)=(n−1)!\Gamma(n) = (n - 1)!); α0=∑kαk\alpha_0 = \sum_k \alpha_k. Formulas as in Bishop, Pattern Recognition and Machine Learning, chapter 2 and appendix B.

Numbers. Binomial: a model with true accuracy 0.7 on a 500-item eval scores 350350 on average, with standard deviation 500×0.7×0.3=10.25\sqrt{500 \times 0.7 \times 0.3} = 10.25 items (2.0 points): the noise in any single eval run. Poisson: at rate λ=2\lambda = 2, P(Y=3)=23e−2/3!=0.180P(Y = 3) = 2^3 e^{-2} / 3! = 0.180. Laplace with b=1b = 1 has variance 2. Beta(2, 2) has mean 0.5 and standard deviation 0.224. Dirichlet(2, 1, 1) has mean (0.5,0.25,0.25)(0.5, 0.25, 0.25).

How they relate. A Bernoulli is a categorical with K=2K = 2 and a binomial with n=1n = 1. A binomial is a sum of nn independent Bernoullis (so its mean and variance are nn times theirs, by linearity and by variances adding). A Poisson is the limit of a binomial with many tries and a small chance each (n→∞n \to \infty, np=λnp = \lambda). A Beta is a Dirichlet with two components. The Gaussian is the limit of sums of many independent pieces (the central limit theorem, section 4), which is why it models noise. When counts vary more than their mean (overdispersion, common when some users click far more than others), the negative binomial, with variance μ+μ2/r\mu + \mu^2/r for a dispersion parameter rr, replaces the Poisson.

Foundations: sample spaces, Kolmogorov's axioms, and counting against belief (depth)

The sample space Ω\Omega lists every outcome (for the tiny model, {cat,dog,sat}\{\text{cat}, \text{dog}, \text{sat}\}); an event is a set of outcomes ("the next word is an animal" is {cat,dog}\{\text{cat}, \text{dog}\}). Everything on this page follows from three rules stated by Kolmogorov in 1933 (Foundations of the Theory of Probability, English translation, chapter 1):

P(A)≥0,P(Ω)=1,P(A∪B)=P(A)+P(B)  when A∩B=⌀.P(A) \ge 0, \qquad P(\Omega) = 1, \qquad P(A \cup B) = P(A) + P(B) \ \text{ when } A \cap B = \varnothing.

Consequences: P(not A)=1−P(A)P(\text{not } A) = 1 - P(A), and P(A∪B)=P(A)+P(B)−P(A∩B)P(A \cup B) = P(A) + P(B) - P(A \cap B). Fair die: P(even)=3/6=0.5P(\text{even}) = 3/6 = 0.5; P(at least 5)=2/6=0.333P(\text{at least } 5) = 2/6 = 0.333. Tiny model: P(animal)=0.665+0.245=0.910P(\text{animal}) = 0.665 + 0.245 = 0.910.

Counting (frequentist): a probability is a long-run fraction, which needs a repeatable experiment. Belief (Bayesian): a degree of belief given what you know ("this checkpoint will beat the baseline: 70%"). Both obey the same rules (Cox, 1946: any consistent way of grading belief by numbers must follow them, up to relabelling). The tiny model's 9% is a belief; it becomes checkable by counting when many 9% predictions are collected and scored, which is calibration (section 8). The sample space is the vocabulary (language models), the label set (classifiers) or the real line (regression).

2. The multivariate Gaussian: covariance is a shape

For x∈ℝdx \in \mathbb{R}^d with mean μ\mu and covariance matrix Σ\Sigma:

𝒩(x;μ,Σ)=1(2π)ddet⁡Σexp⁡(−12(x−μ)⊤Σ−1(x−μ)).\mathcal{N}(x; \mu, \Sigma) = \frac{1}{\sqrt{(2\pi)^d \det \Sigma}} \exp\!\Big(-\tfrac12 (x - \mu)^\top \Sigma^{-1} (x - \mu)\Big).

The exponent is the squared Mahalanobis distance, distance from the mean in units of the spread in each direction, so equal-density points lie on ellipses. The eigenvectors of Σ\Sigma are the ellipse's axes and the square roots of its eigenvalues their half-lengths; det⁡Σ\det \Sigma is the squared volume scale. Sampling: factor Σ=LL⊤\Sigma = LL^\top (Cholesky, LL lower triangular), draw ε\varepsilon with independent standard Gaussian entries, return x=μ+Lεx = \mu + L\varepsilon; its covariance is 𝔼[Lεε⊤L⊤]=LIL⊤=Σ\mathbb{E}[L\varepsilon\varepsilon^\top L^\top] = L\,I\,L^\top = \Sigma. This is the reparameterisation of section 11 in matrix form.

  1. Noise first. ε\varepsilon has two independent standard Gaussian entries: a round bell, 𝒩(0,I)\mathcal{N}(0, I). The dots are the first 200 of the slider's 400 seeded draws; the rings are Mahalanobis distance 1 and 2.
  2. Multiply by LL. x=Lεx = L\varepsilon with L=(100.80.6)L = \begin{pmatrix}1 & 0 \\ 0.8 & 0.6\end{pmatrix}: every dot slides, the bell stretches into a ridge along the diagonal, and Σ=LL⊤\Sigma = LL^\top has correlation 0.8.
  3. The axes are the eigenvectors. Seen from above: the long axis points along (1,1)(1, 1) with half-length 1.8=1.342\sqrt{1.8} = 1.342, the short one along (1,−1)(1, -1) with 0.2=0.447\sqrt{0.2} = 0.447; det⁡Σ=1.8×0.2=0.36\det\Sigma = 1.8 \times 0.2 = 0.36.
  4. The exponent is a distance. Two points 1.342 from the mean: along the long axis it is Mahalanobis distance 1 and density 0.161; along the short axis it is 1.342/0.447=3.01.342 / 0.447 = 3.0 and density 0.003. Distance is measured in units of the spread in each direction.
  5. Near singular. At ρ=0.95\rho = 0.95 the eigenvalues are 1.95 and 0.05, det⁡Σ=0.0975\det\Sigma = 0.0975, and the peak density rises from 0.265 to 0.510: the ridge collapses towards a line and Σ−1\Sigma^{-1} blows up.

Predict, then drag: what happens to the ellipse and to det⁡Σ\det\Sigma as ρ\rho goes to 0.95? Default: Σ=(10.80.81)\Sigma = \begin{pmatrix}1 & 0.8 \\ 0.8 & 1\end{pmatrix}, L=(100.80.6)L = \begin{pmatrix}1 & 0 \\ 0.8 & 0.6\end{pmatrix}, eigenvalues 1.8 and 0.2.

Used for: Gaussian noise in diffusion models and VAEs; Gaussian processes; weight initialisation (𝒩(0,σ2)\mathcal{N}(0, \sigma^2) with σ\sigma set by fan-in); Gaussian discriminant analysis; the Laplace approximation and K-FAC (a Gaussian around the trained weights); the Fréchet Inception Distance (two Gaussians fitted to features).

The same 400 noise draws, stretched and sheared by LL

400 points drawn as μ+Lε\mu + L\varepsilon from a fixed seed (the same ε\varepsilon for every setting); ellipses at Mahalanobis distance 1 and 2. At ρ=0\rho = 0 the ellipse aligns with the axes; near 0.95 the cloud collapses onto a line: the smaller eigenvalue goes to 0, Σ\Sigma nears singular and Σ−1\Sigma^{-1} blows up, the numerical trouble behind adding a small "jitter" to the diagonal. The decompositions are on Linear algebra for ML.

3. Expectation and variance, and the algebra ML leans on

𝔼x∼p[f(x)]=∑xf(x)p(x)\mathbb{E}_{x \sim p}[f(x)] = \sum_x f(x)\,p(x) (an integral for densities) is the probability-weighted average; a training objective is 𝔼(x,y)∼data[ℓ]\mathbb{E}_{(x, y) \sim \text{data}}[\ell]. On the tiny model, if the next word really were drawn from its own bet, the expected loss is

𝔼[−ln⁡p(Y)]=−(0.665ln⁡0.665+0.245ln⁡0.245+0.090ln⁡0.090)=0.832 nats,\mathbb{E}[-\ln p(Y)] = -(0.665 \ln 0.665 + 0.245 \ln 0.245 + 0.090 \ln 0.090) = 0.832 \text{ nats},

the entropy of pp (owned by Information theory for ML). Four rules carry almost every argument in ML papers:

  • Linearity holds without independence: 𝔼[aX+bY]=a𝔼[X]+b𝔼[Y]\mathbb{E}[aX + bY] = a\,\mathbb{E}[X] + b\,\mathbb{E}[Y] for any random variables. So a minibatch gradient is an unbiased estimate of the full gradient, and counting by indicators works: shuffle 10 name tags onto 10 people and the expected number of people with their own tag is 10×1/10=110 \times 1/10 = 1, though the matches are dependent (if nine match, the tenth must). A model giving the right token probability qtq_t at each of nn positions gets ∑tqt\sum_t q_t right in expectation, however the positions depend on each other.
  • Variances add only for uncorrelated variables: Var⁡(X+Y)=Var⁡(X)+Var⁡(Y)+2Cov⁡(X,Y)\operatorname{Var}(X + Y) = \operatorname{Var}(X) + \operatorname{Var}(Y) + 2\operatorname{Cov}(X, Y) and Var⁡(aX+b)=a2Var⁡(X)\operatorname{Var}(aX + b) = a^2 \operatorname{Var}(X). For nn independent draws, the variance of their average is σ2/n\sigma^2 / n: the root of every error bar (section 4).
  • Zero correlation does not mean independent. XX uniform on {−1,0,1}\{-1, 0, 1\} and Y=X2Y = X^2: Cov⁡=𝔼[X3]−𝔼[X]𝔼[X2]=0\operatorname{Cov} = \mathbb{E}[X^3] - \mathbb{E}[X]\,\mathbb{E}[X^2] = 0, yet YY is a function of XX. Correlation ρ=Cov⁡(X,Y)/(σXσY)\rho = \operatorname{Cov}(X, Y)/(\sigma_X \sigma_Y) measures only linear association (jointly Gaussian variables are the exception); mutual information (on Information theory for ML) catches any dependence.
  • A one-hot categorical has covariance diag⁡(p)−pp⊤\operatorname{diag}(p) - pp^\top: for the tiny model the diagonal is (0.223,0.185,0.082)(0.223, 0.185, 0.082) (each pi(1−pi)p_i(1 - p_i)) and Cov⁡(cat,dog)=−0.665×0.245=−0.163\operatorname{Cov}(\text{cat}, \text{dog}) = -0.665 \times 0.245 = -0.163. The same matrix is the softmax's Jacobian and the cross-entropy's Hessian in the scores (section 7).
Definitions, the die and umbrella numbers, and the laws of total expectation and variance (depth)

𝔼[X]=∑xxp(x)\mathbb{E}[X] = \sum_x x\,p(x); 𝔼[f(X)]=∑xf(x)p(x)\mathbb{E}[f(X)] = \sum_x f(x)\,p(x) needs no new distribution (the law of the unconscious statistician). Linearity in one line: ∑x,y(ax+by)p(x,y)=a∑xxp(x)+b∑yyp(y)\sum_{x,y}(ax + by)\,p(x,y) = a\sum_x x\,p(x) + b\sum_y y\,p(y). Var⁡(X)=𝔼[(X−𝔼X)2]=𝔼[X2]−𝔼[X]2\operatorname{Var}(X) = \mathbb{E}[(X - \mathbb{E}X)^2] = \mathbb{E}[X^2] - \mathbb{E}[X]^2 (expand the square, use linearity); the standard deviation σ\sigma is its square root, in the units of XX. Cov⁡(X,Y)=𝔼[XY]−𝔼[X]𝔼[Y]\operatorname{Cov}(X, Y) = \mathbb{E}[XY] - \mathbb{E}[X]\,\mathbb{E}[Y]. For a vector, the covariance matrix is Σ=𝔼[(x−μ)(x−μ)⊤]\Sigma = \mathbb{E}[(x - \mu)(x - \mu)^\top].

Die: 𝔼[X]=3.5\mathbb{E}[X] = 3.5, a value it never shows; Var⁡(X)=35/12=2.917\operatorname{Var}(X) = 35/12 = 2.917. Umbrella (section 5): 𝔼[XY]=P(X=1,Y=1)=0.24\mathbb{E}[XY] = P(X = 1, Y = 1) = 0.24, so Cov⁡=0.24−0.3×0.38=0.126\operatorname{Cov} = 0.24 - 0.3 \times 0.38 = 0.126; Var⁡(X)=0.3×0.7=0.21\operatorname{Var}(X) = 0.3 \times 0.7 = 0.21, Var⁡(Y)=0.38×0.62=0.2356\operatorname{Var}(Y) = 0.38 \times 0.62 = 0.2356; ρ=0.126/0.21×0.2356=0.566\rho = 0.126 / \sqrt{0.21 \times 0.2356} = 0.566.

𝔼[X]=𝔼[𝔼[X|Y]],Var⁡(X)=𝔼[Var⁡(X|Y)]+Var⁡(𝔼[X|Y]).\mathbb{E}[X] = \mathbb{E}\big[\mathbb{E}[X \mid Y]\big], \qquad \operatorname{Var}(X) = \mathbb{E}\big[\operatorname{Var}(X \mid Y)\big] + \operatorname{Var}\big(\mathbb{E}[X \mid Y]\big).

Average within each group, then average the group averages; the spread splits into within-group plus between-group. Illustrative: 70% of tokens easy (mean loss 1.0, variance 0.5), 30% hard (mean 4.0, variance 2.0). Mean 0.7×1.0+0.3×4.0=1.90.7 \times 1.0 + 0.3 \times 4.0 = 1.9; within 0.7×0.5+0.3×2.0=0.950.7 \times 0.5 + 0.3 \times 2.0 = 0.95, between 0.7×(1−1.9)2+0.3×(4−1.9)2=1.890.7 \times (1 - 1.9)^2 + 0.3 \times (4 - 1.9)^2 = 1.89, total 2.84. Most of the spread is between groups, which is why loss curves are often reported by data source. The law of total variance is the decomposition behind ensembles and the bias-variance split (on Statistics for ML). Variance and covariance also describe gradient noise, feature scaling and normalisation layers, and covariance matrices drive PCA and whitening.

Two classic counting results: birthday collisions and the coupon collector (depth; moved from the root's retired Practice drills)

Birthday collisions. With 23 people and 365 equally likely birthdays, the chance that all differ is ∏i=022365−i365=0.4927\prod_{i=0}^{22} \frac{365 - i}{365} = 0.4927, so at least one pair shares a birthday with probability 0.5073: just over even odds. There are (232)=253\binom{23}{2} = 253 pairs, each with a 1/365 chance, and a collision becomes likely after about 2ln⁡2⋅N\sqrt{2 \ln 2 \cdot N} draws from NN values (Birthday problem). Collisions arrive after about N\sqrt{N} draws, not NN: hashing into N=232N = 2^{32} ids (feature hashing, dedup fingerprints) gives even odds of a collision after only about 77,163 items, and sampling with replacement repeats examples sooner than intuition says.

The coupon collector (linearity of expectation at work). A sampler returns one of 10 classes uniformly each draw. Having seen kk classes, a new one appears with probability (10−k)/10(10 - k)/10, a geometric wait of 10/(10−k)10/(10 - k) draws on average; expectations add, so seeing every class takes 10(1+12+⋯+110)=10H10=29.2910\left(1 + \frac12 + \dots + \frac1{10}\right) = 10 H_{10} = 29.29 draws on average, about three times the number of classes, and the last class alone takes 10. In general nHn≈nln⁡nn H_n \approx n \ln n (Coupon collector's problem). It sizes how many samples until every class, expert or shard is seen, and how many generations until every distinct answer appears in sampling-based evaluation and pass@k.

Averages of the tiny model's token losses settle (top) and turn Gaussian (bottom)

Top: one stream of draws from pp, its running mean against nn (log scale) with the band 0.832±1.96×0.651/n0.832 \pm 1.96 \times 0.651/\sqrt{n}. Bottom: 2,000 independent averages of nn draws each, histogram against the CLT's 𝒩(0.832,0.6512/n)\mathcal{N}(0.832, 0.651^2/n) curve, on a fixed axis. Seeded generator (mulberry32); src/recompute.py reruns the same generator and reproduces every counter.

4. The law of large numbers and the central limit theorem, by simulation

Most expectations in ML (an expected reward, an expected loss over all texts, a predictive integral) are sums over too many outcomes to compute, so they are estimated by an average of draws, the Monte Carlo estimate:

𝔼x∼p[f(x)]≈μˆn=1n∑i=1nf(xi),SE⁡(μˆn)=σfn.\mathbb{E}_{x \sim p}[f(x)] \approx \hat\mu_n = \frac1n \sum_{i=1}^{n} f(x_i), \qquad \operatorname{SE}(\hat\mu_n) = \frac{\sigma_f}{\sqrt{n}}.

Two theorems say why this works. The law of large numbers: μˆn\hat\mu_n converges to 𝔼[f]\mathbb{E}[f] as nn grows (it is unbiased by linearity). The central limit theorem: for finite variance, the error μˆn−𝔼[f]\hat\mu_n - \mathbb{E}[f] is close to Gaussian with standard deviation σf/n\sigma_f/\sqrt{n}, whatever the shape of ff's distribution. On the tiny model, f=−ln⁡p(word)f = -\ln p(\text{word}) takes only three values (0.408, 1.408, 2.408), with mean 0.832 and standard deviation 0.651: nothing Gaussian about it.

Predict, then step: at n=100n = 100 token losses per average, how wide is the spread of the averages? (Answer: 0.651/100=0.0650.651/\sqrt{100} = 0.065; 10,000 draws give 0.0065.) And at n=1n = 1, does "within 1.96 standard errors" catch 95% of draws?

  1. n=1n = 1: each "average" is one token loss. Three spikes at 0.408, 1.408 and 2.408, nothing like a bell; the ±1.96\pm 1.96 band catches only 90.6% of them, not 95%: the Gaussian rule needs averaging first.
  2. n=2n = 2: five possible averages. The spikes start to fill in towards the middle; the spread, 0.462, is already 1/21/\sqrt{2} of one draw's.
  3. n=4n = 4: the shape is rounding off. Still skewed to the right (the bet piles mass on the cheap word cat), but the curve is a fair summary.
  4. n=10n = 10: close to Gaussian. Spread 0.206 against the CLT's 0.651/10=0.2060.651/\sqrt{10} = 0.206; 95.7% of the averages fall inside ±1.96\pm 1.96 standard errors.
  5. n=30n = 30. Spread 0.120 (theory 0.119); the running mean of the single stream (top) has settled inside its band.
  6. n=100n = 100: about ±0.065\pm 0.065. Spread 0.063 against 0.651/100=0.0650.651/\sqrt{100} = 0.065: a 100-token average pins the mean loss to about ±0.065\pm 0.065 per standard error.
  7. n=1,000n = 1{,}000: ten times the samples, about a third of the error. Spread 0.0205 against the CLT's 0.0206, and 94.9% inside the band; the running mean reads 0.795, inside 0.832±0.0400.832 \pm 0.040. The law of large numbers says where the error goes, the CLT how fast and in what shape.

Four times the samples halve the error, whatever the dimension: that is why Monte Carlo is the default in high dimensions, and why an eval of 100 items cannot separate two models 2 points apart (a 70% accuracy on 100 items has standard error 0.7×0.3/100=0.046\sqrt{0.7 \times 0.3/100} = 0.046, 4.6 points). Where the Gaussian approximation fails (heavy tails, infinite variance, small nn on a skewed metric), and how to build intervals and tests from it, is Statistics for ML's.

Used for: minibatch gradients (a Monte Carlo estimate of the full-data gradient); policy gradients and RL returns; the ELBO and diffusion losses (sampled noise and time steps); MCMC predictive averages; pass@k and other sampled eval metrics.

Importance sampling: estimating under pp with draws from qq (depth)

If you can only sample from qq, reweight: 𝔼p[f]=𝔼q[f(x)p(x)/q(x)]\mathbb{E}_p[f] = \mathbb{E}_q\big[f(x)\, p(x)/q(x)\big]. The ratio p/qp/q is the importance weight; with qq uniform over the tiny model's three words, the weights are 3p=(1.996,0.734,0.270)3p = (1.996, 0.734, 0.270). It is unbiased but its variance explodes when qq puts little mass where pp has a lot. PPO's probability ratio and every off-policy correction are importance weights (on Policy gradients and actor-critic); the IWAE bound is importance sampling inside the ELBO (on Variational inference and generative-model maths).

5. Conditioning, independence and Bayes' rule

The question. A toxicity filter catches 95% of toxic messages and wrongly flags only 5% of clean ones. It flags a message. How likely is the message to be toxic? (Most people say about 95%. The answer below is 16%.)

One table, three readings

The umbrella example (carried from the old page and rechecked): X=1X = 1 "it rained", P(X=1)=0.3P(X = 1) = 0.3; Y=1Y = 1 "carried an umbrella", with P(Y=1|X=1)=0.8P(Y = 1 \mid X = 1) = 0.8 and P(Y=1|X=0)=0.2P(Y = 1 \mid X = 0) = 0.2. The joint distribution, one cell per pair:

umbrella Y=1Y = 1no umbrella Y=0Y = 0row sum: P(X)P(X)
rain X=1X = 10.240.060.30
dry X=0X = 00.140.560.70
column sum: P(Y)P(Y)0.380.621
  • Joint: the four cells. Marginal: sum out the other variable, P(x)=∑yP(x,y)P(x) = \sum_y P(x, y), the sums in the margins (for densities, p(x)=∫p(x,y)dyp(x) = \int p(x, y)\,dy). "Marginalising out" is the most common move in probabilistic ML: the evidence in Bayes' rule, the likelihood of a latent-variable model and the ELBO are marginals.
  • Conditional: one row or column, renormalised, P(A|B)=P(A∩B)/P(B)P(A \mid B) = P(A \cap B)/P(B): given rain, (0.24,0.06)/0.30=(0.8,0.2)(0.24, 0.06)/0.30 = (0.8, 0.2). The product rule P(A∩B)=P(A|B)P(B)P(A \cap B) = P(A \mid B)\,P(B) builds the cells: 0.8×0.3=0.240.8 \times 0.3 = 0.24. The law of total probability P(A)=∑iP(A|Bi)P(Bi)P(A) = \sum_i P(A \mid B_i)\,P(B_i) builds the margins: P(Y=1)=0.8×0.3+0.2×0.7=0.38P(Y = 1) = 0.8 \times 0.3 + 0.2 \times 0.7 = 0.38. So P(X=1|Y=1)=0.24/0.38=0.632P(X = 1 \mid Y = 1) = 0.24 / 0.38 = 0.632: the umbrella raised rain from 0.3 to 0.632.
  1. The joint. One bar per pair of values, its height the probability: rain and umbrella 0.24, rain and none 0.06, dry and umbrella 0.14, dry and none 0.56. The four add to 1.
  2. Marginals: sum out the other variable. Each row flows into P(X)P(X): rain 0.30, dry 0.70. Each column flows into P(Y)P(Y): umbrella 0.38, none 0.62.
  3. Condition on the umbrella. Keep the umbrella column and divide it by its total, 0.38: rain becomes 0.24/0.38=0.6320.24 / 0.38 = 0.632, dry 0.368. Seeing the umbrella raised rain from 0.3 to 0.632.
  4. Independence would be a product. The glass lids sit at P(x)P(y)P(x)P(y): 0.114 for rain and umbrella against the bar's 0.24, and 0.186, 0.266 and 0.434 for the other cells. The bars miss every lid, so rain and umbrellas are dependent.

Independence, and the two meanings of "independent"

AA and BB are independent when P(A∩B)=P(A)P(B)P(A \cap B) = P(A)\,P(B), a property of the joint and nothing else. Here the cell is 0.24 but P(X=1)P(Y=1)=0.3×0.38=0.114P(X = 1)P(Y = 1) = 0.3 \times 0.38 = 0.114: rain and umbrellas are dependent. The experimental meaning is different: the "independent variable" is what you set or feed in (the input xx, a feature or covariate) and the "dependent variable" is what you measure (the target yy). The two meet in one sentence: learning is possible only because input and target are dependent in the probability sense. If P(y|x)=P(y)P(y \mid x) = P(y), the best any model can do is predict the base rate.

The chain rule. Applying the product rule repeatedly, with no assumption at all, p(x1,…,xn)=∏t=1np(xt|x<t)p(x_1, \dots, x_n) = \prod_{t=1}^{n} p(x_t \mid x_{\lt t}). This identity is the whole design of an autoregressive language model: it learns only the conditional p(xt|x<t)p(x_t \mid x_{\lt t}), one softmax per position, and the log of the product is the sum of per-token losses. If the earlier words had probabilities q1q_1 and q2q_2, "the cat sat" gets q1×q2×0.090q_1 \times q_2 \times 0.090 and loss −ln⁡q1−ln⁡q2+2.408-\ln q_1 - \ln q_2 + 2.408. Masked and diffusion language models factor the joint differently; perplexity and bits per byte, sums of per-token losses, are on Information theory for ML.

Conditional independence, X⟂Y|ZX \perp Y \mid Z, means P(X,Y|Z)=P(X|Z)P(Y|Z)P(X, Y \mid Z) = P(X \mid Z)\,P(Y \mid Z): once ZZ is known, the other adds nothing. It powers Naive Bayes (P(x1,…,xd|c)=∏jP(xj|c)P(x_1, \dots, x_d \mid c) = \prod_j P(x_j \mid c)), graphical models (the graph is a map of which conditional independences hold) and the i.i.d. assumption (training examples independent and identically distributed, so a dataset's probability factors into a product over examples, section 7). Dependent variables can be conditionally independent: ice-cream sales and drownings both rise in summer, and are roughly independent given the temperature.

Independence for random variables, and an independent version of the umbrella (depth)

For random variables, XX and YY are independent when P(x,y)=P(x)P(y)P(x, y) = P(x)P(y) holds for every pair of values; equivalently P(A|B)=P(A)P(A \mid B) = P(A). Had both umbrella conditionals been equal (say both 0.38), every cell would equal the product of its marginals and the two would be independent. A controlled input is not thereby statistically independent of anything. For the tiny model, the next word after "the cat" is not distributed like a random word; that dependence is what it learns.

Bayes' rule, with base rates

P(A|B)=P(B|A)P(A)P(B)=P(B|A)P(A)P(B|A)P(A)+P(B|not A)P(not A).P(A \mid B) = \frac{P(B \mid A)\, P(A)}{P(B)} = \frac{P(B \mid A)\, P(A)}{P(B \mid A)P(A) + P(B \mid \text{not } A)P(\text{not } A)}.

P(A)P(A) is the prior (for a class, its base rate), P(B|A)P(B \mid A) the likelihood, P(A|B)P(A \mid B) the posterior, and P(B)P(B) the evidence (marginal likelihood) that makes it add to 1: posterior is proportional to likelihood times prior. Counting with natural frequencies (Gigerenzer and Hoffrage, 1995, who showed people reason with them far better): of 10,000 messages with 1% toxic, 100 are toxic and 95 of those are flagged; 9,900 are clean and 495 of those are flagged. Of the 590 flagged, only 95 are toxic:

P(toxic|flag)=0.95×0.010.95×0.01+0.05×0.99=9595+495=0.161.P(\text{toxic} \mid \text{flag}) = \frac{0.95 \times 0.01}{0.95 \times 0.01 + 0.05 \times 0.99} = \frac{95}{95 + 495} = 0.161.
  1. Prior: the base rate. 1% of messages are toxic, 99% clean.
  2. Likelihood: what the flag says. P(flag|toxic)=0.95P(\text{flag} \mid \text{toxic}) = 0.95, P(flag|clean)=0.05P(\text{flag} \mid \text{clean}) = 0.05: on its own the flag looks damning.
  3. Multiply, class by class. 0.01×0.95=0.00950.01 \times 0.95 = 0.0095 against 0.99×0.05=0.04950.99 \times 0.05 = 0.0495: the clean messages produce about five times as many flags, because there are 99 times as many of them.
  4. Normalise by the evidence. Divide both by P(flag)=0.059P(\text{flag}) = 0.059 so they add to 1: P(toxic|flag)=0.161P(\text{toxic} \mid \text{flag}) = 0.161, the 95 toxic among the 590 flagged.
  5. The same filter at a 20% base rate. Prior (0.2,0.8)(0.2, 0.8): products 0.19 and 0.04, P(flag)=0.230P(\text{flag}) = 0.230, and P(toxic|flag)=0.826P(\text{toxic} \mid \text{flag}) = 0.826: now the flags are mostly right.

Predict, then drag: which lifts precision more at a 1% base rate, sensitivity from 95% to 100%, or the false positive rate from 5% to 0.5%?

Used for: reading any detector (toxicity, fraud, a judge flagging failures) against its base rate; precision against recall on imbalanced data (Evaluation metrics); correcting a classifier trained on balanced data and deployed where the class is rare (multiply its output odds by the deployment prior odds over the training prior odds, Bayes' rule applied twice); Naive Bayes; and the posterior over parameters (section 9), the same rule with AA = "the parameters are θ\theta" and BB = "the data".

The flags are mostly false alarms when the class is rare

toxic, flaggedtoxic, missedclean, flagged (false alarm)clean, not flagged

Each dot is 10 of 10,000 messages (rounded to whole dots for the picture; the numbers are exact). Defaults reproduce the 0.161 above by construction; inputs are illustrative. At a 20% base rate the same filter's flags become mostly right; at a 0.5% false positive rate and 1% base rate, precision jumps to 66%: the false positive rate matters more than sensitivity when the class is rare.

6. Softmax as a distribution, and temperature

Softmax turns any real scores into a categorical distribution, pi=ezi/∑kezkp_i = e^{z_i} / \sum_k e^{z_k}: exponentiate (everything positive), divide by the total (everything sums to 1). Two properties do most of the work:

  • Only differences of scores matter. Adding the same constant to every ziz_i cancels in the ratio: z=(2,1,0)z = (2, 1, 0) and z=(1000,999,998)z = (1000, 999, 998) are the same distribution. Ratios are exponentials of gaps: pcat/pdog=e2−1=2.718p_{\text{cat}}/p_{\text{dog}} = e^{2 - 1} = 2.718. This invariance is what makes the stable log-sum-exp possible (section 12).
  • Temperature rescales the gaps. pi(T)∝ezi/T∝pi1/Tp^{(T)}_i \propto e^{z_i / T} \propto p_i^{1/T}. At T=0.5T = 0.5 the tiny model's bet becomes (0.867,0.117,0.016)(0.867, 0.117, 0.016), the same as squaring pp and renormalising; at T=2T = 2, (0.506,0.307,0.186)(0.506, 0.307, 0.186). As T→0T \to 0 all mass goes to the top score (greedy decoding); as T→∞T \to \infty the bet becomes uniform. Dividing by T>0T \gt 0 never changes which word is top.

Predict, then drag: at T=2T = 2, is sat's probability closer to 0.09 or to 0.2? And what is the entropy at T=10T = 10, next to its ceiling ln⁡3=1.099\ln 3 = 1.099?

One knob between "always the top word" and "any word at random"

The tiny model's scores z=(2,1,0)z = (2, 1, 0) divided by TT, then softmax. T=1T = 1 is the model's own bet, (0.665,0.245,0.090)(0.665, 0.245, 0.090), entropy 0.832 nats. Values recomputed in src/recompute.py.

Temperature appears in three different jobs. Decoding: sampling at T<1T \lt 1 concentrates on likely tokens; top-k and top-p go further and cut the tail, so the sampled text is no longer a sample from the model (the sampler stack, its order and min-p, with a live lab on a real model, are on Sampling and Decoding). Calibration: one TT fitted after training fixes over- or underconfidence without touching accuracy (section 8). Distillation: soft targets at a raised temperature expose the teacher's ranking of the wrong answers (Hinton, Vinyals and Dean, 2015).

Top-k and top-p on the tiny model (depth; decoding is owned by Sampling and Decoding)

Every decoding knob replaces pp by another distribution and samples from that. Top-k: keep the kk most probable, renormalise; k=1k = 1 is greedy. Top-p (nucleus): keep the smallest set of most probable items whose total reaches a threshold (0.9 here), renormalise. At top-p 0.9: cat (0.665) is not enough, cat plus dog (0.910) is, so sat is removed and the bet becomes (0.731,0.269,0)(0.731, 0.269, 0). None of these changes the model. Sampling from a truncated distribution means the text's probability under the model is no longer what you sampled from, which matters when the samples train another model (RL, distillation).

7. From distribution to loss: maximum likelihood

A loss is not a free design choice. The recipe is three moves: (1) say which distribution yy follows given the input, with the network outputting its parameter; (2) the loss for one example is −ln⁡p(y|output)-\ln p(y \mid \text{output}); (3) drop every term that does not depend on the output. For i.i.d. examples the probability of the dataset is a product, so the log-likelihood is a sum, ln⁡p(D|θ)=∑iln⁡p(yi|xi,θ)\ln p(D \mid \theta) = \sum_i \ln p(y_i \mid x_i, \theta), and

θˆMLE=arg⁡maxθ⁡ln⁡p(D|θ)=arg⁡minθ⁡∑i=1n(−ln⁡p(yi|xi,θ)).\hat\theta_{\text{MLE}} = \arg\max_\theta \ln p(D \mid \theta) = \arg\min_\theta \sum_{i=1}^{n} \big(-\ln p(y_i \mid x_i, \theta)\big).

Training a network with BCE, cross-entropy, MSE, L1 or the Poisson loss is maximum-likelihood estimation under the matching distribution:

Why "prediction minus target" every time. Bernoulli, categorical, Gaussian (fixed σ\sigma) and Poisson are all in the exponential family, p(y|η)=h(y)exp⁡(η⊤T(y)−A(η))p(y \mid \eta) = h(y)\exp\big(\eta^\top T(y) - A(\eta)\big), where η\eta, the natural parameter, is exactly what the last layer outputs (the logit, the logits, the log-rate, the mean), T(y)T(y) is the sufficient statistic (yy or the one-hot vector) and AA is the log-partition function, the log of the normaliser. Differentiating AA gives the mean, A′(η)=𝔼[T(Y)]A'(\eta) = \mathbb{E}[T(Y)], so the NLL ℓ=A(η)−ηT(y)−ln⁡h(y)\ell = A(\eta) - \eta T(y) - \ln h(y) has

dℓdη=𝔼[T(Y)]−T(y),d2ℓdη2=A′′(η)=Var⁡(T)≥0:\frac{d\ell}{d\eta} = \mathbb{E}[T(Y)] - T(y), \qquad \frac{d^2\ell}{d\eta^2} = A''(\eta) = \operatorname{Var}(T) \ge 0:

what the model expected minus what was observed, with a curvature that is the model's own variance, independent of the label and never negative, so the loss is convex in the logits. On the tiny model with target sat, the gradient is p−esat=(0.665,0.245,−0.910)p - e_{\text{sat}} = (0.665, 0.245, -0.910), the root page's famous result; had the target been cat, ℓ=−2+2.408=0.408\ell = -2 + 2.408 = 0.408 and the gradient (−0.335,0.245,0.090)(-0.335, 0.245, 0.090). Bernoulli curvature p(1−p)p(1 - p) is 0.25 at z=0z = 0 and 0.09 at z=ln⁡9=2.197z = \ln 9 = 2.197 (where p=0.9p = 0.9): a confident output sits on a flatter part of the loss. That same number is the Hessian in the logit, the variance of the Bernoulli and its Fisher information; the three readings are on the root's "Curvature is read three ways".

Five targets, five distributions, one recipe

TargetDistribution for y|xy \mid xNetwork output and activationLoss (its NLL, constants dropped)Gradient in the output
yes or noBernoullilogit zz, sigmoidBCE: ln⁡(1+ez)−yz\ln(1 + e^z) - yzpˆ−y\hat p - y
one of KKCategoricallogits zz, softmaxcross-entropy: −zy+ln⁡∑kezk-z_y + \ln\sum_k e^{z_k}p−eyp - e_y
real numberGaussian, fixed σ\sigmamean yˆ\hat y, nonesquared error / 2σ22\sigma^2(yˆ−y)/σ2(\hat y - y)/\sigma^2
real number with outliersLaplace, fixed bbyˆ\hat y, noneabsolute error / bbsign⁡(yˆ−y)/b\operatorname{sign}(\hat y - y)/b
countPoissonlog-rate zz, expez−yze^z - yzλ−y\lambda - y

Highlighted: every row from the exponential family has a "prediction minus target" gradient. The Laplace is not in the family, so its gradient is a sign, the same size for every wrong prediction. Each row is live in the Distribution explorer (its lower panel: the loss against the network's output, gradient checked against a numerical derivative).

The numbers (spam filter, carried and rechecked)
Output pˆ=0.8\hat p = 0.8. Spam (y=1y = 1): loss −ln⁡0.8=0.223-\ln 0.8 = 0.223, gradient 0.8−1=−0.20.8 - 1 = -0.2. Not spam (y=0y = 0): loss −ln⁡0.2=1.609-\ln 0.2 = 1.609, gradient 0.80.8. The confident wrong answer costs 7.2 times the right one, without bound as it nears certainty. Squared error on a yes-or-no label is a Gaussian model of a binary outcome, the wrong distribution, and through a sigmoid it barely moves a confidently wrong model (what the logit gradient means, measured: Loss functions). The loss and the distribution are one decision.

What MLE is, in one more sentence each. The likelihood L(θ)=p(D|θ)L(\theta) = p(D \mid \theta) is not a distribution over θ\theta: a coin with 3 heads in 3 has L(p)=p3L(p) = p^3, whose area over [0,1][0, 1] is 1/41/4, not 1; turning it into one needs a prior (section 9). Dividing the NLL by nn gives the cross-entropy from the data's empirical distribution to the model, which is KL(pdata‖pθ)\text{KL}(p_{\text{data}} \,\|\, p_\theta) plus a constant, so MLE minimises forward KL and is "mass-covering" (it pays heavily for giving any observed outcome tiny probability; on Information theory for ML). And on small data it overfits: after 3 heads in 3 flips, pˆMLE=1\hat p_{\text{MLE}} = 1, a confident claim that tails is impossible, the reason for section 9. Its estimator properties (bias, variance, consistency) are on Statistics for ML.

Used for: pretraining (next-token MLE), supervised fine-tuning, every classifier and regressor; fitting any distribution's parameters (a Gaussian for anomaly detection, a Poisson for counts); why outputs are left as logits and the loss is computed on them (fused, stable, convex in the logit); which output activation goes with which target. The catalogue of losses beyond these five (focal, Huber, hinge, contrastive, z-loss) is on Loss functions; the gradient checks are in the root's Gradient lab.

Each of the five losses derived, with numbers (depth)

Bernoulli to BCE. y|x∼Bernoulli(pˆ)y \mid x \sim \text{Bernoulli}(\hat p), pˆ=σ(z)=1/(1+e−z)\hat p = \sigma(z) = 1/(1 + e^{-z}): ℓ=−[yln⁡pˆ+(1−y)ln⁡(1−pˆ)]\ell = -\big[y \ln \hat p + (1 - y)\ln(1 - \hat p)\big]. Using ln⁡pˆ=−ln⁡(1+e−z)\ln \hat p = -\ln(1 + e^{-z}) and ln⁡(1−pˆ)=−z−ln⁡(1+e−z)\ln(1 - \hat p) = -z - \ln(1 + e^{-z}): ℓ=ln⁡(1+ez)−yz\ell = \ln(1 + e^{z}) - yz, the form A(z)−zT(y)A(z) - zT(y), so ∂ℓ/∂z=σ(z)−y=pˆ−y\partial \ell / \partial z = \sigma(z) - y = \hat p - y. Through the chain rule instead, ∂ℓ/∂pˆ=(pˆ−y)/(pˆ(1−pˆ))\partial \ell/\partial \hat p = (\hat p - y)/(\hat p(1 - \hat p)) and σ′(z)=pˆ(1−pˆ)\sigma'(z) = \hat p(1 - \hat p) cancel (Calculus and optimisation for ML, section 2 has every step). PyTorch's torch.distributions.Bernoulli.log_prob is literally -binary_cross_entropy_with_logits(logits, value) (torch 2.14.1 source, saved in src/inputs/).

Categorical to softmax cross-entropy. ℓ=−ln⁡py=−zy+ln⁡∑kezk\ell = -\ln p_y = -z_y + \ln \sum_{k} e^{z_k}, ∂ℓ/∂zk=pk−[k=y]\partial \ell/\partial z_k = p_k - [k = y]: the derivative of ln⁡∑kezk\ln\sum_k e^{z_k} in zkz_k is pkp_k, that of −zy-z_y is −1-1 for k=yk = y. With K=2K = 2 and z=(z1,0)z = (z_1, 0) this is exactly sigmoid plus BCE. Tiny model, target sat: ℓ=−zsat+ln⁡11.107=0+2.408=2.408\ell = -z_{\text{sat}} + \ln 11.107 = 0 + 2.408 = 2.408; raise the right score, lower the others in proportion to the probability they took.

Gaussian to squared error. y|x∼𝒩(yˆ,σ2)y \mid x \sim \mathcal{N}(\hat y, \sigma^2), σ\sigma fixed: ℓ=(y−yˆ)22σ2+12ln⁡(2πσ2)\ell = \frac{(y - \hat y)^2}{2\sigma^2} + \tfrac12 \ln(2\pi\sigma^2), ∂ℓ/∂yˆ=(yˆ−y)/σ2\partial \ell/\partial \hat y = (\hat y - y)/\sigma^2; MSE is Gaussian maximum likelihood, and the constant minimising it over a sample is the mean. σ=1\sigma = 1, prediction 2.5, target 3: ℓ=0.125+0.919=1.044\ell = 0.125 + 0.919 = 1.044, of which only the 0.125 depends on the model; gradient −0.5-0.5. Learning the variance too (heteroscedastic regression): ℓ=12(ln⁡σ2+(y−yˆ)2/σ2)\ell = \tfrac12\big(\ln \sigma^2 + (y - \hat y)^2/\sigma^2\big) plus a constant, exactly PyTorch's gaussian_nll_loss (with full=False it drops 12ln⁡2π\tfrac12\ln 2\pi, and it clamps σ2\sigma^2 at eps; torch 2.14.1 source in src/inputs/). The optimum is σ2=(y−yˆ)2\sigma^2 = (y - \hat y)^2: with residual 0.5, the loss is 0.125 at σ2=1\sigma^2 = 1 and −0.193-0.193 at σ2=0.25\sigma^2 = 0.25. The 1/σ21/\sigma^2 weight lets the model give up on hard points by inflating σ2\sigma^2; Seitzer et al., 2022 propose the β\beta-NLL fix.

Laplace to absolute error. ℓ=|y−yˆ|/b+ln⁡2b\ell = |y - \hat y|/b + \ln 2b, gradient sign⁡(yˆ−y)/b\operatorname{sign}(\hat y - y)/b. Heavier tails than the Gaussian, so a large residual is charged linearly and one outlier cannot dominate; the minimising constant is the median. b=1b = 1, prediction 2.5, target 3: ℓ=0.5+ln⁡2=1.193\ell = 0.5 + \ln 2 = 1.193; gradient −1-1.

Poisson to the Poisson loss. λ=ez\lambda = e^{z} (the log link keeps the rate positive): ℓ=λ−yln⁡λ+ln⁡y!=ez−yz+ln⁡y!\ell = \lambda - y\ln\lambda + \ln y! = e^{z} - yz + \ln y!, gradient λ−y\lambda - y; ln⁡y!\ln y! is dropped (PyTorch's PoissonNLLLoss with log_input=True). Rate 2, observed 3: P(Y=3)=8e−2/6=0.180P(Y = 3) = 8e^{-2}/6 = 0.180, NLL 2−3ln⁡2+ln⁡6=1.7122 - 3\ln 2 + \ln 6 = 1.712, model-dependent part 2−3×0.693=−0.0792 - 3 \times 0.693 = -0.079 (a loss that drops constants can be negative); gradient −1-1.

The exponential family: the table of natural parameters, the derivation, and GLMs (depth)
Distributionη\eta (what the network outputs)T(y)T(y)A(η)A(\eta)A′(η)A'(\eta) = meanA′′(η)A''(\eta) = variance
Bernoullilogit z=ln⁡p1−pz = \ln\frac{p}{1 - p}yyln⁡(1+ez)\ln(1 + e^{z})σ(z)=p\sigma(z) = pp(1−p)p(1 - p)
Categoricallogits zz (one per class)one-hot eye_yln⁡∑kezk\ln \sum_k e^{z_k}softmax⁡(z)=p\operatorname{softmax}(z) = pdiag⁡(p)−pp⊤\operatorname{diag}(p) - pp^\top
Poissonlog-rate z=ln⁡λz = \ln\lambdayyeze^{z}λ\lambdaλ\lambda
Gaussian, σ=1\sigma = 1mean μ\muyyμ2/2\mu^2/2μ\mu1

h(y)h(y) is a base measure that does not depend on η\eta (it drops out of every gradient); A(η)=ln⁡∑yh(y)eη⊤T(y)A(\eta) = \ln \sum_y h(y) e^{\eta^\top T(y)}. Check one row by hand: py(1−p)1−y=exp⁡(yln⁡p1−p+ln⁡(1−p))p^y(1 - p)^{1 - y} = \exp\big(y \ln\frac{p}{1 - p} + \ln(1 - p)\big), and ln⁡(1−p)=−ln⁡(1+ez)\ln(1 - p) = -\ln(1 + e^z), so η=z\eta = z, T=yT = y, A=ln⁡(1+ez)A = \ln(1 + e^z), h=1h = 1. The Laplace is not in the family (|y−μ||y - \mu| cannot be written as ηT(y)\eta\, T(y)). Reference: Bishop, PRML, section 2.4; Murphy, Probabilistic Machine Learning: An Introduction, section 3.4.

Fact 1: A′A' is the mean. With the derivative of ln⁡u\ln u being u′/uu'/u:

A′(η)=∑yh(y)T(y)eηT(y)∑yh(y)eηT(y)=∑yT(y)h(y)eηT(y)−A(η)⏟p(y|η)=𝔼[T(Y)].A'(\eta) = \frac{\sum_y h(y)\, T(y)\, e^{\eta T(y)}}{\sum_y h(y)\, e^{\eta T(y)}} = \sum_y T(y)\, \underbrace{h(y)\, e^{\eta T(y) - A(\eta)}}_{p(y \mid \eta)} = \mathbb{E}[T(Y)].

Once more: A′′(η)=𝔼[T2]−𝔼[T]2=Var⁡(T)A''(\eta) = \mathbb{E}[T^2] - \mathbb{E}[T]^2 = \operatorname{Var}(T), never negative, so AA is convex. Fact 2 follows: ℓ=A(η)−ηT(y)−ln⁡h(y)\ell = A(\eta) - \eta T(y) - \ln h(y) has dℓ/dη=A′(η)−T(y)d\ell/d\eta = A'(\eta) - T(y).

When the network's output is linear in the features, this is a generalised linear model (GLM); the inverse of A′A' is the canonical link: logit for Bernoulli (logistic regression), log for Poisson (Poisson regression), identity for Gaussian (linear regression). At the maximum-likelihood optimum, the average predicted TT equals the average observed TT (set the summed gradient to zero), so a fitted logistic regression with an intercept predicts the training base rate exactly on average. The Fisher information equals A′′A'' with respect to η\eta; with respect to the weights it equals only the generalised Gauss-Newton part of the Hessian (Martens, 2020), which is what natural gradient uses. The exponential family is the maximum-entropy distribution matching given expectations (on Information theory for ML); in energy-based models, AA is the log of the partition function they cannot compute.

Two MLEs derived without skipping a step, and what MLE guarantees (depth)

The coin. hh heads and tt tails: ℓ(p)=hln⁡p+tln⁡(1−p)\ell(p) = h\ln p + t\ln(1 - p), ℓ′(p)=h/p−t/(1−p)=0\ell'(p) = h/p - t/(1 - p) = 0 gives h(1−p)=tph(1 - p) = tp, so pˆMLE=h/(h+t)\hat p_{\text{MLE}} = h/(h + t), the observed frequency. As a function of yy with θ\theta fixed the likelihood formula sums to 1; as a function of θ\theta with yy fixed it need not. The log also stops thousands of small probabilities underflowing to zero (section 12) and makes minibatch training possible.

The Gaussian. ℓ=−n2ln⁡(2πσ2)−12σ2∑i(xi−μ)2\ell = -\frac{n}{2}\ln(2\pi\sigma^2) - \frac{1}{2\sigma^2}\sum_i (x_i - \mu)^2. In μ\mu: 1σ2∑i(xi−μ)=0\frac{1}{\sigma^2}\sum_i (x_i - \mu) = 0 gives μˆ=1n∑ixi\hat\mu = \frac1n \sum_i x_i. In σ2\sigma^2: −n2σ2+12σ4∑i(xi−μ)2=0-\frac{n}{2\sigma^2} + \frac{1}{2\sigma^4}\sum_i (x_i - \mu)^2 = 0 gives σˆ2=1n∑i(xi−μˆ)2\hat\sigma^2 = \frac1n \sum_i (x_i - \hat\mu)^2. Data (2,4,4,4,5,5,7,9)(2, 4, 4, 4, 5, 5, 7, 9): μˆ=40/8=5\hat\mu = 40/8 = 5; squared deviations sum to 32, so σˆMLE2=32/8=4\hat\sigma^2_{\text{MLE}} = 32/8 = 4, against the "divide by n−1n - 1" estimate 32/7=4.57132/7 = 4.571: the MLE of the variance is biased low because μˆ\hat\mu was fitted to the same data (why, and when it matters: Statistics for ML).

Guarantees (under regularity conditions; Wasserman, All of Statistics, chapter 9). Consistent: θˆ\hat\theta converges to the true parameter as nn grows, if the model family contains it. Asymptotically efficient: in the large-data limit no consistent estimator has lower variance (it reaches the Cramér-Rao bound, the inverse Fisher information). Invariant: the MLE of g(θ)g(\theta) is g(θˆ)g(\hat\theta). MLE is the baseline that MAP and Bayesian methods correct when data is scarce.

8. Proper scoring rules and calibration, measured on real models

Could a model lower its log loss by exaggerating its confidence? No. A scoring rule S(r,y)S(r, y) charges a forecaster who announced rr when yy happened; it is proper if, when the true probability is qq, the expected charge 𝔼y∼q[S(r,y)]\mathbb{E}_{y \sim q}[S(r, y)] is lowest at r=qr = q, and strictly proper if that is the only minimum (Gneiting and Raftery, 2007). Under a strictly proper rule the best strategy is to report what you believe.

The numbers (true q=0.7q = 0.7)
Log loss: reporting 0.7 costs 0.611 on average; exaggerating to 0.9 costs 0.765; hedging to 0.5 costs 0.693. Honesty wins.
Brier score (r−y)2(r - y)^2, also strictly proper: q(1−r)2+(1−q)r2q(1 - r)^2 + (1 - q)r^2 is 0.21 at 0.7 and 0.25 at 0.9.
Absolute error |r−y||r - y| is improper: its expectation q(1−r)+(1−q)rq(1 - r) + (1 - q)r is linear in rr, 0.42 at 0.7 but 0.30 at r=1r = 1. It rewards claiming certainty, for the same reason L1 picks the median, and the median of a Bernoulli with q>0.5q \gt 0.5 is 1. Accuracy only looks at which side of 0.5 you are on, so it cannot reward honest probabilities either.
Why the log loss is strictly proper (proof)

The expected log loss is f(r)=−[qln⁡r+(1−q)ln⁡(1−r)]f(r) = -[q\ln r + (1 - q)\ln(1 - r)]. Set its derivative to zero:

f′(r)=−qr+1−q1−r=0⟹q(1−r)=r(1−q)⟹r=q,f'(r) = -\frac{q}{r} + \frac{1 - q}{1 - r} = 0 \;\Longrightarrow\; q(1 - r) = r(1 - q) \;\Longrightarrow\; r = q,

and f′′(r)=q/r2+(1−q)/(1−r)2>0f''(r) = q/r^2 + (1 - q)/(1 - r)^2 \gt 0, so it is the unique minimum. For KK classes the expected loss minus its minimum is ∑kqkln⁡(qk/rk)\sum_k q_k \ln(q_k / r_k), the KL divergence, zero only at r=qr = q (Gibbs' inequality, on Information theory for ML).

So a model trained by maximum likelihood, on data like its test data, should come out calibrated: among predictions made with confidence about 70%, about 70% are right (P(Y=yˆ|cˆ=c)=cP(Y = \hat y \mid \hat c = c) = c). A reliability diagram bins predictions by confidence (15 bins here) and plots each bin's accuracy against its confidence; the expected calibration error is the size-weighted gap (Guo et al., 2017, eq. 3):

ECE=∑b=1Bnbn|acc⁡(b)−conf⁡(b)|.\text{ECE} = \sum_{b=1}^{B} \frac{n_b}{n}\,\big|\operatorname{acc}(b) - \operatorname{conf}(b)\big|.

Measured here on two small open base models and one instruct-tuned version, predicting the next token of WikiText-2 (20,480 tokens each, top-1 confidence, computed offline):

ModelTop-1 accuracyECE at T=1T = 1NLL (nats/token)
GPT-2 (124M)35.4%0.0153.624
Qwen2.5-0.5B (base)45.7%0.0132.787
Qwen2.5-0.5B-Instruct44.1%0.0222.884

Predict, then drag: GPT-2 sits on the diagonal at T=1T = 1. At T=0.6T = 0.6, do the bars fall below the diagonal or rise above it, and does accuracy change?

Both base models are close to the diagonal: when they put 70% on their top token, they are right about 70% of the time (GPT-2's 0.700 bin: 71.7% correct; Qwen's: 64.4%, its largest gap). The instruct-tuned Qwen, run on raw text without a chat template, is slightly overconfident (average top-1 confidence 46.2% against 44.1% correct), and T=1.05T = 1.05 cuts its ECE from 0.022 to 0.012. Small models on 20,480 tokens of one Wikipedia sample (Qwen may have seen Wikipedia in training; GPT-2's WebText removed it, Radford et al., 2019, section 2.1): a demonstration of the measurement, not a ranking.

Pretrained models are close to the diagonal; one temperature moves every bar

Reliability diagram

accuracy in the bingap to the diagonal (confidence minus accuracy)share of tokens in the bin (bottom strip)

ECE and NLL against temperature

ECE (left axis)NLL in nats per token (right axis)current TT

Dividing every logit by TT before the softmax is temperature scaling. At T=0.6T = 0.6 every GPT-2 bar falls below the diagonal (overconfident: ECE 0.250 against 0.015); at 1.6 they rise above it. The instruct model's bars at T=1T = 1 sit a little below, and its best TT by NLL is 1.05. Accuracy never moves: dividing by TT keeps the top token. The NLL is proper, so the TT minimising it is the temperature-scaling fit (Guo et al. fit it on a validation set; here it is fitted and shown on the same tokens, an in-sample illustration); ECE's minimum need not coincide with it.

Calibration can be lost, by depth and by post-training, and one fitted temperature recovers much of it (evidence below). Report ECE beside the NLL or Brier score, which are proper: ECE depends on the number of bins, looks only at the top class, and scores 0 for a model that always predicts the base rate.

The evidence that calibration is lost and fixed, and what calibration is used for (depth)

Guo et al., 2017 found deep image classifiers overconfident (a 110-layer ResNet on CIFAR-100, their Figure 1, against a well-calibrated 5-layer LeNet from 1998; their Table 1 uses the same 15 bins as here) and that temperature scaling "is surprisingly effective at calibrating predictions". The GPT-4 technical report (Figure 8) says "the pre-trained model is highly calibrated" on an MMLU subset, and that "post-training hurts calibration significantly". Label smoothing changes the target, so it trades calibration of the top class for other behaviour (measured on Loss functions). Metric definitions are on Evaluation metrics; a judge's calibration on LLM-as-judge.

Used for: trusting a classifier's probability as a probability (risk thresholds, abstaining when unsure, cascades that escalate low-confidence cases); temperature scaling after training; checking a post-trained model's confidence before using it as a verifier or judge; choosing proper metrics (log loss, Brier) over accuracy when probabilities matter.

Three positions as the models saw them, and how this was computed (provenance)
  • Text: the test split of WikiText-2 (raw), Salesforce/wikitext, wikitext-2-raw-v1, concatenated; the first 20,480 tokens under each model's own tokenizer, scored in windows of 512 tokens (each window starts without earlier context, so its first tokens are hard).
  • Models: openai-community/gpt2 (124M), Qwen/Qwen2.5-0.5B (base) and Qwen/Qwen2.5-0.5B-Instruct, in float32 with transformers 5.18.0 and torch 2.14.1 on CPU; no chat template for the instruct model, so it is scored on text unlike its post-training data.
  • Measures: top-1 confidence binned into 15 equal-width bins (Guo et al., 2017, eq. 3); NLL is the average −ln⁡p(true token)-\ln p(\text{true token}) at each TT from 0.50 to 2.00 in steps of 0.05. Script src/inputs/calib.py, output src/inputs/calibration.json; src/recompute.py recomputes every ECE from the stored bins.
  • Caveats: one text sample, 20,480 tokens, three small models; Qwen's training data may include Wikipedia (GPT-2's removed it). Read the numbers as the measurement made concrete, not as a comparison of the models.

9. Priors: MAP is "loss plus regulariser", the posterior keeps every answer

Put a prior p(θ)p(\theta) on the parameters. By Bayes' rule the posterior is p(θ|D)∝p(D|θ)p(θ)p(\theta \mid D) \propto p(D \mid \theta)\,p(\theta); its peak is the MAP estimate, and its logarithm adds one term to the loss:

θˆMAP=arg⁡minθ⁡[NLL(θ)−ln⁡p(θ)].\hat\theta_{\text{MAP}} = \arg\min_\theta \big[\text{NLL}(\theta) - \ln p(\theta)\big].

So everything trained as "loss plus regulariser" is MAP under some prior. A Gaussian prior wj∼𝒩(0,τ2)w_j \sim \mathcal{N}(0, \tau^2) gives −ln⁡p(w)=∑jwj2/(2τ2)-\ln p(w) = \sum_j w_j^2/(2\tau^2) + const: L2, with λ=1/(2τ2)\lambda = 1/(2\tau^2), so a tight prior is strong regularisation. A Laplace prior gives 1b∑j|wj|\frac1b\sum_j |w_j|: L1, whose sharp point at zero drives weights exactly to zero. A Beta(a,ba, b) prior on a coin acts like a−1a - 1 heads and b−1b - 1 tails seen in advance, and a Dirichlet(2, ..., 2) prior on a categorical makes MAP add-one (Laplace) smoothing: word counts after "the" of cat 3, dog 1, sat 0 give MLE (0.75,0.25,0)(0.75, 0.25, 0), so "the sat" has probability 0 and infinite loss; add one to each count: (4,2,1)/7=(0.571,0.286,0.143)(4, 2, 1)/7 = (0.571, 0.286, 0.143).

  1. Every bet is a point. A distribution over cat, dog and sat is a point of this triangle (the tiny bet (0.665,0.245,0.090)(0.665, 0.245, 0.090) is marked); a corner is certainty. The words seen after "the": cat 3, dog 1, sat 0.
  2. The likelihood. qcat3qdogq_{\text{cat}}^3\, q_{\text{dog}}, the probability each bet gave those counts. Its peak, the MLE (0.75,0.25,0)(0.75, 0.25, 0), lies on the edge where sat is 0, so "the sat" would get probability 0 and an infinite loss. (Each surface in Fig. 5 is scaled to the same peak height; only its shape matters.)
  3. The prior Dirichlet(2, 2, 2). Proportional to qcatqdogqsatq_{\text{cat}}\, q_{\text{dog}}\, q_{\text{sat}}: zero on every edge, highest at the centre (1/3,1/3,1/3)(1/3, 1/3, 1/3). It acts like one extra sighting of each word.
  4. Posterior ∝\propto likelihood ×\times prior. qcat4qdog2qsatq_{\text{cat}}^4\, q_{\text{dog}}^2\, q_{\text{sat}}, a Dirichlet(5, 3, 2). Its peak, the MAP, (4,2,1)/7=(0.571,0.286,0.143)(4, 2, 1)/7 = (0.571, 0.286, 0.143), has moved off the edge: add-one smoothing.
  5. What "the sat" costs. −ln⁡qsat-\ln q_{\text{sat}}: infinite at the MLE, −ln⁡0.143=1.946-\ln 0.143 = 1.946 at the MAP, and 1.609 under the posterior mean (5,3,2)/10=(0.5,0.3,0.2)(5, 3, 2)/10 = (0.5, 0.3, 0.2), which is the full posterior's predictive (below).

One overconfident estimate costs an infinite loss; the posterior pays 1.253 nats

The counter adds up each method's log loss on predicting the next flip before seeing it. Credible intervals are the 2.5% and 97.5% quantiles of the Beta posterior, computed in the page by numerical integration (Simpson's rule, 4,000 panels) and checked against src/recompute.py. MLE's first prediction, before any data, is taken as 0.5. The flips are illustrative.

The full posterior goes further: bet with every parameter value, weighted by its plausibility, through the predictive distribution

p(y∗|D)=∫p(y∗|θ)p(θ|D)dθ,p(D)=∫p(D|θ)p(θ)dθ.p(y^* \mid D) = \int p(y^* \mid \theta)\, p(\theta \mid D)\, d\theta, \qquad p(D) = \int p(D \mid \theta)p(\theta)\,d\theta.

The evidence p(D)p(D) is the probability the model as a whole gave the data; it compares models. For a coin, a Beta prior is conjugate: ph(1−p)t⋅pa−1(1−p)b−1=pa+h−1(1−p)b+t−1p^{h}(1 - p)^{t} \cdot p^{a - 1}(1 - p)^{b - 1} = p^{a + h - 1}(1 - p)^{b + t - 1}, so the posterior is Beta(a+h,b+t)\text{Beta}(a + h, b + t): updating is adding counts, and the predictive probability of heads is the posterior mean a′/(a′+b′)a'/(a' + b'). With the mild prior Beta(2, 2) and 3 heads in 3: MLE 1; MAP, the mode of Beta(5, 2), 4/5=0.84/5 = 0.8; Bayesian predictive, its mean, 5/7=0.7145/7 = 0.714, with posterior standard deviation 5×2/(72×8)=0.160\sqrt{5 \times 2 / (7^2 \times 8)} = 0.160.

Predict, then step: twelve flips, H H H T H H T H T H H T. On flip 4 (the first tails), what log loss does each method pay? Before: MLE alone, one number. After: the posterior, with MLE, MAP and mean marked and the 95% credible interval shaded.

  1. Before any flip: the prior Beta(2, 2). Centred on 0.5 but wide: 95% of its mass lies between 0.094 and 0.906. It acts like one imaginary head and one imaginary tail.
  2. Three heads in three: Beta(5, 2). MAP 0.8, mean (the next-flip bet) 0.714, 95% interval 0.359 to 0.957: leaning to heads, still very unsure. Tails is possible.
  3. Flip 4 is tails: it costs 1.253 nats. The bet on tails was 2/7, so the surprise is −ln⁡(2/7)=1.253-\ln(2/7) = 1.253. The posterior moves left to Beta(5, 3).
  4. Flips 5 to 8: H H T H. Beta(8, 4): mean 0.667, 95% interval 0.390 to 0.891, narrowing as the counts add up; the running log loss is 5.394 nats.
  5. After 12 flips (8 heads, 4 tails): Beta(10, 6). MLE 0.667, MAP 0.643, mean 0.625, 95% interval 0.384 to 0.837. The answers converge as data swamps the prior; the total log loss, 8.518 nats, is minus the log of the evidence.

After flip 3 the Bayesian predictive was 5/75/7 for heads, so the tails cost −ln⁡(2/7)=1.253-\ln(2/7) = 1.253 nats, large but finite; MLE had bet 0 on tails. The Bayesian sum over all 12 predictions is 8.518 nats, and it equals exactly −ln⁡p(D)-\ln p(D), minus the log evidence of the 12 flips under Beta(2, 2): by the chain rule (section 5), the evidence is the product of the sequential predictive probabilities. After 12 flips the MLE (0.667), MAP (0.643) and mean (0.625) are close: the prior's 2 imaginary flips are being swamped.

Used for: weight decay and L1, smoothing counts, uncertainty for small data and decisions (Thompson sampling in Bandits and exploration draws from exactly this Beta posterior per arm), and model comparison by evidence; the full list is in the first block below.

Where priors are used, ridge by hand, L2 against weight decay, and why MAP is not invariant (depth)

Used for: weight decay and L1 (Gaussian and Laplace priors); smoothing counts (Dirichlet priors); label smoothing (read as a prior towards the uniform distribution); regularisation strength read as a belief about weight size; uncertainty for small data and decisions (active learning, Bayesian optimisation, Thompson sampling in Bandits and exploration, which draws from exactly this Beta posterior per arm); model comparison by evidence; the conceptual basis of VAEs and diffusion (a posterior over latent variables, approximated). Credible intervals against confidence intervals, and Bayes factors, are on Statistics for ML.

One-weight ridge regression. Fit y=wxy = wx to x=(1,2,3)x = (1, 2, 3), y=(2,3,7)y = (2, 3, 7) with Gaussian noise of variance σ2\sigma^2. The MLE minimises ∑i(yi−wxi)2\sum_i (y_i - wx_i)^2: wˆ=∑xiyi/∑xi2=29/14=2.071\hat w = \sum x_i y_i / \sum x_i^2 = 29/14 = 2.071. With the prior, the objective is ∑i(yi−wxi)2+σ2τ2w2\sum_i (y_i - wx_i)^2 + \frac{\sigma^2}{\tau^2} w^2 (the NLL times 2σ22\sigma^2); with σ2/τ2=1\sigma^2/\tau^2 = 1, wˆ=29/(14+1)=1.933\hat w = 29/(14 + 1) = 1.933, pulled towards the prior mean 0. τ2\tau^2 is the prior variance: how large you believe weights can plausibly be; ‖w‖22=∑jwj2\|w\|_2^2 = \sum_j w_j^2.

L2 is not weight decay in Adam. In adaptive optimisers an L2 term in the loss is not the same as decoupled weight decay (AdamW, Loshchilov and Hutter, 2019); the two coincide only for plain SGD. Both are on Regularisation.

MAP is not invariant to reparameterisation: the peak of a density moves when you change variables, because densities pick up a Jacobian factor. The coin's posterior Beta(5, 2) peaks at p=0.8p = 0.8; as a density over the logit η=ln⁡p1−p\eta = \ln\frac{p}{1 - p} it gains the factor dp/dη=p(1−p)dp/d\eta = p(1 - p), becomes ∝p5(1−p)2\propto p^5 (1 - p)^2, and peaks at p=5/7=0.714p = 5/7 = 0.714. The MLE has no such problem (it is invariant), nor does the full posterior: one reason to prefer the posterior to its peak, and why MAP is not "the Bayesian answer". With the flat prior Beta(1, 1), the predictive is (h+1)/(n+2)(h + 1)/(n + 2), Laplace's rule of succession (0.8 after 3 heads in 3).

When the posterior integral is intractable (depth)

For a neural network the posterior over millions of weights has no closed form, so it is approximated:

  • Variational inference: fit a simple distribution (say a Gaussian per weight) by maximising the ELBO; on Variational inference and generative-model maths.
  • Markov chain Monte Carlo (MCMC): a random walk whose visits are distributed like the posterior (Metropolis-Hastings, Hamiltonian Monte Carlo); averages over its samples estimate the predictive integral (section 4).
  • Laplace approximation: a Gaussian at the MAP with covariance the inverse Hessian of the loss (often approximated by the Fisher or K-FAC).
  • Deep ensembles: train several networks from different random initialisations and average their predictions, a cheap and strong practical approximation (Lakshminarayanan et al., 2017).

Two routes from uniform numbers to the same distribution

One uniform per draw for inverse CDF, three for Gumbel-max. Bars are frequencies after each batch; the ticks are pp. Steps go 1, 2, 3, 10, 100, 1,000, 10,000 draws; the error shrinks like 1/n1/\sqrt{n} (section 4).

10. Sampling: inverse CDF, Gumbel-max and Gumbel-softmax

A computer makes uniform numbers in [0,1)[0, 1); generation needs draws from p=(0.665,0.245,0.090)p = (0.665, 0.245, 0.090). Two exact routes:

  • Inverse CDF. Draw uu and return the first value whose CDF reaches it, x=F−1(u)x = F^{-1}(u); then P(X≤x)=P(u≤F(x))=F(x)P(X \le x) = P(u \le F(x)) = F(x). Tiny model, CDF (0.665,0.910,1)(0.665, 0.910, 1): u<0.665u \lt 0.665 gives cat, 0.665≤u<0.9100.665 \le u \lt 0.910 dog, otherwise sat; u=0.7u = 0.7 gives dog. Continuous: the exponential has F(x)=1−e−λxF(x) = 1 - e^{-\lambda x}, so x=−ln⁡(1−u)/λx = -\ln(1 - u)/\lambda; with λ=2\lambda = 2 and u=0.5u = 0.5, x=0.347x = 0.347, the median. Hugging Face transformers samples with torch.multinomial(probs, num_samples=1) (v5.18.0 generation/utils.py, excerpt in src/inputs/).
  • Gumbel-max. Add independent Gumbel noise gi=−ln⁡(−ln⁡ui)g_i = -\ln(-\ln u_i) to each logit and take the largest: arg⁡maxi⁡(zi+gi)∼Categorical⁡(softmax⁡(z))\arg\max_i (z_i + g_i) \sim \operatorname{Categorical}(\operatorname{softmax}(z)). No normalisation is needed. Uniforms u=(0.2,0.9,0.5)u = (0.2, 0.9, 0.5) give g=(−0.476,2.250,0.367)g = (-0.476, 2.250, 0.367), z+g=(1.524,3.250,0.367)z + g = (1.524, 3.250, 0.367): dog.

Predict, then step: both samplers use the same seeded uniform stream. After 10 draws, will either be within 0.05 of pp on every word? After 10,000?

  1. No draws yet. The ticks mark p=(0.665,0.245,0.090)p = (0.665, 0.245, 0.090); both samplers will land on them, by different routes.
  2. Draw 1: u=0.455u = 0.455. Below 0.665, so cat.
  3. Draw 2: u=0.308u = 0.308. Cat again.
  4. Draw 3: u=0.661u = 0.661. Just below 0.665: cat. Three draws, three cats; three draws say little about pp.
  5. 10 draws. One draw moves a frequency by 0.1, so the bars are still far from the ticks: the typical error for cat is 0.665×0.335/10=0.149\sqrt{0.665 \times 0.335 / 10} = 0.149.
  6. 100 draws. The bars close in; the error for cat is about 0.047.
  7. 1,000 draws. About 0.015 for cat.
  8. 10,000 draws. About 0.005: both routes land on pp, the error shrinking like 1/n1/\sqrt{n} (section 4).

The exponential race, how vLLM samples. Since −ln⁡(−ln⁡u)=−ln⁡E-\ln(-\ln u) = -\ln E with E=−ln⁡uE = -\ln u exponential, arg⁡maxi⁡(zi−ln⁡Ei)=arg⁡maxi⁡pi/Ei\arg\max_i (z_i - \ln E_i) = \arg\max_i\, p_i / E_i. The same draw: E=(1.609,0.105,0.693)E = (1.609, 0.105, 0.693), pi/Ei=(0.413,2.323,0.130)p_i/E_i = (0.413, 2.323, 0.130), also dog. vLLM v0.11.0's random_sample is probs.div_(q).argmax(dim=-1) with q.exponential_(), avoiding the CPU-GPU synchronisation that torch.multinomial causes, per its own comment.

Gumbel-softmax, at the level of why. An argmax has zero gradient almost everywhere, so a discrete sample blocks backpropagation. Replacing the argmax with a softmax at temperature τ\tau, softmax⁡((z+g)/τ)\operatorname{softmax}((z + g)/\tau), gives a differentiable approximate one-hot sample (the Gumbel-softmax or Concrete relaxation, Jang et al., 2017; Maddison et al., 2017): as τ→0\tau \to 0 it becomes the exact Gumbel-max sample, and at larger τ\tau it is smoother with lower-variance but biased gradients. The noise gg does not depend on zz, so it is a reparameterisation (section 11) for discrete choices. PyTorch's F.gumbel_softmax draws its Gumbels as -empty_like(logits).exponential_().log() (torch 2.14.1).

Used for: text generation; RL rollouts (GRPO and PPO sample several answers per prompt); Gumbel-top-k for sampling without replacement; Gumbel-softmax for discrete latent variables and differentiable architecture search; inverse CDF and Cholesky (section 2) for continuous draws.

Why Gumbel-max gives exactly the softmax (proof)

A standard Gumbel has CDF P(g≤x)=exp⁡(−e−x)P(g \le x) = \exp(-e^{-x}) (inverse CDF: g=−ln⁡(−ln⁡u)g = -\ln(-\ln u)). So Mj=zj+gjM_j = z_j + g_j has CDF exp⁡(−ezj−m)\exp(-e^{z_j - m}) and density ezi−mexp⁡(−ezi−m)e^{z_i - m}\exp(-e^{z_i - m}). Item ii wins when Mi=mM_i = m and every other Mj≤mM_j \le m:

P(i wins)=∫−∞∞ezi−me−ezi−m∏j≠ie−ezj−mdm=∫−∞∞ezie−mexp⁡(−Se−m)dm,S=∑jezj.P(i \text{ wins}) = \int_{-\infty}^{\infty} e^{z_i - m} e^{-e^{z_i - m}} \prod_{j \ne i} e^{-e^{z_j - m}}\, dm = \int_{-\infty}^{\infty} e^{z_i} e^{-m} \exp\!\big(-S e^{-m}\big)\, dm, \quad S = \sum_j e^{z_j}.

Substitute s=e−ms = e^{-m} (ds=−sdmds = -s\,dm): the integral becomes ∫0∞ezie−Ssds=ezi/S\int_0^\infty e^{z_i} e^{-Ss}\,ds = e^{z_i}/S, exactly the softmax.

11. Reparameterisation: why gradients can pass through a random sample

Training a VAE or a diffusion model needs ∇θ𝔼x∼pθ[f(x)]\nabla_\theta\, \mathbb{E}_{x \sim p_\theta}[f(x)], with the parameters inside the distribution being sampled. "Draw a random number" has no derivative. There are two ways round it:

  • Score function (REINFORCE, likelihood ratio): ∇θ𝔼pθ[f(x)]=𝔼pθ[f(x)∇θln⁡pθ(x)]\nabla_\theta\, \mathbb{E}_{p_\theta}[f(x)] = \mathbb{E}_{p_\theta}\big[f(x)\, \nabla_\theta \ln p_\theta(x)\big], from ∇θpθ=pθ∇θln⁡pθ\nabla_\theta p_\theta = p_\theta \nabla_\theta \ln p_\theta. It works for any distribution and any ff, even a non-differentiable reward (Williams, 1992), but it only sees ff's value, not its slope, so it is noisy: one sample x2(x−μ)=(1+ε)2εx^2 (x - \mu) = (1 + \varepsilon)^2 \varepsilon has mean 2 and variance 30.
  • Reparameterisation (pathwise): write the sample as x=gθ(ε)x = g_\theta(\varepsilon) with parameter-free noise, for a Gaussian x=μ+σεx = \mu + \sigma\varepsilon, ε∼𝒩(0,1)\varepsilon \sim \mathcal{N}(0, 1). The expectation is now over ε\varepsilon, which does not depend on θ\theta, so the gradient moves inside: ∇θ𝔼ε[f(gθ(ε))]=𝔼ε[∇xf(x)∇θgθ(ε)]\nabla_\theta\, \mathbb{E}_{\varepsilon}[f(g_\theta(\varepsilon))] = \mathbb{E}_{\varepsilon}[\nabla_x f(x)\, \nabla_\theta g_\theta(\varepsilon)]. One sample 2x=2(1+ε)2x = 2(1 + \varepsilon) has mean 2 and variance 4.

Subtracting a baseline b=𝔼[f]=2b = \mathbb{E}[f] = 2 from ff keeps the score-function mean and cuts its variance to 18, still 4.5 times the pathwise estimator's. That gap is why VAEs (Kingma and Welling, 2013) use the reparameterisation, and why policy gradients, which cannot (the reward is not differentiable in the sampled text), work so hard on baselines. The ELBO, the VAE and the diffusion loss that use it, and the variance gap measured up to 100 dimensions, are on Variational inference and generative-model maths; baselines and advantages on Policy gradients and actor-critic.

Move the randomness to an input the parameters do not touch

Same target, f(x)=x2f(x) = x^2 with x∼𝒩(μ,1)x \sim \mathcal{N}(\mu, 1) at μ=1\mu = 1 (true gradient 2μ=22\mu = 2); variances of a one-sample gradient estimate, derived exactly (a 200,000-draw simulation in src/recompute.py agrees).

The variance of the score-function estimator, worked (derivation)

𝔼[x2]=μ2+1\mathbb{E}[x^2] = \mu^2 + 1. Score function with x=1+εx = 1 + \varepsilon: variance 𝔼[(ε+2ε2+ε3)2]−4=34−4=30\mathbb{E}[(\varepsilon + 2\varepsilon^2 + \varepsilon^3)^2] - 4 = 34 - 4 = 30, using 𝔼ε2=1\mathbb{E}\varepsilon^2 = 1, 𝔼ε4=3\mathbb{E}\varepsilon^4 = 3, 𝔼ε6=15\mathbb{E}\varepsilon^6 = 15. With the baseline, (x2−2)ε=(2ε+ε2−1)ε(x^2 - 2)\varepsilon = (2\varepsilon + \varepsilon^2 - 1)\varepsilon, whose second moment is 4×3+15+1−2×3=224 \times 3 + 15 + 1 - 2 \times 3 = 22, so the variance is 22−4=1822 - 4 = 18. Pathwise: Var⁡(2+2ε)=4\operatorname{Var}(2 + 2\varepsilon) = 4.

Used for: VAEs (sampling the latent); diffusion (xt=α‾tx0+1−α‾tεx_t = \sqrt{\bar\alpha_t}\,x_0 + \sqrt{1 - \bar\alpha_t}\,\varepsilon is a reparameterisation); SAC's squashed Gaussian policy; Gumbel-softmax for discrete choices (section 10); the Cholesky sampler of section 2.

12. Log-probabilities and log-sum-exp

Probabilities of whole sequences are products of many small numbers, so every library works in log space. A 100-token sentence at the tiny model's 0.090 per token has probability 0.090100=10−104.60.090^{100} = 10^{-104.6}: below float32's smallest positive number (about 1.4×10−451.4 \times 10^{-45}), so it rounds to 0 and its log to −∞-\infty. Its log-probability, 100×(−2.408)=−240.8100 \times (-2.408) = -240.8, is an ordinary number, and products become sums (the chain rule of section 5, the i.i.d. sum of section 7).

The one place a log-probability needs care is the softmax normaliser. ln⁡py=zy−ln⁡∑kezk\ln p_y = z_y - \ln\sum_k e^{z_k}, and ln⁡∑kezk\ln\sum_k e^{z_k}, the log-sum-exp, overflows for large scores. Because softmax depends only on differences of scores (section 6), subtract the largest first:

LSE⁡(z)=ln⁡∑kezk=m+ln⁡∑kezk−m,m=maxk⁡zk.\operatorname{LSE}(z) = \ln \sum_k e^{z_k} = m + \ln \sum_k e^{z_k - m}, \qquad m = \max_k z_k.

The rule: keep logits and log-probabilities, call the fused functions (cross_entropy, log_softmax, logsumexp), never log(softmax(z)). How floats overflow and underflow, the animated naive-against-stable softmax with every intermediate's bits, log-softmax, logsigmoid and BCE with logits are on Numerical computing for ML (its sections 7 and 8); the root's Gradient lab panel 5 shows the float32 and float64 overflow points.

Subtract the max and the overflow disappears

Before: exponentiate, then normalise

scores zz(1000, 999, 998)
eze^{z} in float32(inf, inf, inf): e88.7e^{88.7} is already the largest float32
p=ez/∑ezp = e^z / \sum e^zinf / inf = NaN
loss −ln⁡psat-\ln p_{\text{sat}}NaN, and the run is lost

After: subtract the max, then exponentiate

z−mz - m(0, -1, -2)
ez−me^{z - m}(1, 0.368, 0.135), sum 1.503
pp(0.665, 0.245, 0.090): the tiny model's bet, since these scores are (2,1,0)+998(2, 1, 0) + 998
LSE⁡\operatorname{LSE}, loss1000+ln⁡1.503=1000.4081000 + \ln 1.503 = 1000.408; 1000.408−998=2.4081000.408 - 998 = 2.408

Reference

Notation you will meet in papers (reference)

The probability notation that stops readers most often, each decoded once. The root's Notation decoder tab decodes whole landmark equations.

WrittenRead asExample
x∼px \sim pxx is drawn from (distributed as) ppε∼𝒩(0,I)\varepsilon \sim \mathcal{N}(0, I)
𝔼x∼p[f(x)]\mathbb{E}_{x \sim p}[f(x)]the average of ff when xx comes from pp𝔼(x,y)∼𝒟[ℓ]\mathbb{E}_{(x, y) \sim \mathcal{D}}[\ell], the expected loss over data
pθ(y|x)p_\theta(y \mid x), p(y|x;θ)p(y \mid x; \theta), p(y|x,θ)p(y \mid x, \theta)probability of yy given xx, under parameters θ\theta (the semicolon says θ\theta is a setting, not a random variable)a language model pθ(xt|x<t)p_\theta(x_t \mid x_{\lt t})
𝒩(x;μ,Σ)\mathcal{N}(x; \mu, \Sigma)the Gaussian density evaluated at xxthe diffusion forward process
∝\proptoproportional to: equal up to a constant that makes it sum to 1posterior ∝\propto likelihood ×\times prior
X⟂Y|ZX \perp Y \mid ZXX and YY independent given ZZNaive Bayes
𝟙[⋅]\mathbb{1}[\cdot], [⋅][\cdot]1 if the condition holds, else 0accuracy =1n∑i𝟙[yˆi=yi]= \frac1n\sum_i \mathbb{1}[\hat y_i = y_i]
θˆ\hat\theta, θ∗\theta^*an estimate; the optimum or true valueθˆMLE\hat\theta_{\text{MLE}}
qϕ(z|x)q_\phi(z \mid x)an approximate posterior with its own parameters ϕ\phia VAE encoder
sg[⋅]\text{sg}[\cdot], θ‾\bar\thetastop-gradient; a frozen copytargets in RL and self-distillation
Two mistakes the sections above do not show (depth)

Assuming i.i.d. when it fails. Near-duplicate items, many items from one document, or test data leaked into training make examples dependent, so the likelihood is not a clean product and every error bar is too narrow (handled on Statistics for ML).

Forgetting that decoding changes the distribution. Text sampled at top-p 0.9 or temperature 0.7 is not a sample from the model; probabilities computed under the model do not describe it (section 6).