Course contents 04 / 34

04 / 34 · Foundations

Fitting distributions with KL

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.

On this page 5

The data have two clusters, one around −3-3 and one around −8-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-5.5 with a standard deviation of 2.552.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 QQ with trainable parameters to a target PP by gradient descent, with the KL divergence of the entropy note as the loss and the trainable Gaussian as the model.

How the parameters are trained#

In one dimension the model is Q=N(μ,σ2)Q = \mathcal N(\mu, \sigma^2) with parameters θ=(μ,log⁡σ)\theta = (\mu, \log\sigma); storing σ\sigma 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 QQ from the current parameters, evaluates its log-density at fixed samples xi∼Px_i \sim P, and computes the loss, a sample estimate of DKL(P ∥ Q)D_{\mathrm{KL}}(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 η\eta the step is

μ←μ−η ∂ loss∂μ,log⁡σ←log⁡σ−η ∂ loss∂log⁡σ.\begin{aligned} \mu &\leftarrow \mu - \eta\,\frac{\partial\,\text{loss}}{\partial \mu}, \\ \log\sigma &\leftarrow \log\sigma - \eta\,\frac{\partial\,\text{loss}}{\partial \log\sigma}. \end{aligned}

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

The KL training loop as a cycleSix boxes connected clockwise. Trainable parameters mu and s equal to log sigma, with requires_grad true, build the distribution Q equal to a normal with mean mu and variance sigma squared, where sigma is exp of s. Q is evaluated at samples x_i drawn from P, which also come with the true densities p of x_i. The loss is the mean of log p minus log q, an estimate of KL of P from Q. loss.backward gives the gradients of the loss with respect to mu and s. optimizer.step moves mu and s against the gradient, and the updated parameters feed the next iteration.Trainable parametersμ, s = log σrequires_grad=TrueDistributionQ = 𝒩(μ, σ²)σ = exp(s)Densities at xᵢq(xᵢ) and p(xᵢ)Lossmean(log p(xᵢ) − log q(xᵢ))≈ KL(P ‖ Q)Gradients∂loss/∂μ, ∂loss/∂soptimizer.step()μ ← μ − η·∂loss/∂μs ← s − η·∂loss/∂sfixed samples xᵢ ~ Ppx = p(xᵢ), known true densitybuild Qlog_probkl_loss(px, qx)loss.backward().gradupdated μ, s:next iteration↻ repeat; zero_grad() firstoptimizer = Adam([train_mu, train_log_std])“optimize these tensors by gradient”The KL training loop as a cycleSix boxes stacked vertically, top to bottom: trainable parameters mu and s equal to log sigma, the distribution Q equal to a normal with mean mu and variance sigma squared with sigma equal to exp of s, the densities q and p at the samples x_i drawn from P, the loss equal to the mean of log p minus log q, the gradients of the loss with respect to mu and s, and optimizer.step which moves mu and s against the gradient. An arrow on the left returns from the last box to the first: the updated parameters feed the next iteration.Adam([train_mu, train_log_std])optimize these tensors by gradientTrainable parametersμ, s = log σrequires_grad=Truebuild QDistributionQ = 𝒩(μ, σ²)σ = exp(s)Q.log_prob(xᵢ)Densities at xᵢq(xᵢ) and p(xᵢ)kl_loss(px, qx)Lossmean(log p(xᵢ) − log q(xᵢ))≈ KL(P ‖ Q)loss.backward()Gradients∂loss/∂μ, ∂loss/∂sgradientsoptimizer.step()μ ← μ − η·∂loss/∂μs ← s − η·∂loss/∂sxᵢ ~ P, p(xᵢ)updated μ, s → next iteration
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.

The loss is a Monte Carlo estimate of KL#

KL is an expectation under PP, so we can estimate it by averaging over samples x1,…,xN∼Px_1, \dots, x_N \sim P:

DKL(P ∥ Q)=Ex∼P[log⁡p(x)−log⁡q(x)]≈1N∑i=1N[log⁡p(xi)−log⁡q(xi)].\begin{aligned} D_{\mathrm{KL}}(P\,\|\,Q) &= \mathbb E_{x\sim P}\big[\log p(x) - \log q(x)\big] \\ &\approx \frac1N\sum_{i=1}^{N}\big[\log p(x_i) - \log q(x_i)\big]. \end{aligned}

By the law of large numbers the average converges to the expectation as NN grows. Averaging log⁡2\log_2 instead of ln⁡\ln reports the loss in bits; it rescales the loss and its gradients by 1/ln⁡2≈1.4431/\ln 2 \approx 1.443.

Figure

The sample estimate of KL(P‖Q)

Monte Carlo estimate of the KL divergenceUpper plot: a red Gaussian P centred at 3 and a wider blue Gaussian Q centred at 1.5, with forty short red ticks along the axis for samples drawn from P. Lower plot: the curve log p minus log q, which is positive between about 2 and 6.4 and negative on both sides. Dots on the curve at the sample positions are mostly in the positive region; their average, 0.72 nats, estimates the exact KL divergence of 0.63 nats.p(x)q(x)xᵢ ~ P−20246−2−1012mean = 0.72 (exact 0.63)Q underestimates p:log p − log q > 0Q overestimates: < 0,but few samples herelog p − log qx−20246Monte Carlo estimate of the KL divergenceUpper plot: a red Gaussian P centred at 3 and a wider blue Gaussian Q centred at 1.5, with forty short red ticks along the axis for samples drawn from P. Lower plot: the curve log p minus log q, which is positive between about 2 and 6.4 and negative on both sides. Dots on the curve at the sample positions are mostly in the positive region; their average, 0.72 nats, estimates the exact KL divergence of 0.63 nats.p(x)q(x)xᵢ ~ P−20246−2−1012mean = 0.72exact KL = 0.63Q too low:log p − log q > 0Q too high: < 0,few sampleslog p − log qx−20246
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 RR with density rr, each term is reweighted by wi=p(xi)/r(xi)w_i = p(x_i)/r(x_i), the importance weight; this needs r>0r > 0 wherever p>0p > 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)\mathcal N\big((-5,-5), \mathbf I\big): after 4800 Adam steps the loss reads −0.0020-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 log⁡q\log q over the samples is at least the average of log⁡p\log p. How far below zero follows from Wilks’ theorem (Wilks, 1938). When the family contains PP, 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\chi^2 with kk degrees of freedom for kk fitted parameters. The intuition: near its maximum the log-likelihood is a quadratic bowl, and the noise of the sample shifts the maximum by kk independent, roughly normal amounts, each of which adds half a squared standard normal to the gain. The loss is minus the gain divided by NN, and a χk2\chi^2_k variable has mean kk, so

