Probability for machine learning
A language model is a probability distribution. Given the text so far, it assigns a probability to every possible next token, and generating text means drawing from that distribution, one token at a time. Training it means choosing parameters that make the real text in the training set as probable as possible. Evaluating it means asking how probable it finds text it has never seen.
So probability is not background material for modern AI. It is the language the models are written in. This section covers the parts you will use constantly (expectation and variance, the three distributions that do most of the work, Bayes rule, maximum likelihood, priors as regularizers, and sampling), and it ends with a numerical trick, the log-sum-exp, that every loss function in this book depends on.
Random variables, expectation, and variance
A random variable is a quantity whose value is uncertain, described by a distribution. A discrete one, like the next token, has a probability mass function that sums to 1. A continuous one, like a weight drawn at initialization, has a density that integrates to 1. (A density can exceed 1. Only its integral over an interval is a probability.)
The expectation is the probability-weighted average,
In plain words, the expectation is the long-run average value, and to average a function of you weight the function's values by the probabilities, with no need to work out the distribution of first.
The most useful property is linearity. always, whether or not and are independent. Most expectation calculations in machine learning are linearity plus bookkeeping.
The variance measures spread around the mean, , and its square root is the standard deviation. Three rules carry most of the weight.
- . Shifting does nothing, and scaling by scales the variance by .
- If and are independent, . In general there is an extra , where .
- If and are independent with mean zero, .
Worked example, the variance argument behind attention
Here is a calculation you will use twice in this book. Draw two vectors with independent entries of mean 0 and variance 1. What is the variance of their dot product ?
Each term has mean and, by the third rule, variance . The terms are independent, so by the second rule the variances add, and . The typical size of a dot product is therefore , which for is about 23. Dividing by brings the variance back to 1, by the first rule. That division is exactly the scaling in scaled dot-product attention (§4.3), where unscaled scores would push the softmax into saturation. The same three rules, applied to a layer's pre-activations, give the Xavier and He initializations of §0.7.
Averages get more precise, at a rate of one over root n
Average independent copies of , each with variance . By the rules above, the average has variance , so its standard deviation, the standard error, is . The law of large numbers says the average converges to , and the central limit theorem says its fluctuations around the mean look Gaussian with that standard deviation, whatever the distribution of (as long as its variance is finite).
That rate shows up all over machine learning. A minibatch gradient over examples has noise that shrinks like (§0.6). An accuracy measured on 1,000 test questions has a standard error of about percentage points near 50%, so a 1-point gap between two models on that benchmark is noise. Confidence intervals, paired comparisons between two models, and how many test questions you need are developed in §0.11, and applied to model evaluations in §14.7.
The distributions that do most of the work
Bernoulli. A single yes-or-no outcome, , with . Its mean is and its variance is . Binary classifiers, reward models comparing two answers, and dropout masks are all Bernoulli. A classifier usually outputs a logit and sets , where in this section with an argument is the sigmoid and a bare is a standard deviation.
Categorical. One of outcomes, with probabilities summing to 1. Every softmax output is a categorical distribution, and every language model's next-token prediction is one with , the vocabulary size. If you encode the outcome as a one-hot vector , its mean is and its covariance is . That is exactly the softmax Jacobian from §0.2, which is no coincidence. For every distribution in this family (the exponential families), the derivative of the mean with respect to the natural parameters, which for the categorical are the logits, is the covariance.
Gaussian (normal). A continuous value with mean and variance , written , with density
In plain words, the log-density is a downward parabola centered at the mean, and its curvature is set by the variance. Gaussians appear for three reasons. The central limit theorem makes sums of many small effects Gaussian. They are the maximum-entropy distribution for a given mean and variance (§0.5), the "least assuming" choice. And they are algebraically convenient, since sums and linear maps of Gaussians stay Gaussian.
Multivariate Gaussian. A vector with mean and covariance matrix (symmetric and positive definite), with density
The quadratic form in the exponent is the squared Mahalanobis distance, a distance that accounts for correlations and different scales. Its level sets are ellipsoids (ellipses in 2-D) whose axes point along the eigenvectors of , with half-lengths proportional to the square roots of its eigenvalues. (Eigenvectors of symmetric matrices, and what positive definite means geometrically, are the subject of §0.10.) To sample, factor with the Cholesky decomposition ( lower triangular), draw , and set . Its covariance is , as required.
Joint, marginal, and conditional probability
Most questions worth asking involve two or more random variables at once, such as a word and the word that follows it. Their joint distribution gives the probability of every combination. Summing out one variable gives the marginal distribution of the other, . Dividing the joint by a marginal gives the conditional distribution, the probability of once you know ,
In plain words, to condition on , keep only the slice of the joint table where and rescale it so it sums to 1. The second form, the product rule, builds a joint out of a marginal and a conditional.
A small table makes this concrete. Let be whether it rained and whether the grass is wet, with joint probabilities , , , and (sprinklers explain the 0.08).
Rain makes wet grass very likely, . Wet grass makes rain likely but less so, , because the sprinklers also wet the grass. The two conditionals are different numbers, and confusing them is one of the most common errors in reasoning about evidence. Bayes rule, below, is the bridge between them. We will meet this same table again in §0.5, where we measure how much the grass tells us about the rain.
Two variables are independent when the joint factors into its marginals, , which is the same as for every . Knowing one tells you nothing about the other. Rain and wet grass are not independent (, not 0.30). Independence is the assumption that makes the variance rules above work, and it is what turns the probability of a whole data set into a product, as we will use for maximum likelihood.
Applying the product rule over and over factors the joint distribution of any sequence,
where means all the elements before position . This is the chain rule of probability, and it holds for any distribution, with no assumptions at all. An autoregressive language model is this identity with a neural network supplying each factor, predicting every token from the ones before it (§3.1).
Bayes rule
Bayes rule turns a model of how data arise from causes into a belief about the causes given the data. It follows in one line from the product rule, because the joint can be factored either way, . Divide by . For a hypothesis and observed data ,
In plain words, the posterior is the prior times the likelihood, renormalized. The denominator is the marginal probability of the data, the joint summed over every hypothesis (sometimes called the law of total probability). The names matter. is the prior (belief before the data), is the likelihood (how well the hypothesis predicts the data), and is the posterior.
The classic worked problem shows why the prior cannot be ignored. A disease affects 1% of people. A test catches 99% of cases and has a 1% false-positive rate. You test positive. How likely are you to have the disease? The numerator is . The denominator adds the false positives, . The posterior is . A "99% accurate" test gives a coin flip, because the disease is rare, so the healthy people's false positives are as numerous as the true positives. Make the disease ten times rarer (0.1%) and the posterior drops to 9%.
This is the reasoning behind any detector of rare events, including the safety classifiers of §19.7. A classifier with a low false-positive rate can still produce mostly false alarms if what it detects is rare enough. In the language of §0.11, the posterior here is the classifier's precision, and it depends on the base rate in a way that recall and the false-positive rate do not.
A posterior that survives thousands of observations
Implement posterior(prior, lik) for hypotheses. prior has shape (K,). lik has shape (K,) for one observation, or (M, K) for M independent observations, where lik[m, k] is the probability of observation m under hypothesis k. Return the posterior, shape (K,). With thousands of observations the product of likelihoods underflows to 0 in float64, so work in log space.
Maximum likelihood, where losses come from
Suppose a model with parameters assigns probability to each possible data point, and we observe independent data . The likelihood is the probability of the whole data set as a function of , and maximum likelihood estimation (MLE) picks the that makes it largest,
In plain words, choose the parameters under which the data you actually saw are as probable as possible, which is the same as minimizing the average negative log-probability. We take logs for two reasons. A product of thousands of probabilities underflows (you just saw this), while a sum of logs does not. And sums are much easier to differentiate.
Almost every loss in this book is a negative log-likelihood in disguise.
Bernoulli gives binary cross-entropy. With where , the negative log-likelihood is , the binary cross-entropy. Reward models (§16.3) and DPO (§17.2) are trained with exactly this loss.
Categorical gives cross-entropy. With , the negative log-likelihood is , the cross-entropy of §0.2. Language-model pretraining is maximum likelihood on next tokens, nothing more.
Gaussian gives squared error. With and Gaussian noise of fixed variance , the negative log-likelihood is plus a constant. Minimizing it is least squares. So "use MSE" is secretly the assumption "my errors are Gaussian", which tells you when it is a bad idea (heavy-tailed noise, where one outlier dominates).
Worked example, the MLE of a Gaussian
Given samples , maximize . Setting the derivatives to zero,
In plain words, the MLE of the mean is the sample mean, and the MLE of the variance is the average squared deviation from it.
That variance estimate is biased. Its expectation is , slightly too small, because was fitted to the same data and sits closer to the samples than the true mean does. Dividing by instead (Bessel's correction) removes the bias. With , the MLE underestimates the variance by 20% on average. For the large of machine learning it hardly matters, but it is a favorite interview question, and you will meet the versus choice again inside BatchNorm (§0.7).
Fit a multivariate Gaussian and score points stably
Implement fit_gaussian(X) returning the MLE (mu, Sigma) for data X of shape (N, d) (divide by ), and mvn_logpdf(X, mu, Sigma) returning the log-density of each row, shape (N,). Do not call np.linalg.inv or np.linalg.det. Use a Cholesky factor for both the quadratic form and the log-determinant, which keeps it accurate in high dimensions where underflows.
MAP, and priors as regularizers
Maximum likelihood trusts the data completely. With little data and a flexible model, that is a problem. Flip a coin three times, see three heads, and the MLE says the coin always lands heads. Fit a degree-9 polynomial to 10 points and the MLE passes through every point while oscillating wildly between them.
The Bayesian fix is to put a prior on the parameters and maximize the posterior instead, which is called maximum a posteriori (MAP) estimation. By Bayes rule, , so
In plain words, MAP is maximum likelihood plus a penalty, and the penalty is the negative log-prior.
Now look at what common priors become.
- A Gaussian prior has . That is the L2 penalty, called weight decay in deep learning (§0.6 and §0.7).
- A Laplace prior has , the L1 penalty, which drives many weights to exactly zero.
Here is the derivation for linear regression, which is worth doing once in full. Let with , noise , and prior . The negative log-posterior, dropping constants, is
Its gradient is . Setting it to zero and multiplying by ,
In plain words, MAP with a Gaussian prior is ridge regression, and the regularization strength is the ratio of noise variance to prior variance. A tight prior (small ) or noisy data (large ) means strong regularization. As the prior becomes flat and you recover least squares. A bonus is that is always invertible for , even when .
The MLE fit needs enormous coefficients (the largest is about 370,000) to thread every point, and it generalizes badly. A modest prior, , shrinks the largest coefficient to about 10 and cuts the test error by more than half. A stronger one, , already flattens the fit too much and the error rises again. That is the bias side of the trade-off you'll meet in §0.7.
The coin makes the same point with a prior you can see. For a coin with heads probability , the Beta distribution , with density proportional to , is a convenient prior. After heads and tails the posterior is , so the prior acts like imaginary heads and imaginary tails added to the data (for the MAP estimate, the most probable value, it is and ). The MLE is , and the MAP estimate is . Try three heads and no tails with a weak prior, then add data and watch the prior's influence fade.
MAP linear regression
Implement map_linear_regression(X, y, sigma2, tau2) returning for Gaussian noise variance sigma2 and Gaussian prior variance tau2 on every weight. Use np.linalg.solve, not an explicit inverse. It must work when there are more features than examples.
Sampling
Generating from a model means sampling, and several of the most important gradient estimators in machine learning are really facts about sampling.
Inverse CDF. If is uniform on and is a cumulative distribution function, then has distribution . For a categorical distribution, is the running sum of the probabilities, and inverting it is a binary search. The word2vec negative sampler of §1.5 is built exactly this way.
The Gumbel-max trick. To sample from without computing the softmax, add independent Gumbel noise to every logit and take the argmax,
In plain words, perturb every logit with the right kind of noise and pick the largest. It never exponentiates, so it cannot overflow. It parallelizes trivially, and it underlies the Gumbel-softmax (or Concrete) relaxation that makes discrete choices differentiable (Jang et al., 2017, and Maddison, Mnih & Teh, 2017). The trick itself is much older, a consequence of the extreme-value statistics named after Emil Gumbel.
∂ Why Gumbel noise gives exactly the softmax
A standard Gumbel variable has CDF and density . Category wins if for all , that is, . Condition on . The other noises are independent, so
Multiply by the density of and integrate. Writing (now including , which contributes the from the density),
Substitute , so and the limits become to . The integral is , the softmax. ∎
Temperature. Divide the logits by a temperature before the softmax and sample from . (In this paragraph is a temperature, not the prior scale of the MAP discussion.) A temperature below 1 sharpens the distribution toward the argmax, and one above 1 flattens it toward uniform. This is the main knob of text generation (§6.4).
Sample from logits with the Gumbel-max trick
Implement gumbel_max_sample(logits, n, rng) that returns n independent samples (an int array of shape (n,)) from using the Gumbel-max trick, without computing a softmax or calling rng.choice. It must work for logits like [1000, 1000] where a naive softmax overflows.
Two ways to differentiate through randomness
Often we need the gradient of an expectation, , where the distribution itself depends on . Reinforcement learning needs this (the expected reward of a policy), and so do variational autoencoders. There are two standard estimators, and the contrast between them is a classic interview topic.
The score-function estimator, also called REINFORCE or the log-derivative trick, uses ,
In plain words, sample, then weight each sample's log-probability gradient by how good the sample was. It works for any , even a non-differentiable one like a reward from a human or a unit test, which is why it is the foundation of policy gradients (§15.3). Its weakness is high variance.
The reparameterization estimator writes the sample as a differentiable function of and fixed noise. For a Gaussian, with , so . It needs to be differentiable and the distribution to be reparameterizable, but its variance is usually far lower. It is the trick that lets variational autoencoders train by backpropagation through a random sampling step.
Both are unbiased. But with the per-sample variance of the score-function estimator is exactly 30 (expand and use the Gaussian moments and ), against 4 for the reparameterized one. So it needs about 7.5 times as many samples for the same precision. The cell's per-sample standard deviations, about 5.8 and 2.0, are close to the theoretical and . Much of §15.4 is about cutting that variance with baselines.
The log-sum-exp trick and the stable softmax
Every softmax, every cross-entropy, and every log-likelihood of a categorical model computes , the log-sum-exp, which we write for logits . You met it, and the trick that makes it safe, in §0.2. This section completes the story, with the limits of each floating-point format, the two facts that make LSE a friendly function, and the edge cases (masked rows, infinities) that production code must handle. Computed naively, it breaks. overflows to infinity once exceeds about 88.7 in float32 or 709.8 in float64, and in float16 it overflows once passes about 11, so in low precision perfectly ordinary logits already break it. In the other direction, if every is very negative, every underflows to 0 and the log returns .
As in §0.2, the fix factors out the largest term. Let . Then
In plain words, subtract the maximum before exponentiating and add it back after the log. Now every exponent is at most 0, so nothing overflows, and the largest term is exactly , so the sum is at least 1 and the log is safe.
The same shift gives the stable softmax, since (softmax is shift invariant, as we saw from its Jacobian in §0.2). And it gives the stable log-softmax, , which you should always use instead of taking the log of a softmax, because a probability that underflowed to 0 has a log of .
Two more facts make log-sum-exp a friendly function. It is a smooth maximum, since . And its gradient is the softmax, , which is the one-line derivation of from §0.2.
The same idea, carried out in blocks so the maximum can be updated as new scores arrive, is the online softmax at the heart of FlashAttention (§12.2).
A log-sum-exp you can trust
Implement logsumexp(z, axis=-1, keepdims=False) and log_softmax(z, axis=-1) for arrays of any shape. They must not overflow for huge values, must return -inf (not NaN) for a slice whose entries are all -inf (which happens with fully masked attention rows), and must return inf for a slice that contains +inf, all without floating-point warnings. (A log_softmax of a slice that is entirely -inf is undefined, and may return NaN.) Do not use scipy.special.logsumexp.
In PyTorch
torch.distributions packages densities, sampling, and both gradient estimators. sample() draws without a gradient path, rsample() uses reparameterization, and log_prob gives what the score-function estimator needs.
Read more
- Bishop (2006). Pattern Recognition and Machine Learning. Chapters 1 and 2 are the classic treatment of MLE, MAP, the Gaussian, and the polynomial example above.
- Murphy (2022). Probabilistic Machine Learning: An Introduction. Chapters 2 to 4 cover the probability, distributions, and estimation used here, freely available.
- Blitzstein & Hwang (2019). Introduction to Probability. The book behind Harvard's Stat 110, the best first course in probability, with free lectures and a free edition.
- Mohamed, Rosca, Figurnov & Mnih (2020). Monte Carlo Gradient Estimation in Machine Learning. The definitive survey of score-function and reparameterization estimators.
- Jang, Gu & Poole (2017). Categorical Reparameterization with Gumbel-Softmax. The Gumbel-max trick in practice and its differentiable relaxation.
- Blanchard, Higham & Higham (2021). Accurately computing the log-sum-exp and softmax functions. A careful numerical analysis of the shift trick.