🤖 AI/ML

KL Divergence

Kullback-Leibler Divergence

Measures the difference between two probability distributions. Used in VAEs, distillation, and more.

📖 Detailed Explanation

KL Divergence (Kullback-Leibler Divergence) is an information-theory-based metric that measures the difference between two probability distributions P and Q. It quantifies "how much information is lost when P is approximated by Q," and a value of 0 means the two distributions are identical.

Proposed in 1951 by Solomon Kullback and Richard Leibler, KL Divergence is also called relative entropy. Subtracting the entropy H(P) from the Cross-Entropy gives the KL Divergence, and it is closely related to loss functions in classification problems.

Mathematically, D_KL(P||Q) = sum(P(x) * log(P(x)/Q(x))). It is asymmetric, so D_KL(P||Q) != D_KL(Q||P), and this property is used importantly in VAE regularization, Knowledge Distillation, and more.

In practice, it is used as a core component in VAE latent space regularization, model distillation (the student imitates the teacher), PPO in reinforcement learning (limiting policy change), Adversarial Training, and more. In 2025 research, GKL (Generalized KL) Divergence achieved SOTA on RobustBench.

💻 Code Example

import torch
import torch.nn.functional as F
import numpy as np
from scipy.special import kl_div as scipy_kl

# NumPy로 KL Divergence 직접 구현
def kl_divergence_numpy(p, q, epsilon=1e-10):
    """KL(P || Q): P가 실제 분포, Q가 근사 분포"""
    p = np.array(p) + epsilon
    q = np.array(q) + epsilon
    return np.sum(p * np.log(p / q))

# 예시: 실제 분포 vs 예측 분포
p_true = [0.1, 0.2, 0.3, 0.4]      # 실제 분포
q_approx = [0.25, 0.25, 0.25, 0.25]  # 균등 분포 (나쁜 근사)
q_good = [0.12, 0.22, 0.28, 0.38]    # 좋은 근사

print(f"KL(P || Q_bad): {kl_divergence_numpy(p_true, q_approx):.4f}")
print(f"KL(P || Q_good): {kl_divergence_numpy(p_true, q_good):.4f}")

# PyTorch KLDivLoss (Knowledge Distillation 예시)
# 주의: PyTorch는 입력이 log_softmax여야 함
teacher_logits = torch.tensor([[2.0, 1.0, 0.5, 0.1]])
student_logits = torch.tensor([[1.8, 1.1, 0.4, 0.2]])

temperature = 2.0  # soft label을 위한 온도
teacher_soft = F.softmax(teacher_logits / temperature, dim=-1)
student_log_soft = F.log_softmax(student_logits / temperature, dim=-1)

# reduction='batchmean'이 수학적 정의와 일치
kl_loss = F.kl_div(student_log_soft, teacher_soft, reduction='batchmean')
print(f"Knowledge Distillation KL Loss: {kl_loss.item():.4f}")

# VAE에서의 KL Divergence (잠재 공간 정규화)
def vae_kl_loss(mu, log_var):
    """q(z|x) ~ N(mu, sigma^2)와 p(z) ~ N(0, 1) 사이의 KL"""
    return -0.5 * torch.sum(1 + log_var - mu.pow(2) - log_var.exp())

mu = torch.randn(32, 64)       # 배치 32, 잠재 차원 64
log_var = torch.randn(32, 64)
print(f"VAE KL Loss: {vae_kl_loss(mu, log_var).item():.2f}")

🗣️ Say It Like This in Practice

💬 In a Meeting
"In Knowledge Distillation, we use KL Divergence to measure how well the student model imitates the teacher's soft labels. Setting the temperature to around 2 to 4 makes the soft labels smoother, so training is more stable."
💬 In an Interview
"KL Divergence is asymmetric, so D_KL(P||Q) and D_KL(Q||P) are different. In a VAE, the KL term is included in the loss to bring the approximate distribution q(z|x) closer to the prior distribution p(z)=N(0,1). This is what regularizes the latent space."
💬 In a Technical Discussion
"The reason we use a KL penalty in PPO is that training becomes unstable if the policy changes abruptly. By limiting the KL Divergence from the previous policy, we ensure stable updates."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Using reduction='mean' with PyTorch KLDivLoss

It does not match the mathematical definition. You must use reduction='batchmean' to compute the correct KL Divergence value.

❌
Confusing the order of P and Q

In D_KL(P||Q), P is the actual (target) distribution and Q is the approximate (prediction) distribution. If the order is swapped, you get a completely different value.

✅
Adding epsilon to zero probabilities

If P(x)>0 where Q(x)=0, the KL becomes infinite. Add a small value of around 1e-10 to ensure numerical stability.

🔗 Related Terms

📚 Learn More