E[loss]≈−E[χk2]2N=−k2N=−52000=−0.0025 nats=−0.0036 bits.\begin{aligned} \mathbb E[\text{loss}] &\approx -\frac{\mathbb E[\chi^2_k]}{2N} = -\frac{k}{2N} \\ &= -\frac{5}{2000} = -0.0025 \text{ nats} \\ &= -0.0036 \text{ bits}. \end{aligned}

In 2000 simulated fits the estimate averages −0.0036-0.0036 bits with a standard deviation of 0.00230.0023, so −0.0020-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.

What the gradients are#

For a 1-D Gaussian, log⁡q(x)=−log⁡σ−12log⁡2π−(x−μ)22σ2\log q(x) = -\log\sigma - \tfrac12\log 2\pi - \frac{(x-\mu)^2}{2\sigma^2}. The term log⁡p(xi)\log p(x_i) does not depend on the parameters, so only −log⁡q-\log q contributes (natural logarithms):

∂ loss∂μ=−1N∑i=1Nxi−μσ2,∂ loss∂log⁡σ=1N∑i=1N[1−(xi−μ)2σ2].\begin{aligned} \frac{\partial\,\text{loss}}{\partial \mu} &= -\frac1N\sum_{i=1}^{N}\frac{x_i-\mu}{\sigma^2}, \\ \frac{\partial\,\text{loss}}{\partial \log\sigma} &= \frac1N\sum_{i=1}^{N}\left[1 - \frac{(x_i-\mu)^2}{\sigma^2}\right]. \end{aligned}

The second line uses σ−2=e−2log⁡σ\sigma^{-2} = e^{-2\log\sigma}, whose derivative in log⁡σ\log\sigma is −2σ−2-2\sigma^{-2}, and the derivative 11 of log⁡σ\log\sigma itself. Both vanish when μ\mu is the sample mean and σ2=1N∑i(xi−μ)2\sigma^2 = \frac1N\sum_i (x_i-\mu)^2 the biased sample variance: the maximum-likelihood estimates, as the entropy note predicted. The gradient never needs pp; the values p(xi)p(x_i) only make the reported number equal to the KL. With real data, where pp is unknown, we drop that constant and minimize the negative log-likelihood −1N∑ilog⁡q(xi)-\frac1N\sum_i \log q(x_i).

The exact KL between two 1-D Gaussians shows where the steps lead. Take DKL=EP[log⁡p(x)−log⁡q(x)]D_{\mathrm{KL}} = \mathbb E_P[\log p(x) - \log q(x)], write both log-densities as above, and use EP[(x−μP)2]=σP2\mathbb E_P[(x-\mu_P)^2] = \sigma_P^2 and EP[(x−μ)2]=σP2+(μP−μ)2\mathbb E_P[(x-\mu)^2] = \sigma_P^2 + (\mu_P-\mu)^2. The constants 12log⁡2π\tfrac12\log 2\pi cancel, and

DKL(N(μP,σP2) ∥ N(μ,σ2))=log⁡σσP+σP2+(μP−μ)22σ2−12.\begin{aligned} &D_{\mathrm{KL}}\big(\mathcal N(\mu_P, \sigma_P^2)\,\|\,\mathcal N(\mu, \sigma^2)\big) \\ &\quad= \log\frac{\sigma}{\sigma_P} + \frac{\sigma_P^2 + (\mu_P - \mu)^2}{2\sigma^2} - \frac12 . \end{aligned}

The last term is −σP2/(2σP2)-\sigma_P^2/(2\sigma_P^2), from log⁡p\log p.

Figure

Fitting Q = 𝒩(μ, σ²) to P = 𝒩(3, 1) by gradient descent on KL(P‖Q)

