Module contents
Lesson 1 of 28Review 80 min

Review: learning a distribution, divergences and the map of generative models

Review maximum likelihood as forward KL minimization and alternative divergences (reverse KL, Jensen-Shannon, Wasserstein and Fisher), focusing on the behavior each induces. Build a taxonomy based on likelihood access, investigate disjoint low-dimensional supports, and introduce the trade-off between quality, diversity and speed.

After this lesson you can

  • Prove that maximizing expected log-likelihood minimizes KL(p_data ‖ p_θ).
  • Predict whether a divergence objective may cover multiple modes or concentrate on one.
  • Classify generative models by whether they provide an exact likelihood, a bound, or neither.
  • Use disjoint supports to explain why JS has no gradient while Wasserstein distance does.
  • Build the 2D and digit datasets used throughout the module.

Before you start

One distribution, several questions

An image classifier returns a label for an image. A generator must answer a different question: which images could appear, and how often? If it always produces a perfect image of a single digit, individual quality may be high and coverage poor. If it assigns probability to every possible image as well as much noise, it may cover the data while producing unconvincing samples.

Training samples are not the distribution. Memorizing the finite dataset may look convincing during training yet fail on new examples. The separation between training and evaluation matters here as much as it does for a classifier. Before choosing an architecture, consider which error matters. In the figure, a deliberately limited family, a single Gaussian, tries to represent two groups. Change the objective and observe both the fit and the region between groups.

InteractiveOne Gaussian against two modes
  • Data p
  • Gaussian q
Step 120 / 120

p is an equally weighted Gaussian mixture with means −3 and 3 and deviation 0.55. Descent uses numerical quadrature: its result depends on initialization and does not certify a global optimum.

Objective
1.8
Mean of q0.00
Deviation of q3.05
Approximate objective1.020
Compare objectives on the same mixture. A single Gaussian cannot represent both peaks exactly: the compromise depends on the divergence and the fit initialization.

Choosing an objective does not make an insufficient family expressive. The figure is a toy mathematical model, not a measurement of an image model. To understand its behavior, first establish the assumptions under which likelihood has an exact interpretation.

Maximum likelihood and coding in bits

Let pp and qθq_\theta be densities with respect to the same measure. Assume p≪qθp\ll q_\theta, finite entropy H(p)=−∫plog⁡pH(p)=-\int p\log p and finite relevant integrals. With natural logarithms,

KL⁡(p ∥ qθ)=∫plog⁡pqθ=−H(p)−Ep[log⁡qθ(X)].\KL(p\,\|\,q_\theta)=\int p\log\frac{p}{q_\theta} =-H(p)-\E_p[\log q_\theta(X)].

Since H(p)H(p) does not depend on θ\theta, maximizing expected log-likelihood is equivalent to minimizing forward KL. If qθq_\theta is zero where pp has mass, KL is infinite. Given independent observations x1,…,xnx_1,\ldots,x_n from pp, replace the expectation by the empirical mean. This is the maximum-likelihood estimator, not a guarantee of having minimized population KL with a finite sample. The log-likelihood adds the contribution of each observation.

For discrete symbols, −log⁡2q(x)-\log_2 q(x) is the ideal code length in bits associated with qq; its expectation is the cross-entropy. A loss of LL nats per example with DD discrete components corresponds to L/(Dln⁡2)L/(D\ln 2) bits per dimension. Continuous densities are not probabilities of exact values: they change with the units and can exceed 1. Comparing discrete images with continuous models requires specifying quantization and dequantization. Adding uniform noise within each cell relates density and cell probability, but does not automatically turn a pointwise log-density into a probability mass.

The divergence determines what is penalized

Forward and reverse KL weight different regions. KL⁡(p∥q)\KL(p\|q) integrates under the data: ignoring a region of positive probability is costly if qq is small there. KL⁡(q∥p)\KL(q\|p) integrates under the model: assigning mass where pp is small is costly, whereas an ignored mode does not directly appear in the expectation under qq. This explains the tendency to cover modes or concentrate on one when a single Gaussian approximates a separated mixture. It does not prove that every reverse-KL optimization collapses, or that forward KL covers all modes well with finite data and capacity.

