Skip to publication

16 min read

KL divergence — why the direction you minimize changes what you get

KL divergence looks like a distance but fails the triangle inequality and isn't symmetric: DKL(PQ)DKL(QP)D_{KL}(P\|Q) \neq D_{KL}(Q\|P). Maximum likelihood minimizes one direction; variational inference is forced into the other. The same formula, pointed backward, will happily ignore an entire mode of the distribution you're trying to model.

By the end you should be able to compute DKL(PQ)D_{KL}(P\|Q) for two discrete distributions, predict whether forward or reverse KL covers or ignores a mode of PP, and diagnose which direction a trained model minimized from its mode-covering or mode-seeking behavior.

Generated from model knowledge. Verify claims independently.
Contents

Cost of distributional mismatch

What does it cost, in expected bits, to believe QQ when the true distribution is PP?

The gambler models the die with QQ, a single peak stacked on face 1. The die itself follows PP, which splits its mass almost evenly between face 1 and face 4 — matching QQ at face 1 but leaving face 4 almost untouched. Every roll the gambler bets according to QQ instead of PP, something is lost, but nothing yet turns that loss into a number.

A first guess is to line up P(x)P(x) and Q(x)Q(x) face by face and sum the plain differences. That number treats every face as interchangeable; it never asks what a wrong belief actually costs. The cost shows up in coding. An optimal code built for QQ spends about logQ(x)-\log Q(x) bits on outcome xx, the shortest expected length any code tuned to QQ can achieve .

excess(x)=logP(x)logQ(x)\text{excess}(x) = \log P(x) - \log Q(x)
Coding outcome xx with a code built for QQ costs logQ(x)-\log Q(x) bits instead of the logP(x)-\log P(x) bits an optimal code for PP would use, a per-outcome overspend of logP(x)logQ(x)\log P(x) - \log Q(x) bits.

On the die, this overspend is largest exactly on face 4, the face PP favors and QQ neglects; face 1 costs little because QQ already tracks PP there. To turn the per-outcome overspend into one number, average it the way rolls actually happen, expectation under the true distribution the true PP, not under the gambler's mistaken QQ.

EP[logP(x)logQ(x)]\mathbb{E}_P[\log P(x) - \log Q(x)]
Averaging the per-outcome excess over outcomes drawn from the true PP gives the expected extra bits per roll spent by believing QQ.

Summing this weighted excess over all six faces gives one scalar mismatch score for the whole die. But face 1's overspend and some other face's possible undershoot could in principle offset each other, and nothing said so far rules out the total landing below zero, which would mean the wrong code somehow saves bits on average.

KL divergence definition

How do we formalize the mismatch cost as DKL(PQ)D_{KL}(P\|Q)?

Take the excess-bit cost for one face of the die, say face 4: logP(4)logQ(4)\log P(4) - \log Q(4). That is a single number tied to a single outcome. The die has six faces, and PP does not visit them equally — it puts almost half its weight on two distant faces and almost none on the rest. Do you add the six per-face costs straight up, or weight each one by how often that face actually comes up under PP? Get this wrong and the total either treats a face PP never sees as equally important, or lets a face PP cares about vanish into the average.

Weight each per-face cost by its true frequency and sum: EP[logP(x)logQ(x)]=xP(x)(logP(x)logQ(x))=xP(x)logP(x)Q(x)\mathbb{E}_P[\log P(x) - \log Q(x)] = \sum_x P(x)\left(\log P(x) - \log Q(x)\right) = \sum_x P(x)\log\frac{P(x)}{Q(x)}. This sum has a name, the forward KL divergence.

DKL(PQ)=xP(x)logP(x)Q(x)D_{KL}(P\|Q) = \sum_x P(x)\log\frac{P(x)}{Q(x)}
DKL(PQ)D_{KL}(P\|Q) averages the log-ratio logP(x)Q(x)\log\frac{P(x)}{Q(x)} under PP itself, so faces PP visits often dominate the sum and faces it almost never visits contribute almost nothing regardless of how wrong QQ is about them.

