Skip to content
BIASED

Fitting distributions with KL

We fit a Gaussian by gradient descent and see that the forward KL matches moments and covers both modes, while the reverse KL picks one.

A training loop for two numbers

The topic Entropy, cross-entropy and KL showed that minimizing the forward KL DKL(P ∥ Qθ)D_{\mathrm{KL}}(P \,\|\, Q_\theta) is the same as maximizing the likelihood of samples from PP. Now we run that minimization and look at the answer it gives. The model is the simplest one from Multivariate Gaussians: a single one-dimensional Gaussian.

We write the model as Qθ=N(μ,σ2)Q_\theta = \mathcal N(\mu, \sigma^2) with parameters θ=(μ,s)\theta = (\mu, s), where s=log⁡σs = \log\sigma. The optimizer moves ss anywhere on the real line, and σ=es\sigma = e^s stays positive whatever step it takes.

In a toy problem we choose the target ourselves, so its density pp is known. Then the KL can be estimated by Monte Carlo from samples x1,…,xN∼Px_1, \dots, x_N \sim P:

DKL(P ∥ Qθ)≈1N∑i=1N[log⁡p(xi)−log⁡qθ(xi)].D_{\mathrm{KL}}(P \,\|\, Q_\theta) \approx \frac1N \sum_{i=1}^N \big[\log p(x_i) - \log q_\theta(x_i)\big].

The samples stay fixed during training. Each step builds QθQ_\theta from the current μ\mu and σ=es\sigma = e^s, evaluates log⁡qθ\log q_\theta at the samples, averages, and differentiates. Then gradient descent moves both parameters against their gradients with a learning rate η\eta:

μ←μ−η ∂L∂μ,s←s−η ∂L∂s.\mu \leftarrow \mu - \eta\,\frac{\partial \mathcal L}{\partial \mu}, \qquad s \leftarrow s - \eta\,\frac{\partial \mathcal L}{\partial s}.

In practice Adam replaces the plain step: it rescales each coordinate using running statistics of its gradients. Autograd computes the derivatives; here we will also find them by hand.

Where the gradients vanish

For one sample the loss is the negative log-density of a 1-D Gaussian, written through ss:

−log⁡qθ(x)=12log⁡2π+s+(x−μ)22e2s.-\log q_\theta(x) = \tfrac12\log 2\pi + s + \frac{(x - \mu)^2}{2e^{2s}} .

Its derivative in μ\mu is −(x−μ)/σ2-(x - \mu)/\sigma^2. Averaged over the samples it gives

∂L∂μ=−1N∑i=1Nxi−μσ2.\frac{\partial \mathcal L}{\partial \mu} = -\frac1N\sum_{i=1}^N \frac{x_i - \mu}{\sigma^2}.

It vanishes exactly when μ\mu is the sample mean xˉ\bar x. The derivative in ss has the same structure: it vanishes when σ2\sigma^2 equals the average squared deviation 1N∑i(xi−xˉ)2\frac1N\sum_i (x_i - \bar x)^2.

So gradient descent on the forward KL ends at the sample mean and the biased sample variance (divided by NN, not N−1N - 1). Gradient descent arrives where a formula could have taken us directly: the best Gaussian copies the first two moments of the data. This is moment matching, and it is what maximum likelihood does for any Gaussian, in any dimension: the fitted covariance is the sample covariance.

What to trust in a KL estimate

In the toy problem we can also read off the value of the KL, not just its gradient. One surprise: after training, the estimate on the training samples is often slightly negative, although KL is never negative.