To see why a forward fit of a Gaussian covers the mixture, suppose q=N(μ,σ2)q=\Normal(\mu,\sigma^2) in one dimension and that pp has finite positive variance. The part of the NLL depending on μ\mu and σ\sigma is log⁡σ+Ep[(X−μ)2]/(2σ2)\log\sigma+\E_p[(X-\mu)^2]/(2\sigma^2). Differentiation gives the optimum μ=EpX\mu=\E_p X and σ2=Var⁡pX\sigma^2=\Var_p X. For two equally weighted components with centers −a-a and aa and variance s2s^2, this gives zero mean and variance a2+s2a^2+s^2. If aa is large relative to ss, the optimal Gaussian necessarily assigns mass to the gap. Reverse KL penalizes this region of low density under pp. It can nevertheless have multiple local minima and its result depends on the optimization.

Jensen-Shannon uses m=(p+q)/2m=(p+q)/2 and JS⁡(p,q)=[KL⁡(p∥m)+KL⁡(q∥m)]/2\operatorname{JS}(p,q)=[\KL(p\|m)+\KL(q\|m)]/2. It is symmetric and bounded by ln⁡2\ln 2 with natural logarithms. It belongs to the f-divergences; its bound avoids infinities but can leave a flat objective. The Wasserstein distance W1W_1 minimizes E∥X−Y∥\E\|X-Y\| over all couplings with marginals PP and QQ. It considers how far mass must move as well as overlap. Finite first moments make it finite.

Fisher divergence compares score fields for positive differentiable densities with finite integrals: Ep∥∇xlog⁡p(X)−∇xlog⁡q(X)∥2\E_p\|\nabla_x\log p(X)-\nabla_x\log q(X)\|^2. It does not require the normalizing constant of qq because its spatial gradient vanishes. It does require score information and regularity assumptions; it is not a universal distance between arbitrary measures.

The direction of evaluation matters too. A model assigning high probability to typical examples may assign excessive probability to out-of-distribution observations; pointwise density is not a universal measure of semantic similarity. Conversely, judging a handful of hand-picked samples can hide a missing mode. Useful evaluation combines held-out log-likelihood when available with diversity and quality, and checks memorization and splits. The evaluation lesson measures these properties separately.

The geometry of support

Take PP uniform on (u,0)(u,0) and QθQ_\theta uniform on (u,θ)(u,\theta), with u∈[0,1]u\in[0,1]. For θ≠0\theta\ne0 the supports are disjoint: both KL divergences are infinite and JS⁡=ln⁡2\operatorname{JS}=\ln2. The coupling preserving uu moves every point by ∣θ∣|\theta|, so W1≤∣θ∣W_1\le |\theta|. The difference between the means of the second coordinate gives the lower bound W1≥∣θ∣W_1\ge |\theta|, establishing equality. For θ>0\theta>0, the derivative of JS is zero and that of W1W_1 is one. At zero the support changes; do not confuse this discontinuity with an ordinary gradient.

InteractiveTwo parallel supports
  • Data
  • Shifted model
  • W₁
  • JS
  • KL (if it fits on axis)

Lines are supports before noise. Points use a fixed sample and the same random displacement in both distributions; curves compute full measures, not distances between those points. Without noise, KL is infinite for θ > 0 and JS jumps from 0 to log 2.

0.80
0.00
Forward KL (nats)∞
JS (nats)0.693
W₁0.80
The supports are disjoint: KL is infinite and JS stays constant for all positive separations.
Move the separation and add noise. Without noise, JS is constant whereas transporting mass costs an amount proportional to separation. With noise, the distributions being compared are smoothed versions.

Adding positive-variance Gaussian noise to both distributions creates positive, overlapping densities and can provide a gradient signal. If noise is too small relative to separation, however, the numerical signal may remain tiny. Shifted supports and Wasserstein topology motivate the analysis of Arjovsky, Chintala and Bottou; changing divergence alone does not guarantee stable training.

From noise to data: a map of model families