Trajectory of Q while minimizing KL to a Gaussian targetTop: the red target density P, a normal with mean 3 and standard deviation 1, and seven blue curves for Q at increasing iterations, drawn from faint and thin to solid and bold. The first Q is a tall narrow bump at minus 2. The next ones become very wide and flat, then move right and narrow down until the last, boldest curve almost coincides with P. Bottom: the KL divergence on a log scale drops from about 51 nats to almost zero over 1600 iterations, with a long plateau around 1.5 nats while Q is wide.00.20.40.60.8−6−4−20246810xdensityP = 𝒩(3, 1)start: 𝒩(−2, 0.5²)iteration 50:very wide,σ = 3.83iteration 1600:μ = 2.92, σ = 1.0110⁻³10⁻²10⁻¹110¹10²040080012001600iterationKL(P‖Q), natsplateau ≈ 1.5: Q wide and still off-centreTrajectory of Q while minimizing KL to a Gaussian targetTop: the red target density P, a normal with mean 3 and standard deviation 1, and seven blue curves for Q at increasing iterations, drawn from faint and thin to solid and bold. The first Q is a tall narrow bump at minus 2. The next ones become very wide and flat, then move right and narrow down until the last, boldest curve almost coincides with P. Bottom: the KL divergence on a log scale drops from about 51 nats to almost zero over 1600 iterations, with a long plateau around 1.5 nats while Q is wide.00.20.40.60.8−4048xdensityPstart: 𝒩(−2, 0.5²)iter. 50:σ = 3.83iter. 1600:μ = 2.92σ = 1.0110⁻³10⁻²10⁻¹110¹10²08001600iterationKL(P‖Q), natsplateau ≈ 1.5:Q wide, off-centre
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⁡σ)(\mu, \log\sigma) the trajectory shows the priorities of the forward KL. While QQ is narrow and far away, most of PP‘s mass sits where q≈0q \approx 0, and the cheapest fix is to widen QQ: σ\sigma jumps up in the first steps while μ\mu only creeps. Once QQ covers PP, μ\mu moves across and σ\sigma shrinks back. The order comes from the gradient sizes. From the closed form, ∂/∂log⁡σ=1−(σP2+(μP−μ)2)/σ2\partial/\partial\log\sigma = 1 - \big(\sigma_P^2 + (\mu_P-\mu)^2\big)/\sigma^2 grows like (μP−μ)2/σ2(\mu_P-\mu)^2/\sigma^2, while ∂/∂μ=(μ−μP)/σ2\partial/\partial\mu = (\mu-\mu_P)/\sigma^2 grows only like ∣μP−μ∣/σ2\lvert\mu_P-\mu\rvert/\sigma^2. Adam, which normalizes each coordinate’s step, moves both at a similar rate and reaches the same optimum by a different path.

What KL assumes#

The formula for continuous distributions (Kullback and Leibler, 1951),

DKL(P ∥ Q)=∫p(x) log⁡p(x)q(x) dx,D_{\mathrm{KL}}(P\,\|\,Q) = \int p(x)\,\log\frac{p(x)}{q(x)}\,dx ,

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).

(a) Common support#

The support of a distribution is the set of its possible values, supp⁡p={x:p(x)>0}\operatorname{supp} p = \lbrace x : p(x) > 0\rbrace. If q(x)=0q(x) = 0 on a region to which PP gives positive probability, log⁡p(x)q(x)=∞\log\frac{p(x)}{q(x)} = \infty there and the divergence is infinite. Formally, DKL(P ∥ Q)D_{\mathrm{KL}}(P\,\|\,Q) is finite only if PP is absolutely continuous with respect to QQ, written P≪QP \ll Q: wherever PP has mass, QQ 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 −log⁡q(xi)-\log q(x_i) 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

A model with holes versus a blurry modelTwo plots of the same red standard normal density P. In the first, Q is a flat box between minus 1.5 and 1.5 and zero outside; the tails of P outside the box are shaded red and labelled p greater than 0, q equal to 0, so log p over q is infinite and KL is infinite. In the second, Q is a wider blue Gaussian that is positive everywhere and KL is finite, about 0.128 nats.Q with holesKL(P‖Q) = ∞−1.51.5QPp > 0, q = 0⇒ log p/q = ∞q = 0“Blurry” Gaussian QKL(P‖Q) = 0.128 natsPq > 0everywhere−202A model with holes versus a blurry modelTwo plots of the same red standard normal density P. In the first, Q is a flat box between minus 1.5 and 1.5 and zero outside; the tails of P outside the box are shaded red and labelled p greater than 0, q equal to 0, so log p over q is infinite and KL is infinite. In the second, Q is a wider blue Gaussian that is positive everywhere and KL is finite, about 0.128 nats.Q with holesKL(P‖Q) = ∞−1.51.5QPp > 0, q = 0⇒ log p/q = ∞q = 0“Blurry” Gaussian QKL(P‖Q) = 0.128 natsPq > 0everywhere−202
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)>0q(x) > 0 but p(x)=0p(x) = 0 contribute 00 to DKL(P ∥ Q)D_{\mathrm{KL}}(P\,\|\,Q); they matter only for the reverse direction.

(b) Integrability#

