Probability from first principles¶
Probability is bookkeeping for uncertainty: three axioms, one definition (conditioning) and one operation (expectation). Every model in modern AI, from a spam filter to a frontier LLM, is a machine that outputs a probability distribution, and every training loss is an expectation.
10,000 ft
A language model does not output a word; it outputs a distribution over the next token and then samples from it. A classifier outputs \(p(y \mid \mathbf{x})\). A diffusion model learns to draw samples from the distribution of images. A reinforcement-learning policy is a distribution over actions. Training minimises an expected loss, and every benchmark score is an estimate with an error bar. Probability is the shared language of all of it. This page builds that language from the axioms; the distributions page stocks it with the shapes AI actually uses, estimation turns it into learning, information theory turns it into the cross-entropy loss, and statistics for evals turns it into honest measurement.
2,000 ft
Start with the set of everything that could happen (the sample space). Questions you can ask about the outcome are events (subsets). A probability assigns each event a number obeying three axioms. A random variable is a function that turns an outcome into a number; its distribution says how likely each value is. Conditioning restricts the world to the part where something is known and rescales; from it come the product rule, the chain rule (the factorisation every autoregressive LLM uses) and Bayes' rule. Expectation averages a quantity over the distribution; losses, risks and metrics are expectations, and sample averages converge to them at a rate of \(1/\sqrt{n}\).
Ground level¶
Outcomes, events and three axioms¶
Roll two fair dice. The sample space \(\Omega\) is the set of all 36 ordered pairs \((1,1), (1,2), \dots, (6,6)\). An event is any question with a yes/no answer about the outcome, represented as the set of outcomes where the answer is yes: "the sum is 7" is the event \(\{(1,6),(2,5),(3,4),(4,3),(5,2),(6,1)\}\). A probability is a function \(P\) from events to numbers obeying three rules, written down by Andrey Kolmogorov in 1933:
- Non-negativity. \(P(A) \ge 0\) for every event \(A\).
- Normalisation. \(P(\Omega) = 1\): something happens.
- Additivity. If \(A_1, A_2, \dots\) are disjoint (no outcome in two of them), then \(P(A_1 \cup A_2 \cup \cdots) = P(A_1) + P(A_2) + \cdots\).
That is all. With fair dice each of the 36 outcomes gets \(1/36\), so additivity gives \(P(\text{sum}=7) = 6/36 = 1/6\). Everything else on this page is derived from these three lines plus a definition of conditioning. For instance, \(A\) and its complement \(A^c\) are disjoint and together make \(\Omega\), so \(P(A) + P(A^c) = 1\); and since \(A \cup B\) splits into the disjoint pieces \(A\) and \(B \setminus A\), you get inclusion–exclusion, \(P(A \cup B) = P(A) + P(B) - P(A \cap B)\).
Probability is area
Picture \(\Omega\) as a unit square and each event as a region. Probability is the region's area. Disjoint regions add; the whole square has area 1; overlap is subtracted once so it is not counted twice. Conditioning (below) is zooming into one region and calling its area 1.
Random variables are functions¶
A random variable is neither random nor a variable: it is a function \(X: \Omega \to \mathbb{R}\) that turns an outcome into a number. "The sum of the two dice" is the function \(X(a,b) = a + b\). The randomness lives in which outcome occurs; \(X\) just reads a number off it. This matters in AI because one outcome supports many random variables at once. One draw of a training example \((\mathbf{x}, y)\) gives you the input, the label, the model's prediction, the loss and the gradient: five random variables, all functions of the same draw.
The distribution of \(X\) is the list of probabilities of its values. For a discrete \(X\) it is a probability mass function (PMF), \(p(x) = P(X = x)\); for the dice sum, \(p(7) = 6/36\) and \(p(2) = p(12) = 1/36\). Every random variable also has a cumulative distribution function (CDF), \(F(x) = P(X \le x)\), which rises from 0 to 1 and is the object that makes sampling possible (see Sampling).
Continuous variables and the density trap¶
For a continuous quantity (a weight, a latent vector, a pixel intensity) every single value has probability zero: \(P(X = 0.5) = 0\), because there are uncountably many values to share the mass. Instead we describe it by a probability density function (PDF) \(p(x)\) such that
A density is probability per unit length, not a probability. It must integrate to 1 but can exceed 1 anywhere: the uniform distribution on \([0, 0.5]\) has density 2 on that interval. This is why a model's log-likelihood on continuous data can be positive, and why the "bits per dimension" reported for image models depends on how pixels were discretised before the density was evaluated.
A density is not a probability
\(p(x) = 3.2\) is perfectly legal; \(P(A) = 3.2\) never is. When you compare densities across models, both must be densities over the same space with the same units, or the comparison is meaningless.
Joint, marginal and conditional: one worked table¶
Suppose you evaluate a model on a benchmark whose questions come in three difficulty levels. Pick a question at random; the outcome has two random variables, difficulty \(D\) and whether the model was correct \(C\). Their joint distribution \(p(d, c)\) is a table that sums to 1:
| correct | wrong | marginal \(p(d)\) | |
|---|---|---|---|
| easy | 0.45 | 0.05 | 0.50 |
| medium | 0.21 | 0.09 | 0.30 |
| hard | 0.06 | 0.14 | 0.20 |
| marginal \(p(c)\) | 0.72 | 0.28 | 1.00 |
- Marginalising sums out the variable you don't care about: overall accuracy is \(p(\text{correct}) = 0.45 + 0.21 + 0.06 = 0.72\). This is the sum rule, \(p(c) = \sum_d p(d, c)\).
- Conditioning restricts to a row or column and renormalises: accuracy on hard questions is \(p(\text{correct} \mid \text{hard}) = 0.06 / 0.20 = 0.30\).
- Conditioning the other way answers a different question: among the failures, how many are hard? \(p(\text{hard} \mid \text{wrong}) = 0.14 / 0.28 = 0.50\). Half the errors come from a fifth of the questions.
The headline accuracy 0.72 is a mixture of 0.90, 0.70 and 0.30 weighted by how many questions of each kind the benchmark happens to contain: \(0.5 \times 0.90 + 0.3 \times 0.70 + 0.2 \times 0.30 = 0.72\). That is the law of total probability, and it is why changing the mix of a benchmark can move a score with no change to the model. Two models compared on differently mixed test sets can even reverse order (Simpson's paradox); statistics for evals returns to this.
The chain rule is the language model¶
Conditioning rearranges into the product rule: \(p(a, b) = p(a)\, p(b \mid a)\). Apply it repeatedly and you get the chain rule of probability, which holds for any joint distribution with no assumptions at all:
This one identity is the design of every autoregressive language model, from Shannon's 1948 \(n\)-gram experiments through Bengio et al.'s neural language model to GPT-style transformers: learn the conditional \(p(x_t \mid x_{<t})\) well, and you have the whole joint distribution over text, both to score a sentence (multiply the conditionals) and to generate one (sample them left to right). The model families differ only in how much of \(x_{<t}\) they look at and how they compute the conditional.
A worked example with a bigram model (each word conditioned on the previous one only) built from the counts in "the cat sat . the cat ran . the dog sat .": after "the", "cat" followed twice and "dog" once, so \(p(\text{cat} \mid \text{the}) = 2/3\). Then
and \(p(\text{dog ran .} \mid \text{the}) = \tfrac13 \times 0 \times 1 = 0\), because "dog ran" never occurred. A single unseen pair zeroes the whole sentence. Fixing that (smoothing, or better, a model that generalises across similar words) is where estimation and neural networks come in. In practice we add log-probabilities instead of multiplying probabilities, since a product of thousands of numbers below 1 underflows; see numerical computing.
Bayes' rule: reversing a conditional¶
The product rule can be written two ways, \(p(a)\,p(b \mid a) = p(b)\,p(a \mid b)\). Divide and you have Bayes' rule:
It converts the conditional you can measure into the one you want. A worked example: an automated checker flags hallucinated answers. It catches 90% of real hallucinations (sensitivity), wrongly flags 5% of good answers (false-positive rate), and 2% of answers are actually hallucinated (the base rate). An answer gets flagged. How likely is it to be a real hallucination?
Only about 27%. The check is good, yet most of its flags are false alarms, because good answers outnumber bad ones 49 to 1. The cleanest way to see it is to count 10,000 answers, the "natural frequency" format that Gigerenzer and Hoffrage (1995) showed people reason about far more accurately than percentages:
Three readings of Bayes' rule are worth keeping apart. As arithmetic it is the identity above. As inference it updates a prior belief \(p(a)\) into a posterior \(p(a \mid b)\) after seeing evidence \(b\); the likelihood \(p(b \mid a)\) says how well each hypothesis predicted what you saw. As a design pattern it says that a generative model of how data arises, \(p(b \mid a)\), plus a prior, gives you a classifier for free. Naive Bayes spam filters, the "noisy channel" view of speech recognition and machine translation, and Bayesian deep learning are all this pattern.
Confusing \(p(a \mid b)\) with \(p(b \mid a)\)
"90% of hallucinations get flagged" is not "90% of flags are hallucinations". Swapping the two is the prosecutor's fallacy, and it is the most common probability error in model evaluation, fraud detection and medical AI. Always ask what the base rate is.
Independence, conditional independence and i.i.d.¶
Events \(A\) and \(B\) are independent if knowing one tells you nothing about the other: \(p(A \mid B) = p(A)\), equivalently \(p(A, B) = p(A)\,p(B)\). In the table above, difficulty and correctness are clearly not independent: \(p(\text{easy}, \text{correct}) = 0.45\) but \(p(\text{easy})\,p(\text{correct}) = 0.36\).
Conditional independence, \(p(A, B \mid C) = p(A \mid C)\,p(B \mid C)\), is the more useful idea, and it neither implies nor is implied by plain independence. Take a coin whose bias you don't know; it is either fair or always lands heads, with equal prior probability. Given the coin, two flips are independent. Without knowing the coin, they are not: seeing heads on the first flip makes the "always heads" coin more likely, which raises the chance of heads on the second (from 0.75 to \(\frac{0.5 \cdot 1 + 0.5 \cdot 0.25}{0.75} = 0.833\)). This is exactly the situation of training data: examples are modelled as independent given the true data distribution, which is unknown, so seeing some examples does tell you about the next.
Machine learning leans on such assumptions everywhere:
- i.i.d. data (independent and identically distributed) lets the likelihood of a dataset factor into a product over examples, which becomes a sum of per-example losses after a log. When deployment data is drawn from a different distribution, the assumption breaks; that is distribution shift (see data in production).
- Naive Bayes assumes features are conditionally independent given the class. Wrong in almost every real case, it still ranks classes well but produces overconfident probabilities.
- The Markov assumption cuts the chain rule's conditioning set down to the last \(k\) tokens (\(n\)-gram models) or one hidden state (RNNs, state-space models). Transformers are interesting precisely because they keep the whole \(x_{<t}\), up to the context length.
- Graphical models (see probabilistic graphical models) are a language for writing down which conditional independences hold.
Expectation is where the loss lives¶
The expectation of a random variable is its probability-weighted average, \(\mathbb{E}[X] = \sum_x x\, p(x)\) (or \(\int x\, p(x)\, dx\)). For the dice sum it is 7. You rarely need \(\mathbb{E}[X]\) alone; you need the expectation of some function of it, and the law of the unconscious statistician says you can compute it directly from \(X\)'s distribution: \(\mathbb{E}[g(X)] = \sum_x g(x)\, p(x)\).
Training a model is minimising an expectation. With data distribution \(\mathcal{D}\), model parameters \(\theta\) and per-example loss \(\ell\), the quantity you actually care about is the risk
which you cannot compute, because you don't have \(\mathcal{D}\), only a sample from it. So you minimise the empirical risk, the average loss over the training set, and you estimate its gradient on a minibatch of \(B\) examples. Because expectation is linear, the minibatch gradient is an unbiased estimate of the full gradient: right on average, noisy in any single step. The code below measures this on a linear-regression problem: averaged over 4,000 draws, the minibatch gradient matches the full-data gradient to two decimals for every batch size, while the noise in a single minibatch gradient falls from 1.90 at \(B=8\) to 0.67 at \(B=64\) and 0.23 at \(B=512\), a factor of about \(\sqrt{8} \approx 2.83\) for each eightfold increase. That \(1/\sqrt{B}\) law is why doubling the batch does not halve the number of steps you need, and it is the starting point of every argument about batch size and learning rate (see optimisers).
Linearity of expectation, \(\mathbb{E}[aX + bY] = a\,\mathbb{E}[X] + b\,\mathbb{E}[Y]\), holds whether or not \(X\) and \(Y\) are independent. It is the most useful fact in this page. It is why the expected accuracy of a model is the average of its per-question probabilities of being right, why the loss of a sequence is the sum of per-token losses, and why you can reason about the expected number of anything (bugs, tokens, collisions) without knowing the joint distribution.
Variance, covariance and the square-root law¶
Variance measures spread: \(\operatorname{Var}(X) = \mathbb{E}[(X - \mu)^2] = \mathbb{E}[X^2] - \mu^2\) with \(\mu = \mathbb{E}[X]\); the standard deviation is its square root, in the units of \(X\). Covariance measures whether two variables move together, \(\operatorname{Cov}(X, Y) = \mathbb{E}[(X - \mu_X)(Y - \mu_Y)]\), and correlation is covariance divided by both standard deviations, a number in \([-1, 1]\).
The rule that runs most of experimental AI: if \(X_1, \dots, X_n\) are independent with variance \(\sigma^2\), their mean \(\bar{X}\) has variance \(\sigma^2 / n\), so its standard deviation is \(\sigma / \sqrt{n}\). To halve the noise of an average you need four times the data. A benchmark of 100 questions answered at 70% accuracy has a standard error of \(\sqrt{0.7 \times 0.3 / 100} = 0.046\): two models that differ by 3 points on it cannot be told apart. Statistics for evals builds on exactly this.
Two facts complete the picture. The law of large numbers says \(\bar{X}\) converges to \(\mu\) as \(n\) grows. The central limit theorem says more: the fluctuations of \(\bar{X}\) around \(\mu\), scaled by \(\sqrt{n}\), become Gaussian whatever the shape of the original distribution (as long as its variance is finite). The figure shows both, for losses drawn from a skewed exponential distribution:
Uncorrelated is not independent
If \(X\) is uniform on \([-1, 1]\) and \(Y = X^2\), then \(\operatorname{Cov}(X, Y) = \mathbb{E}[X^3] = 0\), yet \(Y\) is a deterministic function of \(X\). Covariance only sees linear association. Mutual information (information theory) sees all of it.
Sampling: from uniform noise to any distribution¶
A computer produces (pseudo-)random numbers \(U\) uniform on \([0, 1)\). Everything else is built from them. The general trick is the inverse CDF: if \(F\) is the CDF of the distribution you want, then \(X = F^{-1}(U)\) has exactly that distribution, because \(P(X \le x) = P(U \le F(x)) = F(x)\).
For a discrete distribution, such as an LLM's next-token probabilities, the inverse CDF is a search: lay the probabilities end to end on \([0, 1)\), draw \(U\), and pick the token whose segment it lands in. With \(p(\text{cat}) = 2/3\) and \(p(\text{dog}) = 1/3\), any \(U < 0.667\) gives "cat". That is all "sampling from the model" means; temperature, top-\(k\) and top-\(p\) (see decoding) reshape the distribution before this step.
For a continuous distribution the same rule gives closed forms. The exponential CDF is \(F(x) = 1 - e^{-x}\), so \(X = -\ln(1 - U)\) (or just \(-\ln U\), since \(1 - U\) is also uniform) is exponential. The Gumbel-max trick used to sample categoricals in parallel, and the reparameterisation trick that makes VAEs trainable, are both this idea: write the random thing as a deterministic function of simple noise (see distributions).
First principles¶
Why these rules and no others? Three independent arguments arrive at the same axioms, which is the strongest reason to trust them.
- Frequencies. If probability means long-run relative frequency, the axioms are forced: frequencies are non-negative, the frequency of "anything" is 1, and frequencies of disjoint events add. This is the frequentist reading, and it is how you should read an eval score.
- Coherent betting. Treat \(P(A)\) as the price at which you would buy or sell a ticket paying 1 if \(A\) happens. Bruno de Finetti showed in the 1930s that if your prices violate the axioms, a bookmaker can sell you a set of tickets that loses money whatever happens (a "Dutch book"). Price "rain" at 0.6 and "no rain" at 0.6, and someone sells you both for 1.2; exactly one pays out, so you lose 0.2 for sure. Coherent prices must obey the axioms.
- Consistent reasoning. Richard Cox (1946) asked what rules any system for grading the plausibility of propositions with real numbers must follow if it is to agree with ordinary logic and never reach different answers by different valid routes. Under mild conditions, the answer is: the sum and product rules, up to a relabelling. E. T. Jaynes built a whole account of probability as extended logic on this (see Go deeper). This is the Bayesian reading, and it is how you should read a model's predictive distribution.
Why define conditioning as a ratio? Learning that \(B\) happened rules out every outcome outside \(B\). Whatever you believe next must give zero to the ruled-out outcomes, and should not change the relative plausibility of the outcomes that survive (nothing you learned distinguishes them). The only way to do both and still sum to 1 is to keep \(P(A \cap B)\) and divide by \(P(B)\). Restrict, then rescale.
Why the machinery of σ-algebras? For finite \(\Omega\) you can give every subset a probability. For continuous spaces you cannot: there are subsets of \([0, 1]\) (Vitali sets) to which no "length" can be assigned consistently with countable additivity and translation invariance. Kolmogorov's fix is to declare which subsets are events (a σ-algebra, closed under complements and countable unions) and assign probability only to those. In applied AI you will almost never meet a non-measurable set, but the fix explains two things you will meet: single points of a continuous variable have probability zero, so densities rather than point probabilities are the basic object; and limits of events (like "the average converges") are well-defined events.
What breaks if you bend the rules? Scores that don't sum to 1 are not probabilities, which is why classifiers end in a softmax or sigmoid. Treating dependent evidence as independent (counting the same signal twice) produces overconfidence, the failure of Naive Bayes and of ensembles of correlated models. And assuming the test distribution equals the training distribution, when it does not, makes every expectation you computed answer the wrong question.
History¶
From gambling tables to measure theory
The subject begins in 1654 with letters between Blaise Pascal and Pierre de Fermat on how to split the stakes of an unfinished game. Christiaan Huygens printed the first textbook in 1657. Jacob Bernoulli's Ars Conjectandi (published 1713, after his death) proved the first law of large numbers, and Abraham de Moivre found the normal approximation to the binomial in 1733, the first central limit theorem. Thomas Bayes's essay on inverse probability was published by Richard Price in 1763, two years after Bayes died; Pierre-Simon Laplace independently developed and generalised the idea from 1774 and used it on real data (birth ratios, astronomy) in his 1812 Théorie analytique des probabilités. Andrey Kolmogorov's 1933 Grundbegriffe put the whole subject on measure theory with the three axioms above. Claude Shannon used the chain rule with \(n\)-gram statistics to generate English-like text in 1948, arguably the first statistical language model.
The maths¶
Notation: \(\Omega\) is the sample space, \(\mathcal{F}\) the collection of events, \(P\) the probability measure; capital letters are random variables and lower-case letters their values.
The axioms and their first consequences
A probability space is \((\Omega, \mathcal{F}, P)\) with \(P(A) \ge 0\), \(P(\Omega) = 1\) and \(P(\bigcup_i A_i) = \sum_i P(A_i)\) for pairwise disjoint \(A_i\). Consequences:
- \(P(\varnothing) = 0\); \(P(A^c) = 1 - P(A)\); \(A \subseteq B \Rightarrow P(A) \le P(B)\).
- Inclusion–exclusion: \(P(A \cup B) = P(A) + P(B) - P(A \cap B)\).
- Union bound: \(P(\bigcup_i A_i) \le \sum_i P(A_i)\) (used constantly in learning theory).
Conditioning, the chain rule, total probability, Bayes
For \(P(B) > 0\), define \(P(A \mid B) = P(A \cap B) / P(B)\). Then:
- Product rule: \(P(A \cap B) = P(A \mid B)\,P(B)\).
- Chain rule: \(P(A_1 \cap \cdots \cap A_n) = \prod_{i=1}^n P(A_i \mid A_1 \cap \cdots \cap A_{i-1})\).
- Total probability, for a partition \(B_1, \dots, B_k\) of \(\Omega\): \(P(A) = \sum_j P(A \mid B_j)\,P(B_j)\).
- Bayes: \(P(B_j \mid A) = \dfrac{P(A \mid B_j)\,P(B_j)}{\sum_i P(A \mid B_i)\,P(B_i)}\).
In density form for random variables: \(p(x, y) = p(x)\,p(y \mid x)\), \(p(y) = \int p(x, y)\,dx\) and \(p(x \mid y) = p(y \mid x)\,p(x) / p(y)\). In the language of inference, \(p(\theta \mid \mathcal{D}) \propto p(\mathcal{D} \mid \theta)\,p(\theta)\): posterior \(\propto\) likelihood \(\times\) prior.
Expectation, variance, covariance
\(\mathbb{E}[g(X)] = \sum_x g(x)\,p(x)\) or \(\int g(x)\,p(x)\,dx\).
\(\operatorname{Var}(X) = \mathbb{E}[(X - \mathbb{E}X)^2] = \mathbb{E}[X^2] - (\mathbb{E}X)^2\), \(\quad \operatorname{Var}(aX + b) = a^2 \operatorname{Var}(X)\),
\(\operatorname{Var}(X + Y) = \operatorname{Var}(X) + \operatorname{Var}(Y) + 2\operatorname{Cov}(X, Y)\).
For a random vector \(\mathbf{x} \in \mathbb{R}^d\) the covariance is the \(d \times d\) matrix \(\Sigma = \mathbb{E}[(\mathbf{x} - \boldsymbol{\mu})(\mathbf{x} - \boldsymbol{\mu})^\top]\), and for a fixed matrix \(A\), \(\operatorname{Cov}(A\mathbf{x}) = A \Sigma A^\top\). This last rule is behind every weight-initialisation scheme: it tells you how a layer scales the variance of its inputs.
Derivation: linearity of expectation needs no independence
For discrete \(X, Y\) with joint PMF \(p(x, y)\):
The only step used is the sum rule (marginalisation). Independence never appears. Variance is different: expanding \(\mathbb{E}[(X + Y - \mu_X - \mu_Y)^2]\) leaves the cross term \(2\,\mathbb{E}[(X - \mu_X)(Y - \mu_Y)] = 2\operatorname{Cov}(X, Y)\), which vanishes only when the variables are uncorrelated. For \(n\) independent copies with variance \(\sigma^2\), \(\operatorname{Var}(\sum_i X_i) = n\sigma^2\), so \(\operatorname{Var}(\bar{X}) = n\sigma^2 / n^2 = \sigma^2 / n\).
Derivation: the weak law of large numbers in four lines
Markov's inequality. For \(X \ge 0\) and \(a > 0\): \(\mathbb{E}[X] \ge \mathbb{E}[X\,\mathbf{1}_{X \ge a}] \ge a\,P(X \ge a)\), so \(P(X \ge a) \le \mathbb{E}[X] / a\).
Chebyshev's inequality. Apply Markov to \((X - \mu)^2\) with \(a = k^2\): \(P(|X - \mu| \ge k) \le \sigma^2 / k^2\).
Weak law. Apply Chebyshev to \(\bar{X}\), whose variance is \(\sigma^2 / n\):
Central limit theorem (statement). If the \(X_i\) are i.i.d. with mean \(\mu\) and finite variance \(\sigma^2\), then \(\sqrt{n}\,(\bar{X} - \mu)/\sigma\) converges in distribution to \(\mathcal{N}(0, 1)\). Chebyshev gives a guaranteed but loose bound; the CLT gives the approximate shape, which is what confidence intervals use.
Tower rule and the law of total variance
\(\mathbb{E}[X] = \mathbb{E}\big[\mathbb{E}[X \mid Y]\big]\) and \(\operatorname{Var}(X) = \mathbb{E}\big[\operatorname{Var}(X \mid Y)\big] + \operatorname{Var}\big(\mathbb{E}[X \mid Y]\big)\).
Read the second one with \(Y\) = "which question" and \(X\) = "score on a sampled answer". The total noise in an eval splits into noise from resampling the model's answer to the same question (first term) and noise from which questions were chosen (second term). The first shrinks if you sample each question several times; only more questions shrink the second.
Change of variables for densities
If \(\mathbf{y} = g(\mathbf{x})\) with \(g\) invertible and differentiable, then
The determinant accounts for how \(g\) stretches volume (probability mass is conserved, so density must shrink where space is stretched). Check in 1-D: \(X \sim \text{Uniform}(0,1)\) and \(Y = -\ln X\) give \(g^{-1}(y) = e^{-y}\), \(|dg^{-1}/dy| = e^{-y}\), so \(p_Y(y) = e^{-y}\): the exponential distribution, as the sampling section claimed. Normalising flows are built entirely on this formula (see the chain rule and Jacobians).
Build it¶
Three small experiments in NumPy: Bayes' rule checked by simulation, the chain rule as a bigram language model, and inverse-CDF sampling of the next token.
import numpy as np
rng = np.random.default_rng(0)
# 1) Bayes by formula and by simulation
prior, tpr, fpr = 0.02, 0.90, 0.05 # base rate, sensitivity, false-positive rate
post = prior * tpr / (prior * tpr + (1 - prior) * fpr)
n = 1_000_000
bad = rng.random(n) < prior
flag = np.where(bad, rng.random(n) < tpr, rng.random(n) < fpr)
print(f"P(bad | flagged): formula {post:.4f}, simulated {bad[flag].mean():.4f}")
# 2) the chain rule: a bigram language model from counts
corpus = "the cat sat . the cat ran . the dog sat .".split()
vocab = sorted(set(corpus)); idx = {w: i for i, w in enumerate(vocab)}
C = np.zeros((len(vocab), len(vocab)))
for a, b in zip(corpus, corpus[1:]):
C[idx[a], idx[b]] += 1
P = C / C.sum(axis=1, keepdims=True) # row i is p(next | word i)
def seq_prob(words):
return np.prod([P[idx[a], idx[b]] for a, b in zip(words, words[1:])])
print("vocab:", vocab)
print("p(next | 'the'):", {w: round(float(p), 3) for w, p in zip(vocab, P[idx["the"]])})
print("p(cat sat . | the) =", round(seq_prob("the cat sat .".split()), 4))
print("p(dog ran . | the) =", round(seq_prob("the dog ran .".split()), 4))
# 3) sampling the next token by inverse CDF
row = P[idx["the"]]
u = rng.random(10_000)
draws = np.searchsorted(np.cumsum(row), u, side="right")
print("empirical:", {vocab[i]: round(float((draws == i).mean()), 3) for i in np.nonzero(row)[0]})
P(bad | flagged): formula 0.2687, simulated 0.2703
vocab: ['.', 'cat', 'dog', 'ran', 'sat', 'the']
p(next | 'the'): {'.': 0.0, 'cat': 0.667, 'dog': 0.333, 'ran': 0.0, 'sat': 0.0, 'the': 0.0}
p(cat sat . | the) = 0.3333
p(dog ran . | the) = 0.0
empirical: {'cat': 0.666, 'dog': 0.334}
Now the square-root law, twice: sample means of skewed losses, and minibatch gradients.
import numpy as np
rng = np.random.default_rng(1)
# Law of large numbers: per-example losses are skewed (exponential, mean 1, sd 1)
for n in [10, 100, 1_000, 10_000]:
means = rng.exponential(1.0, size=(2_000, n)).mean(axis=1)
print(f"n={n:>6}: mean {means.mean():.4f} sd of the mean {means.std():.4f} theory {1/np.sqrt(n):.4f}")
# A minibatch gradient is an unbiased, noisy estimate of the full gradient
N, d = 10_000, 3
X = rng.normal(size=(N, d)); w_true = np.array([2.0, -1.0, 0.5])
y = X @ w_true + rng.normal(scale=0.5, size=N)
w = np.zeros(d)
full = 2 * X.T @ (X @ w - y) / N # gradient of the mean squared error
for B in [8, 64, 512]:
gs = []
for _ in range(4_000):
i = rng.integers(0, N, size=B)
gs.append(2 * X[i].T @ (X[i] @ w - y[i]) / B)
gs = np.array(gs)
print(f"B={B:>4}: mean of minibatch grads {gs.mean(0).round(3)} full {full.round(3)} sd {gs.std(0).mean():.3f}")
n= 10: mean 0.9975 sd of the mean 0.3172 theory 0.3162
n= 100: mean 0.9952 sd of the mean 0.1013 theory 0.1000
n= 1000: mean 0.9999 sd of the mean 0.0320 theory 0.0316
n= 10000: mean 1.0001 sd of the mean 0.0099 theory 0.0100
B= 8: mean of minibatch grads [-3.99 2.023 -0.956] full [-3.969 2.013 -0.967] sd 1.903
B= 64: mean of minibatch grads [-3.95 1.999 -0.981] full [-3.969 2.013 -0.967] sd 0.665
B= 512: mean of minibatch grads [-3.97 2.012 -0.973] full [-3.969 2.013 -0.967] sd 0.233
Things to try
- Change the base rate in the Bayes experiment to 20%. The same checker's flags become 82% reliable. Plot \(p(\text{bad} \mid \text{flag})\) against the base rate from 0.1% to 50%.
- Add one to every count in the bigram table before normalising (Laplace smoothing) and recompute \(p(\text{dog ran .} \mid \text{the})\). Why is the answer no longer zero, and what did you assume to justify it? (Estimation answers.)
- Simulate the two-coin example (fair or always-heads, picked at random) and confirm \(p(H_2 \mid H_1) \approx 0.833\) while \(p(H_2) = 0.75\).
- Replace the exponential losses with a Cauchy distribution (
rng.standard_cauchy). The sample mean never settles. Which assumption of the law of large numbers fails?
Common misconceptions¶
- "Probability 0 means impossible." For continuous variables every exact value has probability 0 and one of them still happens.
- "A model's softmax output is its confidence." It is a distribution the model was trained to output; whether 0.9 means "right 90% of the time" is an empirical property called calibration, and modern networks are often miscalibrated (Guo et al., 2017).
- "Independent events can't happen together." That is disjoint. Disjoint events with non-zero probability are maximally dependent: one happening rules out the other.
- "Averages always settle down." Only if the mean (for the law of large numbers) and the variance (for the \(1/\sqrt{n}\) rate) exist. Heavy-tailed quantities, which do appear in gradient noise and token frequencies, converge slowly or not at all.
Check yourself¶
A density \(p(x) = 4\) on \([0, 0.25]\). Is this a valid distribution? What is \(P(X = 0.1)\)?
Yes: it is non-negative and integrates to \(4 \times 0.25 = 1\). \(P(X = 0.1) = 0\), as for any single point of a continuous variable. Densities measure probability per unit length.
Using the benchmark table, compute \(p(\text{easy} \mid \text{correct})\) and check whether difficulty and correctness are independent.
\(p(\text{easy} \mid \text{correct}) = 0.45 / 0.72 = 0.625\), versus \(p(\text{easy}) = 0.5\). Knowing the answer was correct makes "easy" more likely, so they are dependent. Equivalently, \(p(\text{easy}, \text{correct}) = 0.45 \neq 0.5 \times 0.72 = 0.36\).
Why does the chain rule of probability need no assumption, while an n-gram model does?
The chain rule is an identity: it conditions each variable on all previous ones. An \(n\)-gram model replaces \(p(x_t \mid x_{<t})\) by \(p(x_t \mid x_{t-n+1:t-1})\), a conditional independence assumption (the Markov assumption) that is false for real language but makes counting feasible.
Your minibatch gradient has standard deviation 0.6 at batch size 32. Roughly what is it at batch size 512, and what does that imply for the learning rate?
Noise scales as \(1/\sqrt{B}\): \(0.6 / \sqrt{16} = 0.15\). Less noise allows larger steps, which is the intuition behind scaling the learning rate with batch size, up to the point where the curvature of the loss, not the noise, limits the step (the "critical batch size").
Show that if \(X\) and \(Y\) are independent then \(\operatorname{Cov}(X, Y) = 0\), and give a counterexample to the converse.
Independence gives \(\mathbb{E}[XY] = \sum_{x,y} xy\,p(x)p(y) = \mathbb{E}[X]\,\mathbb{E}[Y]\), so \(\operatorname{Cov}(X,Y) = \mathbb{E}[XY] - \mathbb{E}[X]\mathbb{E}[Y] = 0\). Counterexample: \(X\) uniform on \(\{-1, 0, 1\}\) and \(Y = X^2\); \(\mathbb{E}[XY] = \mathbb{E}[X^3] = 0 = \mathbb{E}[X]\,\mathbb{E}[Y]\), but \(Y\) is determined by \(X\).
A checker with 99% sensitivity and 99% specificity is run on a stream where 0.1% of items are bad. What fraction of flags are real? What single change helps most?
\(\frac{0.99 \times 0.001}{0.99 \times 0.001 + 0.01 \times 0.999} = \frac{0.00099}{0.01098} \approx 9\%\). The false-positive rate dominates because good items vastly outnumber bad ones. Halving the false-positive rate to 0.5% roughly doubles precision (to about 17%); improving sensitivity barely matters. Running a second, independent check on flagged items (so the prior for the second check is 9%) helps most, which is why production systems cascade a cheap filter into an expensive one.
Hard: use the law of total variance to explain why sampling each eval question 5 times does not make a 100-question benchmark as reliable as a 500-question one.
\(\operatorname{Var}(\text{score}) = \mathbb{E}[\operatorname{Var}(X \mid Q)] + \operatorname{Var}(\mathbb{E}[X \mid Q])\). Resampling answers averages down only the first term (answer noise within a question). The second term, the spread of per-question difficulty, is divided only by the number of distinct questions. With 100 questions it stays at its 100-question value however many times you resample.
Go deeper¶
Papers
- Probability, Frequency and Reasonable Expectation — R. T. Cox, 1946. The derivation of the sum and product rules from consistency alone; short and readable.
- How to improve Bayesian reasoning without instruction: frequency formats — Gigerenzer and Hoffrage, 1995. Why the 10,000-answers tree works and percentages don't.
- A Neural Probabilistic Language Model — Bengio, Ducharme, Vincent and Jauvin, 2003. The chain rule plus a neural conditional: the ancestor of every LLM. Read section 1.
- A Mathematical Theory of Communication — Shannon, 1948. Section 3 generates English from n-gram statistics: a language model in all but name.
- On Calibration of Modern Neural Networks — Guo, Pleiss, Sun and Weinberger, 2017. When a network says 0.9, is it right 90% of the time? Often not.
Videos and lectures
- Statistics 110: Probability — Joe Blitzstein, Harvard. The best full probability course on video; lectures 1–7 cover this page.
- Bayes theorem, the geometry of changing beliefs — 3Blue1Brown. Bayes as area, the picture to keep.
- But what is the Central Limit Theorem? — 3Blue1Brown. Why sums become bell curves, and the three assumptions it needs.
- MIT 6.041 Probabilistic Systems Analysis and Applied Probability — Tsitsiklis, MIT OCW. Lectures, notes and problem sets with solutions.
Articles and interactive
- Seeing Theory — Brown University. Interactive chapters on basic probability, compound events and distributions.
- CS229 Review of Probability Theory — Stanford CS229 section notes. Twelve dense pages: the exact subset of probability ML papers assume.
Books
- Introduction to Probability — Blitzstein and Hwang (free PDF). The companion to Stat 110; story proofs and superb exercises.
- Mathematics for Machine Learning — Deisenroth, Faisal and Ong (free PDF). Chapter 6 is probability as used in ML.
- Deep Learning, chapter 3 — Goodfellow, Bengio and Courville. Probability and information theory in one chapter, with ML notation.
- Probability Theory: The Logic of Science (draft) — E. T. Jaynes. Probability as extended logic, built from Cox's theorem. Opinionated and deep.
- Foundations of the Theory of Probability — Kolmogorov, English translation. The 1933 axioms, from the source; under 100 pages.
Where this leads¶
- The distributions that run AI — the specific PMFs and densities (Bernoulli, categorical, Gaussian, Dirichlet …) you will meet in every paper.
- Estimation: MLE, MAP and Bayes — turn Bayes' rule and the i.i.d. product into learning algorithms, and fix the zero-count problem.
- Entropy, cross-entropy and KL divergence — take the log of the chain rule and you have the loss every LLM is trained on.
- Statistics for experiments and evals — the square-root law, made into error bars and significance tests for model comparisons.
- The language-modelling objective — the chain rule as an architecture.