Skip to content
fn

kl_divergence

→Tensor
kl_divergence(p: Distribution, q: Distribution)

Compute the Kullback–Leibler divergence KL(p ∥ q)\mathrm{KL}(p \,\|\, q).

The KL divergence is the expected log-ratio of two probability measures pp and qq defined on the same sample space:

KL(p ∥ q)=Ex∼p ⁣[log⁡p(x)q(x)]=∫p(x)log⁡p(x)q(x) dx\mathrm{KL}(p \,\|\, q) = \mathbb{E}_{x \sim p}\!\left[\log \frac{p(x)}{q(x)}\right] = \int p(x) \log \frac{p(x)}{q(x)} \, dx

It is non-negative (KL(p ∥ q)≥0\mathrm{KL}(p \,\|\, q) \geq 0, with equality iff p=qp = q almost everywhere), is not symmetric in general (KL(p ∥ q)≠KL(q ∥ p)\mathrm{KL}(p \,\|\, q) \neq \mathrm{KL}(q \,\|\, p)), and does not satisfy the triangle inequality — so it is a divergence, not a metric.

Dispatch looks up the most-specific registered ancestor pair in the registry built by register_kl and raises NotImplementedError when no analytical formula is registered.

Parameters

Left-hand distribution.
Right-hand distribution (must share the support / event shape of p).

Returns

Tensor

Non-negative tensor of shape batch_shape giving the per-batch KL divergence in nats.

Raises

NotImplementedError
If the distribution types have not been registered via register_kl.

Notes

KL divergence appears throughout machine learning:

  • Variational inference: the ELBO equals log⁡p(x)−KL(q(z) ∥ p(z∣x))\log p(\mathbf{x}) - \mathrm{KL}(q(\mathbf{z})\,\|\, p(\mathbf{z} \mid \mathbf{x})).
  • VAE training: the encoder regulariser is KL(q(z∣x) ∥ p(z))\mathrm{KL}(q(\mathbf{z} \mid \mathbf{x})\,\|\, p(\mathbf{z})), available analytically for Normal-vs-Normal pairs.
  • Maximum likelihood: minimising negative log-likelihood is equivalent to minimising KL(pdata ∥ pθ)\mathrm{KL}(p_{\text{data}} \,\|\, p_{\theta}).
  • Mode-seeking vs mode-covering: KL(p ∥ q)\mathrm{KL}(p\,\|\,q) is mode-covering in qq; KL(q ∥ p)\mathrm{KL}(q\,\|\,p) is mode-seeking — important for variational approximations.

Examples

>>> import lucid
>>> from lucid.distributions import Normal
>>> from lucid.distributions.kl import kl_divergence
>>> p = Normal(loc=0.0, scale=1.0)
>>> q = Normal(loc=1.0, scale=2.0)
>>> kl_divergence(p, q)  # log(2) + (1 + 1)/8 - 1/2
tensor(0.4431)

Used by 2