If Z∼PZZ\sim P_Z and X=Gθ(Z)X=G_\theta(Z), the generated distribution is the pushforward measure Pθ(A)=PZ(Gθ−1(A))P_\theta(A)=P_Z(G_\theta^{-1}(A)). We can sample without knowing how to evaluate pθ(x)p_\theta(x). For example, if GG reduces dimension, its output may be singular even though ZZ has a density. In an invertible flow of equal dimension, a change of variables instead permits density evaluation if the inverse and Jacobian determinant are tractable.

FamilyWhat it providesHow to obtain a sample
AutoregressiveExact product of evaluable conditionalsSequential component sampling
Normalizing flowExact density when the inverse and Jacobian are tractableInvertible transformation of noise
VAEVariational bound on generally intractable marginal log-likelihoodLatent prior and decoder
GANImplicit procedure, generally without evaluable densityOne generator pass
EnergyUnnormalized energy; partition function is often intractableFor example, a Markov chain
ScoreGradient of log-density, not necessarily normalized densityIterative numerical dynamics
DDPMVariational bound for the specified modelDenoising transitions
Flow matchingContinuous flow field; density can be obtained by integrating the change-of-variables ODE, usually approximatelySolve an ODE

Evaluating a continuous density with a numerical ODE is not the same as a closed-form formula or an exact mass for discrete pixels. A score alone does not provide the normalizing constant for free. The review by Bond-Taylor and colleagues compares families and their trade-offs; Mohamed and Lakshminarayanan explain implicit models as generation procedures.

InteractiveThe generative zoo
Density access and procedure cost
Columns: evaluations or sequential stages in these examples
Access12K = 12
exact
bound
unnormalized
no density
numerical

Path: Sample the first coordinate; then sample the second conditioned on the first.

Product of normalized conditionals. Likelihood is exact if each conditional is evaluable.

  • Reference
  • Illustrative procedure

AR means autoregressive. The reference is an equally weighted Gaussian mixture centered at (±2, 0) with deviation 0.45. Blue points use illustrative analytic procedures, not trained networks. The GAN plot shows only two of three initial noise coordinates. Langevin chains are finite; diffusion and flow matching use Euler, so their results are approximate. Counts describe these paths, not universal times or costs: one evaluation may cost far more than another.

2 / 2
Usual access
exact
Cost of illustrated path
2 sequential conditionals in this 2D example
Select a family and follow its illustrative mechanism. The steps and trajectories are a mathematical model, not results from trained networks or universal costs.

A GAN can produce samples in one pass and still miss modes; an iterative chain has a cost depending on its number of steps; an autoregressive model can evaluate the probabilities of an observed sequence in parallel in some architectures but generates sequentially. Do not compare call counts alone: the cost of each call can differ. The module derives these families, objectives and metrics before studying acceleration, guidance and generalization.

Lab: fitting models and building data

Start with two known isotropic Gaussians in R2\R^2, equally weighted, with centers (−2,0)(-2,0) and (2,0)(2,0) and standard deviation 0.50.5. The training sample uses one seed; the test set uses another. Variance is known to separate the decision about centers from scale. Python indices start at zero. This experiment is an explicit model, not a result on real images.

[ ]Mixture data and densityBrowser
import numpy as np

centers = np.array([[-2., 0.], [2., 0.]])
sigma = 0.5
def sample_mixture(n, seed):
    rng = np.random.default_rng(seed)
    k = rng.integers(0, 2, n)
    return centers[k] + sigma * rng.normal(size=(n, 2))

def log_mixture(x, means, scale):
    z = (x[:, None, :] - means[None, :, :]) / scale
    a = -0.5 * np.sum(z*z, axis=2) - np.log(2*np.pi*scale**2)
    m = a.max(axis=1)
    return m + np.log(np.exp(a - m[:, None]).mean(axis=1))

train = sample_mixture(2000, 7)
test = sample_mixture(2000, 8)
print('Formas:', train.shape, test.shape)
print('NLL de la mezcla verdadera en evaluación:', round(-log_mixture(test, centers, sigma).mean(), 3))