On the die, suppose PP puts 0.450.45 on face 1 and 0.450.45 on face 4, with 0.0250.025 spread over the remaining four faces. The gambler's QQ is unimodal: 0.60.6 on face 1, small residual probability elsewhere. The face-4 term is 0.45log0.45Q(4)0.45\log\frac{0.45}{Q(4)}; if Q(4)Q(4) is small this single log-ratio is large, and it still gets multiplied by 0.450.45 because that is what PP actually assigns to face 4. The face-1 term stays small because Q(1)P(1)Q(1)\approx P(1). Adding all six terms produces one scalar, the mismatch cost of using QQ on a die genuinely distributed as PP.

Nothing in that sum treats PP and QQ interchangeably. Every weight in front of a log-ratio term comes from PP, never from QQ; swap which distribution supplies the weights and the total changes for a structural reason, not from rounding. Whether this number can ever come out negative — letting a badly mismatched QQ score as though it cost nothing — is still open.

Why KL is never negative

Why is DKL(PQ)0D_{KL}(P\|Q) \ge 0 for every pair of distributions, with equality only when P=QP = Q?

Suppose the gambler's QQ happens to overlap one of the die's two heavy faces while missing the other one entirely. At the overlapping face the log-ratio logP(x)Q(x)\log\frac{P(x)}{Q(x)} turns negative, since QQ now assigns that face even more probability than PP does. At the missed face the log-ratio is a large positive number. Could a clever choice of QQ push the PP-weighted sum of these terms below zero, making the mismatch score negative?

Try it directly. Let P(1)=0.45P(1)=0.45, P(4)=0.45P(4)=0.45, and put Q(1)=0.7Q(1)=0.7, Q(4)=0.05Q(4)=0.05. The face-1 term is 0.45log0.450.70.130.45\log\frac{0.45}{0.7}\approx -0.13, negative as hoped. But the face-4 term is 0.45log0.450.050.990.45\log\frac{0.45}{0.05}\approx 0.99, and it overwhelms the negative one. Shuffle the twelve numbers however you like and the same thing happens: mass QQ steals from an underweighted face produces a positive log-ratio large enough to cancel whatever negative term the overlap bought. That is not a coincidence of this particular QQ .

DKL(PQ)=EP ⁣[logQ(x)P(x)]logEP ⁣[Q(x)P(x)]=logxQ(x)=log1=0D_{KL}(P\|Q) = -\,\mathbb{E}_P\!\left[\log\frac{Q(x)}{P(x)}\right] \ge -\log\mathbb{E}_P\!\left[\frac{Q(x)}{P(x)}\right] = -\log\sum_x Q(x) = -\log 1 = 0
Because log\log is concave, Jensen's inequality flips the usual inequality: the expectation of the log is at most the log of the expectation. Applied to Q(x)/P(x)Q(x)/P(x) averaged under PP, every term telescopes to xQ(x)=1\sum_x Q(x)=1, so the whole expression collapses to zero from below.

Jensen's inequality is tight exactly when the quantity being averaged, Q(x)/P(x)Q(x)/P(x), is constant across every face with P(x)>0P(x)>0. Since both PP and QQ sum to 1 over the same six faces, that constant can only be 1, forcing Q(x)=P(x)Q(x)=P(x) everywhere. This is why the two-peak, one-peak setup above never actually reaches zero: QQ cannot equal PP while restricted to a single mode, so some positive residual is guaranteed no matter how the gambler tunes it.

So DKL(PQ)D_{KL}(P\|Q) is a legitimate non-negative mismatch score, zero only when the gambler's QQ matches PP face for face. It is still not a distance in the usual sense: relabel which distribution on this same die gets called PP and which gets called QQ, and the number the formula returns changes, not just cosmetically.

Forward vs reverse KL

How different are DKL(PQ)D_{KL}(P\|Q) and DKL(QP)D_{KL}(Q\|P) for the same pair, and why?

You already have DKL(PQ)D_{KL}(P\|Q) for the die: true PP splits its weight almost evenly across two distant faces, and the gambler's QQ piles almost everything onto one face sitting between them. Flip the formula — write QQ first, PP second — and recompute. A number that behaves like a distance between two objects shouldn't care which one you call first. Swap PP and QQ everywhere in DKL(PQ)=xP(x)logP(x)Q(x)D_{KL}(P\|Q)=\sum_x P(x)\log\frac{P(x)}{Q(x)} and check whether the result matches what you already found.

