Ten problems on entropy, cross-entropy and the Kullback–Leibler divergence: the Bernoulli entropy and its maximum, why the uniform distribution maximises entropy, bits, nats and perplexity, cross-entropy as entropy plus KL, label smoothing, a proof that KL is non-negative, forward and reverse KL, the KL between two Gaussians and the VAE term with its gradients, with worked solutions and the mistakes that swap the arguments or drop a factor.
Before you start
Entropy, cross-entropy and the KL divergence are three views of one quantity: the average number of nats it costs to describe outcomes from one distribution using another. Cross-entropy is the loss a classifier is trained on, the KL divergence is the term a variational autoencoder adds to it, and entropy is the floor neither can go below. These ten problems compute each by hand, prove the one inequality everything rests on, show that the two orders of KL prefer different fits, and derive the closed forms for Gaussians that a VAE uses. The five mistakes at the end are the ones that produce a plausible number: KL with its arguments swapped, a zero probability treated as harmless, a Gaussian log term without its ,21, a VAE gradient taken in the wrong variable, and a label-smoothed loss expected to reach zero.
p and q are distributions over K outcomes :i=1,…,K: every pi≥0 and ,∑ipi=1, and the same for .q.log is the natural log, and quantities measured with it are in nats; log2 gives bits.
The entropy is ,H(p)=−∑ipilogpi, the cross-entropy is ,H(p,q)=−∑ipilogqi, and the Kullback–Leibler divergence is .KL(p∥q)=∑ipilog(pi/qi).
Zero probabilities follow the usual conventions: a term with pi=0 is 0 in all three sums (,0log0=0, the limit of tlogt as ),t→0+), and a term with pi>0 and qi=0 makes H(p,q) and KL(p∥q) equal to .+∞.
u is the uniform distribution, .ui=1/K.y is a one-hot target, 1 at the true class c and 0 elsewhere, and 1 is the all-ones vector.
N(μ,σ2) is the Gaussian with mean ,μ, variance σ2>0 and density .2πσ21e−(x−μ)2/(2σ2). For densities the sums become integrals: .KL(p∥q)=∫p(x)logq(x)p(x)dx.Ep[f] is the expectation of f under .p.
The perplexity of a distribution or a model is eH with H in nats, equivalently 2H with H in bits: the number of equally likely outcomes that would have the same entropy.
The softmax page derives the gradient of cross-entropy with respect to the logits, ,s−y, including soft targets; this page works with the distributions themselves.
The entropy of a coin with probability p of heads is H(p)=−plogp−(1−p)log(1−p) for .0<p<1. Compute ,H′(p), find the p that maximises ,H, and give the maximum in nats and in bits.
··
Over K outcomes, use a Lagrange multiplier to find the distribution p that maximises .H(p). Then show that ,KL(p∥u)=logK−H(p), and use it to confirm that the stationary point is the global maximum.
·
Let .p=(21,41,81,81). Compute H(p) in bits and in nats, and its perplexity. Then: a language model's mean negative log-likelihood on a test set is 2.3 nats per token. What is its perplexity?
··
Show that .H(p,q)=H(p)+KL(p∥q). Then take label smoothing with K classes and :0<ε<1: the target is .p=(1−ε)y+Kε1. Write H(p,q) in terms of logqc and ,∑ilogqi, and give its minimum over .q.
···
Use the inequality logt≤t−1 for t>0 to prove that ,KL(p∥q)≥0, with equality only when .q=p.
·
Let p=(21,21) and .q=(109,101). Compute KL(p∥q) and .KL(q∥p).
··
Let ,p=(21,0,21), a distribution with two modes, and consider two approximations: ,qA=(1,0,0), which keeps one mode, and ,qB=(31,31,31), which covers everything. Compute KL(p∥q) and KL(q∥p) for both, and say which approximation each direction prefers.
···
Let p=N(μ1,σ12) and .q=N(μ2,σ22). Derive
KL(p∥q)=logσ1σ2+2σ22σ12+(μ1−μ2)2−21.
···
A VAE encoder outputs μ∈Rd and s∈Rd with ,sj=logσj2, defining ;q=N(μ,diag(σ2)); the prior is .N(0,I). Show that
KL(q∥N(0,I))=21j=1∑d(μj2+esj−sj−1),
and compute its gradients with respect to μ and .s.
··
Data x1,…,xN take values in ;{1,…,K}; outcome i occurs ni times, and p^i=ni/N is the empirical distribution. A model assigns probabilities .q. Show that the mean negative log-likelihood equals ,H(p^,q), and use it to find the q that maximises the likelihood and the smallest mean negative log-likelihood.
Answers
;H′(p)=logp1−p; the maximum is at ,p=21, where H=ln2≈0.693 nats =1 bit
,p=u,,pi=1/K, with maximum ;H(u)=logK; for every ,p,H(p)=logK−KL(p∥u)≤logK
H(p)=47 bits =47ln2≈1.213 nats; perplexity ;27/4≈3.364; a mean NLL of 2.3 nats gives perplexity e2.3≈9.97
;H(p,q)=H(p)+KL(p∥q); with label smoothing ,H(p,q)=−(1−ε)logqc−Kε∑ilogqi, minimised at q=p with value H(p)>0
KL(p∥q)≥0 for all ,p,q, with equality if and only if q=p
,KL(p∥qA)=∞,;KL(p∥qB)=ln23;,KL(qA∥p)=ln2,:KL(qB∥p)=∞: the forward KL prefers the covering ,qB, the reverse KL the single-mode qA
KL(p∥q)=lnσ1σ2+2σ22σ12+(μ1−μ2)2−21
;KL=21∑j(μj2+esj−sj−1);∇μKL=μ and ∂KL/∂sj=21(esj−1)=21(σj2−1)
Mean NLL ;=H(p^,q)=H(p^)+KL(p^∥q); it is minimised at ,qi=ni/N, where it equals H(p^)
Worked solutions
Problem 1
The entropy of a coin with probability p of heads is H(p)=−plogp−(1−p)log(1−p) for .0<p<1. Compute ,H′(p), find the p that maximises ,H, and give the maximum in nats and in bits.
.dpd[−plogp]=−logp−1.Product rule: p differentiates to ,1, and .p⋅p1=1.
.dpd[−(1−p)log(1−p)]=log(1−p)+1.The same derivative at ,1−p, times the inner derivative ,−1, which flips both signs.
.H′(p)=log(1−p)−logp=logp1−p.Add steps 1 and 2; the −1 and +1 cancel.
H′(p)>0 for ,p<21,H′(p)=0 at ,p=21, and H′(p)<0 for .p>21.logt>0 exactly when ,t>1, and (1−p)/p>1 exactly when .p<21. So H rises and then falls, and its one stationary point is the maximum.
.H(21)=−21log21−21log21=log2.Both terms are equal.
;H′(p)=logp1−p; the maximum is at ,p=21, where H=ln2≈0.693 nats =1 bitDividing by ln2 converts nats to bits, because .log2t=lnt/ln2. A fair coin is the most uncertain coin, and one flip carries exactly one bit.
Problem 2
Over K outcomes, use a Lagrange multiplier to find the distribution p that maximises .H(p). Then show that ,KL(p∥u)=logK−H(p), and use it to confirm that the stationary point is the global maximum.
.L(p,λ)=−∑ipilogpi+λ(∑ipi−1).The constraint ∑ipi=1 enters with a multiplier. The constraints pi≥0 can be left out: ∂H/∂pi=−logpi−1→+∞ as ,pi→0+, so a maximiser never sits on that boundary.
,∂L/∂pi=−logpi−1+λ=0, so .pi=eλ−1.Only the i-th term of each sum contains .pi. The right-hand side is the same for every ,i, so all the pi are equal.
,∑ipi=Keλ−1=1, so ,pi=1/K, and .H(u)=−∑iK1logK1=logK.The constraint fixes the common value.
.KL(p∥u)=∑ipilog(Kpi)=logK∑ipi+∑ipilogpi=logK−H(p).,pi/ui=Kpi, the log of a product is a sum of logs, and .∑ipi=1.
,p=u,,pi=1/K, with maximum ;H(u)=logK; for every ,p,H(p)=logK−KL(p∥u)≤logKKL≥0 with equality only when the two distributions are equal (Problem 5), so step 4 bounds every entropy by ,logK, with equality only at .p=u. No second-derivative test is needed.
Problem 3
Let .p=(21,41,81,81). Compute H(p) in bits and in nats, and its perplexity. Then: a language model's mean negative log-likelihood on a test set is 2.3 nats per token. What is its perplexity?
H(p)=21⋅1+41⋅2+81⋅3+81⋅3=47 bits.Each probability is a power of ,2, and .−log22−k=k.
H(p)=47ln2≈1.213 nats.,lnt=ln2⋅log2t, so every term, and the sum, scales by .ln2.
Perplexity .=27/4=e(7/4)ln2≈3.364.The base of the exponential must match the unit of :H:2 for bits, e for nats. Both give the same number. It lies between 2 and :4: the distribution is as uncertain as a fair choice among about 3.4 outcomes.
The mean negative log-likelihood is the cross-entropy between the test data and the model, in nats, so the perplexity is .e2.3.Problem 10 shows the mean negative log-likelihood is a cross-entropy; the unit is nats because the loss used .ln.
H(p)=47 bits =47ln2≈1.213 nats; perplexity ;27/4≈3.364; a mean NLL of 2.3 nats gives perplexity e2.3≈9.97The model is, on average, as unsure of the next token as a uniform choice among about ten.
Problem 4
Show that .H(p,q)=H(p)+KL(p∥q). Then take label smoothing with K classes and :0<ε<1: the target is .p=(1−ε)y+Kε1. Write H(p,q) in terms of logqc and ,∑ilogqi, and give its minimum over .q.
.KL(p∥q)=∑ipilogpi−∑ipilogqi=−H(p)+H(p,q).,log(pi/qi)=logpi−logqi, and each sum is one of the definitions.
.H(p,q)=H(p)+KL(p∥q).Rearrange step 1.
H(p) does not depend on ,q, so minimising H(p,q) over q is minimising ,KL(p∥q), and the minimum is ,H(p), at .q=p.,KL(p∥q)≥0, with equality only at q=p (Problem 5).
.H(p,q)=−∑i[(1−ε)yi+Kε]logqi=−(1−ε)logqc−Kε∑ilogqi.Cross-entropy is linear in its first argument, and the one-hot y picks out the term .i=c.
;H(p,q)=H(p)+KL(p∥q); with label smoothing ,H(p,q)=−(1−ε)logqc−Kε∑ilogqi, minimised at q=p with value H(p)>0The second term penalises any class whose probability goes to ,0, which is how smoothing stops the logits growing without bound. Because p is not one-hot, :H(p)>0: the loss has a floor above zero (the last mistake below).
Problem 5
Use the inequality logt≤t−1 for t>0 to prove that ,KL(p∥q)≥0, with equality only when .q=p.
logt≤t−1 for every ,t>0, with equality only at .t=1.f(t)=t−1−logt has ,f′(t)=1−1/t, negative for t<1 and positive for ,t>1, so its minimum is .f(1)=0.
Let .S={i:pi>0}. If qi=0 for some ,i∈S, then .KL(p∥q)=+∞>0. Otherwise .−KL(p∥q)=∑i∈Spilogpiqi.Terms with pi=0 are 0 by convention, and .−log(pi/qi)=log(qi/pi).
.∑i∈Spilogpiqi≤∑i∈Spi(piqi−1)=∑i∈Sqi−1.Step 1 with ,t=qi/pi>0, multiplied by the positive weight ;pi; then .∑i∈Spi=1.
,∑i∈Sqi≤∑iqi=1, so .−KL(p∥q)≤0.Leaving out terms of a sum of non-negative numbers can only make it smaller.
Equality needs qi/pi=1 for every i∈S (step 3) and ∑i∈Sqi=1 (step 4), so qi=pi on S and qi=0=pi off it.The equality case of step 1 applies term by term, because every weight pi in step 3 is positive.
KL(p∥q)≥0 for all ,p,q, with equality if and only if q=pThis is Gibbs' inequality. It is what makes H(p) the floor of the cross-entropy (Problem 4), logK the ceiling of the entropy (Problem 2) and the empirical distribution the maximum-likelihood fit (Problem 10).
Problem 6
Let p=(21,21) and .q=(109,101). Compute KL(p∥q) and .KL(q∥p).
.KL(p∥q)=21log9/101/2+21log1/101/2=21log95+21log5=21log925=log35.The definition, then 21(loga+logb)=21logab and .21log(25/9)=log(5/3).
.KL(q∥p)=109log1/29/10+101log1/21/10=0.9log1.8−0.1log5.The weights now come from ,q, and .log(1/5)=−log5.
;KL(p∥q)=ln35≈0.511;KL(q∥p)=0.9ln1.8−0.1ln5≈0.368The two differ, so KL is not symmetric and not a distance. The larger one weights by ,p, which puts half its mass on an outcome q gives only :101: KL is large when the first distribution is often surprised by the second.
Problem 7
Let ,p=(21,0,21), a distribution with two modes, and consider two approximations: ,qA=(1,0,0), which keeps one mode, and ,qB=(31,31,31), which covers everything. Compute KL(p∥q) and KL(q∥p) for both, and say which approximation each direction prefers.
.KL(p∥qA)=+∞.Outcome 3 has p3=21>0 and ,qA,3=0, so its term is .21log(21/0)=+∞.
.KL(p∥qB)=21log1/31/2+0+21log1/31/2=log23≈0.405.The middle term has p2=0 and is 0 by convention.
.KL(qA∥p)=1⋅log1/21=log2≈0.693.Now the weights are qA's; the terms with qA,i=0 vanish.
.KL(qB∥p)=+∞.Outcome 2 has qB,2=31>0 and .p2=0.
,KL(p∥qA)=∞,;KL(p∥qB)=ln23;,KL(qA∥p)=ln2,:KL(qB∥p)=∞: the forward KL prefers the covering ,qB, the reverse KL the single-mode qAKL(p∥q) is infinite when q misses mass that p has, so minimising it over q spreads q out (mass-covering). KL(q∥p) is infinite when q puts mass where p has none, so minimising it shrinks q onto one mode (mode-seeking). Maximum likelihood minimises the forward direction (Problem 10); variational inference, including the VAE, minimises the reverse.
Problem 8
Let p=N(μ1,σ12) and .q=N(μ2,σ22). Derive
KL(p∥q)=logσ1σ2+2σ22σ12+(μ1−μ2)2−21.
,logp(x)=−21log(2πσ12)−2σ12(x−μ1)2, and likewise for .q.The log of the density in the definitions.
.logp(x)−logq(x)=logσ1σ2−2σ12(x−μ1)2+2σ22(x−μ2)2.The 2π cancels, and .−21logσ12+21logσ22=log(σ2/σ1).
.Ep[(x−μ1)2]=σ12.The definition of the variance of .p.
.Ep[(x−μ2)2]=σ12+(μ1−μ2)2.Write x−μ2=(x−μ1)+(μ1−μ2) and expand: the cross term is .2(μ1−μ2)Ep[x−μ1]=0.
.KL(p∥q)=Ep[logp(x)−logq(x)]=logσ1σ2−2σ12σ12+2σ22σ12+(μ1−μ2)2.KL is the expectation under p of the log-ratio; expectation is linear, so steps 3 and 4 apply term by term.
KL(p∥q)=lnσ1σ2+2σ22σ12+(μ1−μ2)2−21Sanity check: with μ1=μ2 and σ1=σ2 it is .0+21−21=0. The mean difference is measured in units of q's spread, ,σ2, which is again not symmetric.
Problem 9
A VAE encoder outputs μ∈Rd and s∈Rd with ,sj=logσj2, defining ;q=N(μ,diag(σ2)); the prior is .N(0,I). Show that
KL(q∥N(0,I))=21j=1∑d(μj2+esj−sj−1),
and compute its gradients with respect to μ and .s.
Both densities are products over coordinates, so ,logq(x)−logp0(x)=∑j[logqj(xj)−logp0(xj)], and the KL is .∑jKL(N(μj,σj2)∥N(0,1)).A diagonal covariance makes the coordinates independent, the log of a product is a sum, and the expectation of each term involves only ,xj, whose distribution under q is .N(μj,σj2).
Each term is .−logσj+21(σj2+μj2)−21.Problem 8 with ,μ1=μj,,σ1=σj,,μ2=0,.σ2=1.
,−logσj=−21logσj2=−21sj, and .σj2=esj.Rewrite in the variable the encoder outputs.
.KL=21∑j(μj2+esj−sj−1).Steps 2 and 3, summed over .j.
∂KL/∂μj=μj and .∂KL/∂sj=21(esj−1).Only the j-th term contains μj or ;sj;21μj2 differentiates to ,μj, and 21(esj−sj) to .21(esj−1).
;KL=21∑j(μj2+esj−sj−1);∇μKL=μ and ∂KL/∂sj=21(esj−1)=21(σj2−1)Both gradients vanish exactly at ,μ=0,,σ2=1, the prior. Outputting s=logσ2 rather than σ2 keeps the variance positive with no constraint on the network.
Problem 10
Data x1,…,xN take values in ;{1,…,K}; outcome i occurs ni times, and p^i=ni/N is the empirical distribution. A model assigns probabilities .q. Show that the mean negative log-likelihood equals ,H(p^,q), and use it to find the q that maximises the likelihood and the smallest mean negative log-likelihood.
.N1∑n=1N−logqxn=∑i=1KNni(−logqi).Group the terms by outcome: the term −logqi appears once for each of the ni data points equal to .i.
.=H(p^,q)=H(p^)+KL(p^∥q).The definition of cross-entropy with ,p^i=ni/N, then Problem 4.
H(p^) does not depend on ,q, and KL(p^∥q)≥0 with equality only at .q=p^.Problem 5. Maximising the likelihood is minimising the mean negative log-likelihood, because log is increasing and .1/N>0.
Mean NLL ;=H(p^,q)=H(p^)+KL(p^∥q); it is minimised at ,qi=ni/N, where it equals H(p^)The maximum-likelihood page reaches the same estimate with a Lagrange multiplier. For a model family qθ that cannot reach ,p^, step 2 still holds: maximum likelihood picks the θ minimising the forward divergence .KL(p^∥qθ).
Where this goes wrong
1. Maximum likelihood written as KL(q_θ ‖ p̂)
KL is often described as the divergence between the model and the data, and the order of its arguments looks like a choice of notation.
Mean NLL =H(p^)+KL(p^∥qθ)Right so far: Problem 10, step 2.
“Fitting a model to data minimises how far the model is from the data, .KL(model∥data).”The phrasing that causes the mistake: it names the model first, but the order is fixed by which distribution the log-loss averages over, and the loss averages over the data.
Maximum likelihood minimises KL(qθ∥p^)p^ is 0 on every outcome that is absent from the data, so KL(qθ∥p^)=∞ for any model that gives an unseen outcome positive probability, including every softmax model. Maximum likelihood minimises ,KL(p^∥qθ), the mass-covering direction (Problem 7); the reverse is the one variational inference minimises.
2. KL term with q_i = 0 dropped as if it were 0 log 0
The convention 0log0=0 makes zero probabilities harmless in an entropy, and it is tempting to apply it to every zero in a KL.
KL(p∥qA)=∑ipilog(pi/qA,i) with p=(21,0,21) and qA=(1,0,0)Right so far: the set-up of Problem 7.
“Terms with a zero probability contribute nothing, so keep only the outcomes where both are positive.”The shortcut that causes the mistake: the convention covers a zero weight pi outside the log, not a zero qi inside it.
KL(p∥qA)=21log11/2=−21ln2A negative KL is already a contradiction of Problem 5. The third term has p3=21 and ,qA,3=0, so it is ,+∞, and so is the KL (Problem 7, step 1). In code the same slip appears as a mask that skips ,qi=0, or a clamp qi≥10−12 that turns ∞ into a large finite number.
3. Gaussian KL with log(σ₂²/σ₁²) and no ½
Gaussians are usually parametrised by their variances, and log-variance is what a network outputs, so the log term gets written with variances.
logp(x)=−21log(2πσ12)−(x−μ1)2/(2σ12)Right so far: Problem 8, step 1.
“The normalising constants contribute the log of the ratio of the variances.”The shortcut that causes the mistake: dropping the 21 that comes from the square root in .1/2πσ2.
KL=log(σ22/σ12)+2σ22σ12+(μ1−μ2)2−21The log term is twice what it should be: log(σ2/σ1)=21log(σ22/σ12) (Problem 8). With ,μ1=μ2,,σ1=1,σ2=2 the correct value is ln2+81−21≈0.318 and this gives .ln4−83≈1.011. The test p=q still gives ,0, so only a check with unequal variances catches it.
4. VAE gradient for log σ² computed as the derivative in σ
Code calls the encoder's second output “the variance”, and the KL is easiest to differentiate in the form it was first written in, with .σj.
KLj=−logσj+21(σj2+μj2)−21Right so far: Problem 9, step 2.
“Differentiate with respect to the variance parameter, ,σj, and pass that to the encoder.”The habit that causes the mistake: the encoder outputs ,sj=logσj2, and the gradient backprop needs is with respect to that output.
∂KL/∂sj=σj−1/σjThat is .∂KL/∂σj. With ,σj=esj/2,,dσj/dsj=σj/2, so ∂KL/∂sj=(σj−1/σj)σj/2=21(σj2−1) (Problem 9). Both vanish at ,σj=1, which hides the slip, but at σj=3 the wrong value is 38 against the correct .4.
5. Reading a label-smoothed loss of 0.51 as far from optimal
A one-hot cross-entropy can be driven towards ,0, and a loss curve trained with label smoothing gets read on the same scale.
H(p,q)=H(p)+KL(p∥q) with p=(1−ε)y+Kε1Right so far: Problem 4.
“A perfect model has zero loss.”The assumption that causes the mistake: it holds only for a one-hot target, whose entropy is .0.
With ε=0.1 and ,K=10, a training loss that levels off at 0.51 nats means the model is still far from its targetsThe floor is ,H(p), with pc=0.91 and the other nine entries :0.01:.−0.91ln0.91−9(0.01)ln0.01≈0.500. A loss of 0.51 is a KL of about ,0.01, almost at the optimum. Subtract H(p) before reading the curve.