Log-sum-exp prevents overflow. For an isotropic Gaussian with fixed scale ss, the gradient of NLL with respect to its mean is (μ−xˉ)/s2(\mu-\bar x)/s^2. Here the single Gaussian has fixed scale 2 and only its mean is fitted. We are not calculating the full optimum of mean and variance from the previous section. In the mixture, each point distributes responsibility among components according to posterior probability; each center’s gradient is the average of those responsibilities multiplied by (μk−x)/s2(\mu_k-x)/s^2. We implement this without an external optimizer.

[ ]Maximum likelihood by gradient descentBrowser
def fit_single(x, steps=120, lr=0.1, scale=2.0):
    mu = np.array([1., 1.])
    for _ in range(steps):
        mu -= lr * (mu - x.mean(axis=0)) / scale**2
    return mu

def fit_mix(x, steps=100, lr=0.12, scale=0.5):
    mu = np.array([[-1., 0.5], [1., -0.5]])
    for _ in range(steps):
        delta = mu[None, :, :] - x[:, None, :]
        a = -0.5 * np.sum(delta*delta, axis=2) / scale**2
        a -= a.max(axis=1, keepdims=True)
        responsibility = np.exp(a)
        responsibility /= responsibility.sum(axis=1, keepdims=True)
        grad = (responsibility[:, :, None] * delta).mean(axis=0) / scale**2
        mu -= lr * grad
    return mu

single = fit_single(train)
mix = fit_mix(train)
print('Media de una gaussiana:', np.round(single, 2))
print('Centros de la mezcla:', np.round(mix, 2))
print('NLL de gaussiana simple en evaluación:', round(-log_mixture(test, single[None, :], 2.).mean(), 3))
print('NLL de mezcla ajustada en evaluación:', round(-log_mixture(test, mix, sigma).mean(), 3))

The wide Gaussian also occupies the gap between modes. Now minimize the reverse KL of a Gaussian with fixed scale s=0.5s=0.5 relative to the known mixture. With x=μ+sϵx=\mu+s\epsilon and ϵ∼N(0,I)\epsilon\sim\Normal(0,I), the entropy term of qq does not depend on μ\mu; the gradient is the expectation of −∇xlog⁡p(x)-\nabla_x\log p(x). We reuse fixed noise within each fit to reduce gradient variation. This is a Monte Carlo estimate, not a proof of global optimality.

[ ]Reverse KL by reparameterizationBrowser
def reverse_fit(start, steps=100, lr=0.08):
    rng = np.random.default_rng(12)
    eps = rng.normal(size=(1000, 2))
    mu = np.array(start, dtype=float)
    for _ in range(steps):
        x = mu + sigma * eps
        delta = centers[None, :, :] - x[:, None, :]
        a = -0.5 * np.sum(delta*delta, axis=2) / sigma**2
        a -= a.max(axis=1, keepdims=True)
        r = np.exp(a)
        r /= r.sum(axis=1, keepdims=True)
        score = (r[:, :, None] * delta).sum(axis=1) / sigma**2
        mu += lr * score.mean(axis=0)
    return mu

print('Inicialización izquierda:', np.round(reverse_fit([-1., 0.]), 2))
print('Inicialización derecha:', np.round(reverse_fit([1., 0.]), 2))

This fit knows the true density, an advantage unavailable with arbitrary real data. The two initializations reveal different local solutions. Do not attribute the difference solely to divergence when changing the family, scale or optimization too. By contrast, the library estimator fits a mixture with learned covariances, so it does not solve exactly the same fixed-scale problem either.

Now use two components for reverse KL as well. If qμq_\mu is their equally weighted mixture, we can reparameterize one sample from each component. The gradient with respect to their centers averages ∇xlog⁡qμ(x)−∇xlog⁡p(x)\nabla_x\log q_\mu(x)-\nabla_x\log p(x) by component and weight. The explicit derivative of log⁡qμ\log q_\mu has zero expectation under qμq_\mu provided differentiation and integration can be interchanged. Here the Gaussians are regular and scale is fixed. The experiment shows what happens for this initialization; others may lead to a different local optimum.