It doesn't match. forward KL divergence weights every log-ratio by P(x)P(x): the two distant faces the gambler barely touches carry heavy weight, because that's where PP lives. reverse KL divergence weights the same kind of ratio by Q(x)Q(x) instead: the single face the gambler favors carries almost all the weight, because that's where QQ lives . Swapping PP and QQ doesn't just flip a sign — it moves the averaging measure onto a different set of faces. On a face where PP is large and QQ is tiny, DKL(PQ)D_{KL}(P\|Q) pays a heavy P(x)P(x)-weighted penalty for that mismatch; DKL(QP)D_{KL}(Q\|P) barely notices, because Q(x)Q(x) is tiny there and the term gets almost no weight. The two sums are built from the same log-ratios but averaged under different distributions, so in general DKL(PQ)DKL(QP)D_{KL}(P\|Q) \neq D_{KL}(Q\|P).

How swapping the averaging measure changes the KL value

Forward DKL(PQ)D_{KL}(P\|Q) dominates right at the edges of the range, where xx is near 0 or 1 and QQ abandons a face PP still visits, while reverse DKL(QP)D_{KL}(Q\|P) stays bounded there. But in the interior the ordering can flip: at p=0.1p=0.1, reverse KL exceeds forward KL at every sampled xx from 0.275 to 0.725, so which direction is larger depends on where xx sits relative to pp, not just on the distance between them.

How swapping the averaging measure changes the KL value: live curves controlled by True weight on the gambler's favored face p-0.190.51.191.882.570.050.270.50.720.95
Divergence (nats)Gambler's weight on that face xx
Forward DKL(PQ)D_{KL}(P\|Q)Reverse DKL(QP)D_{KL}(Q\|P)

This collapses the six-face die to two outcomes: the face under the gambler's peak, with true weight pp and gambler weight xx, versus every other face lumped together and held fixed once lumped. It isolates the asymmetry; it is not the full six-face computation.

Notice what the swap actually cost you: it silently changed which mistakes matter. A modeler who fits by minimizing DKL(PQ)D_{KL}(P\|Q) is telling the procedure to worry most about faces where the true die rolls often. A modeler who minimizes DKL(QP)D_{KL}(Q\|P) is telling it to worry most about faces where its own guess rolls often. Choosing which distribution sits on which side of the bar is a modeling decision with consequences, not free notation.

Mode-covering forward KL

What does minimizing DKL(PQ)D_{KL}(P\|Q) over QQ do to QQ's shape, and why does maximum likelihood use this direction?

Force QQ's single hump onto face 11: Q(1)Q(1) soaks up most of the mass, and Q(6)Q(6) is left near zero. But P(6)P(6) is close to P(1)P(1), so the per-outcome excess bit cost term at face 66, logP(6)logQ(6)\log P(6) - \log Q(6), explodes as Q(6)0Q(6) \to 0, and DKL(PQ)D_{KL}(P\|Q) takes on a huge value from that one face alone. Put the hump on face 66 instead and the same disaster happens at face 11. Neither placement is cheap, because DKL(PQ)=blurbterm005b0022006500780070006500630074006100740069006f006e002d00500022002c006e0075006c006c005d[logP(x)logQ(x)]D_{KL}(P\|Q) = ⁣blurbterm005b0022006500780070006500630074006100740069006f006e002d00500022002c006e0075006c006c005d⁣[\log P(x) - \log Q(x)] is an average taken under PP: any face PP visits often but QQ nearly ignores gets charged, repeatedly, at whatever rate PP actually visits it.

Minimizing DKL(PQ)D_{KL}(P\|Q) over QQ therefore refuses to let Q(x)Q(x) sit near zero at any face where P(x)P(x) is not already near zero, call it zero-avoiding. With QQ restricted to one hump, the cheapest single location is the one that keeps both heavy faces at moderate distance rather than starving either one: somewhere between face 11 and face 66. The optimal one-peak QQ lands in that middle ground, spreading mass toward both true peaks instead of committing to one. This is exactly what maximum likelihood does on real data: fitting QQ by maximizing likelihood over samples drawn from PP minimizes DKL(PQ)D_{KL}(P\|Q) up to a constant that does not depend on QQ, so a unimodal model fit this way to bimodal data blurs between the two modes rather than picking one and abandoning the other.

