AI Logic

Loss Functions

KL Divergence

Updated:

Graph of the KL divergence. With the target distribution fixed at P = (0.3, 0.7) and q of the predicted distribution Q = (q, 1 āˆ’ q) on the horizontal axis, it plots D_KL(P‖Q) (solid) and D_KL(Q‖P) (dashed). Both are 0 at q = 0.3, and at q = 0.9 they are 1.03 and 0.79, differing by direction. Legend on the right

Background and Overview

The KL divergence is a quantity that expresses how different two probability distributions PP and QQ are as a single non-negative number. It is 0 when PP and QQ are identical and grows as they differ. In deep learning it is used as a loss function for pulling a model's distribution QQ toward the true (or target) distribution PP. The name comes from Kullback and Leibler, who introduced the quantity in a 1951 paper; in information theory it is also called relative entropy.

DKL(Pā€‰āˆ„ā€‰Q)=āˆ‘xP(x)log⁔P(x)Q(x)D_{\mathrm{KL}}(P \,\|\, Q) = \sum_{x} P(x) \log \frac{P(x)}{Q(x)}

For continuous distributions, the sum is replaced by an integral and probabilities by probability densities. The log is the natural logarithm.

It means "the average extra surprise that someone who believes QQ feels, compared with someone who knows PP, when observing data drawn from PP." For example, in a town where the weather is really 70% sunny and 30% rainy, a person who assumes 50% sunny and 50% rainy is slightly more surprised on sunny days than someone who knows the true probabilities, and slightly less surprised on rainy days. This "extra surprise" averaged over the true frequencies is the KL divergence.

The figure at the top shows its value for a distribution over two outcomes, with the target distribution fixed at P=(0.3,Ā 0.7)P = (0.3,\ 0.7) and the predicted distribution Q=(q,Ā 1āˆ’q)Q = (q,\ 1-q) varied.

  • It is 0 only when Q=PQ = P: At q=0.3q = 0.3, both curves are 0.
  • Swapping the direction changes the value: At q=0.9q = 0.9, DKL(P∄Q)ā‰ˆ1.03D_{\mathrm{KL}}(P\|Q) \approx 1.03 and DKL(Q∄P)ā‰ˆ0.79D_{\mathrm{KL}}(Q\|P) \approx 0.79.
  • It grows without bound when QQ puts nearly zero probability where PP says something happens: As qq approaches 0 or 1, the solid curve keeps rising.

Definition and Computation

The KL divergence DKL(P∄Q)D_{\mathrm{KL}}(P\|Q) between discrete distributions is computed as follows. As a three-class example, let the target distribution be P=(0.7, 0.2, 0.1)P = (0.7,\ 0.2,\ 0.1) and the model distribution be Q=(0.5, 0.3, 0.2)Q = (0.5,\ 0.3,\ 0.2).

  1. For each class, compute the log of the probability ratio log⁔P(x)Q(x)\log \dfrac{P(x)}{Q(x)}. It is positive for classes where PP is larger and negative where it is smaller.
  2. Multiply it by P(x)P(x). Here this gives 0.7log⁔0.70.5ā‰ˆ0.2360.7 \log \frac{0.7}{0.5} \approx 0.236, 0.2log⁔0.20.3ā‰ˆāˆ’0.0810.2 \log \frac{0.2}{0.3} \approx -0.081, and 0.1log⁔0.10.2ā‰ˆāˆ’0.0690.1 \log \frac{0.1}{0.2} \approx -0.069.
  3. Sum over all classes. Here DKL(P∄Q)ā‰ˆ0.085D_{\mathrm{KL}}(P\|Q) \approx 0.085.

Some terms can be negative, but the total is always non-negative. The main properties are as follows.

  • Non-negative, and 0 only when P=QP = Q: This is what justifies using it as a measure of difference.
  • Swapping the direction usually changes the value: Reversing the direction in the example above gives DKL(Q∄P)ā‰ˆ0.092D_{\mathrm{KL}}(Q\|P) \approx 0.092. For this reason it is called a divergence rather than a distance.
  • It is infinite if Q(x)=0Q(x) = 0 somewhere P(x)>0P(x) > 0: Where P(x)=0P(x) = 0, the term is treated as 0log⁔0=00 \log 0 = 0 and not added.

It is related to the cross-entropy H(P,Q)=āˆ’āˆ‘xP(x)log⁔Q(x)H(P, Q) = -\sum_x P(x) \log Q(x) as follows.

H(P,Q)=H(P)+DKL(Pā€‰āˆ„ā€‰Q)H(P, Q) = H(P) + D_{\mathrm{KL}}(P \,\|\, Q)

