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 is the same as maximizing the likelihood of samples from . 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 with parameters , where . The optimizer moves anywhere on the real line, and stays positive whatever step it takes.
In a toy problem we choose the target ourselves, so its density is known. Then the KL can be estimated by Monte Carlo from samples :
The samples stay fixed during training. Each step builds from the current and , evaluates at the samples, averages, and differentiates. Then gradient descent moves both parameters against their gradients with a learning rate :
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 :
Its derivative in is . Averaged over the samples it gives
It vanishes exactly when is the sample mean . The derivative in has the same structure: it vanishes when equals the average squared deviation .
So gradient descent on the forward KL ends at the sample mean and the biased sample variance (divided by , not ). 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 , so on them beats even the true . For a model with fitted parameters, a classical result (Wilks' theorem) gives the expected size of the effect:
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 where , the KL is infinite. A Gaussian is positive everywhere, but far in the tails underflows to in floating point. That is why the loss is always computed from , never from .
- Integrability. Matching supports is not enough. If is a heavy-tailed Cauchy distribution and is Gaussian, grows like while decays only like , and the integral diverges.
- Normalization. Both densities must integrate to . If the model used with a learnable , the loss would fall by , and the optimizer would push up forever.
One Gaussian, two modes
Now make the target harder. Let be an equal mixture of two narrow Gaussians, one at and one at :
A single Gaussian cannot match two modes. Which compromise does the forward KL choose? Write the expected loss for any , not just samples:
It depends on only through its mean and variance. So the minimum is again moment matching: and , whatever the shape of .
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 , and
The result covers both modes, at a price. Its peak sits in the empty gap between them. About of its mass lies in , where has about . Sampling from this mostly produces points that never occur in the data. The forward KL is mass-covering (also called mode-covering): it avoids zeros of wherever , 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:
Now every point where puts mass is checked against . The moment-matched Gaussian puts nearly a third of its mass in the gap. There, at , and , so each such point costs nats. Points in regions where is tiny are heavily penalized, and regions that ignores cost nothing at all.
So the reverse KL prefers to sit on one mode. Take , an exact copy of the right-hand component. Wherever has mass, the far mode contributes nothing, so , and
Ignoring the second mode costs only this much. never visits it; it pays only because, on its own territory, is half of . Numerical minimization of the reverse KL lands on this fit, or on its mirror at . The reverse KL is mode-seeking (also called zero-forcing): it drives to zero wherever is small, and stays sharp by giving up modes.
Far from the target
Return to the start of training, , far from both modes. The table compares three Gaussians under three losses, in nats; the best value in each column is in bold.
| forward | reverse | ||
|---|---|---|---|
| start, | 17.88 | 19.50 | 0.645 |
| moment-matched, | 0.936 | 3.709 | 0.255 |
| one mode, | 24.31 | 0.693 | 0.216 |
At the start, about of the nats of forward KL come from the far mode at , eight standard deviations from . A missed mode dominates the forward KL, and its gradient pulls hard. In it equals here, and it grows with the distance between and . The reverse KL also pulls hard, because 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 , and at the start it is already close to the cap. Moving a little barely changes it: its gradient in is about , eighty times weaker. A squared error between densities, , has the same problem when the two do not overlap, and on top of that its value changes with the units of . 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 . It needs samples from and the model's , and nothing else: the 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 . It needs samples from the model and , but only up to a constant: if , then , and does not depend on . 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 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 are neural networks with millions of parameters stacked in many layers. The objective stays the same, the average . 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.
Answers are saved on the server and tied to this browser until you sign in.