Overview
Two probability distributions over the same choices can be compared by asking how surprised you would be, on average, if you expected one and saw the other. KL divergence measures that extra surprise. It is zero when the prediction matches the target exactly and positive otherwise. It is not a distance in the usual sense, because swapping the two arguments gives a different number. In the direction used here, the target does the weighting: the prediction is punished wherever the target has mass and the prediction has too little.
A short history
Solomon Kullback and Richard Leibler defined the divergence in the 1951 paper 'On Information and Sufficiency', building on Shannon's information theory. It measures the expected extra information needed when one distribution is used in place of another. It is not symmetric. In machine learning it underlies maximum likelihood, variational inference and knowledge distillation, which Hinton, Vinyals and Dean described in 2015.
How it works
- Take a target distribution and a prediction, each of shape (N, ..., C), with classes on the last axis.
- Turn the prediction into log-probabilities according to
input: use it as is, take the log of clipped probabilities, or apply log-softmax to logits. - For each class compute . Where the term is taken as 0.
- Sum the terms and scale by
reduction. The defaultbatchmeandivides by the batch size, which gives the mean divergence per row. - In
backward, return the gradient in the form the prediction was given. For logits it is when each target row sums to 1.
Watch out for
- The default
inputis log-probabilities. Passing probabilities or logits without changinginputgives a meaningless number and no error. - The
meanreduction divides by every element, classes included, so it understates the divergence by a factor of . Usebatchmeanfor the true per-row value. - The divergence is infinite when the prediction gives zero probability to something the target allows. The
epsclip keeps it finite but very large. - KL is not symmetric. Fitting to minimise spreads over all of the target's modes, while the reverse direction lets lock onto one.
Use cases
When to use it
Knowledge distillation, where a student matches a teacher's soft outputs, and any setting that compares two distributions, such as policy constraints in reinforcement learning or the regulariser of a VAE.
In industry
- Model compression
- Distillation trains a small student model to match the softened output distribution of a large teacher by minimising KL divergence.
- Reinforcement learning
- Policy optimisation methods such as TRPO limit the KL divergence between the old and new policy so that each update stays small.
- Generative models
- Variational autoencoders include a KL term that keeps the encoder's distribution over codes close to a chosen prior.
Choosing it: what must hold
- Both the prediction and the target are probability distributions over the same set of outcomes.
- The prediction gives nonzero probability wherever the target does, or the divergence becomes infinite.
- A decision about direction, since the divergence from target to prediction differs from the reverse.
When to choose something else
| If | Use instead |
|---|---|
| The target is a single correct class | Softmax cross-entropy, which differs only by a constant |
| You need a symmetric and bounded measure | Jensen-Shannon divergence |
| The targets are real numbers, not distributions | Mean squared error |
Math foundations
The definition
The average, under the target , of the log-ratio between target and prediction. Terms with contribute nothing.
Never negative
Known as Gibbs' inequality. It is what makes the divergence usable as a loss: the minimum is zero, reached only by a perfect match.
Relation to cross-entropy
Cross-entropy minus the entropy of the target. When the target is fixed, its entropy is a constant, so minimising KL and minimising cross-entropy give the same gradients.
Not symmetric
The first argument does the weighting. The template computes the direction with the target first, which is the one that matches maximum likelihood.
Gradient with respect to logits
Predicted minus target, the same form as cross-entropy. The template keeps the general factor so that unnormalised targets are still handled correctly.
Symbols
- target probability of class c,
target - predicted probability of class c, from
pred - predicted logit of class c, when
inputis logits - the number of classes on the last axis
- the cross-entropy between target and prediction
- the entropy of the target
Worked by hand
Target and prediction . Compute the divergence in both directions. Use and .
The two directions give 0.5108 and 0.3681. The first is larger because the target puts half its mass on a class the prediction nearly rules out.
Visual example
Loading the example.
Try this
- Move across the curve: the height is what the model is charged.
- Move each control and watch which part of the curve it changes.
Code sample
import numpy as np
from impl import KLDivergence
from config import KLDivergenceConfig
loss = KLDivergence(KLDivergenceConfig(input="logits"))
teacher = np.array([[0.7, 0.2, 0.1]]) # target probabilities
student_logits = np.array([[1.0, 0.5, 0.0]]) # raw scores of the model being trained
print(loss.forward(student_logits, teacher)) # 0.0785 nats
print(loss.backward(student_logits, teacher)) # softmax(student_logits) - teacherRead the implementation (72 lines)
"""KL divergence between discrete distributions: KL(target || pred) = sum(t * (log t - log q)).
NumPy only. `forward` returns the divergence, `backward` its gradient with respect to the prediction.
"""
from __future__ import annotations
import numpy as np
try:
from .config import KLDivergenceConfig
except ImportError: # run from the template's own folder
from config import KLDivergenceConfig
def _log_softmax(z: np.ndarray, axis: int = -1) -> np.ndarray:
"""log(softmax(z)) along `axis`, with the maximum subtracted first so exp cannot overflow."""
shifted = z - z.max(axis=axis, keepdims=True)
return shifted - np.log(np.exp(shifted).sum(axis=axis, keepdims=True))
class KLDivergence:
"""KL(target || pred), with the prediction given as log-probabilities, probabilities or logits."""
def __init__(self, config: KLDivergenceConfig | None = None) -> None:
self.config = config or KLDivergenceConfig()
def _log_q(self, pred: np.ndarray) -> np.ndarray:
"""Log-probabilities of the prediction, whatever form it was given in."""
if self.config.input == "logits":
return _log_softmax(pred)
if self.config.input == "probs":
return np.log(np.maximum(pred, self.config.eps))
return pred
def _scale(self, pred: np.ndarray) -> float:
"""Factor the reduction puts on every per-element term."""
if self.config.reduction == "batchmean":
return 1.0 / pred.shape[0]
return 1.0 / pred.size if self.config.reduction == "mean" else 1.0
def _inputs(self, pred, target) -> tuple[np.ndarray, np.ndarray]:
"""Both as float arrays of one shape with at least one axis; the target must not be negative."""
pred, target = np.asarray(pred, dtype=float), np.asarray(target, dtype=float)
if pred.shape != target.shape or pred.ndim == 0:
raise ValueError(f"pred and target must share a shape (N, ..., C), got {pred.shape} and {target.shape}")
if (target < 0).any():
raise ValueError("target probabilities must not be negative")
return pred, target
def forward(self, pred: np.ndarray, target: np.ndarray):
"""pred: (N, ..., C) in the configured form. target: same shape, probabilities.
Returns a float, or the per-element terms t * (log t - log q) for "none"."""
pred, target = self._inputs(pred, target)
log_t = np.log(np.where(target > 0, target, 1.0)) # where t = 0 the term is 0 * log 0 = 0
terms = target * (log_t - self._log_q(pred))
return terms if self.config.reduction == "none" else float(terms.sum() * self._scale(pred))
def backward(self, pred: np.ndarray, target: np.ndarray) -> np.ndarray:
"""Gradient of the reduced divergence with respect to pred, in the form pred was given. Same shape.
log_probs: -t. probs: -t / q. logits: softmax(logits) * sum(t) - t along the last axis.
For "none" the gradient of the sum of all terms is returned.
"""
pred, target = self._inputs(pred, target)
if self.config.input == "logits":
local = np.exp(_log_softmax(pred)) * target.sum(axis=-1, keepdims=True) - target
elif self.config.input == "probs":
local = -target / np.maximum(pred, self.config.eps)
else:
local = -target
return local * self._scale(pred)
__call__ = forward- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Build KLDivergence(KLDivergenceConfig(input="probs", reduction="batchmean")) and reproduce the worked example with forward, then swap the arguments. Switch to input="logits", pass the log of the same prediction, and confirm forward agrees and backward equals divided by the batch size.
Check on learning
- In distillation the teacher's output is fixed. Why does it make no difference to the student's gradients whether you minimise KL or cross-entropy against the teacher?
A way to think about it
Use the decomposition. One of the two terms does not depend on the student at all. The loss values differ by that constant, the gradients do not.
- A target has two separate peaks and the model can only represent one. Which peak arrangement does minimising produce, and how does the reverse direction differ?
A way to think about it
In the forward direction, missing any region where has mass is punished heavily. In the reverse, putting mass where has none is punished. Sketch both results.
- The prediction gives exactly zero probability to a class the target gives 0.01. What is the divergence, and what does that say about using it with hard-clipped models?
A way to think about it
Evaluate . A single impossible-but-observed event makes the cost unbounded, which is why some smoothing or clipping is needed.
- You report a KL of 0.002 with the
meanreduction on a 1000-class problem. What is the per-example divergence?A way to think about it
The
meanreduction divided the row sum by the number of classes as well as by the batch size. Undo that division.