Training a Gaussian by gradient descent on a sample estimate of KL, what the divergence quietly assumes, and what forward KL, reverse KL, JS and a least-squares loss do when one Gaussian must fit two modes.
The data have two clusters, one around −3 and one around −8, and the model is a single Gaussian. Minimize the KL divergence from the data to the model, and the Gaussian settles at −5.5 with a standard deviation of 2.55: its densest part sits in the empty gap, where no data point lies. Swap the two arguments of the divergence, and the Gaussian sits on one cluster and ignores the other.
Real models never represent the data exactly, so which of these failures a loss prefers is a property of every generative model trained with it. To see it we fit a Gaussian Q with trainable parameters to a target P by gradient descent, with the KL divergence of the entropy note as the loss and the trainable Gaussian as the model.
In one dimension the model is Q=N(μ,σ2) with parameters θ=(μ,logσ); storing σ through its logarithm keeps it positive whatever the optimizer does. In two dimensions the parameters are the mean and the three raw entries of the Cholesky factor.
One iteration of the fitting loop rebuilds Q from the current parameters, evaluates its log-density at fixed samples xi∼P, and computes the loss, a sample estimate of DKL(P∥Q). Backpropagation then computes the gradient of the loss with respect to each parameter, and the optimizer moves the parameters against it. For plain gradient descent with learning rate η the step is
μlogσ←μ−η∂μ∂loss,←logσ−η∂logσ∂loss.
Adam (Kingma and Ba, 2015) moves in a similar direction but rescales each coordinate’s step by running estimates of the gradient’s mean and magnitude; the PyTorch fits quoted below use it.
Figure
One iteration of the fitting loop
Each iteration rebuilds Q from the trainable μ and s = log σ (so that σ = exp(s) stays positive), scores the fixed samples xᵢ ~ P, computes the sample estimate of KL(P‖Q), back-propagates it and takes one step. The update shown is plain gradient descent; Adam rescales each coordinate's step.
In PyTorch the parameters are tensors created with requires_grad=True, loss.backward() fills their .grad, and optimizer.step() takes the step; the target’s parameters carry no gradient and stay fixed. The Code section runs the same loop in NumPy with the gradients written out by hand.
By the law of large numbers the average converges to the expectation as N grows. Averaging log2 instead of ln reports the loss in bits; it rescales the loss and its gradients by 1/ln2≈1.443.
Figure
The sample estimate of KL(P‖Q)
Top: P = 𝒩(3, 1) in red, Q = 𝒩(1.5, 1.5²) in blue, and 40 samples xᵢ ~ P as ticks. Bottom: log p(x) − log q(x), positive between about 2.0 and 6.4, where Q underestimates P and most samples land. Their mean, 0.723 nats, estimates the exact KL(P‖Q) = 0.628 nats.
If the samples come from another distribution R with density r, each term is reweighted by wi=p(xi)/r(xi), the importance weight; this needs r>0 wherever p>0.
The estimate can be negative although KL never is. Fit a full-covariance 2-D Gaussian, five parameters, to 1000 fixed samples of N((−5,−5),I): after 4800 Adam steps the loss reads −0.0020 bits. The model is fitted to the same samples on which the loss is evaluated. The target is one of the candidate Gaussians, so at the maximum-likelihood fit the average of logq over the samples is at least the average of logp. How far below zero follows from Wilks’ theorem (Wilks, 1938). When the family contains P, its log-likelihood is smooth and the true parameters lie inside the parameter set, twice the gain in total log-likelihood of the fit over the true parameters is approximately χ2 with k degrees of freedom for k fitted parameters. The intuition: near its maximum the log-likelihood is a quadratic bowl, and the noise of the sample shifts the maximum by k independent, roughly normal amounts, each of which adds half a squared standard normal to the gain. The loss is minus the gain divided by N, and a χk2 variable has mean k, so
In 2000 simulated fits the estimate averages −0.0036 bits with a standard deviation of 0.0023, so −0.0020 is a typical value. An honest estimate of the fitted model’s divergence needs fresh samples, as held-out data does for any model.
For a 1-D Gaussian, logq(x)=−logσ−21log2π−2σ2(x−μ)2. The term logp(xi) does not depend on the parameters, so only −logq contributes (natural logarithms):
The second line uses σ−2=e−2logσ, whose derivative in logσ is −2σ−2, and the derivative 1 of logσ itself. Both vanish when μ is the sample mean and σ2=N1∑i(xi−μ)2 the biased sample variance: the maximum-likelihood estimates, as the entropy note predicted. The gradient never needs p; the values p(xi) only make the reported number equal to the KL. With real data, where p is unknown, we drop that constant and minimize the negative log-likelihood −N1∑ilogq(xi).
The exact KL between two 1-D Gaussians shows where the steps lead. Take DKL=EP[logp(x)−logq(x)], write both log-densities as above, and use EP[(x−μP)2]=σP2 and EP[(x−μ)2]=σP2+(μP−μ)2. The constants 21log2π cancel, and
Fitting Q = 𝒩(μ, σ²) to P = 𝒩(3, 1) by gradient descent on KL(P‖Q)
Q starts at 𝒩(−2, 0.5²) and is drawn at iterations 0, 5, 50, 400, 800, 1100, 1600, faint to bold. The first steps mostly inflate σ (to 3.83 by iteration 50, while μ creeps to −1.49); then μ slides to 3 and σ shrinks to 1, ending at μ = 2.92, σ = 1.01 after 1600 steps. Lower panel: KL in nats, log scale. Closed-form KL, plain gradient descent on (μ, log σ), learning rate 0.01.
With plain gradient descent on (μ,logσ) the trajectory shows the priorities of the forward KL. While Q is narrow and far away, most of P‘s mass sits where q≈0, and the cheapest fix is to widen Q: σ jumps up in the first steps while μ only creeps. Once Q covers P, μ moves across and σ shrinks back. The order comes from the gradient sizes. From the closed form, ∂/∂logσ=1−(σP2+(μP−μ)2)/σ2 grows like (μP−μ)2/σ2, while ∂/∂μ=(μ−μP)/σ2 grows only like ∣μP−μ∣/σ2. Adam, which normalizes each coordinate’s step, moves both at a similar rate and reaches the same optimum by a different path.
is a meaningful, finite number only under conditions (a)–(c) below; (d) and (e) are choices that must be made consistently (Cover and Thomas, 2006, §8.5; Murphy, 2023, §5.1).
The support of a distribution is the set of its possible values, suppp={x:p(x)>0}. If q(x)=0 on a region to which P gives positive probability, logq(x)p(x)=∞ there and the divergence is infinite. Formally, DKL(P∥Q) is finite only if P is absolutely continuous with respect to Q, written P≪Q: wherever P has mass, Q must have mass too.
This is one reason models trained by maximum likelihood use densities that are positive everywhere, such as Gaussians: the per-sample loss −logq(xi) stays finite at every observed point. Positivity alone does not make a model blurry. Combined with the forward KL, which punishes any missed mass, it makes a model that cannot represent the data spread probability between and around the modes, which is one explanation offered for the blurry samples of likelihood-trained image models (Theis, van den Oord and Bethge, 2016).
Figure
Common support: Q must not have holes where P lives
P = 𝒩(0, 1) in red. Left: Q uniform on [−1.5, 1.5]. The shaded tails hold 13.4% of P's mass, and there p(x) > 0 while q(x) = 0, so the integrand p log(p/q) is infinite and KL(P‖Q) = ∞. Right: a “blurry” Gaussian Q = 𝒩(0, 1.5²) is positive everywhere, and KL(P‖Q) = 0.128 nats.
The condition is one-sided. Points where q(x)>0 but p(x)=0 contribute 0 to DKL(P∥Q); they matter only for the reverse direction.
The integral must converge, and matching supports are not enough. Let P be a standard Cauchy distribution and Q=N(0,σ2). Both are positive everywhere, and with p(x)=1/(π(1+x2))
logq(x)p(x)=2σ2x2−log(1+x2)+logπ2πσ.
Under P the middle term has the finite mean 2ln2, while EP[x2]=∞, so DKL(P∥Q)=∞. A model with light tails cannot fit heavy-tailed data in KL.
p and q must be probability densities or mass functions: non-negative and integrating to 1. Raw scores such as a classifier’s logits go through a softmax first, and the log_prob of a torch.distributions object is already normalized.
KL is not symmetric, so we must decide which distribution plays the truth. The forward KL DKL(P∥Q) averages over P and penalizes missed modes: Q must cover everything where P lives. It is the direction of maximum likelihood. The reverse KL DKL(Q∥P) averages over Q and penalizes extra mass: Q must not spread to where P≈0. It is the direction of variational inference, including the VAE. The two are also called inclusive and exclusive KL, and their behaviour zero-avoiding, or mode-covering, and zero-forcing, or mode-seeking (Murphy, 2023, §5.1.4).
Figure
Which direction penalizes what: missed modes versus extra mass
P (red) is an equal mixture of 𝒩(±2.5, 0.7²). Left: Q on one mode misses the other, so KL(P‖Q) = 12.06 nats is large while KL(Q‖P) = 0.69 ≈ ln 2. Right: the best forward-KL Gaussian, 𝒩(0, 2.60²), covers both but puts mass where P ≈ 0 (shaded): KL(Q‖P) = 1.54, KL(P‖Q) = 0.62.
Only the forward direction can be estimated from data alone. It needs samples from P and logq at them; the reverse direction needs logp, which real data never provides.
For discrete distributions the integral becomes a sum. Mixing the two gives an infinite divergence: if P has an atom at x, any Q with a density gives {x} probability zero, so P≪Q and DKL(P∥Q)=∞ by condition (a). For continuous data, maximum likelihood is therefore read as a sample estimate of DKL(P∥Q) for the underlying density p. Reading it as the KL of the empirical distribution of the samples works only for discrete outcomes.
A Gaussian Q is positive everywhere, so (a) holds mathematically whatever the target, and it can still fail numerically. Computing qx = Q.log_prob(x).exp() and then qx.log2() underflows in 32-bit floating point once logq(x) drops below about −103: for σ≈1, about 14 standard deviations from μ. The loss is then infinite exactly when Q starts far from P. Working with log_prob directly avoids it.
The two-mode targets below need the same care. Their log-density log(21p1(x)+21p2(x)) is computed from the component log-densities a=logp1(x)+log21 and b=logp2(x)+log21 as
logaddexp(a,b)=max(a,b)+log(1+e−∣a−b∣),
the two-term case of the stable log-sum-exp, which stays finite far from both components.
With a single Gaussian target, KL fitting recovers the target. The informative case is a target the family cannot represent. In 2-D it is an equal mixture of N((−5,−5),I) and N((4,4),I); in 1-D it is
P=21N(−3,0.52)+21N(−8,0.52),
and the model starts from Q=N(0,1). We compare four losses: forward KL, reverse KL, JS and a least-squares loss on density values. None is satisfactory, each for its own reason, and the same trade-offs reappear across generative models (Huszár, 2015; Theis, van den Oord and Bethge, 2016; Isachenko, lecture 5).
The initial Q=N(0,1) barely reaches the far mode at −8, eight standard deviations from its mean. There logq(x)p(x) is huge, and that mode dominates the whole divergence, 17.9 nats. For a Gaussian Q the forward KL stays finite, and its gradient in μ, (μ−EP[x])/σ2=5.5, is large. Overlap matters for the bounded losses, JS and least squares, whose gradients nearly vanish without it.
Figure
When Q misses part of P's support
Top: the two-mode target P and the initial model Q = 𝒩(0, 1). Left of x ≈ −5.1 the model density is below 10⁻⁶, yet P has a whole mode there. Bottom: each point's contribution p(x) log p(x)/q(x) to KL(P‖Q); the far mode dominates the total of 17.9 nats.
Forward KL covers both modes; reverse KL picks one#
Minimizing DKL(P∥Q) makes a single Gaussian cover both modes with a wide spread. Write the forward KL as
DKL(P∥Q)=−H(P)−EP[logq(x)].
Only the second term depends on Q, and for a Gaussian logq depends on x only through x and xx⊤. Minimizing it over μ and Σ gives exact moment matching (Bishop, 2006, §10.7), derived below:
μ∗Σ∗=EP[x],=CovP[x].Derivation
Write m=EP[x] and C=CovP[x], and assume C is positive definite. For q=N(μ,Σ) in d dimensions,
Split x−μ=(x−m)+(m−μ). The cross term averages to zero because EP[x−m]=0, and a scalar equals its trace, E[v⊤Σ−1v]=tr(Σ−1E[vv⊤]), so
EP[(x−μ)⊤Σ−1(x−μ)]=tr(Σ−1C)+(m−μ)⊤Σ−1(m−μ).
The last term is ≥0 and zero only at μ=m, which fixes the mean. For the covariance let λ1,…,λd>0 be the eigenvalues of A=C−1/2ΣC−1/2. The cyclic property of the trace gives tr(Σ−1C)=tr(A−1)=∑i1/λi, and detΣ=detC⋅∏iλi, so the part that depends on Σ is
21logdetC+21i=1∑d(logλi+λi1).
Each term logλ+1/λ has derivative (λ−1)/λ2, negative for λ<1 and positive for λ>1, so it is smallest at λ=1. All eigenvalues equal to 1 means A=I, that is Σ=C.
For the 1-D target, μ∗=−5.5 and, by the law of total variance, σ∗2=0.25+2.52=6.5, so σ∗≈2.55: the average variance within a component is 0.25, and the spread of the two means around −5.5 adds 2.52. For the 2-D target the optimum has mean (−0.5,−0.5). The same law adds the within-component covariance I to the covariance of the two means, which sit at ±(4.5,4.5) from it and contribute 4.52=20.25 to every entry:
Σ∗=(21.2520.2520.2521.25),
one elongated Gaussian along the diagonal through both modes, densest in the empty gap. Its divergence is 1.170 nats, or 1.688 bits. An Adam fit (learning rate 0.1, 2000 fixed samples, started from N(0,I)) reaches this picture at an estimated 1.669 bits after 4800 steps; the gap of 0.019 bits is below the standard deviation of a 2000-sample estimate, about 0.023 bits.
The reverse divergence DKL(Q∥P) averages over samples of Q. It punishes mass where P is small and ignores parts of P that Q misses, so Q locks onto one mode (Bishop, 2006, §10.1.2; Minka, 2005). For two equal, well-separated modes, sitting exactly on one costs only ln2. If Q stays near the first component p1, where the second is negligible, then p≈p1/2 there and
The second term is zero for Q=p1 and positive otherwise, so the best Gaussian is the mode itself, at ln2.
Figure
Fitting one Gaussian to two modes: forward vs reverse KL
Target P = ½𝒩(−3, 0.5²) + ½𝒩(−8, 0.5²). The best single Gaussian under KL(P‖Q), found by grid search, has μ = −5.50, σ = 2.55, the mean and variance of P; its densest part lies in the gap where P ≈ 0. Under KL(Q‖P) the best Gaussian sits on one mode (μ = −3.00, σ = 0.50); the other mode is equally good.
JS never blows up, and it still drops a mode. For the 1-D target the best single Gaussian under the symmetric JS, found by grid search, sits exactly on one mode, at 0.216 nats against 0.255 for the moment-matched Gaussian. Exactly on one mode, Q=p1, the mixture is M=21(P+Q)=43p1+41p2. The modes are ten standard deviations apart, so wherever one component has mass the other is negligible, and each log ratio is a constant on its mode:
Trained runs agree. A fit of the 2-D mixture with Adam (learning rate 0.1, 5000 steps, 5000 fresh samples per step), started from μ=(−2,−2), ends near (−4.99,−5.06) with a nearly unit covariance, on the mode at (−5,−5). In 1-D, plain gradient descent from N(0,1) ends at μ=−2.995, σ=0.495 after 1800 steps, on the nearer mode; Q‘s peak density there, 0.81, is twice the target’s 0.40. Both runs minimized a weighted variant, 0.7DKL(P∥M)+0.3DKL(Q∥M). With the two terms above its one-mode value is (0.7⋅21+0.3)log234=0.65log234≈0.270 bits. The final 1-D Gaussian has exactly this value, 0.270 bits by numerical integration. The 2-D run’s last estimate, 0.2734 bits, is a sample estimate whose standard deviation at 5000 samples is about 0.008 bits, so it agrees with 0.270 up to noise.
Each half of JS is an expectation under its own distribution:
with m=21(p+q) evaluated by logaddexp. The estimate needs samples of both P and Q. The second term depends on Q‘s parameters also through the samples yj, so they must be drawn with the reparameterization trick, y=μ+σε; the runs above drew them without it, so their gradients miss that dependence.
Boundedness has a second cost. When Q and P barely overlap, JS is already close to its maximum ln2 and almost flat. At the initial N(0,1) it is 0.645 nats, 93% of ln2, and its gradient in μ is 0.070 against 5.5 for the forward KL. The same saturation gives the original minimax GAN its vanishing generator gradients (Arjovsky and Bottou, 2017, Theorem 2.4; see the GAN note and Wasserstein GANs).
A least-squares loss on densities is sensitive to scale#
A naive alternative compares density values directly, at samples xi∼P:
LLS=N1i=1∑N(q(xi)−p(xi))2.
Density values depend on the units of the data. Stretching every coordinate by c divides all densities by cd in d dimensions, so the loss shrinks by c2d. Adam absorbs a constant factor, but not the second problem: when Q does not overlap P, q(xi)≈0 at the data points, and the loss sits near the constant EP[p(x)2] with almost no gradient. KL has neither problem. The ratio p/q does not change under rescaling, and −logq(xi) grows like (xi−μ)2/2σ2 far from μ, so the pull grows as Q moves away.
The least-squares loss also has several minima. In 1-D its global minimum, 0.0470, is a wide Gaussian with σ≈2.53, close to the moment-matched one, and a Gaussian on one mode, N(−3.01,1.212), is a local minimum at 0.0495. In 2-D a Gaussian on one mode, N((4,4),1.582I), is a local minimum at 0.00113, while the global one, 0.00102, is centred at (−0.5,−0.5) and stretched along the diagonal (standard deviation 6.5 along it, 0.43 across). An Adam fit started from N((1,1),I), which overlaps only the mode at (4,4), ends on that mode, wider than it; the other mode contributes almost no gradient, because q≈0 there.
For the 1-D target, natural logarithms; the least-squares loss has units of squared density.
Single Gaussian Q
DKL(P∥Q)
DKL(Q∥P)
DJS
LS
initial N(0,1)
17.88
19.50
0.645
0.0901
moment-matched N(−5.5,6.5)
0.936
3.709
0.255
0.0470
one mode N(−3,0.52)
24.31
0.693
0.216
0.0919
∣∂/∂μ∣ at the initial Q
5.5
12.0
0.070
0.0045
Bold marks the best candidate for each loss; for the two KLs and JS it is also the global optimum over all (μ,σ). Forward KL and least squares prefer the wide Gaussian, reverse KL and JS one mode. The last row shows how hard each loss pulls the initial Q: KL strongly, JS and least squares hardly at all.
A forward-KL fit with Adam (learning rate 0.01, 1000 fixed samples) lands on the moment-matched Gaussian, μ=−5.494 and σ=2.566, with an estimated 1.300 bits against the exact 0.936 nats, or 1.350 bits. The difference, 0.050 bits, is 1.6 times the standard deviation of a 1000-sample estimate, which is 0.032 bits.
The families of the course inherit these preferences. Flows and autoregressive models are trained by maximum likelihood, the forward KL, and spread mass rather than drop a mode. The VAE’s encoder is fitted in the reverse direction and tends to under-cover its posterior. The original GAN minimizes JS with an optimal discriminator, and its samples are sharp while modes go missing; in GANs the alternating optimization adds mode collapse of its own.
The 1-D fit of this note in NumPy, with the gradients of “What the gradients are” in place of autograd, followed by the table of the four losses by numerical integration. It uses NumPy and SciPy and runs in a few seconds.
import numpy as npfrom scipy.stats import norm# target P: equal mixture of N(-3, 0.5^2) and N(-8, 0.5^2); half of the samples from eachrng = np.random.default_rng(0)x = np.concatenate([rng.normal(-3, 0.5, 500), rng.normal(-8, 0.5, 500)])log_p = lambda t: np.logaddexp(np.log(0.5) + norm.logpdf(t, -3, 0.5), np.log(0.5) + norm.logpdf(t, -8, 0.5))# forward KL on fixed samples, plain gradient descent on (mu, log sigma), from Q = N(0, 1)mu, log_s, lr = 0.0, 0.0, 0.05for step in range(3000): s = np.exp(log_s) g_mu = -np.mean(x - mu) / s**2 # d loss / d mu g_log_s = np.mean(1 - (x - mu)**2 / s**2) # d loss / d log sigma mu, log_s = mu - lr * g_mu, log_s - lr * g_log_ss = np.exp(log_s)kl = np.mean(log_p(x) - norm.logpdf(x, mu, s)) # the loss, in natsprint(round(mu, 3), round(s, 3), round(x.mean(), 3), round(x.std(), 3), round(kl, 3))# the four losses for three candidate Gaussians, by numerical integrationgrid = np.linspace(-40, 30, 400_001)dx = grid[1] - grid[0]lp = log_p(grid)p = np.exp(lp)def losses(m, s): lq = norm.logpdf(grid, m, s) q = np.exp(lq) lm = np.logaddexp(lp, lq) - np.log(2) # log of the mixture M = (P + Q) / 2 fwd = np.sum(p * (lp - lq)) * dx rev = np.sum(q * (lq - lp)) * dx js = 0.5 * np.sum(p * (lp - lm)) * dx + 0.5 * np.sum(q * (lq - lm)) * dx ls = np.sum(p * (q - p)**2) * dx return np.round([fwd, rev, js, ls], 4)for m, sd in [(0, 1), (-5.5, np.sqrt(6.5)), (-3, 0.5)]: print(losses(m, sd))
Gradient descent stops exactly at the sample mean and the biased sample standard deviation, the maximum-likelihood fit, with an estimated KL of 0.961 nats against the exact 0.936 at the moment-matched Gaussian.
The experiments follow the Distances between distributions notebook of the HSE-LAMBDA Deep Generative Models course. Parts are named by the notebook’s headings (its cells count from 1, markdown included); the numbers quoted are saved outputs of the run kept with the course. The helpers and the first target are described in the Gaussian note.
The single-Gaussian part defines kl_loss, the sample estimate of KL in bits with optional importance weights, and fits the 2-D model to N((−5,−5),I) with Adam (learning rate 0.1) on 1000 fixed samples; the last plot reads KL = -0.0020 at step 4800.
The multimodal part fits the same model to the 2-D mixture on 2000 fixed samples, half from each component, and ends at KL mixture = 1.6688.
The Jensen–Shannon part estimates JS from samples of both distributions and ends at JS loss = 0.2734 with mu = [-4.9879, -5.0583]. Its js_div returns the 0.7/0.3 weighting and draws Q‘s samples with sample() instead of rsample(), so the gradient misses their dependence on Q.
The MSE part fits the density least-squares loss with Adam (learning rate 0.001) from N((1,1),I) and ends on the mode at (4,4) with LSE = 0.0013. The training cell draws fresh samples but reuses px from the JS part, the target densities at other points; recompute px before running it.
The 1-D part fits the two-mode mixture with KL (Adam, learning rate 0.01, 1000 fixed samples; mu = -5.494, std = 2.566 at step 1500) and with JS (SGD, learning rate 0.1; mu = -2.995, std = 0.495 at step 1800), and plots the gradient magnitudes. The KL training cell does not re-create the parameters, and the execution counts show it continued an interrupted run, so its gradient curve starts mid-fit; re-create the parameters before re-running it.
The model so far had five parameters and a closed-form density. Real generative models replace the five parameters with a neural network, and many give up the closed-form density. The next note collects the network machinery used throughout the course: normalization layers, how gradients flow through deep stacks, and the shapes of convolutions.
T. M. Cover, J. A. Thomas. Elements of Information Theory, 2nd ed. Wiley, 2006. §8.5: relative entropy for continuous distributions.
C. M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006. §10.1.2 and Figure 10.3: forward versus reverse KL on a bimodal target; §10.7: moment matching.