25.1 Entropy, Cross-Entropy, and KL Divergence

A loss curve is the first thing we inspect when a classifier trains, and we quickly learn to read its shape: a falling curve is good news, while a flat one is suspicious. The numbers on its vertical axis are harder to interpret. So far we can explain only one of them. A freshly initialized classifier with ten classes reports a loss of about 2.302.30, a value that Section 4.2 used as a sanity check on an untrained network. That number is ln⁡10\ln 10, the cost of naming one of ten labels when the model still considers all ten equally likely. The other end of the curve raises deeper questions. Is a final loss of 0.60.6 good? When a curve levels off, is the plateau a bug in training or an unavoidable property of the data? And if some of the labels are wrong, how low can any model hope to go?

The cross-entropy loss is the average of −log⁡q(y)-\log q(y), which measures how surprised the model is by the label yy that actually occurred. This average splits naturally into two pieces. The first is the entropy: the average surprise experienced by someone who already knows the true distribution of the labels. Because entropy is fixed by the data themselves, no model can reduce it. The second piece is the Kullback--Leibler (KL) divergence: the extra surprise incurred by using an imperfect model instead of the truth. It is never negative, and it vanishes only when the model matches the true distribution. A loss value can therefore be judged only against this irreducible floor.

We already encountered two of these ideas in the previous chapter: maximum likelihood minimizes a cross-entropy (Section 24.6.2.1), and the KL divergence is never negative (Section 24.4.2), a result known as Gibbs' inequality. Whereas those facts served as tools there, here they are our main subject. We begin with a deck of cards and a four-symbol source, where entropy simply counts yes/no questions. From there we compare pairs of distributions, return to our classifier to find its loss floor, and finally examine what changes when targets are softened or when outcomes are continuous real numbers.

The base of the logarithm is merely a choice of unit: base 22 measures information in bits, while base ee measures it in nats. We work in nats throughout, matching the natural logarithm log used in numerical libraries and in reported training losses. Bits are more convenient when counting yes/no questions, so we mark quantities in bits with a subscript 22, as in H2H_2 for entropy. One bit equals ln⁡2≈0.693\ln 2 \approx 0.693 nats. Table 25.1.1 collects the symbols used across this chapter.

Table 25.1.1. Symbols of the information theory chapter. The binary entropy Hb(p)H_b(p) is a function of a number, not of a random variable. The mutual information I(X;Y)I(X;Y) and the last five rows are defined in later sections.
SymbolMeaningUnit
I(x)=−log⁡p(x)I(x) = -\log p(x)self-information (surprisal) of the outcome xx (by convention the letter is shared with the mutual information I(X;Y)I(X;Y))nats
H(X)H(X), H(P)H(P)entropy of a discrete random variable or distribution; a subscript 22, as in H2H_2 and CE2\textrm{CE}_2, marks bitsnats
Hb(p)H_b(p)binary entropy of a coin with heads probability ppnats
h(X)h(X)differential entropy of a continuous random variablenats, depends on the units of XX
DKL(P∥Q)D_{\textrm{KL}}(P \Vert Q)KL divergence from PP to QQnats
CE(P,Q)\textrm{CE}(P, Q)cross-entropy from PP to QQnats
kknumber of classes (size of the set of outcomes)
nnnumber of examples, or of symbols in a message; the dimension in Rn\mathbb{R}^n
p\mathbf{p}, q\mathbf{q}probability vectors on kk classes (truth, model)
z\mathbf{z}logits, with q=softmax(z)\mathbf{q} = \mathrm{softmax}(\mathbf{z})
ϵ\epsilonlabel-smoothing mass (in later sections, a noise variable)
τ\tautemperature
ρ\rholabel-noise rate: the probability that a recorded label is not the clean class
H(X∣Y)H(X \mid Y), I(X;Y)I(X;Y)conditional entropy, mutual informationnats
Df(P∥Q)D_f(P \Vert Q)f-divergence with divergence function ff
TTcritic: a function whose averages under two distributions bound a divergence
ggtest function of an integral probability metric
γ\gammacoupling (transport plan) of two distributions
NNnumber of points in each of two samples that are compared; number of candidates in a contrastive batch

25.1.1 Information and Entropy#

25.1.1.1 Self-Information#

Consider four reports about a freshly shuffled deck of cards. "I see a card" conveys nothing, because the event is certain. "I see a heart" narrows the outcome to one of four equally likely suits, "It is the three of spades" singles out one of 5252 equally likely cards, and reporting the order of the entire deck identifies one of 52!52! possible orderings. The less probable an event is, the more we learn by observing it. Shannon (Shannon, 1948) quantified this idea with the self-information of an outcome xx that occurs with probability p(x)p(x),

I(x)=−log⁡p(x).I(x) = -\log p(x).

This quantity is also called the surprisal of the outcome, the term used in Section 3.1.2.3: the less we expected an outcome, the more it surprises us. Importantly, the surprise belongs to whoever assigned the probability, so a confidently wrong model finds ordinary events deeply surprising. A certain event carries zero information, and halving an outcome's probability adds ln⁡2\ln 2 nats (one bit) to its surprisal. The first three card reports carry 00, ln⁡4≈1.39\ln 4 \approx 1.39, and ln⁡52≈3.95\ln 52 \approx 3.95 nats. In bits, where one bit is the information gained from a single fair coin flip, they carry 00, 22, and 5.705.70.

Why choose a logarithm? We want three properties: a certain event carries zero information, rarer events carry more information, and the information of two independent events adds up. Because independent probabilities multiply, the third requirement reads I(p1p2)=I(p1)+I(p2)I(p_1 p_2) = I(p_1) + I(p_2). The only decreasing functions satisfying this identity are positive multiples of −log⁡p-\log p (Csiszár (2008); Exercise 1 works through the proof). Choosing the constant multiple simply chooses the unit.

Figure 25.1.1:

Self-information I(x)=−log⁡p(x)I(x) = -\log p(x) in nats as a function of the probability pp. Certain events (p=1p = 1) carry zero information, a fair coin (p=12p = \tfrac{1}{2}) carries ln⁡2≈0.693\ln 2 \approx 0.693 nats, and the curve diverges as p→0p \to 0.

Figure 25.1.1 plots the curve: it is decreasing and convex, hits zero at p=1p = 1, and diverges as p→0p \to 0. The fourth card report, the order of the entire deck, sits far out on this curve at ln⁡52!\ln 52!. We can compute its value via the log-gamma function, ln⁡52!=ln⁡Γ(53)\ln 52! = \ln \Gamma(53), without ever forming the 68-digit integer 52!52!.

deck_order = math.lgamma(53)          # ln 52! without forming 52!
print(f'the order of the deck: {deck_order:.2f} nats '
      f'= {deck_order / math.log(2):.1f} bits')
the order of the deck: 156.36 nats = 225.6 bits

Naming the order of a shuffled deck carries 156156 nats, roughly as much information as 226226 fair coin flips.

25.1.1.2 Entropy#

We can compute a surprisal only after an outcome arrives. Beforehand, we can ask how surprised we expect to be on average. Let XX be a discrete random variable taking the value xix_i with probability pip_i. Its entropy is the expected self-information of its outcome,

H(X)=−Ex∼P[log⁡p(x)]=−∑ipilog⁡pi,(25.1.1)H(X) = -\mathbb{E}_{x \sim P}[\log p(x)] = -\sum_i p_i \log p_i, \tag{25.1.1}

with the convention 0log⁡0=00 \log 0 = 0, justified by continuity (tlog⁡t→0t \log t \to 0 as t→0t \to 0): an impossible outcome contributes nothing. Because the entropy depends only on the distribution PP of XX, we write H(P)H(P) and H(X)H(X) interchangeably.

On a finite set, entropy in bits has a concrete operational meaning: it counts the average number of yes/no questions a good questioner needs to identify the outcome. Take the distribution P=(12,14,18,18)P = (\tfrac12, \tfrac14, \tfrac18, \tfrac18) on four symbols a,b,c,da, b, c, d. We will carry this example through the section and call it the dyadic source, since all of its probabilities are powers of 12\tfrac12. A good questioner first asks "Is it aa?", settling the matter half the time. If not, they ask "Is it bb?", and then "Is it cc?", where "no" leaves only dd. The expected number of questions is

12⋅1+14⋅2+18⋅3+18⋅3=1.75,\tfrac12 \cdot 1 + \tfrac14 \cdot 2 + \tfrac18 \cdot 3 + \tfrac18 \cdot 3 = 1.75,

which matches the entropy in bits: H2(P)=12log⁡22+14log⁡24+2⋅18log⁡28=1.75H_2(P) = \tfrac12 \log_2 2 + \tfrac14 \log_2 4 + 2 \cdot \tfrac18 \log_2 8 = 1.75 bits, or 1.2131.213 nats. Each outcome is identified in log⁡2(1/pi)\log_2(1/p_i) questions, which is its self-information in bits.

By contrast, a questioner who ignores the probabilities asks "Is it aa or bb?" and then "Which of the two?", always needing 22 questions. Notice that a questioning strategy is a binary code in disguise: write 11 for yes and 00 for no, and the sequence of answers that identifies an outcome becomes its codeword, here 11, 0101, 001001, and 000000 for aa, bb, cc, and dd. The average question count matched the entropy here because every probability was a power of 12\tfrac12. In the language of codes, Section 25.2 proves that the count is never far off: for any distribution on a finite set, the best strategy needs between H2H_2 and H2+1H_2 + 1 questions on average.

In code, the function entropy masks out zero probabilities, implementing 0log⁡0=00 \log 0 = 0. We will reuse it throughout the section, starting with the dyadic source.

def entropy(p):
    """Entropy of a probability vector, in nats (0 log 0 = 0 by masking)."""
    p = np.asarray(p, dtype=float)
    p = p[p > 0]
    return float(-np.dot(p, np.log(p)))

p_dyadic = np.array([1 / 2, 1 / 4, 1 / 8, 1 / 8])
h = entropy(p_dyadic)
print(f'H = {h:.3f} nats = {h / math.log(2):.2f} bits')
H = 1.213 nats = 1.75 bits

It returns the 1.751.75 bits that we counted in questions.

Because 0≤pi≤10 \le p_i \le 1, every term −pilog⁡pi-p_i \log p_i is non-negative, so H(X)≥0H(X) \ge 0, with equality only for a point mass (a variable whose outcome is certain). Notice also that entropy depends only on the list of probabilities, not on the numerical values or names of the outcomes. A variable taking the values 11, 100100, 10610^6, and 10910^9 with the dyadic probabilities still has an entropy of 1.751.75 bits.