The integral must converge, and matching supports are not enough. Let PP be a standard Cauchy distribution and Q=N(0,σ2)Q = \mathcal N(0, \sigma^2). Both are positive everywhere, and with p(x)=1/(π(1+x2))p(x) = 1/\big(\pi(1 + x^2)\big)

log⁡p(x)q(x)=x22σ2−log⁡(1+x2)+log⁡2π σπ.\log\frac{p(x)}{q(x)} = \frac{x^2}{2\sigma^2} - \log(1 + x^2) + \log\frac{\sqrt{2\pi}\,\sigma}{\pi} .

Under PP the middle term has the finite mean 2ln⁡22\ln 2, while EP[x2]=∞\mathbb E_P[x^2] = \infty, so DKL(P ∥ Q)=∞D_{\mathrm{KL}}(P\,\|\,Q) = \infty. A model with light tails cannot fit heavy-tailed data in KL.

(c) Normalized densities#

pp and qq 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.

(d) Direction#

KL is not symmetric, so we must decide which distribution plays the truth. The forward KL DKL(P ∥ Q)D_{\mathrm{KL}}(P\,\|\,Q) averages over PP and penalizes missed modes: QQ must cover everything where PP lives. It is the direction of maximum likelihood. The reverse KL DKL(Q ∥ P)D_{\mathrm{KL}}(Q\,\|\,P) averages over QQ and penalizes extra mass: QQ must not spread to where P≈0P \approx 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

Missed modes versus extra massTwo plots of the same red bimodal density P with peaks at minus 2.5 and 2.5. In the first, a narrow blue Q sits only on the right peak; the left peak is shaded and labelled missed mode, and the forward divergence KL of P from Q is about 12 nats while the reverse is about 0.69. In the second, a wide blue Gaussian covers both peaks; the area where Q is above P, in the middle and in the outer tails, is shaded and labelled extra mass, and now the reverse divergence, about 1.54 nats, is larger than the forward one, about 0.62.Q misses a modeKL(P‖Q) = 12.06KL(Q‖P) = 0.69−2.502.5QPmissed mode: p > 0, q ≈ 0KL(P‖Q) punishes thisQ spreads mass where P has noneKL(P‖Q) = 0.62KL(Q‖P) = 1.54−2.502.5QPextra mass: q > 0, p ≈ 0KL(Q‖P) punishes thisMissed modes versus extra massTwo plots of the same red bimodal density P with peaks at minus 2.5 and 2.5. In the first, a narrow blue Q sits only on the right peak; the left peak is shaded and labelled missed mode, and the forward divergence KL of P from Q is about 12 nats while the reverse is about 0.69. In the second, a wide blue Gaussian covers both peaks; the area where Q is above P, in the middle and in the outer tails, is shaded and labelled extra mass, and now the reverse divergence, about 1.54 nats, is larger than the forward one, about 0.62.Q misses a modeKL(P‖Q) = 12.06KL(Q‖P) = 0.69−2.502.5QPmissed mode: p > 0, q ≈ 0KL(P‖Q) punishes thisQ spreads mass where P has noneKL(P‖Q) = 0.62KL(Q‖P) = 1.54−2.502.5QPextra mass: q > 0, p ≈ 0KL(Q‖P) punishes this
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 PP and log⁡q\log q at them; the reverse direction needs log⁡p\log p, which real data never provides.

(e) Continuous versus discrete#

For discrete distributions the integral becomes a sum. Mixing the two gives an infinite divergence: if PP has an atom at xx, any QQ with a density gives {x}\lbrace x\rbrace probability zero, so P≪̸QP \not\ll Q and DKL(P ∥ Q)=∞D_{\mathrm{KL}}(P\,\|\,Q) = \infty by condition (a). For continuous data, maximum likelihood is therefore read as a sample estimate of DKL(P ∥ Q)D_{\mathrm{KL}}(P\,\|\,Q) for the underlying density pp. Reading it as the KL of the empirical distribution of the samples works only for discrete outcomes.

In code#

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 log⁡q(x)\log q(x) drops below about −103-103: for σ≈1\sigma \approx 1, about 14 standard deviations from μ\mu. The loss is then infinite exactly when QQ starts far from PP. Working with log_prob directly avoids it.

The two-mode targets below need the same care. Their log-density log⁡(12p1(x)+12p2(x))\log\big(\tfrac12 p_1(x) + \tfrac12 p_2(x)\big) is computed from the component log-densities a=log⁡p1(x)+log⁡12a = \log p_1(x) + \log\tfrac12 and b=log⁡p2(x)+log⁡12b = \log p_2(x) + \log\tfrac12 as

logaddexp⁡(a,b)=max⁡(a,b)+log⁡(1+e−∣a−b∣),\operatorname{logaddexp}(a, b) = \max(a, b) + \log\big(1 + e^{-|a - b|}\big),

the two-term case of the stable log-sum-exp, which stays finite far from both components.

One Gaussian, two modes#

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)\mathcal N\big((-5,-5), \mathbf I\big) and N((4,4),I)\mathcal N\big((4,4), \mathbf I\big); in 1-D it is

P=12 N(−3, 0.52)+12 N(−8, 0.52),P = \tfrac12\,\mathcal N(-3,\, 0.5^2) + \tfrac12\,\mathcal N(-8,\, 0.5^2),