[ ]Reverse KL with two componentsBrowser
def mixture_score(x, means, scale):
    delta = means[None, :, :] - x[:, None, :]
    a = -0.5 * np.sum(delta*delta, axis=2) / scale**2
    a -= a.max(axis=1, keepdims=True)
    r = np.exp(a)
    r /= r.sum(axis=1, keepdims=True)
    return (r[:, :, None] * delta).sum(axis=1) / scale**2

def reverse_mix_fit(start, steps=100, lr=0.12):
    rng = np.random.default_rng(21)
    eps = rng.normal(size=(2, 600, 2))
    mu = np.array(start, dtype=float)
    for _ in range(steps):
        x = mu[:, None, :] + sigma * eps
        flat = x.reshape(-1, 2)
        gradient = (mixture_score(flat, mu, sigma) -
                    mixture_score(flat, centers, sigma)).reshape(2, -1, 2)
        mu -= lr * gradient.mean(axis=1) / 2
    return mu

reverse_mix = reverse_mix_fit([[-1., 0.], [1., 0.]])
print('Centros de mezcla por KL inversa:', np.round(reverse_mix, 2))
print('NLL de esa mezcla en evaluación:', round(-log_mixture(test, reverse_mix, sigma).mean(), 3))

Compare both centers and evaluation NLL, but remember that NLL measures the forward direction and is not the objective just optimized. A two-component model can represent the target mixture; a single Gaussian cannot. Success in this controlled construction does not prove that a mixture learned from real data covers every mode.

[ ]Comparison with scikit-learnBrowser
from sklearn.mixture import GaussianMixture

gm = GaussianMixture(n_components=2, random_state=7, reg_covar=1e-4).fit(train)
print('Centros de biblioteca:', np.round(gm.means_[np.argsort(gm.means_[:, 0])], 2))
print('NLL de biblioteca en evaluación:', round(-gm.score(test), 3))

A distribution benchmark

The following benchmark generates each dataset from scratch and always returns an n×2n\times2 matrix. These are different synthetic distributions: moons and the roll add noise, the spiral and ring have their own scales, and the checkerboard alternates cells. When comparing models, use the same training seeds and different evaluation seeds, and record preprocessing. Do not standardize using statistics calculated on the evaluation set.

[ ]Five reproducible datasetsBrowser
def make_dataset(name, n, seed):
    if n < 1:
        raise ValueError('n debe ser positivo')
    rng = np.random.default_rng(seed)
    if name == 'lunas':
        t = rng.uniform(0, np.pi, n)
        side = rng.integers(0, 2, n)
        x = np.column_stack((np.cos(t), np.sin(t)))
        x[side == 1] = np.column_stack((1-np.cos(t[side == 1]), 0.5-np.sin(t[side == 1])))
        return x + 0.05*rng.normal(size=(n, 2))
    if name == 'espiral':
        t = rng.uniform(0, 4*np.pi, n)
        return np.column_stack((t*np.cos(t), t*np.sin(t))) / (4*np.pi)
    if name == 'anillo':
        k = rng.integers(0, 8, n)
        a = 2*np.pi*k/8
        return 2*np.column_stack((np.cos(a), np.sin(a))) + 0.08*rng.normal(size=(n, 2))
    if name == 'tablero':
        i = rng.integers(0, 4, n)
        j = (2*rng.integers(0, 2, n) + i % 2)
        return np.column_stack((i, j)) + rng.uniform(size=(n, 2)) - 2
    if name == 'rollo':
        t = rng.uniform(1.5*np.pi, 4.5*np.pi, n)
        return np.column_stack((t*np.cos(t), t*np.sin(t))) / (4.5*np.pi) + 0.02*rng.normal(size=(n, 2))
    raise ValueError('dataset desconocido')

for name in ['lunas', 'espiral', 'anillo', 'tablero', 'rollo']:
    x = make_dataset(name, 1000, 17)
    print(name, x.shape, np.round(x.mean(axis=0), 2))