The reason is overfitting. The fitted parameters are tuned to these particular xix_i, so on them qθq_\theta beats even the true pp. For a model with kk fitted parameters, a classical result (Wilks' theorem) gives the expected size of the effect:

E[training estimate]≈−k2N nats.\mathbb E\big[\text{training estimate}\big] \approx -\frac{k}{2N} \text{ nats}.

An honest number needs fresh samples that the fit has never seen.

The estimate also relies on assumptions that are easy to break.

  • Common support. If qθ(x)=0q_\theta(x) = 0 where p(x)>0p(x) > 0, the KL is infinite. A Gaussian is positive everywhere, but far in the tails qθ(x)q_\theta(x) underflows to 00 in floating point. That is why the loss is always computed from log⁡qθ\log q_\theta, never from qθq_\theta.
  • Integrability. Matching supports is not enough. If PP is a heavy-tailed Cauchy distribution and QQ is Gaussian, log⁡pq\log\frac pq grows like x2x^2 while pp decays only like 1/x21/x^2, and the integral diverges.
  • Normalization. Both densities must integrate to 11. If the model used Z⋅qθZ \cdot q_\theta with a learnable ZZ, the loss would fall by log⁡Z\log Z, and the optimizer would push ZZ up forever.

One Gaussian, two modes

Now make the target harder. Let PP be an equal mixture of two narrow Gaussians, one at −3-3 and one at −8-8:

p(x)=12 N(x; −3, 0.52)+12 N(x; −8, 0.52).p(x) = \tfrac12\,\mathcal N(x;\, -3,\, 0.5^2) + \tfrac12\,\mathcal N(x;\, -8,\, 0.5^2).

A single Gaussian cannot match two modes. Which compromise does the forward KL choose? Write the expected loss for any PP, not just samples:

Ex∼P[−log⁡qθ(x)]=12log⁡2π+log⁡σ+Var⁡P[x]+(EP[x]−μ)22σ2.\mathbb E_{x \sim P}\big[-\log q_\theta(x)\big] = \tfrac12\log 2\pi + \log\sigma + \frac{\operatorname{Var}_P[x] + (\mathbb E_P[x] - \mu)^2}{2\sigma^2}.

It depends on PP only through its mean and variance. So the minimum is again moment matching: μ∗=EP[x]\mu^* = \mathbb E_P[x] and σ∗2=Var⁡P[x]\sigma^{*2} = \operatorname{Var}_P[x], whatever the shape of PP.

For a mixture, the law of total variance splits the variance in two: the average variance inside the components plus the variance of the component centres. Here the mean is −5.5-5.5, and

σ∗2=0.52+2.52=6.5,σ∗≈2.55.\sigma^{*2} = 0.5^2 + 2.5^2 = 6.5, \qquad \sigma^* \approx 2.55 .

The result N(−5.5, 6.5)\mathcal N(-5.5,\, 6.5) covers both modes, at a price. Its peak sits in the empty gap between them. About 31%31\% of its mass lies in (−6.5,−4.5)(-6.5, -4.5), where PP has about 0.13%0.13\%. Sampling from this QQ mostly produces points that never occur in the data. The forward KL is mass-covering (also called mode-covering): it avoids zeros of qq wherever p>0p > 0, and blurs everything together to get there.

The reverse KL picks a mode

Swap the arguments. The reverse KL averages over the model instead of the data:

DKL(Qθ ∥ P)=Ex∼Qθ[log⁡qθ(x)−log⁡p(x)].D_{\mathrm{KL}}(Q_\theta \,\|\, P) = \mathbb E_{x \sim Q_\theta}\big[\log q_\theta(x) - \log p(x)\big].

Now every point where QθQ_\theta puts mass is checked against pp. The moment-matched Gaussian puts nearly a third of its mass in the gap. There, at x=−5.5x = -5.5, q≈0.16q \approx 0.16 and p≈3⋅10−6p \approx 3 \cdot 10^{-6}, so each such point costs log⁡qp≈11\log\frac qp \approx 11 nats. Points in regions where pp is tiny are heavily penalized, and regions that QθQ_\theta ignores cost nothing at all.

So the reverse KL prefers to sit on one mode. Take Qθ=N(−3, 0.52)Q_\theta = \mathcal N(-3,\, 0.5^2), an exact copy of the right-hand component. Wherever QθQ_\theta has mass, the far mode contributes nothing, so p(x)≈12qθ(x)p(x) \approx \tfrac12 q_\theta(x), and

DKL(Qθ ∥ P)≈log⁡2≈0.693 nats.D_{\mathrm{KL}}(Q_\theta \,\|\, P) \approx \log 2 \approx 0.693 \text{ nats}.

Ignoring the second mode costs only this much. QθQ_\theta never visits it; it pays only because, on its own territory, pp is half of qθq_\theta. Numerical minimization of the reverse KL lands on this fit, or on its mirror at −8-8. The reverse KL is mode-seeking (also called zero-forcing): it drives qq to zero wherever pp is small, and stays sharp by giving up modes.

Far from the target

Return to the start of training, Qθ=N(0,1)Q_\theta = \mathcal N(0, 1), far from both modes. The table compares three Gaussians under three losses, in nats; the best value in each column is in bold.

QθQ_\theta forward DKL(P ∥ Qθ)D_{\mathrm{KL}}(P \,\|\, Q_\theta) reverse DKL(Qθ ∥ P)D_{\mathrm{KL}}(Q_\theta \,\|\, P) DJSD_{\mathrm{JS}}
start, N(0,1)\mathcal N(0, 1) 17.88 19.50 0.645
moment-matched, N(−5.5, 6.5)\mathcal N(-5.5,\, 6.5) 0.936 3.709 0.255
one mode, N(−3, 0.52)\mathcal N(-3,\, 0.5^2) 24.31 0.693 0.216

At the start, about 15.815.8 of the 17.917.9 nats of forward KL come from the far mode at −8-8, eight standard deviations from μ=0\mu = 0. A missed mode dominates the forward KL, and its gradient pulls hard. In μ\mu it equals 5.55.5 here, and it grows with the distance between μ\mu and EP[x]\mathbb E_P[x]. The reverse KL also pulls hard, because log⁡p\log p is a smooth function that keeps falling away from the modes.

The JS divergence from Entropy, cross-entropy and KL behaves differently. It is capped at log⁡2≈0.693\log 2 \approx 0.693, and at the start it is already close to the cap. Moving QθQ_\theta a little barely changes it: its gradient in μ\mu is about 0.070.07, eighty times weaker. A squared error between densities, ∫(p−qθ)2 dx\int (p - q_\theta)^2\,dx, has the same problem when the two do not overlap, and on top of that its value changes with the units of xx. Where JS does decide, it prefers one sharp mode, like the reverse KL.

Which direction to use

Which direction can we actually use? It depends on what we have.

The forward KL averages over PP. It needs samples from PP and the model's log⁡qθ\log q_\theta, and nothing else: the log⁡p\log p term is a constant. This is the usual generative setting, a dataset and a model, and it is maximum likelihood. Models trained this way, such as normalizing flows and autoregressive models, inherit the mass-covering behaviour: they put probability on every mode, sometimes on the space between modes too.

The reverse KL averages over QθQ_\theta. It needs samples from the model and log⁡p\log p, but only up to a constant: if p=p~/Zp = \tilde p / Z, then log⁡p=log⁡p~−log⁡Z\log p = \log\tilde p - \log Z, and log⁡Z\log Z does not depend on θ\theta. So the reverse direction fits when we can evaluate the target's unnormalized density but cannot sample it. This is exactly the situation in Latent variables and the ELBO, where an encoder is fitted to a posterior known only up to a constant, and it tends to under-cover that posterior. Differentiating through samples of QθQ_\theta is a problem of its own; The reparameterization trick solves it. GANs, whose original objective reduces to JS, produce sharp samples but can lose modes; that topic calls it mode collapse.

Our model had two parameters, and we wrote their gradients by hand. Real models QθQ_\theta are neural networks with millions of parameters stacked in many layers. The objective stays the same, the average −log⁡qθ(xi)-\log q_\theta(x_i). What changes is everything around it: how gradients travel through a deep stack, what keeps them from vanishing or exploding, and which layers suit images. That is the next topic, Batch normalization, gradients and convolutions.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.