8 Probability and loss functions
A language model predicts the next character by assigning a probability to every character that could come next. Training compares those probabilities with the character that actually came next, and the number that measures the mismatch is the loss. This chapter derives that loss from one principle, maximum likelihood: choose the parameters under which the observed data were most probable. Taking logarithms turns the likelihood into a sum, and its negative average is the cross-entropy between the data and the model.
Two pieces of mathematics carry the chapter. Gibbs’ inequality says that the Kullback–Leibler divergence, a measure of how far one probability distribution is from another, is never negative. From it follows that the best model of a sequence of observations drawn from a fixed finite set is the table of relative frequencies, the result that Chapter 9 uses to build a first language model. The softmax function turns a vector of real scores into a distribution, and the gradient of the cross-entropy loss with respect to those scores is the difference between the predicted and the observed distributions. That difference is the vector \(\boldsymbol{\delta}_D\) with which backpropagation (Theorem 7.1) starts.
8.1 Distributions on a finite set
The book’s model reads and writes text as a sequence of tokens, here the 26 letters and one boundary token that marks where a name starts and ends. The set of tokens is the vocabulary \(V\), with \(|V| = 27\) elements; Definition 9.1 in Chapter 9 states these terms precisely. At each position the model’s prediction is a list of 27 non-negative numbers summing to \(1\), one probability for each token that could come next. Such a list is a probability distribution on \(V\).
Probability on a finite sample space \(\Omega\) is as in Definition 6.1. There a random variable takes real values, and the same definitions serve for a function \(X\colon\Omega\to V\) with values in any finite set \(V\), which this chapter also calls a random variable: \(P(X = v)\) is the probability of the event \(\{\omega : X(\omega) = v\}\). For one roll of a fair die, \(\Omega\) is \(\{1, \dots, 6\}\) with each outcome of probability \(\tfrac16\); the random variable “the roll is even”, with values in \(\{\text{yes}, \text{no}\}\), takes each value with probability \(\tfrac12\). Often only these probabilities matter, not \(\Omega\) itself.
A probability distribution on a finite set \(V\) is a function \(p\colon V\to[0, 1]\) with \(\sum_{v\in V}p(v) = 1\). If the elements of \(V\) are numbered \(1, \dots, n\), we also write \(p\) as the vector \(\mathbf{p} = (p_1, \dots, p_n)^\top\) with \(p_i = p(i)\). A random variable \(X\) with values in \(V\) has distribution \(p\) if \(P(X = v) = p(v)\) for each \(v\), and we write \(X \sim p\).
A distribution on \(V\) is also called a categorical distribution. The set of all of them is the probability simplex \(\{\mathbf{p}\in\mathbb{R}^n : p_i \ge 0,\ \sum_ip_i = 1\}\); for \(n = 3\) it is the triangle with corners \(\mathbf{e}_1\), \(\mathbf{e}_2\) and \(\mathbf{e}_3\). The uniform distribution has \(p(v) = 1/|V|\) for every \(v\); it describes equally likely outcomes. For a function \(f\) on \(V\), the expectation of \(f(X)\) is \(\mathbb{E}[f(X)] = \sum_{v\in V}p(v)f(v)\), by the formula over values in Theorem 6.1.
Data consist of many observations, and the model treats them as separate draws that do not influence each other. Roll two fair dice: the sample space is the set of \(36\) equally likely pairs, and the first roll \(X_1\) and the second roll \(X_2\) satisfy \(P(X_1 = 1, X_2 = 2) = \tfrac1{36} = P(X_1 = 1)\,P(X_2 = 2)\), and likewise for every pair of values. As in Definition 6.2, random variables \(X_1, \dots, X_N\) with values in \(V\) are independent if \[ P(X_1 = v_1, \dots, X_N = v_N) = P(X_1 = v_1)\cdots P(X_N = v_N) \qquad\text{for all } v_1, \dots, v_N\in V , \] where the left side is the probability that all \(N\) equalities hold. They are independent draws from \(p\) if in addition each \(X_i\) has distribution \(p\); then the probability of observing the sequence \(v_1, \dots, v_N\) is \(p(v_1)\cdots p(v_N)\). Definition 7.4 extends these notions to real random variables with densities.
8.2 Likelihood
Suppose we observe a sequence of outcomes and want to choose, among several candidate distributions, the one that explains it best. A natural score for a candidate is the probability it gives to exactly what we saw.
Example 8.1 Let \(V = \{\mathtt{a}, \mathtt{b}, \mathtt{c}\}\) and observe \(\mathtt{a}, \mathtt{b}, \mathtt{a}, \mathtt{c}, \mathtt{a}\). If the five observations are independent draws from a distribution \(p\), the probability of this sequence is \(p(\mathtt{a})p(\mathtt{b})p(\mathtt{a})p(\mathtt{c})p(\mathtt{a}) = p(\mathtt{a})^3p(\mathtt{b})p(\mathtt{c})\). The uniform distribution gives \(3^{-5} = 1/243 \approx 0.00412\), and \(p = (0.6, 0.2, 0.2)\) gives \(0.6^3\times0.2^2 = 0.00864\), about twice as much. The second candidate explains the data better.
A model is a family of distributions \(p_{\boldsymbol{\theta}}\) indexed by parameters \(\boldsymbol{\theta}\); in the example the parameters are the three probabilities themselves. Reading the probability of the observed sequence as a function of the parameters gives the likelihood.
Definition 8.1 (Likelihood) Let \(p_{\boldsymbol{\theta}}\) be a distribution on \(V\) for each \(\boldsymbol{\theta}\) in a set \(\Theta\), and let \(x_1, \dots, x_N\in V\) be observations. The likelihood of \(\boldsymbol{\theta}\) is \[ \mathcal{L}(\boldsymbol{\theta}) = \prod_{i=1}^N p_{\boldsymbol{\theta}}(x_i), \] and when \(\mathcal{L}(\boldsymbol{\theta}) > 0\) the log-likelihood is \(\ln\mathcal{L}(\boldsymbol{\theta}) = \sum_{i=1}^N\ln p_{\boldsymbol{\theta}}(x_i)\). A maximum likelihood estimate is a \(\boldsymbol{\theta}\) that maximises \(\mathcal{L}\) over \(\Theta\).
The likelihood is the probability of the observed sequence when the observations are independent draws from \(p_{\boldsymbol{\theta}}\). It is a function of the parameters, with the data held fixed. The logarithm is increasing, so \(\mathcal{L}\) and \(\ln\mathcal{L}\) have the same maximisers wherever \(\mathcal{L} > 0\); in Example 8.1 the log-likelihoods are \(-5\ln3 \approx -5.493\) and \(\ln 0.00864 \approx -4.751\). Training minimises rather than maximises, and works with averages so that the scale does not depend on \(N\). The loss used throughout the rest of the book is the average negative log-likelihood \[ L(\boldsymbol{\theta}) = -\frac{1}{N}\ln\mathcal{L}(\boldsymbol{\theta}) = \frac{1}{N}\sum_{i=1}^N\bigl(-\ln p_{\boldsymbol{\theta}}(x_i)\bigr) , \tag{8.1}\] the average, over the observations, of minus the log-probability the model gave each one.
Logarithms are also a practical necessity. The probability of a sequence of \(1000\) observations, each with probability \(1/27\), is \(27^{-1000} \approx 10^{-1431}\), far below the smallest positive double-precision number (about \(4.9\times10^{-324}\)), so the product rounds to \(0\) (Appendix A). Its logarithm, \(-1000\ln27 \approx -3295.8\), is an ordinary number.
8.3 Entropy and divergence
How unpredictable is a distribution? Measure how unexpected each outcome is by \(-\ln p(v)\), its information content (also called its surprisal): \(0\) for an outcome of probability \(1\), and large for a rare one. A coin that lands heads with probability \(0.9\) gives heads information content \(-\ln0.9 \approx 0.105\) and tails \(-\ln0.1 \approx 2.303\). Weighting by the probabilities, its average information content is \(0.9\times0.105 + 0.1\times2.303 \approx 0.325\). A fair coin gives both outcomes \(\ln2 \approx 0.693\), so its average is \(0.693\): the fair coin is harder to predict.
The definitions below use the natural logarithm and the convention \(0\ln 0 = 0\), which matches the limit \(x\ln x \to 0\) as \(x \to 0^+\). In each sum, terms with \(p(v) = 0\) are \(0\).
Definition 8.2 (Entropy) The entropy of a distribution \(p\) on a finite set \(V\) is \[ H(p) = -\sum_{v\in V}p(v)\ln p(v) = \mathbb{E}_{X\sim p}\bigl[-\ln p(X)\bigr] . \]
Entropy is the expected information content of an outcome drawn from \(p\). Each term \(-p(v)\ln p(v)\) is non-negative, because \(p(v)\le1\), so \(H(p) \ge 0\), and \(H(p) = 0\) exactly when one outcome has probability \(1\) (Exercise 8.1).
Example 8.2 The distribution \((0.6, 0.2, 0.2)\) has entropy \(-0.6\ln0.6 - 0.4\ln0.2 \approx 0.950\). The uniform distribution on \(n\) outcomes has entropy \(-n\cdot\frac1n\ln\frac1n = \ln n\), which is \(\ln 3 \approx 1.099\) for three outcomes and \(\ln 27 \approx 3.296\) for the vocabulary of the book’s model.
A model rarely knows the true distribution. Suppose the data follow \(p = (0.6, 0.2, 0.2)\) but a model predicts the uniform distribution \(q\). The model assigns each outcome information content \(\ln 3\), so on data drawn from \(p\) its average is \(0.6\ln3 + 0.2\ln3 + 0.2\ln3 = \ln3 \approx 1.099\), more than the \(0.950\) that the model \(q = p\) would achieve.
Definition 8.3 (Cross-entropy) The cross-entropy of a distribution \(q\) relative to a distribution \(p\), both on \(V\), is \[ H(p, q) = -\sum_{v\in V}p(v)\ln q(v) = \mathbb{E}_{X\sim p}\bigl[-\ln q(X)\bigr], \] with \(H(p, q) = +\infty\) if \(q(v) = 0\) for some \(v\) with \(p(v) > 0\).
If data are drawn from \(p\) and a model predicts \(q\), then \(H(p, q)\) is the average information content that the model assigns to the data. In particular, if \(\hat p\) is the empirical distribution of observations \(x_1, \dots, x_N\), the fraction \(\hat p(v) = c_v/N\) of them equal to \(v\), where \(c_v\) is the number of observations equal to \(v\), then \[ H(\hat p, q) = -\sum_{v\in V}\frac{c_v}{N}\ln q(v) = -\frac1N\sum_{i=1}^N\ln q(x_i) , \tag{8.2}\] because \(\ln q(v)\) appears once in the second sum for each observation equal to \(v\). So the loss Equation 8.1 is the cross-entropy of the model relative to the empirical distribution.
The excess of the cross-entropy over the entropy, \(1.099 - 0.950 \approx 0.148\) in the example above, measures what the model loses by predicting \(q\) instead of \(p\).
Definition 8.4 (Kullback–Leibler divergence) The Kullback–Leibler divergence of \(q\) from \(p\) is \[ D_{\mathrm{KL}}(p\,\|\,q) = \sum_{v :\, p(v) > 0}p(v)\ln\frac{p(v)}{q(v)}, \] with \(D_{\mathrm{KL}}(p\,\|\,q) = +\infty\) if \(q(v) = 0\) for some \(v\) with \(p(v) > 0\). Whenever it is finite, \(D_{\mathrm{KL}}(p\,\|\,q) = H(p, q) - H(p)\).
The divergence measures the extra average information content that comes from using \(q\) when the data follow \(p\). It is not symmetric: for \(p = (0.6, 0.2, 0.2)\) and the uniform \(u\) on three outcomes, \(D_{\mathrm{KL}}(p\,\|\,u) \approx 0.148\) and \(D_{\mathrm{KL}}(u\,\|\,p) \approx 0.145\). Its central property rests on an inequality for the logarithm.
Lemma 8.1 For every \(x > 0\), \(\ln x \le x - 1\), with equality only at \(x = 1\).
Proof. Let \(h(x) = x - 1 - \ln x\) on \((0, \infty)\). Then \(h(1) = 0\) and \(h'(x) = 1 - 1/x\), which is negative for \(x < 1\) and positive for \(x > 1\). For \(x \ne 1\), the mean value theorem gives a \(\xi\) strictly between \(1\) and \(x\) with \(h(x) = h(x) - h(1) = h'(\xi)(x - 1)\). Since \(\xi - 1\) has the same sign as \(x - 1\), so does \(h'(\xi)\), and the product is positive. So \(h(x) > 0\) for \(x \ne 1\).
Theorem 8.1 (Gibbs’ inequality) For distributions \(p\) and \(q\) on a finite set, \(D_{\mathrm{KL}}(p\,\|\,q) \ge 0\), with equality if and only if \(p = q\).
Proof. If \(q(v) = 0\) for some \(v\) with \(p(v) > 0\) the divergence is \(+\infty\) and \(p \ne q\), so there is nothing to prove. Otherwise let \(S = \{v : p(v) > 0\}\); then \(q(v) > 0\) on \(S\). By Lemma 8.1 with \(x = q(v)/p(v)\), \[ -D_{\mathrm{KL}}(p\,\|\,q) = \sum_{v\in S}p(v)\ln\frac{q(v)}{p(v)} \le \sum_{v\in S}p(v)\Bigl(\frac{q(v)}{p(v)} - 1\Bigr) = \sum_{v\in S}q(v) - 1 \le 0 , \tag{8.3}\] because \(\sum_{v\in S}p(v) = 1\) and \(\sum_{v\in S}q(v) \le 1\). So \(D_{\mathrm{KL}}(p\,\|\,q) \ge 0\).
If \(p = q\), every logarithm in the definition is \(\ln1 = 0\). If \(D_{\mathrm{KL}}(p\,\|\,q) = 0\), both inequalities in Equation 8.3 are equalities. The first one is a sum of term-by-term inequalities with positive weights \(p(v)\), so each term is an equality, and by Lemma 8.1 \(q(v)/p(v) = 1\) for every \(v\in S\). The second gives \(\sum_{v\in S}q(v) = 1\), so \(q(v) = 0 = p(v)\) for \(v \notin S\). Hence \(q = p\).
Corollary 8.1 For every distribution \(p\) on a set \(V\) with \(n\) elements, \(0 \le H(p) \le \ln n\), with \(H(p) = \ln n\) only for the uniform distribution. For every distribution \(q\) on \(V\), \(H(p, q) \ge H(p)\), with equality only for \(q = p\).
Proof. \(H(p) \ge 0\) was shown after Definition 8.2. For the uniform distribution \(u\), \(D_{\mathrm{KL}}(p\,\|\,u) = \sum_v p(v)\ln(np(v)) = \ln n - H(p)\), which is non-negative, and zero only if \(p = u\), by Theorem 8.1. For the last statement, if \(H(p, q) = +\infty\) there is nothing to prove, and otherwise \(H(p, q) - H(p) = D_{\mathrm{KL}}(p\,\|\,q)\).
8.4 Maximum likelihood for a categorical distribution
The simplest model of a sequence of observations from \(V\) treats them as independent draws from an unknown distribution \(q\) on \(V\), with the \(|V|\) values of \(q\) as parameters. In Example 8.1 the candidate \((0.6, 0.2, 0.2)\), which beat the uniform distribution, is the list of relative frequencies \(\tfrac35, \tfrac15, \tfrac15\) of the three outcomes, the fraction of the observations equal to each. Moving towards the uniform distribution, to \((0.5, 0.25, 0.25)\), lowers the likelihood to \(0.5^3\times0.25^2 \approx 0.0078\). No other candidate does better than the relative frequencies.
Theorem 8.2 (Maximum likelihood is relative frequency) Let \(x_1, \dots, x_N\) be observations in a finite set \(V\), let \(c_v\) be the number of them equal to \(v\), and let \(\hat p(v) = c_v/N\). Over all distributions \(q\) on \(V\), the likelihood \(\mathcal{L}(q) = \prod_{i=1}^Nq(x_i)\) is largest at \(q = \hat p\) and nowhere else. Equivalently, \(\hat p\) is the unique minimiser of the loss \(H(\hat p, q)\).
Proof. Group the factors of the likelihood by outcome: \(\mathcal{L}(q) = \prod_{v\in V}q(v)^{c_v}\). At \(q = \hat p\) every factor with \(c_v > 0\) is positive, so \(\mathcal{L}(\hat p) > 0\). If \(q(v) = 0\) for some \(v\) with \(c_v > 0\) then \(\mathcal{L}(q) = 0 < \mathcal{L}(\hat p)\). Otherwise \(\mathcal{L}(q) > 0\) and, by Equation 8.2 and Definition 8.4, \[ \ln\mathcal{L}(q) = \sum_{v\in V}c_v\ln q(v) = -N\,H(\hat p, q) = -N\bigl(H(\hat p) + D_{\mathrm{KL}}(\hat p\,\|\,q)\bigr) . \] By Theorem 8.1 the right side is at most \(-N\,H(\hat p)\), which is its value at \(q = \hat p\), with equality only when \(q = \hat p\). Since \(\ln\) is increasing, the same holds for \(\mathcal{L}\).
In Example 8.1 the counts are \(3, 1, 1\), so the maximum likelihood estimate is \(\hat p = (0.6, 0.2, 0.2)\), and the largest possible likelihood is \(0.00864 = e^{-5H(\hat p)}\). The proof uses no calculus. Setting derivatives to zero would have to respect the constraint \(\sum_vq(v) = 1\) (with a Lagrange multiplier, a method for constrained optimisation that the book does not use), and would not show on its own that the critical point is a maximum. Theorem 9.2 applies the theorem once for each preceding character.
8.5 The softmax function
A network produces a vector of real numbers, and a probabilistic model needs a distribution: non-negative numbers with sum \(1\). Take the scores \((2, 1, 0)\). Exponentiating makes every score positive, giving about \(7.389\), \(2.718\) and \(1\), and dividing by their sum \(11.107\) gives \((0.665, 0.245, 0.090)\), a distribution in which a higher score means a higher probability. The obvious alternative, dividing each score by the sum of the scores, fails: \((2, -1)\) would give \((2, -1)\), which has a negative entry, and \((1, -1)\) has sum \(0\).
Definition 8.5 (Softmax) The softmax of \(\mathbf{z}\in\mathbb{R}^n\) is the vector \(\operatorname{softmax}(\mathbf{z})\in\mathbb{R}^n\) with entries \[ \operatorname{softmax}(\mathbf{z})_i = \frac{e^{z_i}}{\sum_{j=1}^ne^{z_j}} . \] The entries \(z_i\) of the input are called logits.
Every entry of \(\mathbf{p} = \operatorname{softmax}(\mathbf{z})\) is positive and the entries sum to \(1\), so \(\mathbf{p}\) is a distribution on \(\{1, \dots, n\}\) that gives every outcome some probability. The exponential is increasing, so softmax preserves order: \(p_i > p_j\) exactly when \(z_i > z_j\). Every distribution with positive entries arises, from \(z_i = \ln p_i\), because then \(\sum_je^{z_j} = 1\). For \(n = 2\), dividing numerator and denominator by \(e^{z_1}\) gives \(\operatorname{softmax}(\mathbf{z})_1 = 1/(1 + e^{-(z_1 - z_2)})\), the logistic function of the difference of the logits. Solving for that difference gives \(z_1 - z_2 = \ln(p_1/(1 - p_1))\), the logit of \(p_1\) in statistics, which is where the name comes from.
Adding the same number \(c\) to every logit multiplies the numerator and the denominator by \(e^c\), so \[ \operatorname{softmax}(\mathbf{z} + c\mathbf{1}) = \operatorname{softmax}(\mathbf{z}), \tag{8.4}\] where \(\mathbf{1} = (1, \dots, 1)^\top\). Only differences of logits matter. Exercise 8.3 shows that these are the only changes of \(\mathbf{z}\) that leave the softmax alone. The identity has a practical use: computing \(e^{1000}\) overflows in double precision, but subtracting the largest logit first makes every exponent at most \(0\). Theorem A.3 and Appendix A analyse that computation.
Example 8.3 The computation at the start of this section says \(\operatorname{softmax}(2, 1, 0) \approx (0.665, 0.245, 0.090)\). The logits \((1002, 1001, 1000)\) give the same distribution by Equation 8.4, although evaluating \(e^{1002}\) directly gives infinity in double precision.
The logarithm of the denominator appears so often that it has a name.
Definition 8.6 (Log-sum-exp) The log-sum-exp function is \(\operatorname{lse}(\mathbf{z}) = \ln\sum_{j=1}^ne^{z_j}\) for \(\mathbf{z}\in\mathbb{R}^n\).
For \(\mathbf{z} = (2, 1, 0)\), \(\operatorname{lse}(\mathbf{z}) = \ln11.107 \approx 2.408\), a little above the largest logit \(2\). From the definitions, \[ \ln\operatorname{softmax}(\mathbf{z})_i = z_i - \operatorname{lse}(\mathbf{z}) . \tag{8.5}\] With \(m = \max_jz_j\), the sum \(\sum_je^{z_j}\) lies between \(e^m\) (one of its terms) and \(ne^m\) (its \(n\) terms are each at most \(e^m\)), so \[ \max_jz_j \le \operatorname{lse}(\mathbf{z}) \le \max_jz_j + \ln n . \tag{8.6}\] Log-sum-exp is a smooth version of the maximum. The bound also gives the stable way to compute it, \(\operatorname{lse}(\mathbf{z}) = m + \ln\sum_je^{z_j - m}\), in which the sum lies between \(1\) and \(n\).
Theorem 8.3 Log-sum-exp is differentiable on \(\mathbb{R}^n\), and \(\nabla\operatorname{lse}(\mathbf{z}) = \operatorname{softmax}(\mathbf{z})\).
Proof. By the chain rule for one variable, \(\partial\operatorname{lse}/\partial z_k = e^{z_k}/\sum_je^{z_j}\), which is continuous on \(\mathbb{R}^n\). By Theorem 1.6, \(\operatorname{lse}\) is differentiable, and by Theorem 1.5 its gradient is the vector of these partial derivatives.
How does the distribution respond when one logit changes? At \(\mathbf{z} = (2, 1, 0)\), increase \(z_1\) by \(0.01\). The probabilities change by about \((0.00222, -0.00163, -0.00060)\): \(p_1\) rises, and the other two fall, by amounts proportional to their own size, since \(0.00163/0.245 \approx 0.00060/0.090 \approx 0.0066\). The increases and decreases cancel, because the probabilities still sum to \(1\). The next theorem gives these rates exactly: the change is about \(0.01\,p_1(\mathbf{e}_1 - \mathbf{p})\).
Theorem 8.4 (Jacobian of softmax) Softmax is differentiable on \(\mathbb{R}^n\). For \(\mathbf{z}\in\mathbb{R}^n\) and \(\mathbf{p} = \operatorname{softmax}(\mathbf{z})\), \[ \frac{\partial p_i}{\partial z_k} = p_i(\delta_{ik} - p_k), \qquad\text{that is,}\qquad J_{\operatorname{softmax}}(\mathbf{z}) = \operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top , \] where \(\delta_{ik}\) is \(1\) if \(i = k\) and \(0\) otherwise. The matrix \(J = J_{\operatorname{softmax}}(\mathbf{z})\) has these properties:
\(J\) is symmetric;
\(J\mathbf{1} = \mathbf{0}\): each row sums to \(0\), so \(J\) is singular;
\(\mathbf{v}^\top J\mathbf{v} = \sum_ip_iv_i^2 - \bigl(\sum_ip_iv_i\bigr)^2 \ge 0\) for every \(\mathbf{v}\), with equality exactly when \(\mathbf{v}\) is a multiple of \(\mathbf{1}\). So \(J\) is positive semidefinite in the sense of Definition 2.5, its eigenvalues are real, \(0\) is an eigenvalue whose eigenvectors are the non-zero multiples of \(\mathbf{1}\), and every other eigenvalue is positive.
Column \(k\) of \(J\) lists how every probability responds to an increment of the logit \(z_k\): \(p_k\) rises at rate \(p_k(1 - p_k)\) and each other \(p_i\) falls at rate \(p_ip_k\). Row \(i\) lists how \(p_i\) responds to each logit. Entry \((i, k)\) is the rate of change of \(p_i\) per unit increment of \(z_k\).
Proof. Write \(S = \sum_je^{z_j}\), so \(p_i = e^{z_i}/S\) and \(\partial S/\partial z_k = e^{z_k}\). By the quotient rule, \[ \frac{\partial p_i}{\partial z_k} = \frac{\delta_{ik}e^{z_i}S - e^{z_i}e^{z_k}}{S^2} = \delta_{ik}p_i - p_ip_k . \] These partial derivatives are continuous, so softmax is differentiable by Theorem 1.6, and Theorem 1.5 identifies \(J\). Entry \((i, k)\) of \(\operatorname{diag}(\mathbf{p})\) is \(\delta_{ik}p_i\) and entry \((i, k)\) of \(\mathbf{p}\mathbf{p}^\top\) is \(p_ip_k\).
Both \(\operatorname{diag}(\mathbf{p})\) and \(\mathbf{p}\mathbf{p}^\top\) are symmetric.
\(J\mathbf{1} = \mathbf{p} - \mathbf{p}(\mathbf{p}\cdot\mathbf{1}) = \mathbf{p} - \mathbf{p} = \mathbf{0}\), since the entries of \(\mathbf{p}\) sum to \(1\).
\(\mathbf{v}^\top\operatorname{diag}(\mathbf{p})\mathbf{v} = \sum_ip_iv_i^2\) and \(\mathbf{v}^\top\mathbf{p}\mathbf{p}^\top\mathbf{v} = (\mathbf{p}\cdot\mathbf{v})^2\). Apply Theorem 1.1 to the vectors \(\mathbf{a}\) and \(\mathbf{b}\) with \(a_i = \sqrt{p_i}\) and \(b_i = \sqrt{p_i}\,v_i\): \[ \Bigl(\sum_ip_iv_i\Bigr)^2 = (\mathbf{a}\cdot\mathbf{b})^2 \le \|\mathbf{a}\|^2\|\mathbf{b}\|^2 = 1\cdot\sum_ip_iv_i^2 . \] Equality holds exactly when one of \(\mathbf{a}\), \(\mathbf{b}\) is a multiple of the other. Since \(\mathbf{a} \ne \mathbf{0}\), that means \(\mathbf{b} = c\mathbf{a}\) for some \(c\), that is, \(\sqrt{p_i}v_i = c\sqrt{p_i}\) for all \(i\), and since every \(p_i > 0\), \(v_i = c\) for all \(i\).
For the eigenvalues, let \(J\mathbf{v} = \lambda\mathbf{v}\) with \(\mathbf{v} \ne \mathbf{0}\), allowing complex \(\lambda\) and complex entries in \(\mathbf{v}\), and let \(\bar{\mathbf{v}}\) be the vector of complex conjugates. The number \(\bar{\mathbf{v}}^\top J\mathbf{v}\) equals its own conjugate \(\mathbf{v}^\top J\bar{\mathbf{v}}\), because \(J\) is real and symmetric, so it is real. It also equals \(\lambda\sum_i|v_i|^2\), so \(\lambda\) is real, and then \(\mathbf{v}\) can be taken real (the real or the imaginary part of a complex eigenvector is a real one). For real \(\mathbf{v}\), \(\mathbf{v}^\top J\mathbf{v} = \lambda\|\mathbf{v}\|^2\), so \(\lambda \ge 0\), with \(\lambda = 0\) only when \(\mathbf{v}\) is a multiple of \(\mathbf{1}\).
The quantity in (c) has a probabilistic reading: if \(I\) is a random index with distribution \(\mathbf{p}\), then \(\mathbf{v}^\top J\mathbf{v} = \mathbb{E}[v_I^2] - (\mathbb{E}[v_I])^2 = \operatorname{Var}[v_I]\). By Theorem 8.3, \(J\) is also the Hessian of log-sum-exp, the matrix of its second partial derivatives (Definition 2.3), so (c) says that the Hessian of \(\operatorname{lse}\) is positive semidefinite everywhere. Property (b) restates Equation 8.4: moving \(\mathbf{z}\) along \(\mathbf{1}\) does not change \(\mathbf{p}\), so the derivative in that direction is \(\mathbf{0}\).
For \(n = 2\), \(J = p_1p_2\begin{pmatrix}1 & -1\\ -1 & 1\end{pmatrix}\), with eigenvalues \(0\) and \(2p_1p_2\); with \(p_1 = \sigma(z_1 - z_2)\) for the logistic function \(\sigma\), entry \((1,1)\) is the familiar \(\sigma' = \sigma(1 - \sigma)\).
8.6 Cross-entropy loss for a softmax model
A classifier is a model that assigns an input to one of \(n\) classes, numbered \(1, \dots, n\); a language model predicting the next token is one, with the \(27\) tokens as classes. It computes logits \(\mathbf{z}\), turns them into probabilities \(\mathbf{p} = \operatorname{softmax}(\mathbf{z})\), and is scored on the observed class \(y\), the target, by the information content \(-\ln p_y\). By Equation 8.1, the loss on a data set is the average of these numbers, so the gradient of the loss is the average of their gradients. The target \(y\) corresponds to the distribution \(\mathbf{e}_y\) that gives probability \(1\) to class \(y\) and \(0\) to every other class; a vector with one entry \(1\) and the others \(0\) is called one-hot. In this notation \(-\ln p_y = H(\mathbf{e}_y, \mathbf{p})\), the cross-entropy of the prediction relative to the one-hot target.
With the logits \((2, 1, 0)\) and observed outcome \(y = 2\), the loss is \(-\ln0.245 \approx 1.408\). Increasing \(z_2\) by \(0.01\) lowers it by about \(0.0075 \approx 0.01(1 - p_2)\), and increasing \(z_1\) by \(0.01\) raises it by about \(0.0067 \approx 0.01\,p_1\). So the partial derivatives appear to be \(p_i\) for the wrong outcomes and \(p_y - 1\) for the observed one.
Theorem 8.5 (Gradient of the cross-entropy loss) For \(y\in\{1, \dots, n\}\) let \(L(\mathbf{z}) = -\ln\operatorname{softmax}(\mathbf{z})_y\). Then \(L(\mathbf{z}) = \operatorname{lse}(\mathbf{z}) - z_y\), \(L\) is differentiable on \(\mathbb{R}^n\), and \[ \nabla L(\mathbf{z}) = \mathbf{p} - \mathbf{e}_y, \qquad \mathbf{p} = \operatorname{softmax}(\mathbf{z}). \] More generally, for any distribution \(\mathbf{y}\) on \(\{1, \dots, n\}\), the loss \(L(\mathbf{z}) = H(\mathbf{y}, \operatorname{softmax}(\mathbf{z})) = -\sum_iy_i\ln p_i\) has gradient \(\mathbf{p} - \mathbf{y}\); the first case is the one-hot target \(\mathbf{y} = \mathbf{e}_y\).
Proof. By Equation 8.5, \(-\sum_iy_i\ln p_i = \sum_iy_i\bigl(\operatorname{lse}(\mathbf{z}) - z_i\bigr) = \operatorname{lse}(\mathbf{z}) - \mathbf{y}\cdot\mathbf{z}\), since \(\sum_iy_i = 1\). For \(\mathbf{y} = \mathbf{e}_y\) this is \(\operatorname{lse}(\mathbf{z}) - z_y\). By Theorem 8.3 and Example 1.6, \(L\) is differentiable with gradient \(\operatorname{softmax}(\mathbf{z}) - \mathbf{y}\).
The same result follows from Theorem 8.4 by the chain rule: \(\nabla L = -\frac{1}{p_y}\nabla p_y = -\frac{1}{p_y}p_y(\mathbf{e}_y - \mathbf{p}) = \mathbf{p} - \mathbf{e}_y\), using row \(y\) of \(J\). The proof above is shorter because log-sum-exp absorbs the quotient.
The gradient is simple to read. A gradient descent step with learning rate \(\eta > 0\) (Chapter 5) changes the logits by \(-\eta(\mathbf{p} - \mathbf{e}_y)\): it raises the logit of the observed outcome by \(\eta(1 - p_y)\) and lowers every other logit \(z_i\) by \(\eta p_i\), so the outcomes that took the most probability away from \(y\) lose the most. Every component lies strictly between \(-1\) and \(1\), and the components sum to \(0\), as (b) of Theorem 8.4 requires. The gradient is never \(\mathbf{0}\), since \(p_y < 1\), and \(L(\mathbf{z}) > 0\) for every \(\mathbf{z}\); the loss tends to \(0\) only as \(z_y - z_i \to \infty\) for every \(i \ne y\). In the notation of Theorem 7.1, an MLP whose output \(\mathbf{z}_D\) is read as logits has \(\boldsymbol{\delta}_D = \mathbf{p} - \mathbf{e}_y\).
Example 8.4 Take the logits \(\mathbf{z} = (2, 1, 0)\) of Example 8.3 and observed outcome \(y = 2\). Then \(L = -\ln 0.245 \approx 1.408\) and \(\nabla L \approx (0.665, -0.755, 0.090)\). A gradient step with \(\eta = 1\) moves the logits to about \((1.335, 1.755, -0.090)\), where the probability of outcome \(2\) is about \(0.55\) and the loss about \(0.60\).
Example 8.5 (The loss of a uniform model) If all logits are equal, \(\mathbf{p}\) is uniform and \(L = -\ln(1/n) = \ln n\) whatever the observed outcome. For the book’s vocabulary, \(\ln 27 \approx 3.30\). A model whose average loss is above \(\ln|V|\) does worse than one that predicts nothing at all.
The book’s model starts close to the uniform model. Its last layer applies a \(27\times16\) matrix with entries drawn from \(N(0, 0.08^2)\) to a vector of squared norm about \(16\), so by Theorem 7.3 each logit has mean \(0\) and variance about \(0.08^2\times16 \approx 0.10\), a standard deviation of about \(0.32\). The second-order Taylor expansion (Theorem 2.6) approximates a function near a point \(\mathbf{a}\) by \(f(\mathbf{a} + \mathbf{h}) \approx f(\mathbf{a}) + \nabla f(\mathbf{a})\cdot\mathbf{h} + \tfrac12\mathbf{h}^\top\nabla^2f(\mathbf{a})\,\mathbf{h}\). At a constant vector \(c\mathbf{1}\) the softmax is uniform, so by Theorem 8.3 and Theorem 8.4 log-sum-exp has gradient \(\frac1n\mathbf{1}\) and Hessian \(\frac1nI - \frac1{n^2}\mathbf{1}\mathbf{1}^\top\) there. Taking \(c = \bar z\), the average defined below, the expansion gives \[ \operatorname{lse}(\mathbf{z}) \approx \ln n + \bar z + \frac12\cdot\frac1n\sum_i(z_i - \bar z)^2, \qquad \bar z = \frac1n\sum_iz_i . \] The loss is \(\operatorname{lse}(\mathbf{z}) - z_y\), and every logit has mean \(0\), so \(\mathbb{E}[\bar z - z_y] = 0\) and the expected loss is about \(\ln n\) plus half the expected value of \(\frac1n\sum_i(z_i - \bar z)^2\). For a fixed input vector the rows of the matrix are independent, so the logits are independent, each with mean \(0\) and variance \(\sigma^2 \approx 0.10\). Then \(\frac1n\sum_i(z_i - \bar z)^2 = \frac1n\sum_iz_i^2 - \bar z^2\), \(\mathbb{E}[z_i^2] = \sigma^2\) and \(\mathbb{E}[\bar z^2] = \operatorname{Var}[\bar z] = \sigma^2/n\), so its expected value is \(\frac{n-1}{n}\sigma^2\). The expected loss is about \(\ln 27 + \frac12\cdot\frac{26}{27}\cdot0.10 \approx 3.35\). Averaged over 2000 freshly initialised models, each run on a random sequence of tokens, the simulated initial loss is also \(3.35\). The Taylor expansion gives no bound on its own error, and Theorem 11.5 in Chapter 11 replaces the estimate by inequalities.
8.7 Where squared error comes from
Not every loss in machine learning is a cross-entropy, but most are negative log-likelihoods of some model. The squared error is the standard example. Suppose a real-valued observation \(y\) is modelled as \(f(\mathbf{x}; \boldsymbol{\theta})\) plus a random error, the noise, with the normal distribution \(N(0, s^2)\) of Definition 7.4, whose density is \(\varphi(t) = (2\pi s^2)^{-1/2}e^{-t^2/(2s^2)}\). Then \(y\) has density \(\varphi(t - f(\mathbf{x}; \boldsymbol{\theta}))\).
The likelihood of Definition 8.1 multiplies the probabilities of the observations, and for a variable with a density the probability of each exact value is \(0\), so that product would be \(0\) for every \(\boldsymbol{\theta}\). The density is the right replacement. For a small \(\varepsilon > 0\), the probability that \(y\) lands within \(\varepsilon\) of an observed value \(y_i\) is \(\int_{y_i-\varepsilon}^{y_i+\varepsilon}\varphi(t - f)\,dt \approx 2\varepsilon\,\varphi(y_i - f)\), so maximising the product of the densities maximises, approximately, the probability of landing that close to every observation; the factor \((2\varepsilon)^N\) does not depend on \(\boldsymbol{\theta}\). For continuous observations the likelihood therefore uses the density in place of the probability (Wasserman 2004, sec. 9.3), and for independent observations \((\mathbf{x}_i, y_i)\), \(i = 1, \dots, N\), \[ -\ln\mathcal{L}(\boldsymbol{\theta}) = \frac{1}{2s^2}\sum_{i=1}^N\bigl(y_i - f(\mathbf{x}_i; \boldsymbol{\theta})\bigr)^2 + \frac N2\ln(2\pi s^2) . \] For fixed \(s\), maximising the likelihood is the same as minimising the sum of squared errors, because the two differ by a positive factor and a constant. The choice of loss is a choice of noise model: normal noise gives squared error, and a categorical model with softmax outputs gives cross-entropy.
8.8 Notes and further reading
MacKay (2003, ch. 2) introduces entropy, relative entropy and Gibbs’ inequality, which it proves in sec. 2.6, and Cover and Thomas (2006, ch. 2) gives a fuller treatment of the same quantities. Goodfellow et al. (2016, ch. 3) collects the probability and information theory used in deep learning, [ch. 5] discusses maximum likelihood, and [ch. 6] discusses softmax output units and the cross-entropy loss. Wasserman (2004, ch. 9) covers maximum likelihood estimation in general, and Deisenroth et al. (2020, ch. 9) derives least squares from a normal noise model as in Section 8.7.
8.9 Exercises
Exercise 8.1
Show that \(H(p) = 0\) if and only if \(p(v) = 1\) for some \(v\).
For \(p = (\tfrac12, \tfrac14, \tfrac14)\) and the uniform \(u\) on three outcomes, compute \(H(p)\), \(D_{\mathrm{KL}}(p\,\|\,u)\) and \(D_{\mathrm{KL}}(u\,\|\,p)\) exactly.
Exercise 8.2 A coin lands heads with unknown probability \(\theta\). In \(N\) tosses it lands heads \(k\) times, with \(0 < k < N\). Maximise \(\theta^k(1 - \theta)^{N-k}\) over \(0 \le \theta \le 1\) by calculus, and check the answer against Theorem 8.2. What happens when \(k = 0\)?
Exercise 8.3
Show that \(\operatorname{softmax}(\mathbf{z}) = \operatorname{softmax}(\mathbf{z}')\) if and only if \(\mathbf{z} - \mathbf{z}' = c\mathbf{1}\) for some real \(c\).
Find the logits \(\mathbf{z}\) with \(z_1 = 0\) and \(\operatorname{softmax}(\mathbf{z}) = (\tfrac12, \tfrac13, \tfrac16)\).
Exercise 8.4 Let \(\mathbf{z} = (0, \ln 2, \ln 3)\). Find \(\mathbf{p} = \operatorname{softmax}(\mathbf{z})\) and \(J_{\operatorname{softmax}}(\mathbf{z})\), check that its rows sum to \(0\), and compute \(\mathbf{v}^\top J\mathbf{v}\) for \(\mathbf{v} = (1, 0, 0)\) and for \(\mathbf{v} = (1, 1, 1)\).
Exercise 8.5 Let \(\sigma(t) = 1/(1 + e^{-t})\), and for an observed class \(y\in\{0, 1\}\) (often called the label) let \(L(t) = -y\ln\sigma(t) - (1 - y)\ln(1 - \sigma(t))\), the binary cross-entropy.
Show that \(\sigma'(t) = \sigma(t)(1 - \sigma(t))\) and that \(1 - \sigma(t) = \sigma(-t)\).
Show that \(L'(t) = \sigma(t) - y\), and explain how this is the case \(n = 2\) of Theorem 8.5.
Exercise 8.6 Let \(\mathbf{y}\) be a distribution on \(\{1, \dots, n\}\) with every \(y_i > 0\), and \(L(\mathbf{z}) = H(\mathbf{y}, \operatorname{softmax}(\mathbf{z}))\).
Using Corollary 8.1, show that \(L\) attains its minimum value \(H(\mathbf{y})\), exactly at the \(\mathbf{z}\) with \(\operatorname{softmax}(\mathbf{z}) = \mathbf{y}\), and find those \(\mathbf{z}\).
Show that for the one-hot target \(\mathbf{e}_y\) the infimum of \(L\) is \(0\) but is not attained.
Label smoothing replaces \(\mathbf{e}_y\) by \(\mathbf{y} = (1 - \alpha)\mathbf{e}_y + \frac{\alpha}{n}\mathbf{1}\) with \(0 < \alpha < 1\). For \(n = 27\) and \(\alpha = 0.1\), find the difference \(z_y - z_i\) (\(i \ne y\)) at the minimiser.
Exercise 8.7 Observations \(y_1, \dots, y_N\) are modelled as independent draws from \(N(\mu, s^2)\), with \(s > 0\) and \(\mu\) unknown.
Show that the negative log-likelihood, as a function of \(\mu\) for fixed \(s\), is minimised at the mean \(\bar y = \frac1N\sum_iy_i\).
Suppose the \(y_i\) are not all equal, and let \(s\) vary too. Show that at \(\mu = \bar y\) the negative log-likelihood is minimised over \(s > 0\) at \(s^2 = \frac1N\sum_i(y_i - \bar y)^2\).
Exercise 8.8 Prove that for every \(\mathbf{z}\in\mathbb{R}^n\) and every \(y\), \[ -\ln\operatorname{softmax}(\mathbf{z})_y \ge \ln n + \bar z - z_y, \qquad \bar z = \frac1n\sum_iz_i , \] with equality when all \(z_i\) are equal. (Use \(\ln x \le x - 1\), or compare the arithmetic and geometric means of the \(e^{z_i}\).) Deduce that if the logits of a randomly initialised model satisfy \(\mathbb{E}[z_i] = \mathbb{E}[z_y]\) for all \(i\), its expected loss is at least \(\ln n\).