H(P)=āˆ’āˆ‘xP(x)log⁔P(x)H(P) = -\sum_x P(x) \log P(x) is the entropy of PP itself. In the example above, H(P)ā‰ˆ0.802H(P) \approx 0.802 and H(P,Q)ā‰ˆ0.887H(P,Q) \approx 0.887, and the difference is DKL(P∄Q)ā‰ˆ0.085D_{\mathrm{KL}}(P\|Q) \approx 0.085. Since H(P)H(P) does not depend on the model QQ, when PP is fixed, minimizing the cross-entropy with respect to QQ is the same as minimizing the KL divergence.

In classification training where the target is one-hot (1 only for the correct class), H(P)=0H(P) = 0, so the KL divergence and the cross-entropy take the same value. Using cross-entropy for classification amounts to minimizing the KL divergence from the target distribution.

The Choice of Direction Changes How Q Approaches P

When PP is fixed and QQ is pulled toward it, the properties of the resulting QQ depend on which direction of the KL divergence is minimized. Consider a case where PP has two peaks and QQ can only represent single-peaked distributions (such as a normal distribution).

Quantity minimizedWhat is penalized stronglyTendency of the resulting QQ
DKL(P∄Q)D_{\mathrm{KL}}(P\|Q)QQ being small where PP is largeSpreads out to cover both peaks of PP
DKL(Q∄P)D_{\mathrm{KL}}(Q\|P)QQ being large where PP is smallConcentrates on just one peak of PP

The reason lies in which distribution weights the average. DKL(P∄Q)D_{\mathrm{KL}}(P\|Q) averages with the weights of PP, so if QQ is small where PP is large, log⁔PQ\log \frac{P}{Q} becomes large and is penalized heavily. DKL(Q∄P)D_{\mathrm{KL}}(Q\|P) averages with the weights of QQ, so places where QQ puts no probability are not penalized; instead, QQ is penalized for putting probability where PP is small (between the peaks). In the figure at the top as well, as qq approaches 0 the solid curve keeps rising, while the dashed curve stays at about 0.36.

Which direction is better depends on the goal. Training that fits a model to the distribution of the target data (maximum likelihood estimation, knowledge distillation, and so on) usually uses DKL(P∄Q)D_{\mathrm{KL}}(P\|Q).

Uses in Deep Learning

The KL divergence is used either as a loss on its own or as a term added to another loss.

  • Knowledge distillation: With the probability distribution output by the teacher model as PP and the student model's distribution as QQ, minimizing DKL(P∄Q)D_{\mathrm{KL}}(P\|Q) transfers to the student even the teacher's information about "which classes resemble which."
  • R-Drop: The same input is passed twice through a model with Dropout, and the KL divergence between the two output distributions is minimized as the average of both directions.
  • VAE: The loss (the variational lower bound) includes a KL divergence term between the latent-variable distribution qĻ•(z∣x)q_\phi(z \mid x) output by the encoder and the prior pĪø(z)p_\theta(z). It acts as a regularizer that keeps the latent distribution from drifting too far from the prior.
  • Classification training: As in the previous section, when the target is a fixed distribution it means the same as the cross-entropy.

Caveats in Practice

PyTorch's nn.KLDivLoss takes the "log" of the model's distribution as its first argument (input) and the target distribution as its second argument (target). What it computes is DKL(targetā€‰āˆ„ā€‰input)D_{\mathrm{KL}}(\text{target} \,\|\, \text{input}). Apply log_softmax, not softmax, to the model's output before passing it. Passing softmax probabilities directly gives incorrect values and gradients.

Keep the following points in mind as well.

  • Specify reduction="batchmean": The default "mean" divides not only by the batch size but also by the number of classes, so the result is not the mathematical definition. The PyTorch documentation also recommends "batchmean".
  • Keep probabilities in log form: If Q(x)Q(x) is rounded to 0, log⁔0\log 0 becomes infinite. Compute the model's output in log form with log_softmax, and if the target distribution is also held as logs, pass it with log_target=True to avoid loss of precision.
  • Be aware of the direction: DKL(P∄Q)D_{\mathrm{KL}}(P\|Q) and DKL(Q∄P)D_{\mathrm{KL}}(Q\|P) are different quantities. When implementing a formula from a paper, check which distribution the average is taken over.
  • If the target distribution is one-hot, just use cross-entropy: The value is the same, and nn.CrossEntropyLoss is simpler because it accepts class indices directly.

Comparison with Other Loss Functions

The table lines up losses that measure the difference between two distributions or values from the same viewpoints.

