Foundations to Frontier
Tests
E. Deep Learning › E2 Loss Functions (one page each)

KL divergence loss

The Kullback–Leibler divergence KL(p ‖ q) = Σ p log(p/q) measures how much a distribution q fails to match a target p. As a loss it appears in knowledge distillation (matching a teacher's soft predictions), in variational autoencoders (keeping a latent posterior near its prior), in policy optimisation (keeping a new policy near the old) and implicitly in every cross-entropy. It is non-negative, zero only for identical distributions, and asymmetric. This page covers discrete and Gaussian KL, PyTorch's kl_div conventions, distillation with temperature, and the difference between forward and reverse KL. In the exercises you implement these forms, then fit one Gaussian to a two-mode mixture and show that forward KL covers both modes by matching moments while reverse KL stays narrow and, past a critical separation, locks onto a single mode.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

How wrong is a whole distribution?

Sometimes the target is not a single label but a whole distribution: a teacher network’s probabilities over classes, a prior over latent codes, the previous version of a policy. KL divergence measures the mismatch: the average extra surprise from using q when the truth is p. It is zero when they agree and grows as they diverge. It is not symmetric: KL(p ‖ q) and KL(q ‖ p) penalise different mistakes, which changes what a model learns.

KL divergence: a distance that depends on direction
p (shaded) · q (orange)integrand of KL(p‖q) (area = the divergence)
KL(p‖q) = 2.624 nats · KL(q‖p) = 1.073 nats (different!)
KL(p‖q) = ∫ p log(p/q) averages over p. It explodes where p has mass but q is tiny, so it punishes q for missing any part of p (mass-covering). KL(q‖p) averages over q and punishes q for putting mass where p is tiny (mode-seeking). With a two-mode p, try a narrow q on one mode: KL(q‖p) is small while KL(p‖q) is large. The integrand can be negative locally, but the total is always ≥ 0, and zero only when p = q.
Why engineers care

Distillation compresses a large perception model into one small enough for a drone by matching its output distributions with a KL loss. VAEs used for anomaly detection in telemetry include a KL term. Reinforcement-learning methods such as PPO and TRPO limit how far a policy moves per update with KL, which keeps learned controllers from changing too abruptly.

📝 Quick check (Level 0)
0/3 answered
  1. 1. KL(p ‖ q) = 0 exactly when…
  2. 2. Is KL symmetric?
  3. 3. Knowledge distillation matches…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Discrete: KL(p ‖ q) = Σ p_k log(p_k/q_k), with 0·log 0 = 0. For p = (1, 0) and q = (½, ½): log 2 ≈ 0.693. For p = (½, ½) and q = (0.9, 0.1): 0.511, while KL(q ‖ p) = 0.368.
  • Cross-entropy: H(p, q) = H(p) + KL(p ‖ q). With fixed targets p, minimising cross-entropy and minimising KL are the same.
  • Gaussians: KL(N(μ₁, σ₁²) ‖ N(μ₂, σ₂²)) = log(σ₂/σ₁) + (σ₁² + (μ₁ − μ₂)²)/(2σ₂²) − ½. KL(N(1, 1) ‖ N(0, 1)) = 0.5.
  • VAE term: KL(N(μ, σ²) ‖ N(0, 1)) = ½(σ² + μ² − 1 − log σ²), summed over latent dimensions.
  • Jensen–Shannon: JS(p, q) = ½KL(p ‖ m) + ½KL(q ‖ m) with m = (p + q)/2. It is symmetric and at most log 2.
📝 Quick check (Level 1)
0/3 answered
  1. 1. KL((1, 0) ‖ (½, ½)) =
  2. 2. KL(N(0, 1) ‖ N(0, 1)) =
  3. 3. The JS divergence is at most…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

KL in code

Exercise 1.

  • KL is zero for identical distributions and asymmetric: 0.511 against 0.368 above.
  • The Gaussian closed form matches numerical integration.
  • Cross-entropy equals entropy plus KL.
  • PyTorch’s F.kl_div(log_q, p, reduction="batchmean") averages per-example KL.
  • The distillation loss vanishes when student and teacher agree.

PyTorch’s convention catches many people out. F.kl_div(input, target) expects input = log q (log-probabilities of the model) and target = p (probabilities). It computes KL(p ‖ q). Use reduction="batchmean": the default “mean” divides by the number of elements, not examples, which is not the KL.

Distillation (Hinton, Vinyals and Dean, 2015). Soften both teacher and student with temperature T, then minimise T²·KL(p_teacher^T ‖ p_student^T), usually mixed with cross-entropy on the true labels. The T² keeps gradient sizes comparable across temperatures. Higher T exposes the teacher’s “dark knowledge” about which wrong classes are similar.

F.kl_div(F.log_softmax(s / T, -1), F.softmax(t / T, -1), reduction="batchmean") * T * T
🐍 Exercise 1: KL in its forms
Implement discrete and Gaussian KL, PyTorch-style kl_div with batchmean, and the temperature-scaled distillation loss.
📝 Quick check (Level 2)
0/3 answered
  1. 1. F.kl_div's first argument should be…
  2. 2. The correct reduction for a per-example KL is…
  3. 3. Distillation multiplies the KL by…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Properties.

  • KL ≥ 0, with equality only if p = q almost everywhere (Gibbs’ inequality, from Jensen’s inequality applied to −log).
  • It is convex in the pair (p, q).
  • It is not a metric: it is asymmetric and fails the triangle inequality.
  • It is infinite if q = 0 somewhere p > 0.

Forward versus reverse KL. When q comes from a restricted family and cannot match p exactly, the direction matters.

  • Forward KL(p ‖ q) averages log(p/q) over p. Wherever p has mass and q is small the penalty is huge, so q must cover all of p’s mass: it is mode-covering, or mass-covering. For an exponential family q, the forward-KL optimum matches p’s expected sufficient statistics (for a Gaussian, its mean and variance).
  • Reverse KL(q ‖ p) averages over q. q is penalised for putting mass where p has little, but not for missing parts of p, so it is mode-seeking: it can sit on one mode.

Maximum likelihood minimises forward KL from the data; variational inference minimises reverse KL to the posterior. That is why VI tends to underestimate uncertainty.

Information meaning. KL(p ‖ q) is the expected number of extra nats needed to code samples from p using a code optimised for q.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Forward KL(p ‖ q) with a restricted q tends to be…
  2. 2. Variational inference minimises…
  3. 3. For a Gaussian q, the forward-KL fit to any p matches p's…

Level 4: Expert

★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.

Covering versus seeking

History.

  • S. Kullback and R. Leibler (1951) defined the divergence.
  • T. Minka (2001, 2005) analysed forward versus reverse KL in approximate inference (expectation propagation versus variational Bayes).
  • D. Kingma and M. Welling (2014) put the KL term in VAEs.
  • G. Hinton, O. Vinyals and J. Dean (2015) introduced temperature distillation.
  • J. Schulman et al. (2015, 2017) used KL constraints in TRPO and PPO.

Exercise 2. The target p is an equal mixture of two unit-variance Gaussians at ±s/2. The best single Gaussian q is found by grid search under forward and reverse KL, as the separation s grows.

separation s forward KL: mean, sd, value reverse KL: mean, sd, value moment-matched sd √(1 + s²/4)
1 0, 1.105, 0.000 0, 1.105, 0.000 1.118
2 0, 1.419, 0.010 0, 1.419, 0.011 1.414
3 0, 1.822, 0.063 0, 1.733, 0.074 1.803
4 0, 2.226, 0.172 0, 2.014, 0.227 2.236
5 0, 2.718, 0.315 0, 2.340, 0.483 2.693
6 0, 3.158, 0.462 −3.00, 1.000, 0.689 3.162
  • Forward KL matched moments. At every separation its standard deviation equalled √(1 + s²/4) within the grid resolution, so q spread over both modes, including the empty valley between them.
  • Reverse KL stayed narrower. For s ≥ 3 it was narrower than the forward fit, avoiding the valley.
  • At s = 6 reverse KL jumped to one mode, with exactly the component’s mean and width, at a cost of about log 2 = 0.693: the price of ignoring half the mass. For s ≤ 5 the centred compromise was cheaper.
  • The direction is a modelling choice. A distilled student trained with forward KL tries to cover all of the teacher’s options; a variational posterior trained with reverse KL commits to one explanation and underestimates uncertainty.
🐍 Exercise 2 (research): covering versus seeking
Fit a single Gaussian to two-mode mixtures of increasing separation by forward and reverse KL, and compare the fitted means, widths and divergences.

KL in AI, robotics and aerospace

  • Model compression: distilling large perception networks into on-board models uses temperature-scaled KL to a teacher.
  • Safe policy updates: PPO and TRPO bound the KL between successive policies, limiting how much a learned controller changes per update.
  • Anomaly detection: VAEs on telemetry use the KL term to keep latent codes regular, so unusual inputs stand out.

References

  1. S. Kullback, R. A. Leibler (1951). “On information and sufficiency.” Annals of Mathematical Statistics 22(1).
  2. T. Minka (2005). “Divergence measures and message passing.” Microsoft Research Technical Report MSR-TR-2005-173.
  3. G. Hinton, O. Vinyals, J. Dean (2015). “Distilling the knowledge in a neural network.” arXiv:1503.02531.
  4. D. P. Kingma, M. Welling (2014). “Auto-encoding variational Bayes.” Proc. ICLR.
  5. J. Schulman, F. Wolski, P. Dhariwal, A. Radford, O. Klimov (2017). “Proximal policy optimization algorithms.” arXiv:1707.06347.