25.1.1.3 Joint and Conditional Entropy#

In machine learning, a label always comes paired with an input, and a character comes after the text preceding it. We therefore need both the entropy of two variables taken together and the entropy remaining in one variable once the other is known. The first requires nothing new: a pair (X,Y)(X, Y) with joint probability mass function p(x,y)p(x, y) is simply a single random variable whose outcomes are pairs, so its joint entropy is H(X,Y)=−E[log⁡p(X,Y)]H(X, Y) = -\mathbb{E}[\log p(X, Y)]. The conditional entropy is the average surprisal left in YY once XX is observed,

H(Y∣X)=−E[log⁡p(Y∣X)]=∑xp(x) H(Y∣X=x),H(Y \mid X) = -\mathbb{E}[\log p(Y \mid X)] = \sum_x p(x)\, H(Y \mid X = x),

where H(Y∣X=x)H(Y \mid X = x) is the entropy of the conditional distribution p(⋅∣x)p(\cdot \mid x). Because log⁡p(x,y)=log⁡p(x)+log⁡p(y∣x)\log p(x, y) = \log p(x) + \log p(y \mid x), taking expectations on both sides yields the chain rule for entropy:

H(X,Y)=H(X)+H(Y∣X).(25.1.2)H(X, Y) = H(X) + H(Y \mid X). \tag{25.1.2}

In words, the entropy of a pair is the entropy of the first variable plus the uncertainty that remains in the second once the first is known. Applied repeatedly, the chain rule gives H(X1,…,Xn)=∑i=1nH(Xi∣X1,…,Xi−1)H(X_1, \ldots, X_n) = \sum_{i=1}^n H(X_i \mid X_1, \ldots, X_{i-1}): the entropy of a sequence is the sum of the entropies of its symbols, each conditioned on all preceding symbols. A language model predicts text in this same left-to-right order, one symbol at a time.

The questions game illustrates this identity directly. Let XX be the answer to the first question, "Is it aa?", and let YY be the outcome of the dyadic source. Because the answer is a fair coin, H2(X)=1H_2(X) = 1 bit. After "yes", nothing remains to ask (00 bits). After "no", the outcome is bb, cc, or dd with probabilities (12,14,14)(\tfrac12, \tfrac14, \tfrac14), whose entropy is 1.51.5 bits. Averaging over the two answers gives H2(Y∣X)=12⋅0+12⋅1.5=0.75H_2(Y \mid X) = \tfrac12 \cdot 0 + \tfrac12 \cdot 1.5 = 0.75 bits. By the chain rule, H2(X,Y)=1+0.75=1.75H_2(X, Y) = 1 + 0.75 = 1.75 bits: the first answer supplies one bit and the remaining questions supply the rest. This sum equals H2(Y)H_2(Y), as it must: knowing the outcome YY completely determines the answer XX, so H(X∣Y)=0H(X \mid Y) = 0, and the chain rule in the reverse order reads H(X,Y)=H(Y)+0H(X, Y) = H(Y) + 0.

25.1.1.4 Maximum Entropy on a Finite Set#

How large can the entropy of a variable with kk outcomes be? Let us start with the smallest case, a single coin flip. A Bernoulli variable with heads probability pp has the binary entropy

Hb(p)=−plog⁡p−(1−p)log⁡(1−p),H_b(p) = -p \log p - (1-p) \log(1-p),

which is a function of the scalar pp rather than of a random variable. Figure 25.1.2 plots this curve. The entropy vanishes at p∈{0,1}p \in \{0, 1\}, where the outcome is certain, and reaches its peak at the fair coin, Hb(12)=ln⁡2≈0.693H_b(\tfrac12) = \ln 2 \approx 0.693 nats (one bit). A biased coin with p=0.1p = 0.1 has Hb(0.1)≈0.325H_b(0.1) \approx 0.325 nats, because its outcome is much easier to guess.

Figure 25.1.2:

The binary entropy Hb(p)H_b(p) in nats, symmetric about p=12p = \tfrac{1}{2}, where it peaks at ln⁡2≈0.693\ln 2 \approx 0.693 nats. At the deterministic endpoints p=0p = 0 and p=1p = 1, the outcome carries no surprise and the entropy vanishes. The curve is concave: any chord lies below it.

Notice that the curve is concave: the chord joining any two of its points lies below the curve. It peaks at the uniform coin, and the same principle holds for any finite number of outcomes. If XX takes at most kk values, then

H(X)≤log⁡k,H(X) \leq \log k,

with equality if and only if XX is uniform over all kk values. The uniform distribution spreads its probability mass as evenly as possible, making the outcome maximally hard to guess. For four outcomes, the upper bound is log⁡24=2\log_2 4 = 2 bits, which sits 0.250.25 bits above the 1.751.75 bits of the dyadic source. We postpone the proof for a moment until Gibbs' inequality is in place, at which point it takes just a single line. Since that inequality compares two distributions, we turn to comparing distributions next.

25.1.2 KL Divergence and Cross-Entropy#

25.1.2.1 The Kullback--Leibler Divergence#

Suppose we want to measure how badly a model QQ misrepresents a true distribution PP. Information theory answers this with the Kullback--Leibler (KL) divergence, also known as relative entropy (Kullback and Leibler, 1951): the average extra surprisal incurred by someone who believes QQ when outcomes are actually drawn from PP. In the questions game, the KL divergence in bits is the average number of extra questions that a strategy designed for QQ needs on outcomes drawn from PP, up to rounding to whole questions. Let PP and QQ have probability mass functions (or densities) pp and qq. The KL divergence from PP to QQ is

DKL(P∥Q)=Ex∼P[log⁡p(x)q(x)].(25.1.3)D_{\textrm{KL}}(P\|Q) = \mathbb{E}_{x \sim P} \left[ \log \frac{p(x)}{q(x)} \right]. \tag{25.1.3}

The quantity inside the expectation is log⁡p(x)−log⁡q(x)=(−log⁡q(x))−(−log⁡p(x))\log p(x) - \log q(x) = (-\log q(x)) - (-\log p(x)), which is the surprisal of the believer in QQ minus the surprisal of the believer in PP. It is positive where QQ underestimates an outcome (q(x)<p(x)q(x) \lt p(x)) and negative where QQ overestimates it. The KL divergence averages this difference under the true distribution PP.

Because PP supplies both the samples and the numerator, the definition is asymmetric: in general, DKL(P∥Q)≠DKL(Q∥P)D_{\textrm{KL}}(P\|Q) \neq D_{\textrm{KL}}(Q\|P). Outcomes with p(x)=0p(x) = 0 contribute nothing, following the convention 0log⁡(0/q)=00 \log(0/q) = 0. If any outcome has p(x)>0p(x) > 0 while q(x)=0q(x) = 0, however, then DKL(P∥Q)=+∞D_{\textrm{KL}}(P\|Q) = +\infty.

A small numerical example makes the definition concrete, and we will carry it through the rest of the section. Let P=(0.6,0.3,0.1)P = (0.6, 0.3, 0.1) be the truth and Q=(0.2,0.5,0.3)Q = (0.2, 0.5, 0.3) a model on three outcomes. Then

DKL(P∥Q)=0.6ln⁡0.60.2+0.3ln⁡0.30.5+0.1ln⁡0.10.3=0.659−0.153−0.110=0.396 nats,D_{\textrm{KL}}(P\|Q) = 0.6 \ln\frac{0.6}{0.2} + 0.3 \ln\frac{0.3}{0.5} + 0.1 \ln\frac{0.1}{0.3} = 0.659 - 0.153 - 0.110 = 0.396 \textrm{ nats},

whereas the reverse direction gives DKL(Q∥P)=0.365D_{\textrm{KL}}(Q\|P) = 0.365 nats. In bits, the two directions are 0.5710.571 and 0.5270.527. Not only do they differ, but the first value tells us that a questioner who believes QQ asks 0.570.57 more questions per outcome than necessary, averaged over long runs of outcomes drawn from PP.

Here is the discrete KL divergence in code, implementing 0log⁡0=00 \log 0 = 0 by masking out the zero probabilities of PP, just as we did in entropy. We evaluate it on our running pair in both directions, as well as on a model Q′=(0.5,0.5,0)Q' = (0.5, 0.5, 0) that declares the third outcome impossible.

def kl_divergence(p, q):
    """KL(P || Q) for two probability vectors, in nats; inf where q = 0 < p."""
    p, q = np.asarray(p, dtype=float), np.asarray(q, dtype=float)
    m = p > 0
    if np.any(q[m] == 0):
        return float('inf')
    return float(np.dot(p[m], np.log(p[m] / q[m])))

p = np.array([0.6, 0.3, 0.1])
q = np.array([0.2, 0.5, 0.3])
print(f'KL(P||Q) = {kl_divergence(p, q):.4f} nats, '
      f'KL(Q||P) = {kl_divergence(q, p):.4f} nats')
