Excellent question. This gets to the heart of how to practically implement these concepts in a major deep learning framework.
The short answer is: Yes, PyTorch supports calculating both, but not through two explicitly named functions like inclusive_kld and exclusive_kld. You achieve one or the other based on which PyTorch module you use and how you use it.
Here’s the breakdown of how to do it and which one to use.
1. The "Exclusive" KL-Divergence: torch.nn.functional.kl_div
This is the standard, low-level KL-divergence function in PyTorch. It calculates the "exclusive" version, and its behavior is what gives rise to the problems we discussed.
- Function:
torch.nn.functional.kl_div (or its module equivalent torch.nn.KLDivLoss).
- How it works: It computes the standard formula:
sum(p * (log(p) - log(q))).
- Crucial Input Format: This function expects the log-probabilities for the first input (
log(q)) and probabilities for the second input (p). This is a common source of bugs!
- Why it's "Exclusive": If your model's predicted distribution
q has a probability of zero for a certain category, its log-probability will be -inf. This leads to NaNs in the loss and gradient, causing training to crash. It exclusively works when q has a non-zero probability everywhere p does.
Example of Exclusive KL-Divergence (and its problem):
import torch
import torch.nn.functional as F
# Let's say our model's encoder outputs these raw scores (logits)
# for a 4-category discrete latent variable.
logits = torch.tensor([10.0, -10.0, 1.0, 1.0]) # Model is very sure about category 0
# To use F.kl_div, we need log-probabilities for our model's distribution `q`.
log_q = F.log_softmax(logits, dim=-1)
# Now let's create our prior `p` (a uniform distribution)
# F.kl_div expects probabilities for the target.
p_probs = torch.tensor([0.25, 0.25, 0.25, 0.25])
# Calculate the KL divergence
kl_loss = F.kl_div(log_q, p_probs, reduction='batchmean')
print(f"Log probabilities of q: {log_q}")
print(f"Probabilities of p: {p_probs}")
print(f"Exclusive KL Loss: {kl_loss}\n")
# --- Now, let's see the problem ---
# If a log-probability is -inf (because the probability was 0), this can break.
# PyTorch's log_softmax is numerically stable and won't output literal -inf,
# but an extremely small number. The gradient can still vanish.
# If we were to manually create it:
log_q_with_inf = torch.tensor([0.0, -float('inf'), -float('inf'), -float('inf')]) # log of [1, 0, 0, 0]
# kl_loss_broken = F.kl_div(log_q_with_inf, p_probs, reduction='batchmean') -> This will result in NaN
This approach is brittle and generally not recommended for VAEs with discrete latents.
2. The "Inclusive" KL-Divergence: torch.distributions
This is the modern, robust, and recommended way to handle KL-divergence in PyTorch, especially in probabilistic models like VAEs. It is effectively "inclusive" because it uses numerically stable, analytical formulas where possible.
- Module:
torch.distributions
- How it works: You first create distribution objects (
Categorical, Normal, etc.) for your model's prediction q and the prior p. Then, you use a generic kl_divergence function that dispatches to a specialized, stable implementation based on the types of the two distributions.
- Why it's "Inclusive": For the
Categorical distribution, the library implements the KL divergence using a formula sum(q_probs * (q_logits - p_logits)) which avoids the log(0) problem entirely. It correctly and stably handles cases where the model assigns zero probability to a category.
Example of Inclusive KL-Divergence (Recommended Method):
import torch
from torch.distributions import Categorical
from torch.distributions.kl import kl_divergence
# Same logits from our model's encoder
logits_q = torch.tensor([10.0, -10.0, 1.0, 1.0])
# 1. Create the model's distribution `q` from logits
q_dist = Categorical(logits=logits_q)
# 2. Create the prior distribution `p` (uniform over 4 categories)
# It's often easier to define the prior with probabilities.
p_probs = torch.tensor([0.25, 0.25, 0.25, 0.25])
p_dist = Categorical(probs=p_probs)
# 3. Calculate the KL divergence KL(q || p)
# The function automatically uses a stable formula for (Categorical, Categorical).
kl_loss_inclusive = kl_divergence(q_dist, p_dist)
# The result is a single scalar value for this distribution.
# In a VAE, you would average this over the batch.
print(f"Logits of q: {q_dist.logits}")
print(f"Probabilities of p: {p_dist.probs}")
print(f"Inclusive KL Loss: {kl_loss_inclusive}")
# Let's see it handle an extreme case
logits_q_extreme = torch.tensor([100.0, -100.0, -100.0, -100.0])
q_dist_extreme = Categorical(logits=logits_q_extreme)
kl_loss_stable = kl_divergence(q_dist_extreme, p_dist)
print(f"\nInclusive KL with extreme logits: {kl_loss_stable}")
# Note: The result is stable and does not become NaN.
Summary and Recommendation
| Feature | Exclusive KL (F.kl_div) | Inclusive KL (torch.distributions) |
|---|
| How to Calculate | F.kl_div(log_q, p) | kl_divergence(q_dist, p_dist) |
| Input Format | log_q: log-probabilitiesp: probabilities | q_dist, p_dist: distribution objects |
| Numerical Stability | Low. Prone to NaNs if q has zero probability. | High. Uses specialized, stable formulas. |
| Ease of Use | Lower. Requires manual log_softmax and careful handling of inputs. | Higher. More abstract and robust. Matches the math of probabilistic models. |
| Recommended Use | Legacy code, or specific cases where you have log-probs. | Strongly recommended for VAEs, probabilistic models, and any modern code. |
Conclusion:
For implementing a VAE or any model with a discrete latent space where you need to calculate the KL-divergence loss, you should almost always use the torch.distributions module. It provides a stable, "inclusive" calculation that won't break during training and correctly reflects the underlying mathematics.