and the model starts from Q=N(0,1)Q = \mathcal 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).

Far from the target, the missed mode dominates#

The initial Q=N(0,1)Q = \mathcal N(0, 1) barely reaches the far mode at −8-8, eight standard deviations from its mean. There log⁡p(x)q(x)\log\frac{p(x)}{q(x)} is huge, and that mode dominates the whole divergence, 17.917.9 nats. For a Gaussian QQ the forward KL stays finite, and its gradient in μ\mu, (μ−EP[x])/σ2=5.5(\mu - \mathbb E_P[x])/\sigma^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

Forward KL is huge where Q is nearly zero but P is notTop panel: red target density with modes at -8 and -3, blue model density 𝒩(0, 1) centred at 0. A grey band left of x = -5.1 marks where q is below one in a million while p is still positive. At x = -8, q is about 5 times 10 to the -15, and log p over q is about 32 nats. Bottom panel: the integrand p(x) log p(x)/q(x) has a tall peak of about 12.8 at the far mode and a small one at -3; its area, the KL divergence, is 17.9 nats.q(x) < 10⁻⁶, but p(x) > 0−10−8−6−4−202PQ = 𝒩(0, 1)q(−8) ≈ 5·10⁻¹⁵Contribution to KL(P‖Q): p(x) log p(x)/q(x)04812−10−8−6−4−202here log p/q ≈ 32 natsarea = KL(P‖Q) ≈ 17.9 natsif q(x) = 0 where p(x) > 0:KL(P‖Q) = ∞Forward KL is huge where Q is nearly zero but P is notTop panel: red target density with modes at -8 and -3, blue model density 𝒩(0, 1) centred at 0. A grey band left of x = -5.1 marks where q is below one in a million while p is still positive. At x = -8, q is about 5 times 10 to the -15, and log p over q is about 32 nats. Bottom panel: the integrand p(x) log p(x)/q(x) has a tall peak of about 12.8 at the far mode and a small one at -3; its area, the KL divergence, is 17.9 nats.q(x) < 10⁻⁶,but p(x) > 0q(−8) ≈ 5·10⁻¹⁵−10−8−6−4−202PQ = 𝒩(0, 1)Contribution to KL(P‖Q):p(x) log p(x)/q(x)04812−10−8−6−4−202here log p/q ≈ 32 natsarea = KL(P‖Q) ≈ 17.9 natsif q(x) = 0 where p(x) > 0:KL(P‖Q) = ∞
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)D_{\mathrm{KL}}(P\,\|\,Q) makes a single Gaussian cover both modes with a wide spread. Write the forward KL as

DKL(P ∥ Q)=−H(P)−EP[log⁡q(x)].D_{\mathrm{KL}}(P\,\|\,Q) = -H(P) - \mathbb E_P[\log q(x)] .

Only the second term depends on QQ, and for a Gaussian log⁡q\log q depends on xx only through xx and xx⊤xx^{\top}. Minimizing it over μ\boldsymbol\mu and Σ\boldsymbol\Sigma gives exact moment matching (Bishop, 2006, §10.7), derived below:

μ∗=EP[x],Σ∗=Cov⁡P[x].\begin{aligned} \boldsymbol\mu^\ast &= \mathbb E_P[x], \\ \boldsymbol\Sigma^\ast &= \operatorname{Cov}_P[x] . \end{aligned}
Derivation

Write m=EP[x]\mathbf m = \mathbb E_P[x] and C=Cov⁡P[x]\mathbf C = \operatorname{Cov}_P[x], and assume C\mathbf C is positive definite. For q=N(μ,Σ)q = \mathcal N(\boldsymbol\mu, \boldsymbol\Sigma) in dd dimensions,

−EP[log⁡q(x)]=12log⁡det⁡(2πΣ)+12 EP[(x−μ)⊤Σ−1(x−μ)].\begin{aligned} -\mathbb E_P[\log q(x)] ={}& \tfrac12\log\det(2\pi\boldsymbol\Sigma) \\ &+ \tfrac12\,\mathbb E_P\big[(x - \boldsymbol\mu)^{\top}\boldsymbol\Sigma^{-1}(x - \boldsymbol\mu)\big] . \end{aligned}

Split x−μ=(x−m)+(m−μ)x - \boldsymbol\mu = (x - \mathbf m) + (\mathbf m - \boldsymbol\mu). The cross term averages to zero because EP[x−m]=0\mathbb E_P[x - \mathbf m] = 0, and a scalar equals its trace, E[v⊤Σ−1v]=tr⁡(Σ−1E[vv⊤])\mathbb E[v^{\top}\boldsymbol\Sigma^{-1}v] = \operatorname{tr}\big(\boldsymbol\Sigma^{-1}\mathbb E[vv^{\top}]\big), so

EP[(x−μ)⊤Σ−1(x−μ)]=tr⁡(Σ−1C)+(m−μ)⊤Σ−1(m−μ).\begin{aligned} &\mathbb E_P\big[(x - \boldsymbol\mu)^{\top}\boldsymbol\Sigma^{-1}(x - \boldsymbol\mu)\big] \\ &\quad= \operatorname{tr}(\boldsymbol\Sigma^{-1}\mathbf C) + (\mathbf m - \boldsymbol\mu)^{\top}\boldsymbol\Sigma^{-1}(\mathbf m - \boldsymbol\mu) . \end{aligned}