That coverage is not free, it is just an expense forward KL never bills. To keep both peaks fed, QQ's single hump also has to cover the faces between them, faces 22 through 55, where PP places almost no mass. Nothing in blurbterm005b0022006500780070006500630074006100740069006f006e002d00500022002c006e0075006c006c005d[]⁣blurbterm005b0022006500780070006500630074006100740069006f006e002d00500022002c006e0075006c006c005d⁣[\cdot] penalizes QQ for spending probability where PP rarely visits, since P(x)P(x) near zero there makes that term's weight near zero too. A direction that instead averages under QQ would never let QQ pay for outcomes it does not itself predict.

Mode-seeking reverse KL

What does minimizing DKL(QP)D_{KL}(Q\|P) over QQ do instead, and why is variational inference forced into this direction?

Try repeating the forward-KL fix here: average the log-ratio under PP, the true posterior over which die face actually generated the data. That posterior is exactly the object variational inference cannot compute — its normalizing constant sums over every latent configuration, the reason the gambler needs an approximation QQ in the first place. Averaging under PP requires already knowing PP. The only distribution the gambler can sample from and average under is QQ itself.

Swap which distribution does the averaging: DKL(QP)=xQ(x)logQ(x)P(x)D_{KL}(Q\|P) = \sum_x Q(x)\log\frac{Q(x)}{P(x)}, the reverse KL divergence. Every term is now weighted by Q(x)Q(x), so a face where Q(x)=0Q(x)=0 contributes nothing to the sum no matter how large P(x)P(x) is there. The gambler's single-peak QQ is free to ignore one of the two true peaks entirely, as long as it puts all its remaining mass on the other. Minimizing DKL(QP)D_{KL}(Q\|P) over QQ means picking whichever peak makes the log-ratio smallest at the mass QQ actually assigns — collapsing onto one peak of PP, the cheapest one to sit on, and treating the second peak as though it does not exist.

This is mode-seeking behavior, and it is not a modeling preference — it is forced by tractability. Variational inference optimizes a bound built from expectations under QQ alone, never under the true posterior PP, which is exactly why the direction flips . The same asymmetric formula, the same two-peaked die, produces opposite failures depending on which distribution does the averaging: forward KL spreads QQ across both peaks and pays for faces it barely visits, while reverse KL refuses to pay for any face it does not already own and starves the second peak completely.

Maximum likelihood and variational inference therefore inherit opposite failure modes from the same die and the same formula — one blurs across both peaks, the other truncates to one — and telling which direction produced a given fitted QQ from its shape alone is the open diagnostic problem.

Diagnosing the KL direction

Given a fitted model that either blurs across modes or commits to one, how do you diagnose which KL direction produced it?

Hand someone a fitted QQ for the die and hide the training procedure. All they see is a histogram: either mass smeared across faces PP barely visits, or a tight spike on one face while a second, equally plausible face gets nothing. Which loss produced which picture?

Run the causal chain from each direction backward. Forward DKL(PQ)D_{KL}(P\|Q) averages the log-ratio under PP, so it charges QQ for every face PP actually visits, including both of the die's true peaks. A single-peak QQ minimizing that cost has to compromise, sliding its one mode toward the midpoint of the two peaks and picking up nonzero probability on the faces in between. The symptom is diffusion: mass leaking onto outcomes PP considers implausible. That is the signature of maximum likelihood, which is exactly a forward-KL fit to the data-generating PP .

Reverse DKL(QP)D_{KL}(Q\|P) averages the same log-ratio under QQ instead, so any face QQ never visits contributes nothing to the cost regardless of how much probability PP puts there. A single-peak QQ minimizing that cost has no incentive to compromise; it commits entirely to whichever peak is cheaper and reports zero probability for the other, real, peak. The symptom is confident omission, not diffusion. That is the signature of variational inference, forced into this direction because the true posterior PP is intractable to average under .

So the diagnostic reads backward from the shape of QQ: spread mass on low-probability outcomes implicates an average taken under PP; a confident peak with a starved alternative implicates an average taken under QQ. The direction of averaging is not a technicality inside the formula, it is the whole difference between a model that hedges across every mode of the truth and one that bets everything on the cheapest mode it can find. Two log-ratios, two directions of averaging, two failure modes visible in any KL-trained model without ever seeing its loss function.

