Entropy, Cross-Entropy and KL Divergence
Three quantities from information theory run through deep learning. Entropy measures the uncertainty of a distribution, cross-entropy is the loss of almost every classifier and language model, and the KL divergence measures how far one distribution is from another, appearing in VAEs, knowledge distillation and RLHF. More in Information Theory.
Self-information and entropy
The information of an outcome with probability is : rare events are surprising. Entropy is the expected surprise:
With the unit is bits, with it is nats (deep-learning code uses nats). A uniform distribution over outcomes has the maximum entropy ; a certain outcome has entropy 0.
Cross-entropy
If data comes from but we encode (or predict) it with , the expected surprise is the cross-entropy
For a one-hot target (true class ), it reduces to , the classification loss. Averaged over a dataset, it is the negative log-likelihood.
KL divergence
It is , equal to 0 only when (Gibbs' inequality), and not symmetric: in general. Since does not depend on the model , minimizing cross-entropy and minimizing KL to the data distribution are the same thing.
import numpy as np
def H(p): p = p[p > 0]; return -np.sum(p * np.log(p))
def CE(p, q): return -np.sum(p[p > 0] * np.log(q[p > 0]))
def KL(p, q): return CE(p, q) - H(p)
P = np.array([0.7, 0.2, 0.1])
Q = np.array([0.5, 0.3, 0.2])
print(f"H(P) = {H(P):.4f} nats, H(uniform) = ln 3 = {np.log(3):.4f}")
print(f"H(P, Q) = {CE(P, Q):.4f}, KL(P||Q) = {KL(P, Q):.4f}, KL(Q||P) = {KL(Q, P):.4f}")
print(f"KL(P||P) = {KL(P, P):.4f}")
onehot = np.array([0.0, 1.0, 0.0])
print(f"one-hot target, class 1: cross-entropy {CE(onehot, Q):.4f} = -ln Q[1] = {-np.log(Q[1]):.4f}")H(P) = 0.8018 nats, H(uniform) = ln 3 = 1.0986
H(P, Q) = 0.8869, KL(P||Q) = 0.0851, KL(Q||P) = 0.0920
KL(P||P) = 0.0000
one-hot target, class 1: cross-entropy 1.2040 = -ln Q[1] = 1.2040
Forward and reverse KL
When fitting a simple to a complicated , the direction matters. Minimizing ("forward", what maximum likelihood does) forces to cover every region where has mass: mass-covering. Minimizing ("reverse", what variational inference does) lets ignore some modes but punishes it for putting mass where has none: mode-seeking.
import numpy as np
x = np.linspace(-6, 6, 2001); dx = x[1] - x[0]
g = lambda m, s: np.exp(-(x - m)**2 / (2 * s * s)) / (s * np.sqrt(2 * np.pi))
P = 0.5 * g(-2, 0.6) + 0.5 * g(2, 0.6) # two modes
def kl(a, b): return np.sum(a * np.log((a + 1e-300) / (b + 1e-300))) * dx
best_fwd = min(((kl(P, g(m, s)), m, s) for m in np.linspace(-3, 3, 61) for s in np.linspace(0.3, 3, 28)))
best_rev = min(((kl(g(m, s), P), m, s) for m in np.linspace(-3, 3, 61) for s in np.linspace(0.3, 3, 28)))
print(f"forward KL(P||Q) best Gaussian: mean {best_fwd[1]:+.1f}, std {best_fwd[2]:.1f} (covers both modes)")
print(f"reverse KL(Q||P) best Gaussian: mean {best_rev[1]:+.1f}, std {best_rev[2]:.1f} (picks one mode)")forward KL(P||Q) best Gaussian: mean +0.0, std 2.1 (covers both modes)
reverse KL(Q||P) best Gaussian: mean +2.0, std 0.6 (picks one mode)
In software
nn.CrossEntropyLosstakes logits and a class index and computes stably.- Knowledge distillation trains a small model to match a large model's softened outputs with a KL loss.
- RLHF penalizes the KL divergence between the tuned policy and the original model, so it does not drift too far (Policy Gradients and RLHF).
- VAEs add to the reconstruction loss.
Exercises
Exercise 1: Entropy of a coin
Find the entropy in bits of a coin with and of one with .
Answer
1 bit and 0 bits.
Solution
. A certain outcome contributes (and is taken as 0).
Exercise 2: KL is not a distance
For and , compute both KL directions in nats.
Answer
, .
Solution
Exercise 3: Cross-entropy decomposes (code)
Verify for random distributions over 5 outcomes.
Answer
The identity holds.
Solution
import numpy as np
rng = np.random.default_rng(3)
P = rng.dirichlet(np.ones(5)); Q = rng.dirichlet(np.ones(5))
HP = -np.sum(P * np.log(P)); CE = -np.sum(P * np.log(Q)); KL = np.sum(P * np.log(P / Q))
print(np.isclose(CE, HP + KL), KL >= 0)True True
Test yourself
For a one-hot target with true class , the cross-entropy equals…
- 0
Which statement about the KL divergence is true?
- It is symmetric
- It is non-negative and zero only when the distributions are equal
- It can be negative
- It equals the Euclidean distance
Minimizing cross-entropy over is equivalent to minimizing…