print(f"KL(P||Q') = {kl_divergence(p, [0.5, 0.5, 0.0])}")
KL(P||Q) = 0.3961 nats, KL(Q||P) = 0.3653 nats
KL(P||Q') = inf

The second line is the one to remember. The model Q′Q' assigns zero probability to an outcome that occurs one time in ten, and its KL divergence is infinite: a model that declares an event impossible is infinitely surprised when that event happens.

25.1.2.2 Gibbs' Inequality#

Could the average extra surprisal ever be negative? If it could, a wrong model would be less surprised on average than the truth itself. Gibbs' inequality (Gibbs, 1902) rules that out: no model beats the truth on average. Because everything that follows rests on this result, we prove it in full as a consequence of averaging a concave function. For any concave function ff and any random variable XX with finite mean, Jensen's inequality states that

E[f(X)]≤f(E[X]).\mathbb{E}[f(X)] \le f(\mathbb{E}[X]).

In words, averaging first and applying ff second yields the larger value. When XX takes two values, this is simply the statement that the chord lies below the curve in Figure 25.1.2. If ff is strictly concave, equality holds only when XX is constant with probability one (Section 23.3.3.1 proves the general case). We need Jensen's inequality for just one function, the logarithm, which is strictly concave: the logarithm of an average is at least the average of the logarithms.

Proposition (Gibbs' inequality). For any distributions PP and QQ on the same space,

DKL(P∥Q)≥0,D_{\textrm{KL}}(P\|Q) \geq 0,

with equality if and only if P=QP = Q.

Proof. If q(x)=0q(x) = 0 for some xx with p(x)>0p(x) > 0, then the divergence is +∞+\infty and there is nothing to prove, so assume otherwise. Rewrite the divergence as minus the average of log⁡(q(x)/p(x))\log(q(x)/p(x)) under x∼Px \sim P, and apply Jensen's inequality to the logarithm:

DKL(P∥Q)=−Ex∼P ⁣[log⁡q(x)p(x)]≥−log⁡Ex∼P ⁣[q(x)p(x)]=−log⁡ ⁣ ⁣∑x : p(x)>0 ⁣ ⁣q(x)=−log⁡Q(supp P)≥0.\begin{aligned} D_{\textrm{KL}}(P\|Q) &= -\mathbb{E}_{x\sim P}\!\left[\log\frac{q(x)}{p(x)}\right] \geq -\log \mathbb{E}_{x\sim P}\!\left[\frac{q(x)}{p(x)}\right] \\ &= -\log \!\!\sum_{x\,:\,p(x)>0}\!\! q(x) = -\log Q(\textrm{supp}\,P) \geq 0. \end{aligned}

The leading minus sign flips Jensen's "at most" into "at least". The rest of the proof happens in the second line. The expectation runs over the support of PP, the set of outcomes with p(x)>0p(x) > 0. The factors p(x)p(x) cancel, leaving the total QQ-probability of that support, a number at most 11, whose negative logarithm is therefore non-negative. For continuous densities, the same steps hold with integrals in place of sums. For equality to hold, both inequalities must be tight. Because the logarithm is strictly concave, the first is an equality only when q(x)/p(x)q(x)/p(x) equals a constant cc for PP-almost every xx (that is, outside a set of PP-probability zero), and the second requires Q(supp P)=1Q(\textrm{supp}\,P) = 1. Summing (or integrating) q=c pq = c\,p over the support of PP then forces c=1c = 1, so q=pq = p (again outside a set of probability zero for densities). ■\blacksquare

The proof rests on a single idea. Averaged over the truth, the ratio q/pq/p is at most 11, so its logarithm averages to at most 00, with equality only when q/pq/p does not vary at all (meaning q=pq = p). A model incurs no extra surprisal only when it is right.

Gibbs' inequality immediately settles the uniform upper bound we left unproved. For any distribution PP on kk outcomes and the uniform distribution UU on the same set, DKL(P∥U)=∑ipilog⁡(k pi)=log⁡k−H(P)D_{\textrm{KL}}(P\|U) = \sum_i p_i \log(k\,p_i) = \log k - H(P), which is non-negative and vanishes only when P=UP = U.

It also proves that conditioning cannot increase entropy on average. Compare the joint distribution of a pair (X,Y)(X, Y) with the product of its marginals. The log-ratio is log⁡p(x,y)p(x) p(y)=log⁡p(y∣x)−log⁡p(y)\log \frac{p(x, y)}{p(x)\,p(y)} = \log p(y \mid x) - \log p(y), whose expectation under the joint distribution is H(Y)−H(Y∣X)H(Y) - H(Y \mid X). Because that expectation is a KL divergence,

H(Y)−H(Y∣X)=DKL(pX,Y ∥ pX pY)≥0,H(Y) - H(Y \mid X) = D_{\textrm{KL}}(p_{X,Y} \,\|\, p_X\, p_Y) \ge 0,

with equality if and only if XX and YY are independent. On average, knowing XX never makes YY more uncertain. A particular observation, however, can. Suppose YY is tails for certain when X=0X = 0, and a fair coin when X=1X = 1, where X=1X = 1 occurs one time in five. Overall, YY lands heads with probability 0.10.1, so H(Y)=Hb(0.1)≈0.325H(Y) = H_b(0.1) \approx 0.325 nats. Observing X=1X = 1 raises our uncertainty about YY to ln⁡2≈0.693\ln 2 \approx 0.693 nats, yet the conditional entropy averages over both outcomes of XX, giving H(Y∣X)=0.2⋅0.693≈0.139H(Y \mid X) = 0.2 \cdot 0.693 \approx 0.139 nats, less than half of H(Y)H(Y).

25.1.2.3 Cross-Entropy#

Classifiers are trained with a close relative of the KL divergence. The cross-entropy from PP to QQ is the average surprisal of a believer in QQ on outcomes drawn from PP,

CE(P,Q)=−Ex∼P[log⁡q(x)].(25.1.4)\textrm{CE}(P, Q) = -\mathbb{E}_{x \sim P} [\log q(x)]. \tag{25.1.4}

Adding and subtracting log⁡p(x)\log p(x) inside the expectation, which is valid whenever H(P)H(P) is finite, splits the model's surprisal into the truth's own entropy plus the excess divergence:

CE(P,Q)=H(P)+DKL(P∥Q).(25.1.5)\textrm{CE}(P, Q) = H(P) + D_{\textrm{KL}}(P\|Q). \tag{25.1.5}

Cross-entropy is therefore an irreducible entropy floor plus a non-negative excess: by Gibbs' inequality, CE(P,Q)≥H(P)\textrm{CE}(P, Q) \ge H(P), with equality if and only if Q=PQ = P. For our running pair, CE(P,Q)=−(0.6ln⁡0.2+0.3ln⁡0.5+0.1ln⁡0.3)=1.294\textrm{CE}(P, Q) = -(0.6 \ln 0.2 + 0.3 \ln 0.5 + 0.1 \ln 0.3) = 1.294 nats and H(P)=0.898H(P) = 0.898 nats; their difference, 0.3960.396 nats, is the KL divergence we computed earlier. Because H(P)H(P) does not depend on QQ, minimizing the cross-entropy with respect to QQ is equivalent to minimizing the KL divergence. Maximum likelihood on discrete data does precisely this: its average negative log-likelihood is the cross-entropy from the empirical data distribution to the model (Section 24.6.2.1).

Figure 25.1.3 illustrates this decomposition in the questions game for the dyadic source PP and the uniform model U=(14,14,14,14)U = (\tfrac14, \tfrac14, \tfrac14, \tfrac14). Asking questions adapted to PP takes H2(P)=1.75H_2(P) = 1.75 questions on average. Asking two fixed questions under the uniform strategy takes CE2(P,U)=2\textrm{CE}_2(P, U) = 2 questions, so the waste is DKL(P∥U)=0.25D_{\textrm{KL}}(P\|U) = 0.25 bits. Since a questioning strategy is a binary code, these same numbers are average codeword lengths in bits per symbol. (For this particular pair, the reverse divergence DKL(U∥P)D_{\textrm{KL}}(U\|P) also happens to equal 0.250.25 bits, which is why we used a different pair earlier to show that KL divergence is asymmetric.)

Figure 25.1.3:

The decomposition (25.1.5) for the dyadic source P=(12,14,18,18)P = (\tfrac{1}{2}, \tfrac{1}{4}, \tfrac{1}{8}, \tfrac{1}{8}) and the uniform model UU, in bits. Asking questions adapted to PP takes H2(P)=1.75H_2(P) = 1.75 questions on average, asking two fixed questions takes CE2(P,U)=2.0\textrm{CE}_2(P, U) = 2.0, and the waste is DKL(P∥U)=0.25D_{\textrm{KL}}(P\|U) = 0.25 bits.

25.1.2.4 The Chain Rule for KL Divergence#

Entropy splits along a pair: the surprise in (X,Y)(X, Y) is the surprise in XX plus the remaining surprise in YY (Section 25.1.1.3). The KL divergence splits the same way, and for the same reason. Let PX,YP_{X,Y} and QX,YQ_{X,Y} be two joint distributions, factored as p(x,y)=p(x) p(y∣x)p(x, y) = p(x)\,p(y \mid x) and q(x,y)=q(x) q(y∣x)q(x, y) = q(x)\,q(y \mid x). The logarithm of the ratio p(x,y)/q(x,y)p(x, y)/q(x, y) is then a sum of two terms, and taking expectations under PX,YP_{X,Y} yields the chain rule for KL divergence:

DKL(PX,Y∥QX,Y)=DKL(PX∥QX)+Ex∼PX[DKL(PY∣x∥QY∣x)].(25.1.6)D_{\textrm{KL}}(P_{X,Y}\|Q_{X,Y}) = D_{\textrm{KL}}(P_X\|Q_X) + \mathbb{E}_{x \sim P_X}\big[D_{\textrm{KL}}(P_{Y \mid x}\|Q_{Y \mid x})\big]. \tag{25.1.6}

A wrong model of the pair pays for its error about XX, and then, on average, for its error about YY once XX is known. Note that the average runs over the truth PXP_X, not over the model. The identity is one line of algebra, yet the rest of the book leans on three of its consequences.

First, KL divergence adds over independent coordinates. If XX and YY are independent under both PP and QQ, the conditional term no longer depends on xx, and the divergence of the pair is the sum of the two divergences. Ten independent draws from our running pair thus separate PP from QQ by 10⋅0.396=3.9610 \cdot 0.396 = 3.96 nats, which is why long samples tell two distributions apart so much better than short ones. Second, the divergence between two joint distributions is at least the divergence between their marginals, because the conditional term is non-negative by Gibbs' inequality. Throwing a variable away can only make two distributions harder to tell apart. Latent variable models rely on this: the joint divergence over data and latents is, up to a constant, the objective they can compute, and it exceeds the divergence over the data alone by the conditional term, the gap of the evidence lower bound (Section 24.7). Third, applying the rule repeatedly to a sequence gives

DKL(PX1,…,Xn∥QX1,…,Xn)=∑i=1nEx<i∼P[DKL(PXi∣x<i∥QXi∣x<i)],D_{\textrm{KL}}(P_{X_1, \ldots, X_n}\|Q_{X_1, \ldots, X_n}) = \sum_{i=1}^n \mathbb{E}_{x_{\lt i} \sim P}\big[D_{\textrm{KL}}(P_{X_i \mid x_{\lt i}}\|Q_{X_i \mid x_{\lt i}})\big],

so the excess loss of an autoregressive model on a whole sequence is the sum of its excess losses at the individual steps. Predicting each next token well is therefore the same task as modeling the entire sequence well, and Section 25.2.4.1 uses this decomposition to bound the loss of every language model from below.

25.1.3 The Classification Loss#

In a kk-class classification problem, the target for a single example is the one-hot distribution placing all its mass on the recorded label yy, while the model outputs a predicted distribution q=(q1,…,qk)\mathbf{q} = (q_1, \ldots, q_k). The cross-entropy (25.1.4) between them collapses to a single term, −log⁡qy-\log q_y, which is simply the model's surprisal at the observed label. Averaged over nn examples with labels yiy_i and predictions qi\mathbf{q}_i, this gives the cross-entropy loss

CE=−1n∑i=1nlog⁡qi,yi,\textrm{CE} = -\frac{1}{n} \sum_{i=1}^n \log q_{i, y_i},

measured in nats. Deep learning frameworks compute this loss directly from the logits z\mathbf{z}, the unnormalized scores whose softmax is q\mathbf{q}. They apply a numerically stable log-softmax internally, because forming the probabilities first can overflow for large logits and underflow to log⁡0\log 0 for very negative ones (Section 3.3.5.2; Section 23.8.2 derives the stable form). In the subsections that follow, we unpack what this loss tells us about noise in the data, probability calibration, and softened targets.

25.1.3.1 The Irreducible Loss#

At the start of the section, we asked how low the loss can go when some labels are wrong. On a fixed training set, the answer is uninformative: a network large enough to memorize the dataset can fit every recorded label, the wrong ones included, and drive the training loss toward zero. The question has real content only on fresh examples that the model has not seen, and there the one-hot target is not the full truth. In real data, the label is rarely a deterministic function of the input: the same image may receive different labels due to genuine ambiguity or annotation errors. The truth for an input x\mathbf{x} is the conditional distribution from which its label is drawn, and the recorded label is a single sample from it.

Suppose the input x\mathbf{x} and label y∈{1,…,k}y \in \{1, \ldots, k\} follow a joint distribution, where p(⋅∣x)p(\cdot \mid \mathbf{x}) is the true conditional distribution of the label and q(⋅∣x)q(\cdot \mid \mathbf{x}) is any model's prediction. As the number of fresh examples grows, their average loss converges to its expectation over (x,y)(\mathbf{x}, y), which we call the population loss. No model can push this population loss below the average entropy of the label given the input.

Proposition (the irreducible classification loss). The population cross-entropy loss of any model satisfies

E(x,y)[−log⁡q(y∣x)]=Ex[H(p(⋅∣x))]+Ex[DKL(p(⋅∣x) ∥ q(⋅∣x))]≥Ex[H(p(⋅∣x))],(25.1.7)\begin{aligned} \mathbb{E}_{(\mathbf{x}, y)}\big[-\log q(y \mid \mathbf{x})\big] &= \mathbb{E}_{\mathbf{x}}\big[H(p(\cdot \mid \mathbf{x}))\big] + \mathbb{E}_{\mathbf{x}}\big[D_{\textrm{KL}}\big(p(\cdot \mid \mathbf{x}) \,\|\, q(\cdot \mid \mathbf{x})\big)\big] \\ &\ge \mathbb{E}_{\mathbf{x}}\big[H(p(\cdot \mid \mathbf{x}))\big], \end{aligned} \tag{25.1.7}

with equality if and only if q(⋅∣x)=p(⋅∣x)q(\cdot \mid \mathbf{x}) = p(\cdot \mid \mathbf{x}) for almost every x\mathbf{x} (that is, for all inputs outside a set of probability zero).

Proof. Condition on x\mathbf{x}. The inner expectation over yy is the cross-entropy CE(p(⋅∣x),q(⋅∣x))\textrm{CE}(p(\cdot \mid \mathbf{x}), q(\cdot \mid \mathbf{x})), so the decomposition (25.1.5) applies pointwise at every x\mathbf{x} (all entropies are finite, at most log⁡k\log k). Taking the outer expectation over x\mathbf{x} gives the identity. By Gibbs' inequality, every KL term is non-negative, and an average of non-negative terms vanishes if and only if almost all of them are zero. ■\blacksquare

This floor is the conditional entropy of the label given the input (Section 25.1.1.3). It is an intrinsic property of the data: no architecture, extra training data, or longer training schedule can lower it. Of all the results in this section, this is the one to keep in mind whenever you read a loss curve. Three cases illustrate what it implies:

  • A model that predicts the uniform distribution suffers a cross-entropy of ln⁡k\ln k on every input regardless of the labels, giving the familiar 2.302.30 nats for k=10k = 10.
  • When the label is a deterministic function of the input, every H(p(⋅∣x))H(p(\cdot \mid \mathbf{x})) is zero, and a perfect model achieves a loss of 00.
  • Under symmetric label noise, the clean class is determined by the input, while the recorded label matches the clean class with probability 1−ρ1 - \rho and each of the remaining k−1k - 1 classes with probability ρ/(k−1)\rho/(k-1). At every input, the conditional entropy is H=−(1−ρ)log⁡(1−ρ)−ρlog⁡ρk−1=Hb(ρ)+ρlog⁡(k−1)H = -(1-\rho)\log(1-\rho) - \rho\log\tfrac{\rho}{k-1} = H_b(\rho) + \rho\log(k-1). For ρ=0.1\rho = 0.1 and k=10k = 10, this floor is 0.325+0.220=0.5450.325 + 0.220 = 0.545 nats. As long as 1−ρ>ρ/(k−1)1 - \rho > \rho/(k-1), predicting the clean class remains optimal, so the highest achievable accuracy is 1−ρ1 - \rho (here 90%90\%).

Before running the next cell, pause and guess the loss of a confident predictor that assigns probability 0.990.99 to the clean class in this noisy setting. It is right nine times out of ten, and nearly certain every time. The code compares it against the uniform predictor and the Bayes predictor, which reports the true conditional distribution q=pq = p.

k, rho = 10, 0.1
p_noisy = np.array([1 - rho] + [rho / (k - 1)] * (k - 1))  # clean class first
predictors = {'uniform': np.full(k, 1 / k),
              'confident 0.99': np.array([0.99] + [0.01 / (k - 1)] * (k - 1)),
              'Bayes q = p': p_noisy}
print(f'floor = H(p) = {entropy(p_noisy):.3f} nats')
for name, q_hat in predictors.items():
    ce = float(-np.dot(p_noisy, np.log(q_hat)))
    print(f'{name:15s} CE = {ce:.3f} nats')
floor = H(p) = 0.545 nats
uniform         CE = 2.303 nats
confident 0.99  CE = 0.689 nats
Bayes q = p     CE = 0.545 nats

The overconfident predictor suffers a loss of 0.6890.689, well above the floor: every flipped label catches it by surprise, and its high confidence costs far more on the tenth of labels that are flipped than it gains on the rest. Only the Bayes predictor reaches the floor.

We can now answer the question from the opening: is a final loss of 0.60.6 good? On clean labels, where the floor is zero, 0.60.6 still leaves plenty of room for a better model. On these noisy labels, however, it sits within 0.060.06 nats of the floor and leaves almost none. A plateau at the floor is simply a property of the data; only a plateau above the floor points to a limitation of the model or its training. Bear in mind that all of this applies to fresh data. On a held-out split, a loss below the floor cannot come from a better model, and Exercise 2 asks what it signals instead.

So far we derived the loss floor for a single penalty (−log⁡qy-\log q_y), for unmodified one-hot labels, and for countable outcomes. In the remainder of this section we relax each of these three assumptions in turn, examining other penalties, softened targets, and continuous real-valued outcomes.

25.1.3.2 Proper Scoring Rules#

The loss floor is achieved only by the true conditional probabilities, which is just the property we want if we intend to interpret a classifier's outputs as probabilities. Decision theory gives this property a name. A scoring rule assigns a penalty S(q,y)S(\mathbf{q}, y) for reporting the probability vector q\mathbf{q} when class yy actually occurs. The rule is proper if truthful reporting is optimal: when labels follow p\mathbf{p}, the expected penalty Ey∼p[S(q,y)]\mathbb{E}_{y \sim \mathbf{p}}[S(\mathbf{q}, y)] is minimized by reporting q=p\mathbf{q} = \mathbf{p}. It is strictly proper if this truthful report is the unique minimizer. The cross-entropy loss is the log score S(q,y)=−log⁡qyS(\mathbf{q}, y) = -\log q_y, and Gibbs' inequality shows that it is strictly proper: its expected penalty is CE(p,q)\textrm{CE}(\mathbf{p}, \mathbf{q}), which is uniquely minimized at q=p\mathbf{q} = \mathbf{p}.

Consequently, at the population optimum over a model class rich enough to contain the truth, a classifier trained with cross-entropy outputs the true conditional probabilities. In particular, its predictions are calibrated: among all inputs for which the model predicts probability 0.80.8 for a given class, that class actually occurs 80%80\% of the time. (A finite training set or a restricted model class can still leave a trained network miscalibrated in practice.)

The log score is not the only strictly proper scoring rule. The Brier score, S(q,y)=∑j(qj−1(j=y))2S(\mathbf{q}, y) = \sum_j (q_j - \mathbf{1}(j = y))^2, is strictly proper as well, and unlike the log score it imposes a bounded penalty on confident errors where −log⁡qy-\log q_y diverges (Gneiting and Raftery, 2007). Exercise 3 computes its excess penalty and examines a seemingly reasonable rule that turns out to be improper.

25.1.3.3 Label Smoothing#

Until now, our training target has been the one-hot label. Replacing it with a softer target changes both what the loss asks of the logits and where its floor lies, and there is a practical reason to do so. One-hot targets demand something a softmax layer cannot actually produce: assigning probability 11 to the true class requires its logit to be infinitely larger than all the others. As a result, the loss has no finite minimizer, and gradient descent keeps pushing the logits further apart for as long as training runs. Label smoothing (Szegedy et al., 2016) fixes this by mixing the one-hot target ey\mathbf{e}_y with a fraction ϵ\epsilon of the uniform distribution over all kk classes:

pϵ=(1−ϵ) ey+ϵk 1.(25.1.8)\mathbf{p}^\epsilon = (1 - \epsilon)\, \mathbf{e}_y + \frac{\epsilon}{k}\, \mathbf{1}. \tag{25.1.8}

Under this target, the true class receives probability 1−ϵ+ϵ/k1 - \epsilon + \epsilon/k and every other class receives ϵ/k\epsilon/k. The training objective is the ordinary cross-entropy CE(pϵ,q)\textrm{CE}(\mathbf{p}^\epsilon, \mathbf{q}) against this smoothed target (the same loss used in Section 7.6). It is minimized at q=pϵ\mathbf{q} = \mathbf{p}^\epsilon, which a softmax achieves with a finite gap between the logit of the true class and each competing logit:

zy−zj=log⁡1−ϵ+ϵ/kϵ/k=log⁡ ⁣(1+k(1−ϵ)ϵ).z_y - z_j = \log\frac{1 - \epsilon + \epsilon/k}{\epsilon/k} = \log\!\Big(1 + \frac{k(1-\epsilon)}{\epsilon}\Big).

For k=10k = 10 classes and ϵ=0.1\epsilon = 0.1, this optimal logit gap is ln⁡91≈4.51\ln 91 \approx 4.51, and the loss at the optimum equals the entropy of the smoothed target, H(pϵ)=0.500H(\mathbf{p}^\epsilon) = 0.500 nats.

It is instructive to see how quickly the logits drift without smoothing. Consider a single example whose logits start at zero, updated by gradient descent with step size 11. The gradient of the cross-entropy with respect to the logits is q−pϵ\mathbf{q} - \mathbf{p}^\epsilon. With a one-hot target, all wrong classes stay tied, and each step widens the gap gg between the true class and the rest by (1−qy)+qj=k/(eg+k−1)(1 - q_y) + q_j = k/(e^g + k - 1), which is approximately ke−gk e^{-g} once gg is large. Incrementing gg by ke−gk e^{-g} multiplies ege^g by eke−g≈1+ke−ge^{k e^{-g}} \approx 1 + k e^{-g}, thereby adding roughly kk to ege^g on each step. After tt steps we therefore expect eg≈kte^g \approx kt, or g≈ln⁡(kt)g \approx \ln(kt). The gap never stops growing, though its growth is logarithmic: ten times as many steps add only ln⁡10≈2.30\ln 10 \approx 2.30. After 10,00010{,}000 steps, we expect g≈ln⁡105≈11.51g \approx \ln 10^5 \approx 11.51. The next cell runs this gradient descent both without and with smoothing.

k, checkpoints = 10, (10, 100, 1000, 10000)
for eps in (0.0, 0.1):
    p_eps = np.full(k, eps / k)
    p_eps[0] += 1 - eps                   # the true class first
    z = np.zeros(k)                       # the logits of one example
    for step in range(1, checkpoints[-1] + 1):
        q = np.exp(z - z.max())
        z -= q / q.sum() - p_eps          # gradient step, step size 1
        if step in checkpoints:
            log_q = z - z.max() - np.log(np.exp(z - z.max()).sum())
            print(f'eps = {eps}  step {step:5d}  gap = {z[0] - z[1]:5.2f}  '
                  f'loss = {-p_eps @ log_q:.4f}')
print(f'optimum for eps = 0.1: gap = ln 91 = {math.log(91):.2f}, '
      f'loss = H(p_eps) = {entropy(p_eps):.4f}')
eps = 0.0  step    10  gap =  4.29  loss = 0.1158
eps = 0.0  step   100  gap =  6.87  loss = 0.0093
eps = 0.0  step  1000  gap =  9.21  loss = 0.0009
eps = 0.0  step 10000  gap = 11.51  loss = 0.0001
eps = 0.1  step    10  gap =  3.81  loss = 0.5243
eps = 0.1  step   100  gap =  4.51  loss = 0.5003
eps = 0.1  step  1000  gap =  4.51  loss = 0.5003
eps = 0.1  step 10000  gap =  4.51  loss = 0.5003
optimum for eps = 0.1: gap = ln 91 = 4.51, loss = H(p_eps) = 0.5003

With one-hot targets, the logit gap reaches 4.294.29, 6.876.87, 9.219.21, and 11.5111.51. Our approximation ln⁡(kt)\ln(kt) predicts 4.614.61, 6.916.91, 9.219.21, and 11.5111.51: the actual gap starts slightly below the estimate (where ke−gk e^{-g} is still rough) and agrees to two decimal places from 1,0001{,}000 steps onward. Meanwhile, the loss keeps inching downward without ever reaching zero. In a neural network large enough to fit its training set, this unbounded drift manifests as weights that keep growing and predicted probabilities near 11 on every training example, mislabeled ones included. With ϵ=0.1\epsilon = 0.1, by contrast, the gap settles at 4.514.51 by step 100100 and stays there, while the loss comes to rest at 0.5000.500.

Training now has a finite optimum, though a smoothed model must be interpreted with care. Even when it predicts the smoothed target without error, its training loss plateaus at H(pϵ)H(\mathbf{p}^\epsilon) rather than zero. Moreover, its outputs are no longer the true conditional probabilities: no class can receive probability greater than 1−ϵ+ϵ/k1 - \epsilon + \epsilon/k (here 0.910.91). In practice, ϵ=0.1\epsilon = 0.1 is the standard choice, and the training recipe of Section 7.6 adopts it. Exercise 4 explores what label smoothing does to the logits of the incorrect classes.

25.1.3.4 Knowledge Distillation#

Soft targets can also come from another trained model. Knowledge distillation (Hinton et al., 2015) trains a compact student network to imitate a larger teacher network. Instead of training on a one-hot label, the student trains on the teacher's full probability distribution over classes. The fact that a handwritten "2" resembles a "7" much more than it resembles a "0" is information a one-hot label discards; it lives in the teacher's logits for the wrong classes. (Exercise 4 asks why a teacher trained with label smoothing passes on less of this information.)

As with any fixed target distribution, the loss is minimized when the student reproduces the target itself, so the decomposition (25.1.5) adds nothing new here. What does call for explanation is the scale of the loss, which carries a factor that looks arbitrary at first glance.

Because a well-trained teacher's softmax outputs are nearly one-hot, the probabilities it assigns to wrong classes are usually too tiny to exert much pull on the student. We therefore soften both distributions first by dividing the logits by a temperature τ>0\tau > 0 before applying the softmax:

pj(τ)=softmax(ztea/τ)j,qj(τ)=softmax(zstu/τ)j.p_j^{(\tau)} = \mathrm{softmax}(\mathbf{z}^{\textrm{tea}}/\tau)_j, \qquad q_j^{(\tau)} = \mathrm{softmax}(\mathbf{z}^{\textrm{stu}}/\tau)_j.

Setting τ>1\tau > 1 compresses the gaps between logits and shifts probability mass toward the wrong classes. The distillation loss is the KL divergence between these softened distributions, multiplied by τ2\tau^2:

Ldistill=τ2 DKL(p(τ) ∥ q(τ)).(25.1.9)\mathcal{L}_{\textrm{distill}} = \tau^2\, D_{\textrm{KL}}\big(\mathbf{p}^{(\tau)} \,\|\, \mathbf{q}^{(\tau)}\big). \tag{25.1.9}

This loss vanishes if and only if the student matches the softened teacher. To see why the factor τ2\tau^2 is needed, let us differentiate the unscaled KL term with respect to a student logit. Only the cross-entropy part −∑jpj(τ)log⁡qj(τ)-\sum_j p_j^{(\tau)} \log q_j^{(\tau)} depends on the student, and the derivative of a log-softmax at temperature τ\tau is the familiar softmax-minus-target expression scaled by 1/τ1/\tau:

∂∂zjstuDKL(p(τ)∥q(τ))=1τ(qj(τ)−pj(τ)).\frac{\partial}{\partial z^{\textrm{stu}}_j} D_{\textrm{KL}}\big(\mathbf{p}^{(\tau)} \| \mathbf{q}^{(\tau)}\big) = \frac{1}{\tau}\big(q_j^{(\tau)} - p_j^{(\tau)}\big).

Each student logit is thus nudged by the difference between the student's and teacher's softened probabilities for that class, divided by τ\tau.

At high temperatures, that probability difference shrinks too. Subtracting the mean logit zˉ\bar z leaves the softmax unchanged, and for large τ\tau we can expand e(zj−zˉ)/τ≈1+(zj−zˉ)/τe^{(z_j - \bar z)/\tau} \approx 1 + (z_j - \bar z)/\tau to first order. Because the centered deviations zj−zˉz_j - \bar z sum to zero, the softmax denominator is approximately kk, giving softmax(z/τ)j≈1k(1+(zj−zˉ)/τ)\mathrm{softmax}(\mathbf{z}/\tau)_j \approx \tfrac{1}{k}\big(1 + (z_j - \bar z)/\tau\big). Consequently, qj(τ)−pj(τ)q_j^{(\tau)} - p_j^{(\tau)} shrinks like 1/τ1/\tau, and the unscaled gradient shrinks like 1/τ21/\tau^2:

1τ(qj(τ)−pj(τ))  ≈  1k τ2((zjstu−zˉstu)−(zjtea−zˉtea)).\frac{1}{\tau}\big(q_j^{(\tau)} - p_j^{(\tau)}\big) \;\approx\; \frac{1}{k\,\tau^2}\Big(\big(z^{\textrm{stu}}_j - \bar z^{\textrm{stu}}\big) - \big(z^{\textrm{tea}}_j - \bar z^{\textrm{tea}}\big)\Big).

Multiplying the loss by τ2\tau^2 cancels this decay and keeps the gradient magnitude roughly constant as τ\tau varies. That stability is essential in practice because the distillation loss is rarely used in isolation: it is typically added, with a fixed weight, to the standard cross-entropy loss on the hard labels. Without the τ2\tau^2 factor, tuning τ\tau would inadvertently change the relative weight of the two losses. With it, the temperature controls only how much of the teacher's small wrong-class probabilities the student sees.

Let us verify this scaling numerically using teacher logits (5,2,−1)(5, 2, -1) and student logits (3,3,0)(3, 3, 0). Both vectors have mean 22, so τ2\tau^2 times the gradient should converge to 13((1,1,−2)−(3,0,−3))=(−0.667,0.333,0.333)\tfrac13\big((1, 1, -2) - (3, 0, -3)\big) = (-0.667, 0.333, 0.333), which has norm 0.8160.816. In the cell below, we use automatic differentiation to compute the gradient of the unscaled KL term across five temperatures and compare its norm before and after multiplying by τ2\tau^2.

z_tea = torch.tensor([5.0, 2.0, -1.0])
z_stu = torch.tensor([3.0, 3.0, 0.0], requires_grad=True)
print(' tau  |grad|  |tau^2 grad|  tau^2 grad')
for tau in (1.0, 2.0, 5.0, 10.0, 20.0):
    p_tau = torch.softmax(z_tea / tau, 0)
    kl = (p_tau * (torch.log(p_tau) - torch.log_softmax(z_stu / tau, 0))).sum()
    g = torch.autograd.grad(kl, z_stu)[0].numpy()
    print(f'{tau:4.0f}  {np.linalg.norm(g):.4f}  '
          f'{np.linalg.norm(tau**2 * g):12.3f}  {np.round(tau**2 * g, 3)}')
limit = (z_stu - z_stu.mean()) - (z_tea - z_tea.mean())
limit = limit.detach().numpy() / len(limit)
print(f'limit {"":6s}  {np.linalg.norm(limit):12.3f}  {np.round(limit, 3)}')
 tau  |grad|  |tau^2 grad|  tau^2 grad
   1  0.6391         0.639  [-0.462  0.441  0.022]
   2  0.2190         0.876  [-0.672  0.549  0.123]
   5  0.0368         0.920  [-0.741  0.478  0.263]
  10  0.0088         0.884  [-0.719  0.413  0.306]
  20  0.0021         0.854  [-0.697  0.374  0.322]
limit                0.816  [-0.667  0.333  0.333]

Without the τ2\tau^2 factor, the gradient collapses: its norm drops from 0.640.64 at τ=1\tau = 1 to 0.00210.0021 at τ=20\tau = 20, roughly three hundred times smaller, and the final doubling of τ\tau divides it by about four, just as 1/τ21/\tau^2 predicts. With the factor included, the norm stays between 0.640.64 and 0.920.92. It slightly overshoots the asymptotic limit 0.8160.816, peaks near τ=5\tau = 5, and then settles back slowly at a rate of order 1/τ1/\tau (still reading 0.8540.854 at τ=20\tau = 20). Notice also that at τ=1\tau = 1 the loss reduces to the ordinary KL divergence, and for a one-hot teacher (whose entropy is zero) it becomes the ordinary cross-entropy loss, so standard supervised training is a special case.

25.1.4 Entropy and KL Divergence for Densities#

So far every outcome has been discrete and countable. A regression target, by contrast, is a real number described by a probability density, so sums become integrals. The KL divergence survives this transition intact, whereas entropy does not: continuous entropy can become negative and depends on the units in which the variable is measured. Consequently, the negative log-likelihood loss of a continuous model can fall below zero, and its floor shifts whenever we rescale the data. What retains its absolute meaning is the excess above the floor, and with it the difference in loss between any two models evaluated on the same data. (On a first reading, you may skip these three subsections and resume at the final paragraph of the section.)

25.1.4.1 Differential Entropy#

For a continuous random variable XX with density pp, replacing the sum in the discrete entropy with an integral gives the differential entropy:

h(X)=−∫p(x)log⁡p(x) dx.(25.1.10)h(X) = -\int p(x) \log p(x) \,dx. \tag{25.1.10}

This is the expected negative log-density, and density values are not probabilities: they carry units of 1/x1/x and can easily exceed 11. We use a lowercase hh to distinguish differential entropy from the discrete HH, because the two behave quite differently.

The simplest example already shows why. The uniform density on [0,a][0, a] equals 1/a1/a throughout the interval, so h=−∫0a1alog⁡1a dx=log⁡ah = -\int_0^a \tfrac1a \log \tfrac1a \,dx = \log a. When a=12a = \tfrac12, this gives −ln⁡2≈−0.693-\ln 2 \approx -0.693 nats, a negative entropy that no discrete distribution can ever have. Worse yet, measuring the very same length in centimetres instead of metres multiplies aa by 100100 and adds ln⁡100≈4.61\ln 100 \approx 4.61 nats to hh, even though the underlying uncertainty has not changed at all.

The same kind of shift happens under any smooth change of variables. If y=g(x)y = g(x) is invertible with derivative g′g', then the density of YY at g(x)g(x) is pX(x)/∣g′(x)∣p_X(x)/\lvert g'(x)\rvert, and therefore

h(Y)=h(X)+E[log⁡∣g′(X)∣].h(Y) = h(X) + \mathbb{E}\big[\log\lvert g'(X)\rvert\big].

For a random vector x∈Rn\mathbf{x} \in \mathbb{R}^n, both the definition and this transformation rule keep the exact same form, with an integral over Rn\mathbb{R}^n and the Jacobian determinant ∣det⁡∂g/∂x∣\lvert\det \partial g/\partial \mathbf{x}\rvert replacing ∣g′∣\lvert g'\rvert. Stretching a variable increases its differential entropy, while compressing it drives the entropy down without bound. As we will derive in Section 25.1.4.3, a Gaussian with standard deviation σ\sigma has differential entropy h=12log⁡(2πeσ2)h = \tfrac12 \log(2\pi e \sigma^2), which turns negative as soon as σ<(2πe)−1/2≈0.24\sigma \lt (2\pi e)^{-1/2} \approx 0.24.

Fortunately, the KL divergence does not share this sensitivity to units. If we apply the same change of variables to both the data density pp and a model density qq, both are divided by the same Jacobian factor, which cancels inside the ratio p/qp/q. The KL divergence is therefore invariant to invertible reparameterizations. For two uniform densities p1p_1 on [0,a1][0, a_1] and p2p_2 on [0,a2][0, a_2] with a1≤a2a_1 \le a_2, for example, ∫p1log⁡(p1/p2) dx=log⁡(a2/a1)\int p_1 \log(p_1/p_2)\,dx = \log(a_2/a_1): for a1=12a_1 = \tfrac12 and a2=1a_2 = 1, this is ln⁡2≈0.693\ln 2 \approx 0.693 nats whether measured in metres or in centimetres. The cross-entropy −EP[log⁡q]-\mathbb{E}_P[\log q] used to train a continuous model shifts by the same constant as hh, and since that constant does not depend on the model, both the gradients and the minimizer remain unchanged. Whenever h(p)h(p) is finite, the decomposition (25.1.5) still holds with hh in place of HH, so maximum likelihood for densities minimizes DKL(p∥qθ)D_{\textrm{KL}}(p\|q_{\boldsymbol\theta}) at the population level.

Note also that differential entropy is not simply the limit of discrete entropy under fine binning. Partition the real line into cells of width Δ\Delta, and let XΔX_\Delta record which cell contains XX. For a point xix_i inside cell ii, P(XΔ=i)≈p(xi)ΔP(X_\Delta = i) \approx p(x_i)\Delta, and

H(XΔ)+log⁡Δ→h(X)as Δ→0H(X_\Delta) + \log \Delta \to h(X) \quad \textrm{as } \Delta \to 0

whenever pp is regular enough for the Riemann sums to converge to the integrals (for instance, when pp is continuous and both pp and plog⁡pp \log p are Riemann-integrable). The discrete entropy H(XΔ)H(X_\Delta) itself diverges like log⁡(1/Δ)\log(1/\Delta), because a finer grid always demands more yes/no questions, and h(X)h(X) is the finite offset that remains after subtracting that growth. For the uniform density on [0,1][0, 1] with Δ=18\Delta = \tfrac18, all eight cells are equally likely, so H2(XΔ)=3H_2(X_\Delta) = 3 bits and log⁡2Δ=−3\log_2 \Delta = -3, which sum to 0=h0 = h. Exercise 6 proves this limit and tests it numerically on a Gaussian.

25.1.4.2 KL Divergence Between Gaussians#

When a regression model predicts a real number along with its uncertainty, it most often outputs a Gaussian: a mean and a variance. Comparing such a model with the data, or comparing two Gaussian models against each other, requires the KL divergence between two Gaussians, which has a clean closed form. For P=N(μ1,σ12)P = \mathcal{N}(\mu_1, \sigma_1^2) and Q=N(μ2,σ22)Q = \mathcal{N}(\mu_2, \sigma_2^2),

DKL ⁣(N(μ1,σ12) ∥ N(μ2,σ22))=log⁡σ2σ1+σ12+(μ1−μ2)22σ22−12.(25.1.11)D_{\textrm{KL}}\!\left(\mathcal{N}(\mu_1,\sigma_1^2) \,\big\|\, \mathcal{N}(\mu_2,\sigma_2^2)\right) = \log\frac{\sigma_2}{\sigma_1} + \frac{\sigma_1^2 + (\mu_1 - \mu_2)^2}{2\sigma_2^2} - \frac{1}{2}. \tag{25.1.11}

The formula combines a log ratio of standard deviations with the variance and squared mean error of PP, both measured relative to the model's variance σ22\sigma_2^2. As Gibbs' inequality guarantees, it is non-negative and vanishes only when μ1=μ2\mu_1 = \mu_2 and σ1=σ2\sigma_1 = \sigma_2. It is also visibly asymmetric, because σ1\sigma_1 and σ2\sigma_2 enter in different ways. Exercise 7 derives this expression directly from the definition.

Start with the simplest case: a unit mean shift with equal variances, P=N(0,1)P = \mathcal{N}(0, 1) and Q=N(1,1)Q = \mathcal{N}(1, 1). Here the formula reduces to (μ1−μ2)2/(2σ2)=12(\mu_1 - \mu_2)^2/(2\sigma^2) = \tfrac12 nat in either direction. Now let the variances differ instead: take P=N(0,1)P = \mathcal{N}(0, 1) and Q=N(0,4)Q = \mathcal{N}(0, 4), so σ2=2\sigma_2 = 2. Plugging in gives DKL(P∥Q)=ln⁡2+18−12≈0.318D_{\textrm{KL}}(P\|Q) = \ln 2 + \tfrac18 - \tfrac12 \approx 0.318 nats, whereas the reverse direction gives DKL(Q∥P)=−ln⁡2+2−12≈0.807D_{\textrm{KL}}(Q\|P) = -\ln 2 + 2 - \tfrac12 \approx 0.807 nats, more than 2.52.5 times larger.

Figure 25.1.4 reveals where each divergence comes from. In both directions, the integrand changes sign at ∣x∣=(8ln⁡2/3)1/2≈1.36|x| = (8 \ln 2/3)^{1/2} \approx 1.36, where the two densities cross. In panel (a), the wide model explains narrow data: it is too surprised in the core (∣x∣<1.36|x| \lt 1.36, contributing +0.424+0.424) and slightly less surprised than the truth in the tails (contributing −0.106-0.106). In panel (b), the narrow model must explain wide data: the core contributes −0.240-0.240, while the tails, where the narrow model assigns tiny probability to outcomes that actually occur, contribute a hefty +1.046+1.046.

Figure 25.1.4:

Where the KL divergence between N(0,1)\mathcal{N}(0,1) and N(0,4)\mathcal{N}(0,4) comes from. (a) The narrow distribution explained by the wide model: a positive core and slightly negative tails sum to 0.3180.318 nats. (b) The wide distribution explained by the narrow model: the tails, where the narrow model assigns little probability, contribute 1.051.05 nats against a core of −0.24-0.24, for a total of 0.8070.807. The sign changes at ∣x∣=1.36|x| = 1.36 in both directions.

A narrow model is far more surprised by wide data than a wide model is by narrow data. In general, KL divergence penalizes a model severely whenever outcomes occur that it had nearly ruled out, but stays mild when the model merely spreads extra probability over regions where no data appear. What this asymmetry means for fitting generative models in one direction versus the other is the subject of Section 25.3.2.

The definition also suggests a general way to estimate a KL divergence when no closed form exists: draw samples from PP and average log⁡p(x)−log⁡q(x)\log p(x) - \log q(x). Because we will rely on sample-based estimates later, it is worth checking how accurate they are on this Gaussian pair. The next cell implements both the closed form and the Monte Carlo estimator together with its standard error.

def gaussian_kl(mu1, sigma1, mu2, sigma2):
    """Closed-form KL(N(mu1, sigma1^2) || N(mu2, sigma2^2)), in nats."""
    return (math.log(sigma2 / sigma1)
            + (sigma1 ** 2 + (mu1 - mu2) ** 2) / (2 * sigma2 ** 2)
            - 0.5)

def gaussian_log_pdf(x, mu, sigma):
    """Log-density of N(mu, sigma^2) at x."""
    return (-0.5 * math.log(2 * math.pi * sigma ** 2)
            - (x - mu) ** 2 / (2 * sigma ** 2))

def mc_kl(mu1, sigma1, mu2, sigma2, n=200000):
    """Monte Carlo estimate of the same KL from n samples x ~ P, with its
    standard error."""
    x = np.random.default_rng().normal(loc=mu1, scale=sigma1, size=n)
    r = gaussian_log_pdf(x, mu1, sigma1) - gaussian_log_pdf(x, mu2, sigma2)
    return float(r.mean()), float(r.std() / math.sqrt(n))

For the mean shift, we can predict the estimator's accuracy in advance. The log-ratio is log⁡p(x)−log⁡q(x)=12−x\log p(x) - \log q(x) = \tfrac12 - x, which has variance 11 under PP, so the average of n=2⋅105n = 2 \cdot 10^5 samples has standard error 1/n=0.00221/\sqrt{n} = 0.0022.

For the pair with different variances, however, the two directions are not equally easy to estimate. Up to sign, both average the same function, ln⁡2−38x2\ln 2 - \tfrac38 x^2, but one samples from the narrow Gaussian while the other samples from the wide one, where x2x^2 fluctuates four times as much. Let us estimate all three divergences and check.

pairs = {'N(0,1) || N(1,1)': (0.0, 1.0, 1.0, 1.0),
         'N(0,1) || N(0,4)': (0.0, 1.0, 0.0, 2.0),
         'N(0,4) || N(0,1)': (0.0, 2.0, 0.0, 1.0)}
print(f'{"P || Q":18s} {"closed":>7s} {"sampled":>8s} {"std err":>8s}')
for name, args in pairs.items():
    estimate, std_err = mc_kl(*args)
    print(f'{name:18s} {gaussian_kl(*args):7.4f} {estimate:8.4f} {std_err:8.4f}')
P || Q              closed  sampled  std err
N(0,1) || N(1,1)    0.5000   0.5010   0.0022
N(0,1) || N(0,4)    0.3181   0.3169   0.0012
N(0,4) || N(0,1)    0.8069   0.8017   0.0047

The standard errors come out to 0.00220.0022, 0.00120.0012, and 0.00470.0047, and every estimate lands within a few standard errors of the closed form. Notice that the direction sampling from the wide Gaussian is four times noisier than its reverse, meaning it requires sixteen times as many samples to reach the same accuracy. Panel (b) of Figure 25.1.4 explains why: most of this divergence comes from the tails, where the log-ratio is large and samples are sparse. We will encounter this same sampling difficulty at a much larger scale in Section 25.7.

25.1.4.3 Maximum Entropy and the Gaussian#

On a finite set, the uniform distribution maximizes uncertainty. Which density on the real line plays the same role? Without any constraint, none does: no density can be uniform on all of R\mathbb{R}, and stretching a density raises its differential entropy without limit. Suppose instead that we fix the two moments a Gaussian model reports, the mean μ\mu and variance σ2\sigma^2. Among all densities with those two moments, the Gaussian has the largest differential entropy. In this precise sense, a Gaussian noise model makes the fewest assumptions: it commits to a mean and a variance, and to nothing else.

The proof mirrors our one-line argument for the uniform bound, with a single twist. In the discrete case, −log⁡u(x)=log⁡k-\log u(x) = \log k was constant across all outcomes, so every distribution PP had the same cross-entropy log⁡k\log k to the uniform model. Here, let φ\varphi denote the Gaussian density with mean μ\mu and variance σ2\sigma^2. Its surprisal −log⁡φ(x)=12log⁡(2πσ2)+(x−μ)22σ2-\log \varphi(x) = \tfrac{1}{2}\log(2\pi\sigma^2) + \tfrac{(x-\mu)^2}{2\sigma^2} is no longer constant, but it is a quadratic function of xx, and the expectation of a quadratic depends on PP solely through the two moments we fixed. For every density PP with mean μ\mu and variance σ2\sigma^2,

CE(P,φ)=12log⁡(2πσ2)+EP[(x−μ)2]2σ2=12log⁡(2πσ2)+12=12log⁡(2πeσ2).\textrm{CE}(P, \varphi) = \tfrac{1}{2}\log(2\pi\sigma^2) + \frac{\mathbb{E}_P\big[(x-\mu)^2\big]}{2\sigma^2} = \tfrac{1}{2}\log(2\pi\sigma^2) + \tfrac{1}{2} = \tfrac{1}{2}\log(2\pi e \sigma^2).

Remarkably, the cross-entropy to φ\varphi does not depend on which such PP generated the data. Setting P=φP = \varphi reduces cross-entropy to entropy, so this constant is the Gaussian's own differential entropy, the closed form we quoted earlier. For any other density PP with the same moments, the decomposition (25.1.5) (with hh in place of HH) and Gibbs' inequality yield

h(P)=CE(P,φ)−DKL(P∥φ)≤12log⁡(2πeσ2)=h(N(μ,σ2)),(25.1.12)h(P) = \textrm{CE}(P, \varphi) - D_{\textrm{KL}}(P\|\varphi) \leq \tfrac{1}{2}\log(2\pi e \sigma^2) = h(\mathcal{N}(\mu, \sigma^2)), \tag{25.1.12}

with equality if and only if P=N(μ,σ2)P = \mathcal{N}(\mu, \sigma^2). (If h(P)=−∞h(P) = -\infty, the inequality holds trivially.) The gap in this bound, DKL(P∥φ)D_{\textrm{KL}}(P\|\varphi), also has a direct interpretation: it is the excess loss incurred by the best possible Gaussian model when the data are not Gaussian (Exercise 8).

The uniform and Gaussian distributions are two instances of a single principle. Whenever a candidate density's surprisal averages to the same constant under every distribution satisfying the constraints, that candidate maximizes entropy among all of them. Section 24.4.2 establishes this result in full generality for constraints on the expectations of arbitrary statistics, where the maximizing distributions form an exponential family. The geometric distribution on the non-negative integers {0,1,2,…}\{0, 1, 2, \ldots\} is a third example: its surprisal is affine in the outcome, so it maximizes entropy among all distributions on the non-negative integers with a given mean.

Let us step back and see what remains open. Earlier, the discrete model Q′Q' assigned zero probability to an outcome that actually occurred, making its KL divergence infinite; the narrow Gaussian of Figure 25.1.4 came close, accumulating most of its divergence in tails it had nearly ruled out. A generative model that maps a few random numbers into an image places all of its probability mass on a thin surface inside pixel space. If real data do not lie on that exact surface, the KL divergence is infinite regardless of whether the surface passes right next to the data or miles away. Section 25.3 shows that every divergence built from the density ratio p/qp/q shares this blindness, and Section 25.4 develops comparison measures that can still tell near from far. A second question lies even closer at hand. Earlier we counted yes/no questions and read them as binary codewords, but only for a dyadic source whose surprisals were whole numbers of bits. Section 25.2 constructs codes for arbitrary sources and asks how close a real compressor can get to the entropy.

25.1.5 Summary#

A cross-entropy loss measures a model's average surprisal on the data. It decomposes into the entropy of the data, which no model can lower, plus the KL divergence from the data to the model, which by Gibbs' inequality is never negative and vanishes only for the true distribution. Any loss value must therefore be judged against its irreducible floor, the conditional entropy of the label given the input, which on fresh data only the true conditional probabilities can reach. That floor is zero when the input uniquely determines the label, and Hb(ρ)+ρlog⁡(k−1)H_b(\rho) + \rho \log(k-1) under symmetric label noise at rate ρ\rho.

In bits, the entropy of a finite source equals the average number of yes/no questions needed to identify an outcome (to within one question) and is at most log⁡2k\log_2 k for kk outcomes. Softening the targets shifts the optimum: label smoothing creates a finite optimal logit gap with a positive loss floor, while knowledge distillation matches a softened teacher, with the factor τ2\tau^2 keeping the gradient scale steady as the temperature changes. For continuous densities, differential entropy can be negative and shifts with the units of measurement, whereas both the KL divergence and the minimizer of the cross-entropy remain invariant.

25.1.6 Exercises#

  1. Uniqueness of self-information. ● Show that self-information is unique up to scale: if a strictly decreasing function I(p)I(p) on (0,1](0, 1] satisfies I(1)=0I(1) = 0 and I(p1p2)=I(p1)+I(p2)I(p_1 p_2) = I(p_1) + I(p_2) for all p1,p2∈(0,1]p_1, p_2 \in (0, 1], then I(p)=−clog⁡pI(p) = -c \log p for some constant c>0c > 0. Work with the function g(t)=I(e−t)g(t) = I(e^{-t}) for t≥0t \geq 0.

  2. [code] The label-noise floor. Labels on kk classes are correct with probability 1−ρ1-\rho and otherwise uniform over the other k−1k-1 classes, independently of the input.

    1. Assume that the clean label is a function of the input. Show that the population cross-entropy of any classifier is at least Hb(ρ)+ρlog⁡(k−1)H_b(\rho) + \rho\log(k-1), that the optimal prediction is the noisy conditional distribution itself, and that the optimal accuracy is 1−ρ1-\rho whenever 1−ρ>ρ/(k−1)1 - \rho > \rho/(k-1).
    2. Evaluate the floor for k=10k = 10 and ρ=0.05,0.1,0.2\rho = 0.05, 0.1, 0.2.
    3. A colleague reports a validation loss of 0.400.40 nats on a 10-class data set known to have 10%10\% such noise in every split. List possible explanations, and say which of them the floor rules out and which it does not.
    4. Train the softmax regression of Section 3.3 on Fashion-MNIST with 10%10\% of the training and test labels flipped in this way. Compare the test loss with 0.5450.545 and the test accuracy with 90%90\%. The gap is large. Which assumption of (a) does Fashion-MNIST violate, what does the linear model's own error add, and how could you estimate the floor that does apply?
  3. Other scoring rules. A scoring rule S(q,y)S(\mathbf{q}, y) is strictly proper if the expected penalty Ey∼p[S(q,y)]\mathbb{E}_{y \sim \mathbf{p}}[S(\mathbf{q}, y)] is uniquely minimized at q=p\mathbf{q} = \mathbf{p}. For the log score, this property is Gibbs' inequality.

    1. Show that the expected Brier score, with S(q,y)=∑j(qj−1(j=y))2S(\mathbf{q}, y) = \sum_j (q_j - \mathbf{1}(j = y))^2, exceeds the expected Brier score of the truthful report by ∥q−p∥2\|\mathbf{q} - \mathbf{p}\|^2, so that the Brier score is strictly proper (Gneiting and Raftery, 2007).
    2. The linear score S(q,y)=−qyS(\mathbf{q}, y) = -q_y rewards the probability placed on the observed class. Which report minimizes its expected penalty? Is the linear score proper? What does a classifier trained with it report for an input whose label is class 11 with probability 0.60.6 and class 22 with probability 0.40.4?
  4. Label smoothing on ambiguous inputs. ● Label smoothing trains with the target (25.1.8).

    1. In the training distribution, an input x\mathbf{x} carries the label yy with probability p(y∣x)p(y \mid \mathbf{x}). Show that the expected smoothed loss for this input is minimized by q∗(⋅∣x)=(1−ϵ) p(⋅∣x)+ϵk1\mathbf{q}^*(\cdot \mid \mathbf{x}) = (1 - \epsilon)\, p(\cdot \mid \mathbf{x}) + \tfrac{\epsilon}{k}\mathbf{1}. How can p(⋅∣x)p(\cdot \mid \mathbf{x}) be recovered from q∗\mathbf{q}^*? What is the largest probability that the minimizer can assign to a class?
    2. For one example with logits z\mathbf{z} and q=softmax(z)\mathbf{q} = \mathrm{softmax}(\mathbf{z}), the gradient of CE(pϵ,q)\textrm{CE}(\mathbf{p}^\epsilon, \mathbf{q}) with respect to zjz_j is qj−pjϵq_j - p^\epsilon_j. For ϵ>0\epsilon > 0, show that all wrong-class logits are equal at every stationary point.
    3. With one-hot targets (ϵ=0\epsilon = 0), the gradient with respect to a wrong-class logit is qjq_j, and the loss has no stationary point. Show that gradient descent on the logits of one example still shrinks the gap between two wrong-class logits, and explain why this shrinkage stalls as qy→1q_y \to 1. In a network, the logits of all examples are computed from shared features. Which differences between wrong-class logits can therefore survive training with ϵ=0\epsilon = 0? Why does training with ϵ>0\epsilon > 0 remove them?
    4. Müller et al. (2019) observe that teachers trained with label smoothing produce worse students under the distillation loss (25.1.9). Explain this observation with the results of (b) and (c).
  5. [code] Distillation at high temperature. ● Hinton et al. (2015) state in their Section 2.1 that, at high temperature, distillation reduces to matching zero-mean logits by squared error.

    1. Write qj=pj(1+uj)q_j = p_j(1 + u_j), so that ∑jpjuj=0\sum_j p_j u_j = 0, and expand DKL(p∥q)=−∑jpjlog⁡(1+uj)D_{\textrm{KL}}(\mathbf{p} \| \mathbf{q}) = -\sum_j p_j \log(1 + u_j) to second order to obtain
DKL(p∥q)=12∑j(qj−pj)2pj+O(∥q−p∥3).D_{\textrm{KL}}(\mathbf{p} \| \mathbf{q}) = \frac{1}{2}\sum_j \frac{(q_j - p_j)^2}{p_j} + O\big(\|\mathbf{q} - \mathbf{p}\|^3\big).

Combine this expansion with the large-τ\tau approximation of softmax(z/τ)\mathrm{softmax}(\mathbf{z}/\tau) in Section 25.1.3.4 to show that, as τ→∞\tau \to \infty,

τ2DKL(p(τ) ∥ q(τ))→12k∑j=1k((zjstu−zˉstu)−(zjtea−zˉtea))2.\tau^2 D_{\textrm{KL}}\big(\mathbf{p}^{(\tau)} \,\|\, \mathbf{q}^{(\tau)}\big) \to \frac{1}{2k} \sum_{j=1}^k \Big(\big(z^{\textrm{stu}}_j - \bar z^{\textrm{stu}}\big) - \big(z^{\textrm{tea}}_j - \bar z^{\textrm{tea}}\big)\Big)^2.
  1. Evaluate τ2DKL(p(τ)∥q(τ))\tau^2 D_{\textrm{KL}}(\mathbf{p}^{(\tau)} \| \mathbf{q}^{(\tau)}) for τ=1,2,5,10,100\tau = 1, 2, 5, 10, 100 with the logits z_tea =(5,2,−1)= (5, 2, -1) and z_stu =(3,3,0)= (3, 3, 0) of Section 25.1.3.4, and compare it with the limit.
  2. At low temperature, which teacher logits have almost no influence on the loss? Hinton et al. (2015) argue that this can be an advantage and also a drawback. Give one argument for each side, based on what the teacher's own cross-entropy training does to these logits.
  1. [code] Quantized entropy against differential entropy. Let XX have density pp, and let XΔX_\Delta record which cell [iΔ,(i+1)Δ)[i\Delta, (i+1)\Delta) contains XX.

    1. Show that H(XΔ)+log⁡Δ→h(X)H(X_\Delta) + \log \Delta \to h(X) as Δ→0\Delta \to 0 when pp is continuous and pp and plog⁡pp \log p are Riemann-integrable. Write P(XΔ=i)=p(xi)ΔP(X_\Delta = i) = p(x_i)\Delta for some xix_i in the cell, by the mean value theorem for integrals.
    2. Check the limit by hand for the uniform density on [0,1][0, 1] with Δ=18\Delta = \tfrac18. What happens for a cell width that does not divide 11, such as Δ=0.3\Delta = 0.3?
    3. Compute H(XΔ)+log⁡ΔH(X_\Delta) + \log \Delta numerically for X∼N(0,1)X \sim \mathcal{N}(0, 1) with Δ=0.5,0.1,0.01\Delta = 0.5, 0.1, 0.01, using the Gaussian distribution function for the cell probabilities, and compare it with h=12log⁡(2πe)≈1.4189h = \tfrac12\log(2\pi e) \approx 1.4189 nats. (At Δ=0.5\Delta = 0.5 you should find 1.42921.4292.)
    4. Why does H(XΔ)H(X_\Delta) itself diverge as Δ→0\Delta \to 0? A regression target is binned into cells of width Δ\Delta and predicted with a softmax classifier. Which quantity does its loss approach at best, and what must be added to it before it can be compared with the negative log-density of a continuous model?
  2. Gaussian KL divergence. Let P=N(μ1,σ12)P = \mathcal{N}(\mu_1, \sigma_1^2).

    1. Derive the closed form (25.1.11) by writing out Ex∼P[log⁡p(x)−log⁡q(x)]\mathbb{E}_{x\sim P}[\log p(x) - \log q(x)] and using Ex∼P[x]=μ1\mathbb{E}_{x \sim P}[x] = \mu_1 and Ex∼P[(x−μ1)2]=σ12\mathbb{E}_{x\sim P}[(x-\mu_1)^2] = \sigma_1^2.
    2. Let QQ have mean μ1+δ\mu_1 + \delta and standard deviation σ1eη\sigma_1 e^{\eta}. Expand both DKL(P∥Q)D_{\textrm{KL}}(P\|Q) and DKL(Q∥P)D_{\textrm{KL}}(Q\|P) to second order in δ\delta and η\eta. At which order do the two directions first differ?
    3. Evaluate the second-order approximation for P=N(0,1)P = \mathcal{N}(0, 1) and Q=N(0,4)Q = \mathcal{N}(0, 4), and compare it with the exact values 0.3180.318 and 0.8070.807 nats of the two directions.
  3. The excess loss of a Gaussian model. A regression model reports a Gaussian N(m,s2)\mathcal{N}(m, s^2) for a target whose density PP has mean μ\mu, variance σ2\sigma^2 and a finite differential entropy.

    1. Show that CE(P,N(m,s2))\textrm{CE}(P, \mathcal{N}(m, s^2)) is smallest at m=μm = \mu and s2=σ2s^2 = \sigma^2, and that this best Gaussian model exceeds the floor h(P)h(P) by DKL(P∥φ)=h(φ)−h(P)D_{\textrm{KL}}(P\|\varphi) = h(\varphi) - h(P), where φ\varphi is the density of N(μ,σ2)\mathcal{N}(\mu, \sigma^2).
    2. Evaluate the excess for the uniform density on [0,a][0, a], which has variance a2/12a^2/12, and for the Laplace density 12be−∣x∣/b\tfrac{1}{2b} e^{-|x|/b}, which has variance 2b22b^2 and differential entropy 1+log⁡(2b)1 + \log(2b). (You should find about 0.1760.176 and 0.0720.072 nats.)
    3. Neither answer depends on the scale aa or bb. Explain why without computing, from what Section 25.1.4.1 says about a change of units.
    4. The Gaussian has the largest entropy for a given variance, so no density has a higher floor. Is there also a largest excess? Consider densities that concentrate near the two points μ±σ\mu \pm \sigma. What does your answer say about a Gaussian model for a target with two well-separated modes?

Discussions