Sign in

KL divergence

Kullback-Leibler divergence

A measure of how far a predicted distribution is from a target distribution: the extra cost of describing the target using the prediction.

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

  1. Take a target distribution tt and a prediction, each of shape (N, ..., C), with classes on the last axis.
  2. Turn the prediction into log-probabilities ln⁡q\ln q according to input: use it as is, take the log of clipped probabilities, or apply log-softmax to logits.
  3. For each class compute t (ln⁡t−ln⁡q)t\,(\ln t - \ln q). Where t=0t = 0 the term is taken as 0.
  4. Sum the terms and scale by reduction. The default batchmean divides by the batch size, which gives the mean divergence per row.
  5. In backward, return the gradient in the form the prediction was given. For logits it is q−tq - t when each target row sums to 1.

Watch out for

  • The default input is log-probabilities. Passing probabilities or logits without changing input gives a meaningless number and no error.
  • The mean reduction divides by every element, classes included, so it understates the divergence by a factor of CC. Use batchmean for the true per-row value.
  • The divergence is infinite when the prediction gives zero probability to something the target allows. The eps clip keeps it finite but very large.
  • KL is not symmetric. Fitting qq to minimise KL⁡(t∥q)\operatorname{KL}(t \Vert q) spreads qq over all of the target's modes, while the reverse direction lets qq 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

IfUse instead
The target is a single correct classSoftmax cross-entropy, which differs only by a constant
You need a symmetric and bounded measureJensen-Shannon divergence
The targets are real numbers, not distributionsMean squared error

Math foundations

  1. The definition

    KL⁡(t ∥ q)=∑c=1Ctcln⁡tcqc\operatorname{KL}(t \,\Vert\, q) = \sum_{c=1}^{C} t_c \ln \frac{t_c}{q_c}

    The average, under the target tt, of the log-ratio between target and prediction. Terms with tc=0t_c = 0 contribute nothing.

  2. Never negative

    KL⁡(t ∥ q)≥0,KL⁡(t ∥ q)=0  ⟺  t=q\operatorname{KL}(t \,\Vert\, q) \ge 0, \qquad \operatorname{KL}(t \,\Vert\, q) = 0 \iff t = q

    Known as Gibbs' inequality. It is what makes the divergence usable as a loss: the minimum is zero, reached only by a perfect match.

  3. Relation to cross-entropy

    KL⁡(t ∥ q)=−∑ctcln⁡qc⏟H(t, q)  −  (−∑ctcln⁡tc)⏟H(t)\operatorname{KL}(t \,\Vert\, q) = \underbrace{-\sum_{c} t_c \ln q_c}_{H(t,\,q)} \;-\; \underbrace{\Big(-\sum_{c} t_c \ln t_c\Big)}_{H(t)}

    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.

  4. Not symmetric

    KL⁡(t ∥ q)≠KL⁡(q ∥ t)in general\operatorname{KL}(t \,\Vert\, q) \ne \operatorname{KL}(q \,\Vert\, t) \quad \text{in general}

    The first argument does the weighting. The template computes the direction with the target first, which is the one that matches maximum likelihood.

  5. Gradient with respect to logits

    ∂∂zcKL⁡(t ∥ softmax⁡(z))=qc∑ktk−tc  =  qc−tcwhen ∑ktk=1\frac{\partial}{\partial z_c}\operatorname{KL}\big(t \,\Vert\, \operatorname{softmax}(z)\big) = q_c \sum_{k} t_k - t_c \;=\; q_c - t_c \quad \text{when } \textstyle\sum_k t_k = 1

    Predicted minus target, the same form as cross-entropy. The template keeps the general factor so that unnormalised targets are still handled correctly.

Symbols

tct_c
target probability of class c, target
qcq_c
predicted probability of class c, from pred
zcz_c
predicted logit of class c, when input is logits
CC
the number of classes on the last axis
H(t,q)H(t, q)
the cross-entropy between target and prediction
H(t)H(t)
the entropy of the target

Worked by hand

Target t=(0.5,0.5)t = (0.5, 0.5) and prediction q=(0.9,0.1)q = (0.9, 0.1). Compute the divergence in both directions. Use ln⁡(0.5/0.9)=−0.5878\ln(0.5/0.9) = -0.5878 and ln⁡(0.5/0.1)=1.6094\ln(0.5/0.1) = 1.6094.

KL⁡(t ∥ q)=0.5×(−0.5878)+0.5×1.6094=0.5108\operatorname{KL}(t \,\Vert\, q) = 0.5 \times (-0.5878) + 0.5 \times 1.6094 = 0.5108
KL⁡(q ∥ t)=0.9×0.5878+0.1×(−1.6094)=0.5290−0.1609=0.3681\operatorname{KL}(q \,\Vert\, t) = 0.9 \times 0.5878 + 0.1 \times (-1.6094) = 0.5290 - 0.1609 = 0.3681

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) - teacher
Read 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 q−tq - t divided by the batch size.

Check on learning

  1. 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.

  2. A target has two separate peaks and the model can only represent one. Which peak arrangement does minimising KL⁡(t∥q)\operatorname{KL}(t \Vert q) produce, and how does the reverse direction differ?
    A way to think about it

    In the forward direction, missing any region where tt has mass is punished heavily. In the reverse, putting mass where tt has none is punished. Sketch both results.

  3. 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 0.01ln⁡(0.01/0)0.01 \ln(0.01/0). A single impossible-but-observed event makes the cost unbounded, which is why some smoothing or clipping is needed.

  4. You report a KL of 0.002 with the mean reduction on a 1000-class problem. What is the per-example divergence?
    A way to think about it

    The mean reduction divided the row sum by the number of classes as well as by the batch size. Undo that division.