Kullback-Leibler divergence is the single number that answers one question: if you believed distribution Q and the world actually behaves like distribution P, how much are you surprised? It is written D(P‖Q), measured in bits or nats, and it is the quantity hiding inside the KL penalty of RLHF, the loss function of knowledge distillation, the ELBO of variational autoencoders, and the regularizer that stops a fine-tuned model from drifting away from its base.

This guide works through what it measures, why the asymmetry matters in practice, a numeric example you can check by hand, and the three places you will actually meet it in modern AI systems.

The definition, read in plain language

For discrete distributions over the same set of outcomes,

D(P‖Q) = Σ P(x) · log( P(x) / Q(x) )

Read the pieces separately. log(P(x)/Q(x)) is the surprise for one outcome: zero when the two distributions agree there, positive when P says an outcome is more likely than Q expected, negative when P says it is less likely. Then each surprise is weighted by P(x) — how often that outcome actually happens. So KL divergence is the average surprise, measured under the true distribution.

Two properties follow directly and matter more than the formula:

  • It is never negative, and it equals zero only when P and Q are identical. That makes it usable as a loss.
  • It is not symmetric. D(P‖Q) ≠ D(Q‖P) in general, and it does not satisfy the triangle inequality, so it is not a distance despite being used like one. Kullback and Leibler’s 1951 paper introduced it as “information for discrimination,” not as a metric.

The relationship to cross-entropy is worth keeping in your head: D(P‖Q) = H(P,Q) − H(P), where H(P,Q) is the cross-entropy and H(P) the entropy of P. Because H(P) does not depend on your model, minimizing cross-entropy — the standard next-token loss, covered in our softmax and cross-entropy guide — is exactly minimizing KL divergence to the data distribution.

A worked example

Take a three-token vocabulary. The true distribution and your model’s prediction are:

Outcome P (true) Q (model)
A 0.50 0.30
B 0.40 0.30
C 0.10 0.40
Plot of normal distribution probability density curves with different means and variances
Shifting or widening a distribution changes the ratio P/Q at every point, and the KL divergence is the average of those log ratios. Image: Unknown author / Wikimedia Commons, CC BY-SA 3.0

Using natural logarithms (nats):

D(P‖Q) = 0.5·ln(0.5/0.3) + 0.4·ln(0.4/0.3) + 0.1·ln(0.1/0.4)
       = 0.5·0.5108 + 0.4·0.2877 + 0.1·(−1.3863)
       = 0.2554 + 0.1151 − 0.1386
       = 0.2319 nats

Now reverse the arguments:

D(Q‖P) = 0.3·ln(0.3/0.5) + 0.3·ln(0.3/0.4) + 0.4·ln(0.4/0.1)
       = 0.3·(−0.5108) + 0.3·(−0.2877) + 0.4·1.3863
       = −0.1532 − 0.0863 + 0.5545
       = 0.3150 nats

Same two distributions, different answers — and the difference is not arithmetic noise. In D(P‖Q), errors are weighted by how often the outcome truly happens, so the model is punished most for assigning low probability to things that do occur. That is why D(P‖Q) is called the forward KL and produces mass-covering behavior: Q must spread probability over everything P does, or the ratio blows up.

In D(Q‖P), the reverse KL, weights come from the model. The model is punished for putting mass where P has almost none, which encourages it to pick one mode of P and commit — mode-seeking behavior. If you have ever wondered why one generative model hedges and produces blurry averages while another produces sharp but less diverse samples, this asymmetry is often the reason.

One practical trap: if Q(x) = 0 anywhere P(x) > 0, the forward KL is infinite. Implementations add a small epsilon or smooth the distributions, which is why libraries expect log-probabilities as input. PyTorch’s kl_div takes the input in log-space and the target as probabilities by default.

Where it shows up in practice

1. The KL penalty in RLHF

In reinforcement learning from human feedback, a reward model scores the policy’s outputs, and a policy-gradient method such as PPO updates the model to raise that score. Left alone, the policy will find degenerate outputs that score well and read badly — reward hacking. The standard fix, used in the InstructGPT work and nearly everything since, is to subtract a KL term that measures how far the current policy has moved from the frozen reference model, token by token:

reward = reward_model_score − β · D( policy ‖ reference )

The coefficient β is the leash. Too small and the model drifts into gibberish that the reward model happens to like; too large and it barely learns anything. Direct Preference Optimization later showed the optimal policy for this KL-regularized objective has a closed form, which lets you train on preference pairs directly without running PPO at all — but the KL term is still there, folded into the derivation.

2. Knowledge distillation

Knowledge distillation trains a small student to copy a large teacher’s full output distribution rather than just its top answer. The loss is the KL divergence between the teacher’s softened probabilities and the student’s, with temperature T applied to both sets of logits. The information the student gains over hard labels is precisely the structure in the teacher’s distribution — what else it thought was plausible, and how much.

3. Variational inference and VAEs

In a variational autoencoder, the KL term keeps the approximate posterior close to the prior, and the whole training objective (the evidence lower bound) is derivable as “reconstruction accuracy minus KL to the prior.” Here the reverse KL is used deliberately, because its mode-seeking behavior is what makes the optimization tractable.

Reading KL numbers without fooling yourself

  • Units matter. Natural logs give nats, base-2 logs give bits; 1 nat ≈ 1.44 bits. A paper reporting “KL = 8” is meaningless without the base and the normalization (per token? per sequence?).
  • Per-token KL in RLHF is usually small. Values in the single digits of nats per sequence are typical for a well-leashed run; a sudden climb is the first sign of drift.
  • KL is not a percentage of similarity. It is unbounded above. Two distributions can have a KL of 12 and still overlap substantially on common outcomes.
  • Estimated KL has variance. When you cannot sum over the vocabulary and must sample, estimators differ; the low-variance estimator (r − 1) − log r, where r = Q/P, is widely used in RL code because the naive −log r is noisy.

What to watch next

  • Whether KL-free preference methods continue to displace PPO-style pipelines in post-training.
  • The spread of alternative divergences in distillation, such as reverse KL and total variation, when student and teacher capacities differ sharply.
  • How on-policy distillation recipes balance a KL-to-teacher term against a KL-to-reference term.
  • Reporting conventions: more papers stating units and normalization for KL values.
  • Tooling that surfaces per-token KL during fine-tuning runs as a drift alarm.

Key takeaways

  • KL divergence is the average extra surprise from using Q when reality is P; it is zero only if the distributions match.
  • It is asymmetric and not a distance: forward KL covers all the mass, reverse KL seeks a single mode.
  • Minimizing cross-entropy is equivalent to minimizing forward KL to the data distribution.
  • RLHF subtracts β·KL from the reward to keep the policy near its reference model; DPO rewrites the same objective in closed form.
  • Always state the log base and the normalization before comparing KL values across runs or papers.

Frequently asked questions

Is KL divergence a distance?

No. It is never negative and is zero only for identical distributions, but it is asymmetric and violates the triangle inequality, so it is not a metric. Symmetrized variants such as Jensen-Shannon divergence are used when a true distance is needed.

Why is there a KL penalty in RLHF?

It stops the policy from drifting far from the reference model while chasing reward-model scores. Without it, training tends to find outputs that score highly but are degenerate — the classic reward-hacking failure.

What is the difference between forward and reverse KL?

Forward KL weights errors by the true distribution, so the model must cover everything that can happen and tends to hedge. Reverse KL weights errors by the model, so it concentrates on one mode and produces sharper but less diverse behavior.