Loss functionWhat it comparesSymmetric?Range of valuesMain uses
KL divergenceTwo probability distributionsNot symmetricNon-negative (can be infinite)Knowledge distillation, VAEs, pulling a distribution toward a target
Cross-entropyTarget distribution and model distributionNot symmetricAt least the entropy of the target distributionClassification (with a fixed target, it has the same minimizer as KL)
Bidirectional KL divergenceTwo probability distributionsSymmetricNon-negativeAligning two distributions that are both being learned, as in R-Drop
MSE (mean squared error)Two values (vectors)SymmetricNon-negativeRegression; aligning values that are not probabilities

Rough guidelines for choosing are as follows.

  • If the targets are one-hot labels, use cross-entropy: It gives the same value as the KL divergence and is simpler to implement.
  • If the target is itself a probability distribution (such as a teacher model's output), use the KL divergence: Since its value starts from 0, it is easier to read how close the distributions have become.
  • If both distributions move during training and neither can be treated as the target, make it bidirectional and symmetric.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

# Example from the text: target distribution P = (0.7, 0.2, 0.1), model distribution Q = (0.5, 0.3, 0.2)
P = torch.tensor([[0.7, 0.2, 0.1]])
Q = torch.tensor([[0.5, 0.3, 0.2]])

# Computation following the definition D_KL(P‖Q) = Ī£ P log(P / Q)
kl_pq = (P * (P.log() - Q.log())).sum(dim=1)
print(kl_pq.item())          # about 0.085

# nn.KLDivLoss: pass the "log" of the model's distribution as input and the target distribution as target
kl_loss = nn.KLDivLoss(reduction="batchmean")  # "mean" does not give the value of the definition
print(kl_loss(Q.log(), P).item())              # about 0.085 (= D_KL(P‖Q))

# Swapping the direction changes the value
print(kl_loss(P.log(), Q).item())              # about 0.092 (= D_KL(Q‖P))


# Use in knowledge distillation: pull the student's distribution toward the teacher's
T = 4.0                                         # temperature (smooths the distribution)
student_logits = torch.randn(32, 10, requires_grad=True)
teacher_logits = torch.randn(32, 10)
loss = kl_loss(
    F.log_softmax(student_logits / T, dim=1),   # student: log probabilities
    F.softmax(teacher_logits / T, dim=1),       # teacher: probabilities
) * (T * T)
loss.backward()

# When the target distribution is also held as logs, pass log_target=True
kl_loss_log = nn.KLDivLoss(reduction="batchmean", log_target=True)
loss2 = kl_loss_log(F.log_softmax(student_logits, dim=1), F.log_softmax(teacher_logits, dim=1))

FAQ

Q. Isn't the KL divergence a distance?
A.

It does not satisfy the conditions of a distance, so it is not called one. Swapping the direction changes its value (it is not symmetric), and the triangle inequality does not hold. It is used as a quantity expressing "how large the difference between two distributions is."

Q. Should I use cross-entropy or the KL divergence?
A.

If the target distribution does not change during training, minimizing either gives the same model. If the targets are one-hot labels, cross-entropy is simpler. When the target is a soft distribution, such as a teacher model's output, the KL divergence is often used because its value starts from 0 and is easy to read.

Q. The loss became inf (infinity). What is the cause?
A.

A common cause is that the model's distribution puts zero probability on a class where the target distribution puts some probability. Taking the log after softmax rounds the probability to 0, giving log 0. Apply log_softmax to the model's output and pass it to KLDivLoss in log form.

References

  1. S. Kullback and R. A. Leibler, "On Information and Sufficiency," The Annals of Mathematical Statistics, 22(1), 79–86, 1951.
  2. I. Goodfellow, Y. Bengio, and A. Courville, "Deep Learning," MIT Press, 2016, Section 3.13 Information Theory.
  3. A. Zhang, Z. C. Lipton, M. Li, and A. J. Smola, "Dive into Deep Learning," Section 22.11 Information Theory.
  4. D. P. Kingma and M. Welling, "Auto-Encoding Variational Bayes," ICLR, 2014.
  5. PyTorch Documentation, "torch.nn.KLDivLoss."
  6. K. P. Murphy, "Probabilistic Machine Learning: An Introduction," MIT Press, 2022, Section 6.2 Relative entropy (KL divergence) (6.2.5 KL and maximum likelihood estimation, 6.2.6 Forward vs reverse KL).
  7. G. Hinton, O. Vinyals, and J. Dean, "Distilling the Knowledge in a Neural Network," arXiv:1503.02531, 2015.
  8. X. Liang et al., "R-Drop: Regularized Dropout for Neural Networks," NeurIPS, 2021.