TExcelTAD
Home › Math for Deep Learning & LLMs › Entropy, Cross-Entropy and KL Divergence

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 pp is −log⁡p-\log p: rare events are surprising. Entropy is the expected surprise:

H(P)=−∑xP(x)log⁡P(x)=Ex∼P[−log⁡P(x)]H(P) = -\sum_{x} P(x)\log P(x) = \mathbb{E}_{x \sim P}[-\log P(x)]

With log⁡2\log_2 the unit is bits, with ln⁡\ln it is nats (deep-learning code uses nats). A uniform distribution over KK outcomes has the maximum entropy log⁡K\log K; a certain outcome has entropy 0.

Cross-entropy

If data comes from PP but we encode (or predict) it with QQ, the expected surprise is the cross-entropy

H(P,Q)=−∑xP(x)log⁡Q(x)H(P, Q) = -\sum_x P(x)\log Q(x)

For a one-hot target PP (true class yy), it reduces to −log⁡Q(y)-\log Q(y), the classification loss. Averaged over a dataset, it is the negative log-likelihood.

KL divergence

DKL(P∥Q)=∑xP(x)log⁡P(x)Q(x)=H(P,Q)−H(P)D_{\mathrm{KL}}(P \Vert Q) = \sum_x P(x)\log\frac{P(x)}{Q(x)} = H(P, Q) - H(P)

It is ≥0\ge 0, equal to 0 only when P=QP = Q (Gibbs' inequality), and not symmetric: DKL(P∥Q)≠DKL(Q∥P)D_{\mathrm{KL}}(P \Vert Q) \ne D_{\mathrm{KL}}(Q \Vert P) in general. Since H(P)H(P) does not depend on the model QQ, minimizing cross-entropy and minimizing KL to the data distribution are the same thing.

python · try it yourself
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 QQ to a complicated PP, the direction matters. Minimizing DKL(P∥Q)D_{\mathrm{KL}}(P \Vert Q) ("forward", what maximum likelihood does) forces QQ to cover every region where PP has mass: mass-covering. Minimizing DKL(Q∥P)D_{\mathrm{KL}}(Q \Vert P) ("reverse", what variational inference does) lets QQ ignore some modes but punishes it for putting mass where PP has none: mode-seeking.

python · try it yourself
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.CrossEntropyLoss takes logits and a class index and computes −log⁡softmax⁡(z)y-\log\operatorname{softmax}(\mathbf{z})_y 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 DKL(q(z∣x)∥N(0,I))D_{\mathrm{KL}}(q(\mathbf{z} \mid \mathbf{x}) \Vert \mathcal{N}(\mathbf{0}, I)) to the reconstruction loss.

Exercises

Exercise 1: Entropy of a coin

Find the entropy in bits of a coin with P(heads)=0.5P(\text{heads}) = 0.5 and of one with P(heads)=1P(\text{heads}) = 1.

Answer

1 bit and 0 bits.

Solution

−2⋅0.5log⁡20.5=1-2 \cdot 0.5\log_2 0.5 = 1. A certain outcome contributes −1⋅log⁡21=0-1 \cdot \log_2 1 = 0 (and 0log⁡00\log 0 is taken as 0).

Exercise 2: KL is not a distance

For P=(0.5,0.5)P = (0.5, 0.5) and Q=(0.9,0.1)Q = (0.9, 0.1), compute both KL directions in nats.

Answer

DKL(P∥Q)≈0.511D_{\mathrm{KL}}(P \Vert Q) \approx 0.511, DKL(Q∥P)≈0.368D_{\mathrm{KL}}(Q \Vert P) \approx 0.368.

Solution
DKL(P∥Q)=0.5ln⁡0.50.9+0.5ln⁡0.50.1=−0.294+0.805=0.511DKL(Q∥P)=0.9ln⁡0.90.5+0.1ln⁡0.10.5=0.529−0.161=0.368\begin{aligned} D_{\mathrm{KL}}(P \Vert Q) &= 0.5\ln\tfrac{0.5}{0.9} + 0.5\ln\tfrac{0.5}{0.1} = -0.294 + 0.805 = 0.511 \\ D_{\mathrm{KL}}(Q \Vert P) &= 0.9\ln\tfrac{0.9}{0.5} + 0.1\ln\tfrac{0.1}{0.5} = 0.529 - 0.161 = 0.368 \end{aligned}

Exercise 3: Cross-entropy decomposes (code)

Verify H(P,Q)=H(P)+DKL(P∥Q)H(P, Q) = H(P) + D_{\mathrm{KL}}(P \Vert Q) for random distributions over 5 outcomes.

Answer

The identity holds.

Solution
python · try it yourself
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 yy, the cross-entropy H(P,Q)H(P, Q) equals…

  1. H(Q)H(Q)
  2. −log⁡Q(y)-\log Q(y)
  3. Q(y)Q(y)
  4. 0

Which statement about the KL divergence is true?

  1. It is symmetric
  2. It is non-negative and zero only when the distributions are equal
  3. It can be negative
  4. It equals the Euclidean distance

Minimizing cross-entropy H(P,Q)H(P, Q) over QQ is equivalent to minimizing…

  1. H(P)H(P)
  2. DKL(P∥Q)D_{\mathrm{KL}}(P \Vert Q)
  3. DKL(Q∥P)D_{\mathrm{KL}}(Q \Vert P)
  4. H(Q)H(Q)