TensorTau PathToAGI Probability and Uncertainty Level 03

Level 03 · Probability and Uncertainty · Chapter 036

KL Divergence

How can we quantify the mismatch between a true distribution and a model distribution?

1. Two Distributions

Suppose reality is

P=[0.9,0.1]P=[0.9,0.1]

but our model says

Q=[0.5,0.5].Q=[0.5,0.5].

Both are valid probability distributions. Entropy tells us uncertainty inside one distribution. It does not directly tell us how badly QQ approximates PP.

KL divergence does:

DKL(P∥Q)=∑xP(x)log⁡P(x)Q(x).\boxed{D_{KL}(P\|Q)=\sum_x P(x)\log\frac{P(x)}{Q(x)}}.

Interpretation: expected extra log-surprise when data comes from PP but we encode or model it using QQ.


2. Why P Weights the Sum

The world generates outcomes according to PP, so mismatch matters most where PP places mass. A model can waste probability on impossible regions, but it is especially costly when it assigns tiny probability to outcomes reality frequently produces.

If P(x)>0P(x)>0 but Q(x)=0Q(x)=0, KL becomes infinite: the model declared a possible real event impossible.


3. KL Is Not a Distance

KL satisfies

DKL(P∥Q)≥0D_{KL}(P\|Q)\ge0

and equals zero only when the distributions match (almost everywhere).

But generally

DKL(P∥Q)≠DKL(Q∥P).D_{KL}(P\|Q)\ne D_{KL}(Q\|P).

So KL is asymmetric and is not a metric distance.

The direction matters.


4. Connection to Cross-Entropy

Expand:

DKL(P∥Q)=∑Plog⁡P−∑Plog⁡Q.D_{KL}(P\|Q) = \sum P\log P-\sum P\log Q.

Since

H(P)=−∑Plog⁡PH(P)=-\sum P\log P

and

H(P,Q)=−∑Plog⁡Q,H(P,Q)=-\sum P\log Q,

we get

H(P,Q)=H(P)+DKL(P∥Q).\boxed{H(P,Q)=H(P)+D_{KL}(P\|Q)}.

If PP is fixed, minimizing cross-entropy with respect to QQ is equivalent to minimizing DKL(P∥Q)D_{KL}(P\|Q).

This is why classification training can be understood as pushing the model distribution toward the target distribution.


5. Tiny Example

Let target be one-hot:

P=[1,0,0].P=[1,0,0].

Model predicts

Q=[0.7,0.2,0.1].Q=[0.7,0.2,0.1].

Cross-entropy is

−∑iPilog⁡Qi=−log⁡0.7.-\sum_iP_i\log Q_i=-\log0.7.

Only the true class survives because all other PiP_i are zero.

For a one-hot target, H(P)=0H(P)=0, so cross-entropy equals KL divergence from target to model.


6. Code

import numpy as np

def kl(p, q):
    p = np.asarray(p, float)
    q = np.asarray(q, float)
    mask = p > 0
    return np.sum(p[mask] * np.log(p[mask] / q[mask]))

print(kl([0.9, 0.1], [0.5, 0.5]))
print(kl([0.5, 0.5], [0.9, 0.1]))

Predict whether the two outputs match before running.


7. Shape Check

For distributions over 10 classes:

P: [64, 10]
Q: [64, 10]

Compute KL across the class axis and obtain

KL per example: [64]

Average across the batch to get a scalar training objective.


8. Real-World Connection

KL divergence appears in variational inference, VAEs, knowledge distillation, RL policy constraints, distribution shift analysis and information theory. Different KL directions can encourage different approximation behavior, which becomes important in generative modeling.


Mastery Check

  1. Why is KL weighted by PP?
  2. Why can KL be infinite?
  3. Why is it not a metric distance?
  4. Derive H(P,Q)=H(P)+DKL(P∥Q)H(P,Q)=H(P)+D_{KL}(P\|Q).
  5. Why does minimizing cross-entropy minimize KL when PP is fixed?

Bridge to Chapter 037

KL exposed cross-entropy inside its algebra. Now we can study the loss directly and answer the practical question:

Why does classification training use cross-entropy instead of squared error?

Six ways to work the chapter, climbing from explaining it in your own words to investigating it like a researcher. Reading is not enough — this is where the chapter lands.

Explain

Explain KL divergence as “extra surprise from using the wrong model.”

Calculate

Compute both DKL(P∥Q)D_{KL}(P\|Q) and DKL(Q∥P)D_{KL}(Q\|P) for P=[0.8,0.2]P=[0.8,0.2], $Q=[0.5,0.5]` using natural logs.

Predict

What happens if P=[1,0]P=[1,0] and Q=[0,1]Q=[0,1]? Explain before calculating.

Break

Give a numerical example proving KL is asymmetric.

Build

Implement batched KL for tensors [B,C], with careful handling of zero entries in P.

Investigate

Fix P and interpolate Q from uniform toward P. Plot KL and cross-entropy. Explain why the curves differ only by a constant.

Ready to Continue?

Continue when you can derive the cross-entropy/KL identity without memorizing it.