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.
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.
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.
| Idea | In one line | On the tiny model | Used in ML for |
|---|---|---|---|
| Distribution (1, 2) | non-negative numbers, one per outcome, adding to 1 | is a categorical distribution | every output layer |
| Expectation (3) | probability-weighted average | expected loss under its own bet = entropy, 0.832 nats | every loss is an expectation over data |
| LLN and CLT (4) | averages settle, with Gaussian error shrinking as | the mean of 100 token losses is within about 0.065 of 0.832 | minibatches, Monte Carlo, error bars |
| Conditional probability, Bayes (5) | restrict to what you know, renormalise | is | reading classifier scores against base rates |
| Chain rule (5) | a joint is a product of conditionals | a sentence's probability is the product of next-word probabilities | why language models predict one token at a time |
| Softmax and temperature (6) | scores to a distribution; sharpens or flattens it | at , | decoding, calibration, distillation |
| Exponential family (7) | one form covers Bernoulli, categorical, Gaussian, Poisson | gradient of the loss in the scores = | why every standard loss has "prediction minus target" gradients |
| Distribution to loss (7) | loss = minus the log-probability of the truth | choosing BCE, CE, MSE, L1 or Poisson loss | |
| Proper scoring, calibration (8) | the log loss rewards honest probabilities | a pretrained model's 70% should be right 70% of the time | trusting confidences; temperature scaling |
| MLE, MAP, Bayesian (7, 9) | best single answer; with a prior; keep every answer weighted | training = MLE; weight decay = MAP | regularisation, uncertainty, small data |
| Sampling (10) | turn uniform numbers into draws | a uniform number below 0.665 picks cat | text generation, RL, estimating expectations |
| Reparameterisation (11) | write a sample as a function of parameters plus fixed noise | VAEs, diffusion, low-variance gradients | |
| Log space (12) | add log-probabilities; normalise with log-sum-exp | a 100-token sentence at 0.090 per token: , log | every loss and likelihood in practice |
A random variable turns each outcome into a number; reads " is drawn from ". For the tiny model, let be the index of the next word (1 cat, 2 dog, 3 sat), so . A discrete variable has a probability mass function (PMF) that sums to 1; a continuous one has a density (PDF) whose areas are probabilities (any single value has probability 0), ; both have a cumulative distribution function (CDF) , and for a density. The tiny model's CDF steps through 0.665, 0.910, 1; the inverse CDF gives quantiles (the median is ) and is one way to sample (section 10).
For the standard Gaussian, ( is its CDF), so ; 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.
: peak density , yet the shaded area within one standard deviation is 0.6827. Its NLL at the peak is : Gaussian NLL losses can be negative, because densities above 1 are normal. A uniform on has density 2 everywhere.
Three distributions cover almost every output layer:
| Distribution | For | PMF or PDF | Mean | Variance | In ML |
|---|---|---|---|---|---|
| Bernoulli | one yes or no | , | binary labels; dropout masks | ||
| Categorical | one of | , i.e. | (one-hot) | classifiers, next token | |
| Gaussian | a real number | regression 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.
| Distribution | For | PMF or PDF | Mean | Variance | In ML |
|---|---|---|---|---|---|
| Binomial | successes in tries | an accuracy count on items | |||
| Poisson | a count per interval | clicks, events, arrivals | |||
| Laplace | a real number, heavy tails | L1 loss; L1 prior | |||
| Exponential | a waiting time | , | inter-arrival times; the "exponential race" sampler | ||
| Beta | a probability in | prior on a rate (section 9) | |||
| Dirichlet | a probability vector | prior on a categorical; topic models; smoothing |
is 1 when and 0 otherwise. counts the ways to choose which of the tries succeed. is the Beta function, the constant that makes the area 1 ( extends the factorial: ); . 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 on average, with standard deviation items (2.0 points): the noise in any single eval run. Poisson: at rate , . Laplace with has variance 2. Beta(2, 2) has mean 0.5 and standard deviation 0.224. Dirichlet(2, 1, 1) has mean .
How they relate. A Bernoulli is a categorical with and a binomial with . A binomial is a sum of independent Bernoullis (so its mean and variance are times theirs, by linearity and by variances adding). A Poisson is the limit of a binomial with many tries and a small chance each (, ). 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 for a dispersion parameter , replaces the Poisson.
The sample space lists every outcome (for the tiny model, ); an event is a set of outcomes ("the next word is an animal" is ). Everything on this page follows from three rules stated by Kolmogorov in 1933 (Foundations of the Theory of Probability, English translation, chapter 1):
Consequences: , and . Fair die: ; . Tiny model: .
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).
For with mean and covariance matrix :
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 are the ellipse's axes and the square roots of its eigenvalues their half-lengths; is the squared volume scale. Sampling: factor (Cholesky, lower triangular), draw with independent standard Gaussian entries, return ; its covariance is . This is the reparameterisation of section 11 in matrix form.
Predict, then drag: what happens to the ellipse and to as goes to 0.95? Default: , , eigenvalues 1.8 and 0.2.
Used for: Gaussian noise in diffusion models and VAEs; Gaussian processes; weight initialisation ( with 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).
400 points drawn as from a fixed seed (the same for every setting); ellipses at Mahalanobis distance 1 and 2. At the ellipse aligns with the axes; near 0.95 the cloud collapses onto a line: the smaller eigenvalue goes to 0, nears singular and blows up, the numerical trouble behind adding a small "jitter" to the diagonal. The decompositions are on Linear algebra for ML.
(an integral for densities) is the probability-weighted average; a training objective is . On the tiny model, if the next word really were drawn from its own bet, the expected loss is
the entropy of (owned by Information theory for ML). Four rules carry almost every argument in ML papers:
; needs no new distribution (the law of the unconscious statistician). Linearity in one line: . (expand the square, use linearity); the standard deviation is its square root, in the units of . . For a vector, the covariance matrix is .
Die: , a value it never shows; . Umbrella (section 5): , so ; , ; .
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 ; within , between , 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.
Birthday collisions. With 23 people and 365 equally likely birthdays, the chance that all differ is , so at least one pair shares a birthday with probability 0.5073: just over even odds. There are pairs, each with a 1/365 chance, and a collision becomes likely after about draws from values (Birthday problem). Collisions arrive after about draws, not : hashing into 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 classes, a new one appears with probability , a geometric wait of draws on average; expectations add, so seeing every class takes draws on average, about three times the number of classes, and the last class alone takes 10. In general (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.
Top: one stream of draws from , its running mean against (log scale) with the band . Bottom: 2,000 independent averages of draws each, histogram against the CLT's curve, on a fixed axis. Seeded generator (mulberry32); src/recompute.py reruns the same generator and reproduces every counter.
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:
Two theorems say why this works. The law of large numbers: converges to as grows (it is unbiased by linearity). The central limit theorem: for finite variance, the error is close to Gaussian with standard deviation , whatever the shape of 's distribution. On the tiny model, 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 token losses per average, how wide is the spread of the averages? (Answer: ; 10,000 draws give 0.0065.) And at , does "within 1.96 standard errors" catch 95% of draws?
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 , 4.6 points). Where the Gaussian approximation fails (heavy tails, infinite variance, small 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.
If you can only sample from , reweight: . The ratio is the importance weight; with uniform over the tiny model's three words, the weights are . It is unbiased but its variance explodes when puts little mass where 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).
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%.)
The umbrella example (carried from the old page and rechecked): "it rained", ; "carried an umbrella", with and . The joint distribution, one cell per pair:
| umbrella | no umbrella | row sum: | |
|---|---|---|---|
| rain | 0.24 | 0.06 | 0.30 |
| dry | 0.14 | 0.56 | 0.70 |
| column sum: | 0.38 | 0.62 | 1 |
and are independent when , a property of the joint and nothing else. Here the cell is 0.24 but : rain and umbrellas are dependent. The experimental meaning is different: the "independent variable" is what you set or feed in (the input , a feature or covariate) and the "dependent variable" is what you measure (the target ). The two meet in one sentence: learning is possible only because input and target are dependent in the probability sense. If , the best any model can do is predict the base rate.
The chain rule. Applying the product rule repeatedly, with no assumption at all, . This identity is the whole design of an autoregressive language model: it learns only the conditional , one softmax per position, and the log of the product is the sum of per-token losses. If the earlier words had probabilities and , "the cat sat" gets and loss . 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, , means : once is known, the other adds nothing. It powers Naive Bayes (), 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.
For random variables, and are independent when holds for every pair of values; equivalently . 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.
is the prior (for a class, its base rate), the likelihood, the posterior, and 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:
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 = "the parameters are " and = "the data".
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.
Softmax turns any real scores into a categorical distribution, : exponentiate (everything positive), divide by the total (everything sums to 1). Two properties do most of the work:
Predict, then drag: at , is sat's probability closer to 0.09 or to 0.2? And what is the entropy at , next to its ceiling ?
The tiny model's scores divided by , then softmax. is the model's own bet, , entropy 0.832 nats. Values recomputed in src/recompute.py.
Temperature appears in three different jobs. Decoding: sampling at 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 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).
Every decoding knob replaces by another distribution and samples from that. Top-k: keep the most probable, renormalise; 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 . 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).
A loss is not a free design choice. The recipe is three moves: (1) say which distribution follows given the input, with the network outputting its parameter; (2) the loss for one example is ; (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, , and
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 ) and Poisson are all in the exponential family, , where , the natural parameter, is exactly what the last layer outputs (the logit, the logits, the log-rate, the mean), is the sufficient statistic ( or the one-hot vector) and is the log-partition function, the log of the normaliser. Differentiating gives the mean, , so the NLL has
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 , the root page's famous result; had the target been cat, and the gradient . Bernoulli curvature is 0.25 at and 0.09 at (where ): 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".
| Target | Distribution for | Network output and activation | Loss (its NLL, constants dropped) | Gradient in the output |
|---|---|---|---|---|
| yes or no | Bernoulli | logit , sigmoid | BCE: | |
| one of | Categorical | logits , softmax | cross-entropy: | |
| real number | Gaussian, fixed | mean , none | squared error / | |
| real number with outliers | Laplace, fixed | , none | absolute error / | |
| count | Poisson | log-rate , exp |
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).
What MLE is, in one more sentence each. The likelihood is not a distribution over : a coin with 3 heads in 3 has , whose area over is , not 1; turning it into one needs a prior (section 9). Dividing the NLL by gives the cross-entropy from the data's empirical distribution to the model, which is 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, , 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.
Bernoulli to BCE. , : . Using and : , the form , so . Through the chain rule instead, and 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. , : the derivative of in is , that of is for . With and this is exactly sigmoid plus BCE. Tiny model, target sat: ; raise the right score, lower the others in proportion to the probability they took.
Gaussian to squared error. , fixed: , ; MSE is Gaussian maximum likelihood, and the constant minimising it over a sample is the mean. , prediction 2.5, target 3: , of which only the 0.125 depends on the model; gradient . Learning the variance too (heteroscedastic regression): plus a constant, exactly PyTorch's gaussian_nll_loss (with full=False it drops , and it clamps at eps; torch 2.14.1 source in src/inputs/). The optimum is : with residual 0.5, the loss is 0.125 at and at . The weight lets the model give up on hard points by inflating ; Seitzer et al., 2022 propose the -NLL fix.
Laplace to absolute error. , gradient . Heavier tails than the Gaussian, so a large residual is charged linearly and one outlier cannot dominate; the minimising constant is the median. , prediction 2.5, target 3: ; gradient .
Poisson to the Poisson loss. (the log link keeps the rate positive): , gradient ; is dropped (PyTorch's PoissonNLLLoss with log_input=True). Rate 2, observed 3: , NLL , model-dependent part (a loss that drops constants can be negative); gradient .
| Distribution | (what the network outputs) | = mean | = variance | ||
|---|---|---|---|---|---|
| Bernoulli | logit | ||||
| Categorical | logits (one per class) | one-hot | |||
| Poisson | log-rate | ||||
| Gaussian, | mean | 1 |
is a base measure that does not depend on (it drops out of every gradient); . Check one row by hand: , and , so , , , . The Laplace is not in the family ( cannot be written as ). Reference: Bishop, PRML, section 2.4; Murphy, Probabilistic Machine Learning: An Introduction, section 3.4.
Fact 1: is the mean. With the derivative of being :
Once more: , never negative, so is convex. Fact 2 follows: has .
When the network's output is linear in the features, this is a generalised linear model (GLM); the inverse of 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 equals the average observed (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 with respect to ; 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, is the log of the partition function they cannot compute.
The coin. heads and tails: , gives , so , the observed frequency. As a function of with fixed the likelihood formula sums to 1; as a function of with fixed it need not. The log also stops thousands of small probabilities underflowing to zero (section 12) and makes minibatch training possible.
The Gaussian. . In : gives . In : gives . Data : ; squared deviations sum to 32, so , against the "divide by " estimate : the MLE of the variance is biased low because 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: converges to the true parameter as 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 is . MLE is the baseline that MAP and Bayesian methods correct when data is scarce.
Could a model lower its log loss by exaggerating its confidence? No. A scoring rule charges a forecaster who announced when happened; it is proper if, when the true probability is , the expected charge is lowest at , 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 expected log loss is . Set its derivative to zero:
and , so it is the unique minimum. For classes the expected loss minus its minimum is , the KL divergence, zero only at (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 (). 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):
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):
| Model | Top-1 accuracy | ECE at | NLL (nats/token) |
|---|---|---|---|
| GPT-2 (124M) | 35.4% | 0.015 | 3.624 |
| Qwen2.5-0.5B (base) | 45.7% | 0.013 | 2.787 |
| Qwen2.5-0.5B-Instruct | 44.1% | 0.022 | 2.884 |
Predict, then drag: GPT-2 sits on the diagonal at . At , 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 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.
Dividing every logit by before the softmax is temperature scaling. At 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 sit a little below, and its best by NLL is 1.05. Accuracy never moves: dividing by keeps the top token. The NLL is proper, so the 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.
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.
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).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.src/inputs/calib.py, output src/inputs/calibration.json; src/recompute.py recomputes every ECE from the stored bins.Put a prior on the parameters. By Bayes' rule the posterior is ; its peak is the MAP estimate, and its logarithm adds one term to the loss:
So everything trained as "loss plus regulariser" is MAP under some prior. A Gaussian prior gives + const: L2, with , so a tight prior is strong regularisation. A Laplace prior gives : L1, whose sharp point at zero drives weights exactly to zero. A Beta() prior on a coin acts like heads and 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 , so "the sat" has probability 0 and infinite loss; add one to each count: .
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
The evidence is the probability the model as a whole gave the data; it compares models. For a coin, a Beta prior is conjugate: , so the posterior is : updating is adding counts, and the predictive probability of heads is the posterior mean . With the mild prior Beta(2, 2) and 3 heads in 3: MLE 1; MAP, the mode of Beta(5, 2), ; Bayesian predictive, its mean, , with posterior standard deviation .
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.
After flip 3 the Bayesian predictive was for heads, so the tails cost 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 , 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.
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 to , with Gaussian noise of variance . The MLE minimises : . With the prior, the objective is (the NLL times ); with , , pulled towards the prior mean 0. is the prior variance: how large you believe weights can plausibly be; .
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 ; as a density over the logit it gains the factor , becomes , and peaks at . 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 , Laplace's rule of succession (0.8 after 3 heads in 3).
For a neural network the posterior over millions of weights has no closed form, so it is approximated:
One uniform per draw for inverse CDF, three for Gumbel-max. Bars are frequencies after each batch; the ticks are . Steps go 1, 2, 3, 10, 100, 1,000, 10,000 draws; the error shrinks like (section 4).
A computer makes uniform numbers in ; generation needs draws from . Two exact routes:
torch.multinomial(probs, num_samples=1) (v5.18.0 generation/utils.py, excerpt in src/inputs/).Predict, then step: both samplers use the same seeded uniform stream. After 10 draws, will either be within 0.05 of on every word? After 10,000?
The exponential race, how vLLM samples. Since with exponential, . The same draw: , , 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 , , gives a differentiable approximate one-hot sample (the Gumbel-softmax or Concrete relaxation, Jang et al., 2017; Maddison et al., 2017): as it becomes the exact Gumbel-max sample, and at larger it is smoother with lower-variance but biased gradients. The noise does not depend on , 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.
A standard Gumbel has CDF (inverse CDF: ). So has CDF and density . Item wins when and every other :
Substitute (): the integral becomes , exactly the softmax.
Training a VAE or a diffusion model needs , with the parameters inside the distribution being sampled. "Draw a random number" has no derivative. There are two ways round it:
Subtracting a baseline from 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.
Same target, with at (true gradient ); variances of a one-sample gradient estimate, derived exactly (a 200,000-draw simulation in src/recompute.py agrees).
. Score function with : variance , using , , . With the baseline, , whose second moment is , so the variance is . Pathwise: .
Used for: VAEs (sampling the latent); diffusion ( is a reparameterisation); SAC's squashed Gaussian policy; Gumbel-softmax for discrete choices (section 10); the Cholesky sampler of section 2.
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 : below float32's smallest positive number (about ), so it rounds to 0 and its log to . Its log-probability, , 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. , and , the log-sum-exp, overflows for large scores. Because softmax depends only on differences of scores (section 6), subtract the largest first:
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.
| scores | (1000, 999, 998) |
| in float32 | (inf, inf, inf): is already the largest float32 |
| inf / inf = NaN | |
| loss | NaN, and the run is lost |
| (0, -1, -2) | |
| (1, 0.368, 0.135), sum 1.503 | |
| (0.665, 0.245, 0.090): the tiny model's bet, since these scores are | |
| , loss | ; |
The probability notation that stops readers most often, each decoded once. The root's Notation decoder tab decodes whole landmark equations.
| Written | Read as | Example |
|---|---|---|
| is drawn from (distributed as) | ||
| the average of when comes from | , the expected loss over data | |
| , , | probability of given , under parameters (the semicolon says is a setting, not a random variable) | a language model |
| the Gaussian density evaluated at | the diffusion forward process | |
| proportional to: equal up to a constant that makes it sum to 1 | posterior likelihood prior | |
| and independent given | Naive Bayes | |
| , | 1 if the condition holds, else 0 | accuracy |
| , | an estimate; the optimum or true value | |
| an approximate posterior with its own parameters | a VAE encoder | |
| , | stop-gradient; a frozen copy | targets in RL and self-distillation |
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).
Pick a distribution and move its parameters. The top panel draws its PMF or PDF (and CDF), samples from it with a fixed seed, and checks the sample mean and variance against the formulas of the Reading's section 1. The bottom panel reads the same distribution as a loss: fix an observed target , and see the negative log-likelihood as a function of what the network outputs (the natural parameter where there is one, section 7), with its gradient checked against a numerical derivative.
Try: Bernoulli with : the loss is , flat for confident right answers and a straight line of slope for confident wrong ones, and the gradient is exactly . Gaussian against Laplace with the same target: a parabola with a linear gradient against a V with a constant one. Poisson: the loss is not symmetric in the log-rate.
Samples use a seeded generator (mulberry32) with Box-Muller for Gaussians, inverse CDF for the exponential and Laplace, Knuth's multiplication method for the Poisson, sums of Bernoullis for the binomial, Gamma draws (Marsaglia and Tsang, 2000) for Beta and Dirichlet. Formulas: Bishop, PRML, appendix B. Defaults and every formula value are checked against src/recompute.py by src/check_page.mjs.
Reading times for knowledge base pages are taken from each page's own stated time where it gives one, otherwise estimated at about 230 words a minute. Times for outside resources are for the part recommended, checked on 5 October 2026. Every link opens in a new tab.
Nine distributions: PMF or PDF, CDF and seeded samples checked against the mean and variance formulas, then each one read as a loss with its gradient against a numerical derivative.
Which maths each part of ML uses, the tiny model's training step with every number and its owner, then cross-entropy four ways and how to read an equation. Its tabs: Notation decoder, Gradient lab (losses with analytic against numerical gradients, Bernoulli curvature). 13 min, plus 4 in closed details.
Estimators, bias and variance, where the central limit theorem fails, concentration, the bootstrap, hypothesis tests: everything this page hands over after MLE. 31 min, plus 6 in closed details.
Entropy, cross-entropy, KL and mutual information: the log loss read as a code length, MLE as minimising forward KL. 38 min, plus 8 in closed details.
The ELBO, VAEs and diffusion: where sections 9 and 11 lead. 23 min, plus 18 in closed details.
Covariance matrices, quadratic forms, Cholesky and eigendecompositions behind the multivariate Gaussian. 45 min, plus 13 in closed details.
Jacobians, layouts and vector-Jacobian products: the softmax Jacobian in its backprop role. 32 min, plus 22 in closed details.
Derivatives to convexity, Hessians and Newton: why the losses of section 7 are convex in the logits, and how they are minimised. 32 min, plus 11 in closed details.
Floating point and the stable softmax and log-sum-exp that every loss of section 7 is computed with (section 12 here is the short version). 40 min, plus 9 in closed details.
Every loss as a noise model, the statistic each one picks, robust and classification losses, z-loss; label smoothing and calibration measured. 31 min, plus 5 in closed details.
Temperature, top-k, top-p, min-p and the rest on a real model (Sampler lab), and twelve decoders on real text. 19 min, plus 4 in closed details.
L1, L2, weight decay against L2 in Adam, dropout; the MAP reading of section 9 in practice. 32 min, plus 8 in closed details.
Error bars, paired tests and how many eval items you need, measured on real evals. 25 min, plus 11 in closed details.
Precision, recall and base rates (section 5), log loss, Brier and calibration (section 8) among the metrics. 27 min, plus 7 in closed details.
Judges' biases and calibration. 29 min, plus 7 in closed details.
Thompson sampling with Beta posteriors per arm, the coin of section 9 put to work. About 27 min.
The score-function estimator of section 11 with baselines, advantages, importance ratios (PPO). 45 min, plus 9 in closed details.
Logistic regression, Naive Bayes and other models whose probabilistic form is on this page. 29 min, plus 8 in closed details.
Gaussian noise, reparameterised forward process and a variational bound, with live toy models. About 25 min.
Interactive chapters on basic probability, compound probability, distributions and Bayesian inference. When: first, if sections 1 to 5 felt rusty. About 1 h for chapters 1 to 3 and 5.
The best book for rebuilding intuition: conditional probability (ch. 2), random variables (ch. 3 to 5), joint distributions (ch. 7), with the free lecture videos. When: to make sections 1 to 5 automatic. About 10 to 15 h for ch. 1 to 7.
Chapter 6 (probability and distributions, conjugacy, the exponential family) and section 8.3 (MLE and MAP) at exactly this page's level. Free PDF. About 1 h 10 min for ch. 6, 30 min for 8.3.
Chapters 2 and 3 (univariate and multivariate models, the exponential family in 3.4), chapter 4 (MLE, MAP, Bayesian, conjugate priors). Free PDF. When: the reference for every section here. About 6 h for ch. 2 to 4.
Section 1.2 (probability theory), chapter 2 (distributions, 2.4 the exponential family), appendix B (every distribution's moments), chapter 11 (sampling). Free PDF. About 4 h for ch. 1.2 and 2.
The fastest serious route through estimation: chapter 9 for MLE's properties, chapter 11 for Bayesian inference. Carried from the old page. About 3 h for ch. 9 and 11.
A compact refresher; the main notes derive the losses as GLM maximum likelihood (part III). Carried from the old page. About 1 h; main notes part III about 1 h.
Chapters 2 (simple Monte Carlo), 4 (random variable generation, inverse CDF) and 9 (importance sampling). When: research depth on sections 4 and 10. About 4 h.
The theory of section 8: which scores reward honesty, and why. About 1 h 30 min.
Reliability diagrams, ECE with 15 bins, temperature scaling. About 40 min.
Score-function, pathwise and measure-valued estimators compared, with variance analyses: the research version of section 11. About 2 h.
The reparameterisation trick, section 2.4. About 40 min.
Gumbel-max, Gumbel-top-k and Gumbel-softmax, with their uses. About 1 h.
The relaxation of section 10. About 30 min.