PyTorch doesn't have built-in functions specifically labeled as "inclusive" or "exclusive" KL-divergence. However, it provides the building blocks to implement both types, and the standard implementations handle these cases differently depending on how you use them.
Here's what PyTorch offers and how to implement both types:
1. Standard KL-Divergence Functions in PyTorch
torch.nn.functional.kl_div()
This function computes KL-divergence between two distributions, but it expects log-probabilities as input for the predictions and can take either probabilities or log-probabilities for the target.
import torch
import torch.nn.functional as F
# Example with log-probabilities
log_q = torch.log_softmax(logits, dim=-1) # Your predicted log-probs
p = torch.softmax(target_logits, dim=-1) # Target probs
# This is "exclusive" - can fail with zeros
kl_loss = F.kl_div(log_q, p, reduction='batchmean')
torch.distributions.kl_divergence()
This computes KL-divergence between two distribution objects:
from torch.distributions import Categorical, kl_divergence
# Create categorical distributions
q = Categorical(logits=logits)
p = Categorical(probs=torch.ones(K)/K) # Uniform prior
# This handles zeros more gracefully (more "inclusive")
kl_loss = kl_divergence(q, p)
2. Implementing Exclusive KL-Divergence
The exclusive version is straightforward but can be numerically unstable:
def exclusive_kl_categorical(logits, prior_probs):
"""
Exclusive KL-divergence for categorical distributions.
WARNING: Can be unstable if q assigns zero probability to any category.
Args:
logits: Unnormalized log-probabilities from your model
prior_probs: Prior probabilities (e.g., uniform)
"""
q_probs = F.softmax(logits, dim=-1)
# Direct KL calculation - can fail with zeros!
kl = torch.sum(q_probs * (torch.log(q_probs) - torch.log(prior_probs)), dim=-1)
return kl.mean()
3. Implementing Inclusive KL-Divergence
The inclusive version requires more careful handling:
def inclusive_kl_categorical(logits, prior_probs, eps=1e-8):
"""
Inclusive KL-divergence for categorical distributions.
More stable and allows sparse representations.
Args:
logits: Unnormalized log-probabilities from your model
prior_probs: Prior probabilities
eps: Small constant for numerical stability
"""
# Method 1: Add small epsilon (simple but can introduce bias)
q_probs = F.softmax(logits, dim=-1)
q_probs_safe = q_probs + eps
q_probs_safe = q_probs_safe / q_probs_safe.sum(dim=-1, keepdim=True)
kl = torch.sum(q_probs_safe * (torch.log(q_probs_safe) - torch.log(prior_probs)), dim=-1)
return kl.mean()
def inclusive_kl_categorical_stable(logits, prior_logits):
"""
More numerically stable inclusive KL-divergence using log-space computations.
This is the preferred implementation.
Args:
logits: Unnormalized log-probabilities from your model
prior_logits: Log of prior probabilities
"""
log_q = F.log_softmax(logits, dim=-1)
log_p = F.log_softmax(prior_logits, dim=-1)
# Use log-sum-exp for stability
# KL(q||p) = sum_i q_i * (log q_i - log p_i)
q = torch.exp(log_q)
kl = torch.sum(q * (log_q - log_p), dim=-1)
return kl.mean()
4. Best Practice: Using PyTorch Distributions
The most robust approach is to use PyTorch's distribution classes, which handle numerical stability internally:
from torch.distributions import Categorical, kl_divergence
class VAEWithDiscreteLatents(nn.Module):
def __init__(self, num_categories):
super().__init__()
self.num_categories = num_categories
# ... other layers ...
def forward(self, x):
# Get logits from encoder
logits = self.encoder(x) # Shape: [batch_size, num_categories]
# Create distributions
q_z = Categorical(logits=logits)
p_z = Categorical(probs=torch.ones(self.num_categories) / self.num_categories)
# Sample z
z = q_z.sample()
# Calculate KL divergence (this is numerically stable)
kl_loss = kl_divergence(q_z, p_z).mean()
# ... rest of VAE forward pass ...
return reconstruction, kl_loss
5. For Continuous Distributions (e.g., Gaussian VAEs)
For Gaussian VAEs, PyTorch's distribution classes also handle the KL calculation elegantly:
from torch.distributions import Normal, kl_divergence
# Encoder outputs mean and log_var
mu, log_var = self.encoder(x)
std = torch.exp(0.5 * log_var)
# Create distributions
q_z = Normal(mu, std)
p_z = Normal(torch.zeros_like(mu), torch.ones_like(std))
# KL divergence (closed-form for Gaussians)
kl_loss = kl_divergence(q_z, p_z).sum(dim=-1).mean()
Summary
- PyTorch doesn't explicitly distinguish between "inclusive" and "exclusive" KL-divergence in function names
F.kl_div() can be exclusive if you're not careful with zeros
torch.distributions.kl_divergence() is generally more robust and handles edge cases better (more "inclusive")
- For discrete latents, always use the distribution classes or implement careful numerical stability measures
- The key difference is in how you handle zero probabilities and numerical stability
The recommendation is to use PyTorch's distribution classes whenever possible, as they implement numerically stable algorithms that effectively give you "inclusive" behavior without having to worry about the implementation details.