The last term is ≥0\ge 0 and zero only at μ=m\boldsymbol\mu = \mathbf m, which fixes the mean. For the covariance let λ1,…,λd>0\lambda_1, \dots, \lambda_d > 0 be the eigenvalues of A=C−1/2Σ C−1/2\mathbf A = \mathbf C^{-1/2}\boldsymbol\Sigma\,\mathbf C^{-1/2}. The cyclic property of the trace gives tr⁡(Σ−1C)=tr⁡(A−1)=∑i1/λi\operatorname{tr}(\boldsymbol\Sigma^{-1}\mathbf C) = \operatorname{tr}(\mathbf A^{-1}) = \sum_i 1/\lambda_i, and det⁡Σ=det⁡C⋅∏iλi\det\boldsymbol\Sigma = \det\mathbf C \cdot \prod_i \lambda_i, so the part that depends on Σ\boldsymbol\Sigma is

12log⁡det⁡C+12∑i=1d(log⁡λi+1λi).\tfrac12\log\det\mathbf C + \tfrac12\sum_{i=1}^d \Big(\log\lambda_i + \frac{1}{\lambda_i}\Big) .

Each term log⁡λ+1/λ\log\lambda + 1/\lambda has derivative (λ−1)/λ2(\lambda - 1)/\lambda^2, negative for λ<1\lambda < 1 and positive for λ>1\lambda > 1, so it is smallest at λ=1\lambda = 1. All eigenvalues equal to 1 means A=I\mathbf A = \mathbf I, that is Σ=C\boldsymbol\Sigma = \mathbf C.

For the 1-D target, μ∗=−5.5\mu^\ast = -5.5 and, by the law of total variance, σ∗2=0.25+2.52=6.5\sigma^{\ast2} = 0.25 + 2.5^2 = 6.5, so σ∗≈2.55\sigma^\ast \approx 2.55: the average variance within a component is 0.250.25, and the spread of the two means around −5.5-5.5 adds 2.522.5^2. For the 2-D target the optimum has mean (−0.5,−0.5)(-0.5, -0.5). The same law adds the within-component covariance I\mathbf I to the covariance of the two means, which sit at ±(4.5,4.5)\pm(4.5, 4.5) from it and contribute 4.52=20.254.5^2 = 20.25 to every entry:

Σ∗=(21.2520.2520.2521.25),\boldsymbol\Sigma^\ast = \begin{pmatrix} 21.25 & 20.25 \\ 20.25 & 21.25\end{pmatrix},

one elongated Gaussian along the diagonal through both modes, densest in the empty gap. Its divergence is 1.1701.170 nats, or 1.6881.688 bits. An Adam fit (learning rate 0.10.1, 2000 fixed samples, started from N(0,I)\mathcal N(\mathbf 0, \mathbf I)) reaches this picture at an estimated 1.6691.669 bits after 4800 steps; the gap of 0.0190.019 bits is below the standard deviation of a 2000-sample estimate, about 0.0230.023 bits.

The reverse divergence DKL(Q ∥ P)D_{\mathrm{KL}}(Q\,\|\,P) averages over samples of QQ. It punishes mass where PP is small and ignores parts of PP that QQ misses, so QQ locks onto one mode (Bishop, 2006, §10.1.2; Minka, 2005). For two equal, well-separated modes, sitting exactly on one costs only ln⁡2\ln 2. If QQ stays near the first component p1p_1, where the second is negligible, then p≈p1/2p \approx p_1/2 there and

DKL(Q ∥ P)≈EQ[log⁡q(x)p1(x)/2]=ln⁡2+DKL(Q ∥ p1).\begin{aligned} D_{\mathrm{KL}}(Q\,\|\,P) &\approx \mathbb E_Q\Big[\log\frac{q(x)}{p_1(x)/2}\Big] \\ &= \ln 2 + D_{\mathrm{KL}}(Q\,\|\,p_1) . \end{aligned}

The second term is zero for Q=p1Q = p_1 and positive otherwise, so the best Gaussian is the mode itself, at ln⁡2\ln 2.

Figure

Fitting one Gaussian to two modes: forward vs reverse KL