Equal visual scaling on both axes avoids turning a circle into an ellipse. The next function accepts an evaluable density and a sample: it plots the density on a grid and overlays points. Its output cannot estimate a GAN density. In that case samples can be plotted, but a density function must not be invented.

[ ]Density and samples in one planeBrowser
import matplotlib.pyplot as plt

def plot_density_samples(log_density, samples, bounds=(-4, 4), size=80):
    axis = np.linspace(bounds[0], bounds[1], size)
    xx, yy = np.meshgrid(axis, axis)
    grid = np.column_stack((xx.ravel(), yy.ravel()))
    density = np.exp(log_density(grid)).reshape(xx.shape)
    fig, ax = plt.subplots(figsize=(5, 5))
    ax.contourf(xx, yy, density, levels=12, cmap='Blues')
    ax.scatter(samples[:, 0], samples[:, 1], s=3, alpha=0.35, color='black')
    ax.set_aspect('equal')
    ax.set_xlabel('x₁')
    ax.set_ylabel('x₂')
    return fig, ax

fig, ax = plot_density_samples(lambda x: log_mixture(x, mix, sigma), test[:300])
plt.show()

For small digits, sklearn.datasets.load_digits provides 8×88\times8 images and labels. Split indices before fitting transformations. Later stages use MNIST and Fashion-MNIST monochrome images of 28×2828\times28 and CIFAR-10 RGB images of 32×3232\times32; check each source’s license, split and normalization. An 8 GB GPU can host many small experiments, but this is not guaranteed by model family: activations, batch size, optimizer and resolution matter. Start with a small batch and measure memory. Full-scale training belongs to the relevant lab.

The scikit-learn digits, MNIST, Fashion-MNIST and CIFAR-10 pages describe their shapes and splits. load_digits is a copy of a digit dataset distinct from MNIST: do not interpret its intensities or results as MNIST results. To avoid confusing quality with input size, keep resolution, range and shape alongside each experiment.

[ ]Digits and reproducible splitBrowser
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

digits = load_digits()
idx_train, idx_test = train_test_split(np.arange(len(digits.data)), test_size=0.2,
                                       random_state=7, stratify=digits.target)
print('Imagen:', digits.images[0].shape)
print('Entrenamiento y evaluación:', len(idx_train), len(idx_test))

Exercises

ProofThe likelihood constant
Prove: Prove that maximizing expected log-likelihood is equivalent to minimizing forward KL under the integrability and support assumptions of the lesson.
0
Let p be the data density and q the model density.

Step 1 of 3. How does the logarithm of the ratio decompose?

NumericTransport between two points
For P=δ0P=\delta_0 and Q=δ0.5Q=\delta_{0.5} on the real line with absolute distance, calculate W1(P,Q).W_1(P,Q).
NumericJensen-Shannon between two points
For P=δ0P=\delta_0 and Q=δ0.5Q=\delta_{0.5}, calculate JS in nats.
QuizMoving a point
With P=δ0P=\delta_0 and Qθ=δθQ_\theta=\delta_\theta, what are the derivatives of W₁ and JS with respect to θ at θ = 0.5?
QuizWhat can be evaluated
Which classification is correct for typical implementations?
QuizWhat the objective favors
A small-variance Gaussian is fitted to a mixture of two separated modes by minimizing KL(q || p). What behavior may appear?
CodeA reproducible benchmark
Implement make_dataset(name, n, seed) for the five names and distributions specified in the lab: lunas, espiral, anillo, tablero and rollo. Return an (n, 2) array, use default_rng(seed) and raise ValueError if the name is unknown or n is not positive. Also implement plot_density_samples(log_density, samples): evaluate the vectorized function on a grid in the square [-4, 4]², plot its exponential and overlay the samples, returning (fig, ax).
import numpy as np
import matplotlib.pyplot as plt

def make_dataset(name, n, seed):
  pass

def plot_density_samples(log_density, samples):
  pass
Shift+Enter to run
Key idea

A generative model is a distribution or sampling procedure, not a promise of good samples. Likelihood, support geometry, model family and generation cost answer different questions. The rest of the module develops those answers and tests their limits.