Transfer set

Put the pieces together

These questions combine mechanisms from more than one section. Work from the causal chain before opening the answer.

  1. 01

    Suppose the gambler is allowed to drop the unimodal restriction and match QQ exactly to PP's two-peak shape. Using the equality condition from non-negativity together with the forward/reverse weighting mechanism from asymmetry, what happens to DKL(PQ)D_{KL}(P\|Q) and DKL(QP)D_{KL}(Q\|P), and does the blur-versus-collapse distinction from forward-kl and reverse-kl still apply?

    Show answer

    Non-negativity showed equality DKL(PQ)=0D_{KL}(P\|Q)=0 requires Q(x)/P(x)Q(x)/P(x) constant everywhere P(x)>0P(x)>0, which forces Q=PQ=P face for face. If QQ is free to match PP's two peaks exactly, that condition is satisfied, so both DKL(PQ)=0D_{KL}(P\|Q)=0 and, by the same equality condition applied with the roles swapped, DKL(QP)=0D_{KL}(Q\|P)=0. With no mismatch left, the PP-weighting versus QQ-weighting distinction from asymmetry has nothing left to punish differently, so forward KL's mode-covering blur and reverse KL's mode-seeking collapse both vanish. The blur/collapse split from forward-kl and reverse-kl is therefore a symptom of QQ's model class being too restrictive to equal PP, not an inherent property of the KL formula itself.

  2. 02

    Change the die so PP has three roughly equal distant peaks (faces 1, 3, 6) instead of two, with QQ still restricted to one unimodal peak. Using the mechanisms from forward-kl and reverse-kl, predict how the forward-KL-fit QQ and the reverse-KL-fit QQ each change from the two-peak case.

    Show answer

    Forward KL averages the log-ratio under PP, so it still refuses to let Q(x)Q(x) sit near zero at any face PP visits with substantial weight. With three peaks instead of two, the single hump minimizing DKL(PQ)D_{KL}(P\|Q) must now spread enough mass to avoid starving any of the three, so it widens further, straddling all three peak regions rather than just nesting between two, at the cost of even more wasted mass on the faces between them. Reverse KL still averages under QQ, so any face QQ assigns zero mass to costs nothing regardless of how large P(x)P(x) is there; the cost-minimizing single peak still collapses onto whichever one of the three peaks is cheapest, now ignoring two real peaks instead of one. The same PP-weighted-versus-QQ-weighted mechanism produces a wider blur on one side and a deeper omission on the other.

  3. 03

    A trained model's approximate distribution QQ has exactly zero probability on a mode that the true distribution PP assigns substantial weight to. Using the diagnosis mechanism together with the reverse-kl mechanism, explain causally why this happened, and connect it back to what the hook means by the formula 'pointed backward' ignoring an entire mode.

    Show answer

    By the diagnosis section, a confident peak that starves a real alternative implicates reverse DKL(QP)D_{KL}(Q\|P), the direction variational inference is forced into because the true posterior PP is intractable to average under. The reverse-kl mechanism explains why: DKL(QP)D_{KL}(Q\|P) weights every log-ratio term by Q(x)Q(x), so a face where Q(x)=0Q(x)=0 contributes exactly zero to the sum no matter how large P(x)P(x) is there, giving the optimizer no cost, and hence no pressure, to cover that mode. This is the concrete mechanism behind the hook's claim: pointing the same log-ratio formula backward, so it averages under QQ instead of PP, creates a zero-cost path to dropping any mode QQ doesn't already occupy, while forward DKL(PQ)D_{KL}(P\|Q), which weights by PP, would have charged an unbounded cost for exactly that omission.

References

  1. [1]
    Cover & Thomas, Elements of Information Theory — source coding chapter
    Unverified model-knowledge reference; verify independently.
  2. [2]
    Blei, Kucukelbir & McAuliffe, Variational Inference: A Review for Statisticians
    Unverified model-knowledge reference; verify independently.
  3. [3]
    Boyd & Vandenberghe, Convex Optimization — Jensen's inequality background
    Unverified model-knowledge reference; verify independently.