Forward and reverse KL fits of a Gaussian to a bimodal targetTwo panels with the same red bimodal target, peaks at x = -8 and x = -3. Top panel: the Gaussian minimizing KL(P‖Q), mean −5.50 and standard deviation 2.55, is a wide blue curve spanning both modes, with its peak in the empty gap between them; KL(P‖Q) = 0.94 nats. Bottom panel: the Gaussian minimizing KL(Q‖P), mean −3.00 and standard deviation 0.50, is a narrow blue curve on the right mode only, so the solid fit ignores the mode at -8; KL(Q‖P) = 0.69 nats, about ln 2. A dashed curve on the left mode marks the mirror solution, which is equally good.Forward KL: min over Q of KL(P‖Q)−10−8−6−4−2PReverse KL: min over Q of KL(Q‖P)−10−8−6−4−2covers both modes, wideP ≈ 0 herebest Gaussian:μ = −5.50σ = 2.55KL(P‖Q) = 0.94locks ontoone modeμ = −3.00σ = 0.50KL(Q‖P) = 0.69≈ ln 2ignored by thesolid fit;dashed: mirrorfit, as goodForward and reverse KL fits of a Gaussian to a bimodal targetTwo panels with the same red bimodal target, peaks at x = -8 and x = -3. Top panel: the Gaussian minimizing KL(P‖Q), mean −5.50 and standard deviation 2.55, is a wide blue curve spanning both modes, with its peak in the empty gap between them; KL(P‖Q) = 0.94 nats. Bottom panel: the Gaussian minimizing KL(Q‖P), mean −3.00 and standard deviation 0.50, is a narrow blue curve on the right mode only, so the solid fit ignores the mode at -8; KL(Q‖P) = 0.69 nats, about ln 2. A dashed curve on the left mode marks the mirror solution, which is equally good.Forward KL: min over Q of KL(P‖Q)−10−8−6−4−2PReverse KL: min over Q of KL(Q‖P)−10−8−6−4−2covers both modes, wideP ≈ 0 herebest Gaussian: μ = −5.50, σ = 2.55KL(P‖Q) = 0.94 natslocks ontoone modebest Gaussian: μ = −3.00, σ = 0.50KL(Q‖P) = 0.69 nats ≈ ln 2the solid fit ignores the mode at −8;dashed: the mirror fit, equally good
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 does not cover the modes either#

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.2160.216 nats against 0.2550.255 for the moment-matched Gaussian. Exactly on one mode, Q=p1Q = p_1, the mixture is M=12(P+Q)=34p1+14p2M = \tfrac12(P + Q) = \tfrac34 p_1 + \tfrac14 p_2. 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:

DKL(Q ∥ M)≈log⁡213/4=log⁡243,DKL(P ∥ M)≈12log⁡21/23/4+12log⁡21/21/4=12log⁡243.\begin{aligned} D_{\mathrm{KL}}(Q\,\|\,M) &\approx \log_2\tfrac{1}{3/4} = \log_2\tfrac43, \\ D_{\mathrm{KL}}(P\,\|\,M) &\approx \tfrac12\log_2\tfrac{1/2}{3/4} + \tfrac12\log_2\tfrac{1/2}{1/4} \\ &= \tfrac12\log_2\tfrac43 . \end{aligned}

Their average is

DJS≈34log⁡243≈0.311 bits.D_{\mathrm{JS}} \approx \tfrac34\log_2\tfrac43 \approx 0.311 \text{ bits}.

Trained runs agree. A fit of the 2-D mixture with Adam (learning rate 0.10.1, 5000 steps, 5000 fresh samples per step), started from μ=(−2,−2)\boldsymbol\mu = (-2,-2), ends near (−4.99,−5.06)(-4.99, -5.06) with a nearly unit covariance, on the mode at (−5,−5)(-5,-5). In 1-D, plain gradient descent from N(0,1)\mathcal N(0, 1) ends at μ=−2.995\mu = -2.995, σ=0.495\sigma = 0.495 after 1800 steps, on the nearer mode; QQ‘s peak density there, 0.810.81, is twice the target’s 0.400.40. Both runs minimized a weighted variant, 0.7 DKL(P ∥ M)+0.3 DKL(Q ∥ M)0.7\,D_{\mathrm{KL}}(P\,\|\,M) + 0.3\,D_{\mathrm{KL}}(Q\,\|\,M). With the two terms above its one-mode value is (0.7⋅12+0.3)log⁡243=0.65log⁡243≈0.270(0.7 \cdot \tfrac12 + 0.3)\log_2\tfrac43 = 0.65\log_2\tfrac43 \approx 0.270 bits. The final 1-D Gaussian has exactly this value, 0.2700.270 bits by numerical integration. The 2-D run’s last estimate, 0.27340.2734 bits, is a sample estimate whose standard deviation at 5000 samples is about 0.0080.008 bits, so it agrees with 0.2700.270 up to noise.

Each half of JS is an expectation under its own distribution:

DJS(P ∥ Q)=12 Ex∼P[log⁡p(x)m(x)]+12 Ey∼Q[log⁡q(y)m(y)],\begin{aligned} D_{\mathrm{JS}}(P\,\|\,Q) &= \tfrac12\,\mathbb E_{x\sim P}\Big[\log\frac{p(x)}{m(x)}\Big] \\ &\quad + \tfrac12\,\mathbb E_{y\sim Q}\Big[\log\frac{q(y)}{m(y)}\Big], \end{aligned}

with m=12(p+q)m = \tfrac12(p + q) evaluated by logaddexp. The estimate needs samples of both PP and QQ. The second term depends on QQ‘s parameters also through the samples yjy_j, so they must be drawn with the reparameterization trick, y=μ+σεy = \mu + \sigma\varepsilon; the runs above drew them without it, so their gradients miss that dependence.

Boundedness has a second cost. When QQ and PP barely overlap, JS is already close to its maximum ln⁡2\ln 2 and almost flat. At the initial N(0,1)\mathcal N(0, 1) it is 0.6450.645 nats, 93%93\% of ln⁡2\ln 2, and its gradient in μ\mu is 0.0700.070 against 5.55.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∼Px_i \sim P:

LLS=1N∑i=1N(q(xi)−p(xi))2.\mathcal L_{\mathrm{LS}} = \frac1N \sum_{i=1}^{N} \bigl(q(x_i) - p(x_i)\bigr)^2 .

Density values depend on the units of the data. Stretching every coordinate by cc divides all densities by cdc^{d} in dd dimensions, so the loss shrinks by c2dc^{2d}. Adam absorbs a constant factor, but not the second problem: when QQ does not overlap PP, q(xi)≈0q(x_i) \approx 0 at the data points, and the loss sits near the constant EP[p(x)2]\mathbb E_P[p(x)^2] with almost no gradient. KL has neither problem. The ratio p/qp/q does not change under rescaling, and −log⁡q(xi)-\log q(x_i) grows like (xi−μ)2/2σ2(x_i-\mu)^2/2\sigma^2 far from μ\mu, so the pull grows as QQ moves away.

The least-squares loss also has several minima. In 1-D its global minimum, 0.04700.0470, is a wide Gaussian with σ≈2.53\sigma \approx 2.53, close to the moment-matched one, and a Gaussian on one mode, N(−3.01,1.212)\mathcal N(-3.01, 1.21^2), is a local minimum at 0.04950.0495. In 2-D a Gaussian on one mode, N((4,4),1.582 I)\mathcal N\big((4,4), 1.58^2\,\mathbf I\big), is a local minimum at 0.001130.00113, while the global one, 0.001020.00102, is centred at (−0.5,−0.5)(-0.5,-0.5) and stretched along the diagonal (standard deviation 6.56.5 along it, 0.430.43 across). An Adam fit started from N((1,1),I)\mathcal N\big((1,1), \mathbf I\big), which overlaps only the mode at (4,4)(4,4), ends on that mode, wider than it; the other mode contributes almost no gradient, because q≈0q \approx 0 there.

The four losses side by side#

For the 1-D target, natural logarithms; the least-squares loss has units of squared density.

Single Gaussian QQDKL(P ∥ Q)D_{\mathrm{KL}}(P\,\Vert\,Q)DKL(Q ∥ P)D_{\mathrm{KL}}(Q\,\Vert\,P)DJSD_{\mathrm{JS}}LS
initial N(0,1)\mathcal N(0, 1)17.8817.8819.5019.500.6450.6450.09010.0901
moment-matched N(−5.5, 6.5)\mathcal N(-5.5,\, 6.5)0.936\mathbf{0.936}3.7093.7090.2550.2550.0470\mathbf{0.0470}
one mode N(−3, 0.52)\mathcal N(-3,\, 0.5^2)24.3124.310.693\mathbf{0.693}0.216\mathbf{0.216}0.09190.0919
∣∂/∂μ∣\lvert\partial/\partial\mu\rvert at the initial QQ5.55.512.012.00.0700.0700.00450.0045

Bold marks the best candidate for each loss; for the two KLs and JS it is also the global optimum over all (μ,σ)(\mu, \sigma). 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 QQ: KL strongly, JS and least squares hardly at all.

A forward-KL fit with Adam (learning rate 0.010.01, 1000 fixed samples) lands on the moment-matched Gaussian, μ=−5.494\mu = -5.494 and σ=2.566\sigma = 2.566, with an estimated 1.3001.300 bits against the exact 0.9360.936 nats, or 1.3501.350 bits. The difference, 0.0500.050 bits, is 1.6 times the standard deviation of a 1000-sample estimate, which is 0.0320.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.

What you should remember#

  • The loss is a Monte Carlo average of log⁡p−log⁡q\log p - \log q over samples of PP; its gradient needs only log⁡q\log q, which makes it maximum likelihood.
  • An estimate on the training samples is biased low, by about k/(2N)k/(2N) nats for kk parameters.
  • KL is finite only if QQ has mass wherever PP does, the tails are integrable and both are normalized.
  • Forward KL covers every mode and blurs; reverse KL and JS pick one mode and stay sharp.
  • JS saturates at ln⁡2\ln 2 and least squares depends on units; far from the data both give almost no gradient.

Code#

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 np
from 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 each
rng = 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.05
for 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_s
s = np.exp(log_s)
kl = np.mean(log_p(x) - norm.logpdf(x, mu, s))     # the loss, in nats
print(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 integration
grid = 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))
-5.524 2.558 -5.524 2.558 0.961
[17.875  19.5     0.6455  0.0901]
[0.9359 3.7091 0.2554 0.047 ]
[24.3069  0.6931  0.2158  0.0919]

Gradient descent stops exactly at the sample mean and the biased sample standard deviation, the maximum-likelihood fit, with an estimated KL of 0.9610.961 nats against the exact 0.9360.936 at the moment-matched Gaussian.

Notebook#

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)\mathcal N((-5,-5), \mathbf 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.30.7/0.3 weighting and draws QQ‘s samples with sample() instead of rsample(), so the gradient misses their dependence on QQ.
  • The MSE part fits the density least-squares loss with Adam (learning rate 0.001) from N((1,1),I)\mathcal N((1,1), \mathbf I) and ends on the mode at (4,4)(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.

Next#

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.

References#