Variational inference and generative-model maths: ELBO, VAEs, diffusion

The evidence lower bound derived three ways with its gap drawn, mean-field and amortised inference, and the two ways to differentiate through a sample, each on a model you can check by hand; then the derivations the VAE, diffusion and flow-matching pages use. Child of Topic: math. Data as of October 2026. Reading: 23 min, plus 18 in closed details.

The idea in one screen

When a model explains data xx through a hidden cause zz, the log-likelihood log⁡p(x)\log p(x) needs an integral over every zz that nobody can compute; so pick a simple distribution q(z)q(z) and maximise the ELBO, 𝔼q[log⁡p(x,z)−log⁡q(z)]\mathbb{E}_q[\log p(x,z) - \log q(z)], which is always below log⁡p(x)\log p(x) by exactly the gap DKL(q‖p(z|x))D_{\mathrm{KL}}(q \,\Vert\, p(z\mid x)), so raising it trains the model and fits qq to the posterior at once.

Fig. 1: the bound is the evidence minus the gap, on one model where every number is exact. The column on the right is −ELBO-\text{ELBO} in nats, split into −log⁡p(x)-\log p(x) (teal) and the gap (orange).

  1. The model and its evidence. Model A of section 1: prior 𝒩(0,1)\mathcal{N}(0,1) (dashed, behind), x=zx = z + noise of sd 0.5, observed x=1.5x = 1.5. The true posterior 𝒩(1.2, 0.2)\mathcal{N}(1.2,\ 0.2) is shaded. Here the evidence has a closed form, log⁡p(x)=−1.9305\log p(x) = -1.9305: the teal column.
  2. A deliberately poor qq. q=𝒩(0.5, 0.52)q = \mathcal{N}(0.5,\ 0.5^2), too far left and too wide. The ELBO is an average over samples of qq (the dots streaming into the column): −3.1689-3.1689. So log⁡p(x)=−1.9305\log p(x) = -1.9305 splits into ELBO −3.1689-3.1689 plus gap 1.2384, the KL from qq to the posterior.
  3. Move its mean onto the posterior's. At mean 1.2, still with sd 0.5, the gap falls to 0.0134: only the width is wrong now.
  4. Match the width. At sd 0.447, qq is the posterior: gap 0 and ELBO =log⁡p(x)=−1.9305= \log p(x) = -1.9305. The teal part never moved, so every nat the ELBO gained was a nat of KL lost.
  5. Model B: a posterior no Gaussian reaches. With x=z2x = z^2 + noise and x=2x = 2, the posterior has two humps (section 2). The best Gaussian (mean 1.33, sd 0.19) sits on one and leaves a gap of 0.712 nats, close to ln⁡2\ln 2 (section 3). Move qq yourself in section 3's widget.

You need: Bayes' rule and Gaussians (Probability for ML, sections 1, 2 and 5; Monte Carlo and the law of large numbers in section 4) and KL divergence with its forward and reverse directions (Information theory for ML, sections 3 and 4). The models built on the ELBO are taught on their own pages: Autoencoders and VAEs, Diffusion from zero and Flow matching and rectified flow; this page is the mathematics they share, with the derivations they cite in section 7.

Latent variable zz
the hidden cause; never observed.
Prior, decoder
p(z)p(z), and the likelihood pθ(x|z)p_\theta(x\mid z) with trainable θ\theta.
Evidence
the marginal likelihood pθ(x)=∫p(z)pθ(x|z)dzp_\theta(x) = \int p(z)\,p_\theta(x\mid z)\,dz.
Posterior
pθ(z|x)p_\theta(z\mid x), which causes explain this xx.
Variational family
the simple distributions qϕq_\phi we search; ϕ\phi are the variational parameters.
ELBO
evidence lower bound, 𝔼q[log⁡p(x,z)−log⁡q(z)]\mathbb{E}_q[\log p(x,z) - \log q(z)].
Mean field
a qq that factorises over latents.
Amortised inference
one network outputs q(z|x)q(z\mid x) for every xx.
Pathwise, score function
the two ways to differentiate an average under qϕq_\phi (section 5).

1. Latent-variable models, and the integral you cannot do

A latent-variable model tells a two-step story: draw a hidden value zz (the latent variable) from a simple prior p(z)p(z), then draw the data from the likelihood or decoder pθ(x|z)p_\theta(x\mid z), with θ\theta the parameters we train (in a VAE, a network's weights). We only ever see xx, so the probability of an observation is the marginal likelihood or evidence, the joint added up over every zz:

pθ(x)=∫p(z)pθ(x|z)dz.p_\theta(x) = \int p(z)\, p_\theta(x \mid z)\, dz .

Maximum likelihood (Probability for ML, section 7) needs ∑ilog⁡pθ(xi)\sum_i \log p_\theta(x_i) and its gradient, so it needs this integral for every example.

Model A, the running example (sections 1 to 5)

Prior z∼𝒩(0,1)z \sim \mathcal{N}(0, 1); decoder x|z∼𝒩(z,s2)x \mid z \sim \mathcal{N}(z, s^2) with s=0.5s = 0.5; we observe x=1.5x = 1.5. Here the integral has a closed form: xx is a sum of two independent Gaussians (variances 1 and 0.25), so x∼𝒩(0,1.25)x \sim \mathcal{N}(0, 1.25) and

log⁡p(x=1.5)=−12log⁡(2π⋅1.25)−1.522⋅1.25=−1.0305−0.9000=−1.9305,\log p(x{=}1.5) = -\tfrac12 \log(2\pi \cdot 1.25) - \frac{1.5^2}{2 \cdot 1.25} = -1.0305 - 0.9000 = -1.9305,

that is p(x)=0.1451p(x) = 0.1451. Every number in sections 2 to 5 is measured against this −1.9305-1.9305 (src/recompute.py recomputes each one).

Why it is usually impossible. Model A is solvable only because a Gaussian pushed through a straight line stays Gaussian. Make the mean a network's output, x|z∼Bernoulli(decoderθ(z))x \mid z \sim \text{Bernoulli}(\text{decoder}_\theta(z)), and nothing cancels: Kingma and Welling name exactly this case, intractable "in cases of moderately complicated likelihood functions pθ(x|z)p_\theta(x \mid z), e.g. a neural network with a nonlinear hidden layer" (Auto-Encoding Variational Bayes, section 2.1). A grid of 100 points per axis costs 10410^4 decoder calls for a 2-D latent and 103210^{32} for a 16-D one. Naive Monte Carlo (draw zz from the prior, average p(x|z)p(x\mid z)) is unbiased, but almost every prior sample explains a given image terribly, so the average is dominated by rare lucky draws.

Where latents appear. A Gaussian mixture (zz is the cluster; the integral is a sum of KK terms, easy, and its posterior is EM's responsibilities); a VAE (zz a continuous vector of 2 to a few hundred numbers, decoder a network: intractable); a diffusion model (the latents are 1,000 progressively noisier copies of the image, x1,…,xTx_1, \dots, x_T, each as large as the image: intractable); also topic models, probabilistic PCA and Bayesian neural networks (where zz is the weights). Contrast: a next-token model has no latent; p(word|context)p(\text{word}\mid\text{context}) is a softmax, one exact sum over the vocabulary, which is why language models train on plain cross-entropy and need nothing on this page.

2. The posterior, and turning inference into optimisation

The posterior is the distribution of zz after seeing xx, by Bayes' rule (Probability for ML, section 5):

pθ(z|x)=pθ(x|z)p(z)pθ(x).p_\theta(z \mid x) = \frac{p_\theta(x \mid z)\, p(z)}{p_\theta(x)} .

The numerator is easy (run the decoder, evaluate the prior); the denominator is the evidence of section 1. So the posterior is intractable for exactly the same reason, and two jobs need it: inference ("what is this image's latent code?", for representations, compression, editing) and learning, because the gradient of log⁡pθ(x)\log p_\theta(x) is an average under the posterior (Fisher's identity, below), which is also why EM cannot run when the posterior is intractable, the second intractability Kingma and Welling list.

Model A's posterior, exactly

Multiply prior and likelihood and complete the square in zz: −z22−(1.5−z)22⋅0.25-\tfrac{z^2}{2} - \tfrac{(1.5 - z)^2}{2 \cdot 0.25} has leading coefficient −12(1+4)=−52-\tfrac12(1 + 4) = -\tfrac{5}{2}, so the posterior variance is 1/5=0.21/5 = 0.2; the peak is where −z+4(1.5−z)-z + 4(1.5 - z) vanishes, z=6/5=1.2z = 6/5 = 1.2. So p(z|x=1.5)=𝒩(1.2, 0.2)p(z \mid x{=}1.5) = \mathcal{N}(1.2,\ 0.2), standard deviation 0.447. In general 𝒩(x1+s2,s21+s2)\mathcal{N}\!\big(\tfrac{x}{1+s^2}, \tfrac{s^2}{1+s^2}\big): the observation pulls the prior's mean 0 most of the way to 1.5 and shrinks its spread five-fold. This is the shaded curve in the hero figure.

Model B, where no Gaussian fits. Change one thing: x|z∼𝒩(z2,0.25)x \mid z \sim \mathcal{N}(z^2, 0.25), the data is the square of the hidden value plus noise, and observe x=2x = 2. Now z≈+1.37z \approx +1.37 and z≈−1.37z \approx -1.37 explain it equally well: the posterior has two humps. Section 3 measures what that costs a Gaussian qq.

Variational inference: pick the closest simple distribution

Choose a family 𝒬\mathcal{Q} simple enough to sample and evaluate (say all Gaussians, each fixed by a mean and a variance) and take the member closest to the posterior in KL (Information theory for ML, section 3), in this direction (equation (10) of Blei, Kucukelbir and McAuliffe's review):

q∗=arg⁡minq∈𝒬⁡DKL(q(z)‖p(z|x)),DKL(q‖p)=𝔼z∼q[log⁡q(z)p(z|x)].q^{*} = \arg\min_{q \in \mathcal{Q}} D_{\mathrm{KL}}\big(q(z) \,\Vert\, p(z \mid x)\big), \qquad D_{\mathrm{KL}}(q \Vert p) = \mathbb{E}_{z \sim q}\left[\log \frac{q(z)}{p(z \mid x)}\right].

The search is ordinary optimisation over the numbers that define qq, the variational parameters ϕ\phi (μ,σ\mu, \sigma for a Gaussian). ("Variational" comes from the calculus of variations, optimising over functions; here they are indexed by ϕ\phi, so it is gradient ascent on ϕ\phi.)

  • Why this direction (reverse KL). It is an average under qq, which we can sample; DKL(p(z|x)‖q)D_{\mathrm{KL}}(p(z\mid x) \Vert q) would average under the posterior we cannot sample. The price: reverse KL is mode-seeking. It punishes qq for mass where the posterior has none, not for missing some of the posterior's mass, so on a two-humped posterior a Gaussian qq picks one hump. Information theory for ML, section 4 animates it (its reverse fit lands on one mode with a KL of 0.692, about ln⁡2\ln 2); model B shows the same number as an ELBO gap.
  • The KL still contains the posterior. Expand it with p(z|x)=p(x,z)/p(x)p(z \mid x) = p(x, z)/p(x) (Blei et al. eq. 11 to 12):
    DKL(q‖p(z|x))=𝔼q[log⁡q(z)]−𝔼q[log⁡p(x,z)]+log⁡p(x)D_{\mathrm{KL}}\big(q \,\Vert\, p(z\mid x)\big) = \mathbb{E}_q[\log q(z)] - \mathbb{E}_q[\log p(x, z)] + \log p(x)
    The unknown log⁡p(x)\log p(x) does not depend on qq, so minimising the KL over qq is maximising the computable rest with its sign flipped. That quantity is the ELBO.
Fisher's identity, EM, and the sampling road (depth)

Fisher's identity: ∇θlog⁡pθ(x)=𝔼pθ(z|x)[∇θlog⁡pθ(x,z)]\nabla_\theta \log p_\theta(x) = \mathbb{E}_{p_\theta(z \mid x)}\big[\nabla_\theta \log p_\theta(x, z)\big] (differentiate log⁡∫pθ(x,z)dz\log\int p_\theta(x,z)\,dz, then use ∇p=p∇log⁡p\nabla p = p\, \nabla \log p). The EM algorithm alternates exactly the two jobs: compute the posterior (E-step), then maximise the expected log-joint (M-step).

The full Bayesian view (keep every answer, weighted) is Probability for ML, section 9. Sampling methods that target the exact posterior instead of approximating it (MCMC: Metropolis-Hastings, HMC) are the other road; Murphy's Probabilistic Machine Learning: Advanced Topics has a part on each (Further reading). Variational inference is used for every VAE encoder, Bayesian neural networks (Bayes by Backprop), topic models (LDA's original inference), Gaussian processes with inducing points, and the training objective of diffusion models (section 6).

3. The ELBO, derived three ways, and the gap drawn

The definition (Kingma and Welling eq. 2; Blei et al. eq. 13), with log⁡p(x,z)=log⁡p(z)+log⁡p(x|z)\log p(x,z) = \log p(z) + \log p(x\mid z) computable for any zz and 𝔼z∼q\mathbb{E}_{z\sim q} estimated by drawing a few zz and averaging:

ELBO(q)=𝔼z∼q[log⁡p(x,z)−log⁡q(z)].\text{ELBO}(q) = \mathbb{E}_{z \sim q}\big[\log p(x, z) - \log q(z)\big].

Three derivations, because each answers a different question: why it is a bound, how far below it sits, and how to tighten it.

Way 1: Jensen's inequality (why it is a lower bound)

  1. Multiply and divide inside the integral by q(z)q(z) (allowed wherever q(z)>0q(z) > 0):
    log⁡p(x)=log⁡∫q(z)p(x,z)q(z)dz=log⁡𝔼q[p(x,z)q(z)]\log p(x) = \log \int q(z) \frac{p(x,z)}{q(z)}\, dz = \log \mathbb{E}_q\!\left[\frac{p(x,z)}{q(z)}\right]
    .
  2. Jensen's inequality: for a concave function such as log⁡\log, log⁡𝔼[Y]≥𝔼[log⁡Y]\log \mathbb{E}[Y] \ge \mathbb{E}[\log Y] (a chord of a concave curve lies below the curve). With Y=p(x,z)/q(z)Y = p(x,z)/q(z): log⁡p(x)≥𝔼q[log⁡p(x,z)−log⁡q(z)]=ELBO(q)\log p(x) \ge \mathbb{E}_q\big[\log p(x, z) - \log q(z)\big] = \text{ELBO}(q).

A bound for every qq, however bad. Equality needs p(x,z)/q(z)p(x,z)/q(z) constant in zz, which happens only when q(z)∝p(x,z)q(z) \propto p(x, z), that is qq equals the posterior.

Way 2: the KL decomposition (how far below)

Write p(x,z)=p(z|x)p(x)p(x, z) = p(z\mid x)\, p(x) inside the definition; log⁡p(x)\log p(x) is a constant under 𝔼q\mathbb{E}_q, and what remains is a KL (Kingma and Welling eq. 1; Blei et al. eq. 14):

log⁡p(x)=ELBO(q)+DKL(q(z)‖p(z|x))⏟the gap.\log p(x) = \text{ELBO}(q) + \underbrace{D_{\mathrm{KL}}\big(q(z) \,\Vert\, p(z \mid x)\big)}_{\text{the gap}}.

The evidence is the bound plus the gap, and the gap is exactly the reverse KL of section 2: every nat the ELBO gains is a nat the KL loses. When the model's θ\theta also moves, raising the ELBO either raises log⁡pθ(x)\log p_\theta(x) (a better model) or shrinks the gap (a better qq); the ELBO alone cannot tell you which.

Model A, with q=𝒩(0.5, 0.52)q = \mathcal{N}(0.5,\ 0.5^2) (too far left and too wide)

Three averages, each in closed form for Gaussians (using 𝔼q[(a−z)2]=(a−m)2+v\mathbb{E}_q[(a - z)^2] = (a - m)^2 + v for q=𝒩(m,v)q = \mathcal{N}(m, v)):

𝔼q[log⁡p(x|z)]=−12log⁡(2π⋅0.25)−(1.5−0.5)2+0.252⋅0.25=−0.2258−2.5=−2.7258\mathbb{E}_q[\log p(x\mid z)] = -\tfrac12\log(2\pi \cdot 0.25) - \frac{(1.5 - 0.5)^2 + 0.25}{2 \cdot 0.25} = -0.2258 - 2.5 = -2.7258
𝔼q[log⁡p(z)]=−12log⁡2π−0.52+0.252=−0.9189−0.25=−1.1689\mathbb{E}_q[\log p(z)] = -\tfrac12 \log 2\pi - \frac{0.5^2 + 0.25}{2} = -0.9189 - 0.25 = -1.1689

and the entropy of qq, −𝔼q[log⁡q]=12log⁡(2πe⋅0.25)=0.7258-\mathbb{E}_q[\log q] = \tfrac12 \log(2\pi e \cdot 0.25) = 0.7258.

ELBO =−2.7258−1.1689+0.7258=−3.1689= -2.7258 - 1.1689 + 0.7258 = -3.1689. The Gaussian KL from qq to the posterior is 1.23841.2384. Sum: −3.1689+1.2384=−1.9305=log⁡p(x)-3.1689 + 1.2384 = -1.9305 = \log p(x), to every printed digit. A million-sample Monte Carlo estimate of the ELBO gives −3.1692-3.1692. At the posterior the ELBO is −1.9305-1.9305: gap zero. (A two-valued latent by hand: p(x,z=0)=0.2p(x, z{=}0) = 0.2, p(x,z=1)=0.1p(x, z{=}1) = 0.1, q=(0.5,0.5)q = (0.5, 0.5) give log⁡p(x)=ln⁡0.3=−1.204\log p(x) = \ln 0.3 = -1.204 and ELBO 0.5ln⁡(0.2/0.5)+0.5ln⁡(0.1/0.5)=−1.2630.5\ln(0.2/0.5) + 0.5\ln(0.1/0.5) = -1.263; the gap 0.0589 equals the KL from qq to the posterior (0.667,0.333)(0.667, 0.333).)

Model B: when the family cannot reach the posterior

With the two-humped posterior (x=2x = 2, log⁡p(x)=−2.1693\log p(x) = -2.1693 by quadrature), the best Gaussian qq sits on one hump (mean 1.33, standard deviation 0.19) and reaches an ELBO of −2.8811-2.8811: a gap of 0.712 nats that no optimiser can close, close to ln⁡2=0.693\ln 2 = 0.693, the cost of covering only one of two equal humps. Only a richer family closes it (a mixture, or a normalising flow, section 4).

The ELBO rises exactly as the gap shrinks: drag qq

Predict first: on model A, if you widen qq far beyond the posterior, which falls, the reconstruction term or the KL to the prior? And on model B, can any setting make the gap 0?

prior p(z)true posterior p(z | x)your q(z)

Bar: −ELBO-\text{ELBO} split into −log⁡p(x)-\log p(x) and the gap. Model A's defaults are the hero's qq: ELBO −3.1689-3.1689, gap 1.2384; at the posterior 𝒩(1.2,0.4472)\mathcal{N}(1.2, 0.447^2) the gap reads 0. Model B at x=2x = 2: the best Gaussian leaves about 0.71 nats, near ln⁡2\ln 2; lower xx towards 0 and the humps merge, so the gap shrinks. Model B's log⁡p(x)\log p(x) is by quadrature on 2,401 points.

Way 3: importance sampling (a family of tighter bounds)

Way 1's first line says p(x)=𝔼q[w]p(x) = \mathbb{E}_q[w] with the importance weight w=p(x,z)/q(z)w = p(x, z)/q(z): draw zz from qq, reweight by how much more likely the model finds it than qq does (importance sampling, unbiased for p(x)p(x)). Average KK weights (still unbiased, variance falling like 1/K1/K), take the log and apply Jensen again:

ℒK=𝔼z1,…,zK∼q[log⁡1K∑k=1Kp(x,zk)q(zk)]≤log⁡p(x),\mathcal{L}_K = \mathbb{E}_{z_1, \dots, z_K \sim q}\left[\log \frac{1}{K} \sum_{k=1}^{K} \frac{p(x, z_k)}{q(z_k)}\right] \le \log p(x),

the importance-weighted bound of Burda, Grosse and Salakhutdinov (IWAE), Theorem 1: ℒ1\mathcal{L}_1 is the ELBO, ℒK\mathcal{L}_K never decreases as KK grows, and it tends to log⁡p(x)\log p(x) when the weights are bounded. It is computed in logs, with log-sum-exp (Probability for ML, section 12).

The same qq, a better estimator: the bound climbs to log⁡p(x)\log p(x) as KK grows

Model A, same qq: ℒ1=−3.09\mathcal{L}_1 = -3.09 (a Monte Carlo average over 2,000 repeats; the exact ELBO is −3.1689-3.1689), ℒ10=−2.13\mathcal{L}_{10} = -2.13, ℒ100=−1.954\mathcal{L}_{100} = -1.954, ℒ1000=−1.931\mathcal{L}_{1000} = -1.931, against log⁡p(x)=−1.9305\log p(x) = -1.9305. On the MNIST VAE of section 4 the same experiment goes from −150.1-150.1 to −144.6-144.6 nats as KK runs from 1 to 1,000, still far from the truth there: a poor qq makes importance sampling converge slowly.

The form a VAE implements

Split log⁡p(x,z)=log⁡p(x|z)+log⁡p(z)\log p(x,z) = \log p(x \mid z) + \log p(z) and group the prior with qq (Kingma and Welling eq. 3):

ELBO=𝔼q[log⁡p(x|z)]⏟reconstruction−DKL(q(z)‖p(z))⏟stay near the prior.\text{ELBO} = \underbrace{\mathbb{E}_{q}\big[\log p(x\mid z)\big]}_{\text{reconstruction}} - \underbrace{D_{\mathrm{KL}}\big(q(z) \,\Vert\, p(z)\big)}_{\text{stay near the prior}} .

For model A's qq: −2.7258−0.4431=−3.1689-2.7258 - 0.4431 = -3.1689, the same number. Engineers usually minimise the negative ELBO and call it the loss; image papers report it in bits per dimension (divide by Dln⁡2D \ln 2, DD the number of pixels).

4. Choosing the family: mean field, amortised, or richer

Every choice of family trades how close qq can get to the posterior against how cheap it is to fit. Three choices matter.

Mean field, fitted by coordinate ascent

The mean-field family assumes qq factorises over groups of latents, q(z)=∏jqj(zj)q(z) = \prod_j q_j(z_j) (Blei et al. eq. 15). It cannot represent correlations between groups, but each factor's best update is computable: holding the others fixed (Blei et al. eq. 18; Bishop 2006, eq. 10.9),

qj∗(zj)∝exp⁡(𝔼−j[log⁡p(zj,z−j,x)]),q_j^{*}(z_j) \propto \exp\!\Big(\mathbb{E}_{-j}\big[\log p(z_j, z_{-j}, x)\big]\Big),

with 𝔼−j\mathbb{E}_{-j} averaging over every factor except qjq_j. Why: with the others fixed, the ELBO as a function of qjq_j is −DKL(qj‖p~j)-D_{\mathrm{KL}}\big(q_j \,\Vert\, \tilde p_j\big) plus a constant, p~j∝exp⁡(𝔼−j[log⁡p])\tilde p_j \propto \exp(\mathbb{E}_{-j}[\log p]) (Blei et al. eq. 19), smallest (zero) when they match. Cycling through the factors is coordinate ascent variational inference (CAVI); each update can only raise the ELBO, so it converges, to a local optimum.

The example is Bishop's (Pattern Recognition and Machine Learning, section 10.1.3): data x1,…,xN∼𝒩(μ,τ−1)x_1, \dots, x_N \sim \mathcal{N}(\mu, \tau^{-1}) (τ\tau is the precision, one over the variance), priors μ|τ∼𝒩(μ0,(λ0τ)−1)\mu \mid \tau \sim \mathcal{N}(\mu_0, (\lambda_0 \tau)^{-1}) and τ∼Gamma(a0,b0)\tau \sim \text{Gamma}(a_0, b_0). The exact posterior is a known Normal-Gamma, so we can see exactly what q(μ,τ)=q(μ)q(τ)q(\mu, \tau) = q(\mu)\, q(\tau) loses.

Predict first: the exact posterior is a funnel (low precision, wide μ\mu). Will the converged mean-field fit be wider or narrower than it?

Fig. 3: the floor is (μ,τ)(\mu, \tau); the shaded surface is the exact posterior; the walls carry the marginals (exact dashed, qq solid). Ten observations (illustrative, listed below), priors μ0=0,λ0=1,a0=b0=1\mu_0 = 0, \lambda_0 = 1, a_0 = b_0 = 1; start from 𝔼[τ]=1\mathbb{E}[\tau] = 1. Heights are densities.

  1. The exact posterior. The Normal-Gamma posterior of (μ,τ)(\mu, \tau) given the ten points. It leans: when the precision τ\tau is low, μ\mu is less certain, so the hill widens towards the front. Mean field will fit it with a product q(μ)q(τ)q(\mu)\, q(\tau), an axis-aligned shape.
  2. Round 1: update q(μ)q(\mu). q(μ)=𝒩(0.8155, 1/11.00)q(\mu) = \mathcal{N}(0.8155,\ 1/11.00): the mean never changes (it does not depend on τ\tau here); the precision is (λ0+N)𝔼[τ]=11×1(\lambda_0 + N)\,\mathbb{E}[\tau] = 11 \times 1, from the starting guess, so the first q(μ)q(\mu) is far too wide.
  3. Round 1: update q(τ)q(\tau). It averages over the new q(μ)q(\mu): q(τ)=Gamma(6.5, 2.3906)q(\tau) = \text{Gamma}(6.5,\ 2.3906), so 𝔼[τ]=2.7189\mathbb{E}[\tau] = 2.7189.
  4. Rounds 2 to 5: the updates feed each other. A larger 𝔼[τ]\mathbb{E}[\tau] makes the next q(μ)q(\mu) narrower, which lowers bb, which raises 𝔼[τ]\mathbb{E}[\tau]: λN\lambda_N climbs 29.91, 34.47, 34.87, 34.91 and 𝔼[τ]\mathbb{E}[\tau] settles at 3.1735 until nothing moves.
  5. Converged: right centre, too narrow, cannot lean. The product (blue mesh) sits on the posterior's centre (𝔼[τ]\mathbb{E}[\tau] is 3.1735 both ways) but is axis-aligned and tighter: Var⁡(μ)\operatorname{Var}(\mu) is 0.0286 under qq against 0.0344 exactly (17% too small; corrected 2026-11-07 from 0.0287, which rounded 0.028646 twice), and Var⁡(τ)\operatorname{Var}(\tau) 1.549 against 1.679. An axis-aligned product cannot express the funnel, and reverse KL prefers too narrow to too wide.
What mean field gets right and wrong here (all from src/recompute.py)

Data: 1.00, 1.15, 0.86, 0.55, 0.77, 0.50, 1.03, 1.67, 0.75, 0.69 (mean 0.897). CAVI converges in about five rounds to μN=0.8155\mu_N = 0.8155, λN=34.91\lambda_N = 34.91, aN=6.5a_N = 6.5, bN=2.048b_N = 2.048. Blei et al. (section 1): "variational inference generally underestimates the variance of the posterior density".

The two CAVI updates for the Normal-Gamma, derived (depth)
  1. Write the log-joint, keeping only terms with μ\mu or τ\tau:
    log⁡p=N2log⁡τ−τ2∑n(xn−μ)2+12log⁡τ−λ0τ2(μ−μ0)2+(a0−1)log⁡τ−b0τ+const\log p = \tfrac{N}{2}\log\tau - \tfrac{\tau}{2}\sum_n (x_n - \mu)^2 + \tfrac12 \log \tau - \tfrac{\lambda_0 \tau}{2}(\mu - \mu_0)^2 + (a_0 - 1)\log \tau - b_0 \tau + \text{const}
    .
  2. Update q(μ)q(\mu): average over q(τ)q(\tau), which only replaces τ\tau by 𝔼[τ]\mathbb{E}[\tau] in the μ\mu terms. What is left is −𝔼[τ]2[∑n(xn−μ)2+λ0(μ−μ0)2]-\tfrac{\mathbb{E}[\tau]}{2}\big[\sum_n (x_n-\mu)^2 + \lambda_0(\mu-\mu_0)^2\big], a quadratic in μ\mu, so q(μ)=𝒩(μN,λN−1)q(\mu) = \mathcal{N}(\mu_N, \lambda_N^{-1}) with μN=λ0μ0+Nx‾λ0+N\mu_N = \frac{\lambda_0 \mu_0 + N\bar x}{\lambda_0 + N} and λN=(λ0+N)𝔼[τ]\lambda_N = (\lambda_0 + N)\,\mathbb{E}[\tau].
  3. Update q(τ)q(\tau): average over q(μ)q(\mu). The log⁡τ\log\tau terms have coefficient N2+12+a0−1\tfrac{N}{2} + \tfrac12 + a_0 - 1 and the τ\tau terms coefficient −b0−12𝔼μ[∑n(xn−μ)2+λ0(μ−μ0)2]-b_0 - \tfrac12 \mathbb{E}_\mu\big[\sum_n (x_n - \mu)^2 + \lambda_0 (\mu - \mu_0)^2\big]: the log of a Gamma density, so q(τ)=Gamma(aN,bN)q(\tau) = \text{Gamma}(a_N, b_N) with aN=a0+N+12a_N = a_0 + \tfrac{N+1}{2} and bNb_N that bracket, which needs only 𝔼[μ]=μN\mathbb{E}[\mu] = \mu_N and 𝔼[μ2]=μN2+1/λN\mathbb{E}[\mu^2] = \mu_N^2 + 1/\lambda_N.
  4. Each update uses the other's current moments; alternate until nothing moves.

CAVI and its stochastic version (stochastic variational inference, Hoffman et al. 2013) scaled topic models to millions of documents. In deep learning the factors are replaced by a network that outputs qq (next), but "mean field" still names the diagonal-Gaussian qq of every standard VAE: its latents are independent given xx.

Amortised: one network outputs qq for every input

Classical VI optimises separate variational parameters for each data point. A VAE trains one network qϕ(z|x)q_\phi(z \mid x) for all of them: amortised inference (the cost of inference is paid once, in training, and spread over every future query). It is fast and works on new data, but the network may not output the best qq for each input. Cremer, Li and Duvenaud 2018 split the gap accordingly, with q∗q^{*} the best member of the family for that one input:

log⁡p(x)−ℒ[qϕ(z|x)]⏟total gap=log⁡p(x)−ℒ[q∗]⏟approximation gap+ℒ[q∗]−ℒ[qϕ(z|x)]⏟amortisation gap.\underbrace{\log p(x) - \mathcal{L}[q_\phi(z\mid x)]}_{\text{total gap}} = \underbrace{\log p(x) - \mathcal{L}[q^{*}]}_{\text{approximation gap}} + \underbrace{\mathcal{L}[q^{*}] - \mathcal{L}[q_\phi(z\mid x)]}_{\text{amortisation gap}} .

Cremer et al. found the same pattern on larger models: the amortisation gap often dominates; fixes include bigger encoders, iterative refinement of the encoder's output at test time, and semi-amortised VI. Diffusion models avoid the question: their "encoder" is fixed noise, not learned (section 6).

On a trained MNIST VAE, almost the whole gap is the encoder, not the Gaussian family

The 2-D-latent MNIST VAE trained for this page (its training run and latent map are on Autoencoders and VAEs, section 3), first 100 test images (src/data/vae_gap.py). With a 2-D latent, log⁡p(x)\log p(x) is computed almost exactly by quadrature, 161 by 161 decoder evaluations on a grid around each image's posterior: log⁡p(x)=−136.22\log p(x) = -136.22 nats on average. ELBO with the encoder's qq: −144.46-144.46, a total gap of 8.24 nats. ELBO with a Gaussian optimised separately for each image (2,000 Adam steps): −136.31-136.31. So the approximation gap is 0.10 (a diagonal Gaussian fits this model's posteriors almost perfectly) and the amortisation gap 8.15: the encoder is a poor per-image optimiser on test images. Importance weighting with the encoder as proposal reaches only −144.6-144.6 at K=1,000K = 1{,}000 (on 1,000 test images), which is why the quadrature is the truth here.

Richer families: when the Gaussian cannot reach

Model B's 0.71-nat gap needs a family that can bend and split. A normalising flow pushes a simple z0z_0 through invertible maps and keeps an exact density by the change-of-variables formula, log⁡qK(zK)=log⁡q0(z0)−∑klog⁡|det⁡∂fk/∂zk−1|\log q_K(z_K) = \log q_0(z_0) - \sum_k \log\left|\det \partial f_k/\partial z_{k-1}\right| (Rezende and Mohamed, "Variational Inference with Normalizing Flows"); the design problem is a cheap determinant (coupling and autoregressive layers make it triangular). IAF used as the VAE's qq is what fixes model B's problem at scale. Derived, with two checks and the layer types, in section 7.

5. Gradients through samples: score function against reparameterisation

With a neural qϕq_\phi there is no closed-form update; we need ∇ϕ\nabla_\phi of 𝔼z∼qϕ[fϕ(z)]\mathbb{E}_{z\sim q_\phi}[f_\phi(z)], with fϕ(z)=log⁡p(x,z)−log⁡qϕ(z)f_\phi(z) = \log p(x,z) - \log q_\phi(z), an average whose sampling distribution moves with the parameters. Probability for ML, section 11 introduces both estimators on f(x)=x2f(x) = x^2; here they are derived for the ELBO and pushed to the case that decides between them, many latent dimensions.

Score function (REINFORCE, likelihood ratio)

  1. Differentiate under the integral: ∇ϕ∫qϕfϕ=∫∇ϕqϕfϕ+∫qϕ∇ϕfϕ\nabla_\phi \int q_\phi f_\phi = \int \nabla_\phi q_\phi\, f_\phi + \int q_\phi\, \nabla_\phi f_\phi.
  2. Use ∇q=q∇log⁡q\nabla q = q\, \nabla \log q: the first integral is 𝔼q[fϕ∇ϕlog⁡qϕ]\mathbb{E}_q\big[f_\phi\, \nabla_\phi \log q_\phi\big]; ∇ϕlog⁡qϕ(z)\nabla_\phi \log q_\phi(z) is the score of qq.
  3. The second integral is −𝔼q[∇ϕlog⁡qϕ]=−∇ϕ∫qϕ=−∇ϕ1=0-\mathbb{E}_q[\nabla_\phi \log q_\phi] = -\nabla_\phi \int q_\phi = -\nabla_\phi 1 = 0: the score averages to zero.
∇ϕELBO=𝔼qϕ[fϕ(z)∇ϕlog⁡qϕ(z)].\nabla_\phi \text{ELBO} = \mathbb{E}_{q_\phi}\big[f_\phi(z)\,\nabla_\phi \log q_\phi(z)\big].

Try a zz, see how good it was, push qq towards it in proportion. No derivative of ff needed, so it works for discrete zz and non-differentiable rewards (Williams 1992), which is why policy gradients use it.

Reparameterisation (pathwise)

  1. Write the sample as a function of the parameters and of noise that does not depend on them: z=gϕ(ε)=μ+σεz = g_\phi(\varepsilon) = \mu + \sigma\varepsilon, ε∼𝒩(0,1)\varepsilon \sim \mathcal{N}(0, 1) (element-wise for a diagonal Gaussian; Kingma and Welling eq. 5 and 10).
  2. The average is now over ε\varepsilon, whose distribution has no ϕ\phi, so the gradient moves inside: ∇ϕ𝔼ε[fϕ(gϕ(ε))]=𝔼ε[∇ϕfϕ(gϕ(ε))]\nabla_\phi \mathbb{E}_\varepsilon[f_\phi(g_\phi(\varepsilon))] = \mathbb{E}_\varepsilon[\nabla_\phi f_\phi(g_\phi(\varepsilon))].
  3. The chain rule does the rest (∂z/∂μ=1\partial z/\partial\mu = 1, ∂z/∂σ=ε\partial z/\partial \sigma = \varepsilon); autograd treats the sample as one more node.

It uses the slope of ff at the sample, not only its value: one sample already says which way is uphill.

Model A: the gradient of the ELBO with respect to qq's mean, at q=𝒩(0.5,0.52)q = \mathcal{N}(0.5, 0.5^2)

True value: ∂∂mELBO=x−ms2−m=1.00.25−0.5=3.5\frac{\partial}{\partial m}\text{ELBO} = \frac{x - m}{s^2} - m = \frac{1.0}{0.25} - 0.5 = 3.5. Pathwise, one sample gives x−zs2−z\frac{x - z}{s^2} - z (the log⁡q\log q term has no mm once z=m+σεz = m + \sigma\varepsilon); zz enters linearly with slope −(1/s2+1)=−5-(1/s^2 + 1) = -5, so the variance is exactly 25⋅σ2=6.2525 \cdot \sigma^2 = 6.25. Score function, one sample: f(z)(z−m)/σ2f(z)\,(z - m)/\sigma^2, variance 71 by simulation, 25 with a baseline (the average of ff, the ELBO itself) subtracted from ff. Both average to 3.5. Now give the latent dd dimensions (dd independent copies of model A) and ask for the gradient with respect to the first mean: pathwise looks only at coordinate 1, while the score function multiplies the whole ff, a sum of dd noisy terms, by coordinate 1's score.

Same mean, different noise: the score function's variance grows with the dimension, pathwise stays at 6.25

Variance of one-sample estimates (log scale), 400,000 draws each, model A copied dd times. At d=100d = 100 the score-function estimator needs about 65,000 times as many samples as the pathwise one for the same precision (variance 403,466 against 6.25), and still 200 times as many with a baseline (1,256).

A VAE latent has 16 to a few hundred dimensions. That gap is why the reparameterisation trick made VAEs trainable, and why the score function lives on in RL only with heavy variance reduction (baselines, advantages: Policy gradients and actor-critic).

When you cannot reparameterise
Discrete latents (a category, a token) have no smooth gϕg_\phi. Options: the score function with baselines (control variates); the Gumbel-softmax relaxation, a differentiable approximation to a categorical sample (Probability for ML, section 10); or straight-through estimators, which VQ-VAE uses to pass gradients through its codebook lookup (van den Oord et al. 2017).

Fit qq by gradient ascent with either estimator: same destination, different paths

Predict first: with 1 sample per step and step size 0.03, which estimator's ELBO trace wobbles more?

Starts from the qq set in section 3's widget (model A by default) and moves it there too. Gradient ascent on (m,log⁡σ)(m, \log\sigma), seeded so a run repeats exactly. The pathwise estimator uses the slope of log⁡p(x,z)\log p(x, z) at each sample and the closed-form entropy of qq; the score-function estimator uses only the values of log⁡p(x,z)−log⁡q(z)\log p(x,z) - \log q(z), times the score of qq. Both are unbiased; the trace plots the exact ELBO of the current qq.

6. Where the ELBO reappears: VAEs and diffusion

The VAE (Kingma and Welling 2013; Rezende, Mohamed and Wierstra 2014) is sections 3 to 5 with networks: an encoder outputs a diagonal Gaussian qϕ(z|x)q_\phi(z\mid x) (amortised, section 4), a decoder outputs pθ(x|z)p_\theta(x\mid z), the prior is 𝒩(0,I)\mathcal{N}(0, I), and the loss is minus the "reconstruction minus KL" ELBO of section 3 (Kingma and Welling eq. 3 and 7) with one reparameterised sample per image (section 5; their section 2.3). The KL has a closed form, 12∑j(μj2+σj2−1−log⁡σj2)\frac12 \sum_{j} (\mu_j^2 + \sigma_j^2 - 1 - \log \sigma_j^2) (their Appendix B, derived in section 7; 1.750 nats for μ=(1,−0.5)\mu = (1, -0.5), σ=(0.5,2)\sigma = (0.5, 2)). Two consequences are pure ELBO maths: only β=1\beta = 1 on the KL is a bound on log⁡p(x)\log p(x) (a β\beta-VAE trains a rate-distortion objective, Alemi et al. 2018), and the KL is minimised, to 0, by q(z|x)=p(z)q(z\mid x) = p(z), so a decoder that reconstructs well without zz gives nothing a reason to move away: posterior collapse. The model itself (architectures, the units of the loss, the blur, collapse and its fixes, VQ-VAE, the latent scaling factor of latent diffusion) is taught on Autoencoders and VAEs; the MNIST VAE trained for this page, its training curves, latent map and a β\beta sweep, are measured there (sections 3 and 5, closed blocks).

Fig. 5 and Fig. 6 are the same bound with two choices of qq: learned and one-step (VAE), fixed and many-step (diffusion).

  1. Encoder. One image goes through the encoder, which outputs a diagonal Gaussian qϕ(z|x)q_\phi(z\mid x): a mean and a standard deviation per latent dimension. The figure's two-dimensional latent uses D1's worked numbers, μ=(1,−0.5)\mu = (1, -0.5), σ=(0.5,2)\sigma = (0.5, 2) (illustrative; the plates stand for networks and carry no weights).
  2. Noise from the side. z=μ+σ⊙εz = \mu + \sigma \odot \varepsilon with ε∼𝒩(0,I)\varepsilon \sim \mathcal{N}(0, I) drawn outside the network (section 5). The dots are 40 seeded draws: an ellipse of samples on the latent plane, against the prior's rings.
  3. Decoder. Each zz goes through the decoder, which outputs pθ(x|z)p_\theta(x\mid z); the reconstruction term 𝔼q[log⁡pθ(x|z)]\mathbb{E}_q[\log p_\theta(x\mid z)] is estimated with one sample per image.
  4. The KL to the prior. qq's ellipses (1 and 2 sd) against the rings of 𝒩(0,I)\mathcal{N}(0, I): 12(μ2+σ2−1−log⁡σ2)\tfrac12(\mu^2 + \sigma^2 - 1 - \log\sigma^2) per dimension, 0.818 and 0.932, so 1.750 nats. The loss is minus the ELBO: reconstruction minus this KL.
  5. Gradients come back. Autograd runs back through the decoder and through z=μ+σεz = \mu + \sigma\varepsilon (∂z/∂μ=1\partial z/\partial\mu = 1, ∂z/∂σ=ε\partial z/\partial\sigma = \varepsilon) into the encoder; ε\varepsilon has no parameters and gets no gradient. A VAE learns both arrows.

Diffusion is a latent-variable model with latents x1:Tx_{1:T}, each a noisier copy of the data, whose q(x1:T|x0)q(x_{1:T}\mid x_0) is fixed Gaussian noise rather than learned, so there is no amortisation gap to train away. Its ELBO (Ho et al. eq. 3 and 5) telescopes into LT+∑t>1Lt−1+L0L_T + \sum_{t>1} L_{t-1} + L_0, each Lt−1L_{t-1} a KL between two Gaussians with a closed form; writing the true reverse step's mean in terms of the added noise turns each KL into a weighted squared error on the noise, and dropping the weights gives Ho et al.'s one-line loss Lsimple=𝔼‖ε−εθ(xt,t)‖2L_{\text{simple}} = \mathbb{E}\,\|\varepsilon - \varepsilon_\theta(x_t, t)\|^2. That drop is a choice: the true bound weighs t=1t = 1 about 80 times more than t=200t = 200, so LsimpleL_{\text{simple}} is a reweighted ELBO, better samples for slightly worse likelihood. The eight steps, the score view, DDIM, guidance and flow matching are derived in section 7; the models, schedules, samplers and guidance in practice are Diffusion from zero, Flow matching and rectified flow and Latent diffusion and diffusion transformers.

  1. Data at t=0t = 0. 200 of D3's two-moons points, and the worked point x0=(0.5,−0.2)x_0 = (0.5, -0.2) (highlighted).
  2. Forward: add noise, fixed. Each q(xt|xt−1)q(x_t\mid x_{t-1}) adds Gaussian noise and has no parameters. On the linear schedule the signal fraction left, α‾t\bar\alpha_t, is 0.897 at t=100t = 100, 0.659 at 200, 0.0786 at 500 and 4.0×10−54.0\times10^{-5} at 1000: the data is gone.
  3. Any noise level in one jump. q(xt|x0)=𝒩(α‾tx0,(1−α‾t)I)q(x_t\mid x_0) = \mathcal{N}(\sqrt{\bar\alpha_t}\,x_0, (1-\bar\alpha_t)I) (D3). With ε=(1,−0.5)\varepsilon = (1, -0.5): x200=0.8118x0+0.5839ε=(0.9898,−0.4543)x_{200} = 0.8118\,x_0 + 0.5839\,\varepsilon = (0.9898, -0.4543). Training draws tt and the noise; it never runs the chain.
  4. Reverse: learned denoisers. Only the reverse steps pθ(xt−1|xt)p_\theta(x_{t-1}\mid x_t) are learned. The ELBO is two end terms plus one KL between Gaussians per step, each against the true reverse step given x0x_0 (D4).
  5. The weight of each step in the bound. Written in terms of the noise, step tt's KL carries the weight βt/(2αt(1−α‾t))\beta_t/(2\alpha_t(1-\bar\alpha_t)): 0.50 at t=1t = 1, 0.0101 at 100, 0.0060 at 200, 0.0055 at 500, 0.0102 at 1000.
  6. LsimpleL_{\text{simple}} drops the weights. Ho et al. weigh every step the same and predict the noise: a reweighted ELBO, which gives up a little likelihood for better samples (D4).

7. Derivations the generative pages use

Each block derives one result that the model pages cite rather than re-derive; all are optional on a first read. The closed forms are recomputed and checked by Monte Carlo or an independent route in src/recompute.py. In order: the Gaussian KL of every VAE loss; normalising flows (the richer family of section 4); the diffusion forward process; the diffusion ELBO down to "predict the noise"; scores and the SDE view; DDIM; classifier-free guidance; flow matching.

D1. The Gaussian KL in closed form (Kingma and Welling, Appendix B), and the loss in code (derivation)

One dimension first: q=𝒩(μ,σ2)q = \mathcal{N}(\mu, \sigma^2), p=𝒩(0,1)p = \mathcal{N}(0, 1).

  1. Definition: DKL(q‖p)=𝔼q[log⁡q(z)−log⁡p(z)]D_{\mathrm{KL}}(q\Vert p) = \mathbb{E}_q[\log q(z) - \log p(z)].
  2. Write both log-densities: log⁡q(z)=−12log⁡(2πσ2)−(z−μ)22σ2\log q(z) = -\tfrac12\log(2\pi\sigma^2) - \frac{(z-\mu)^2}{2\sigma^2} and log⁡p(z)=−12log⁡2π−z22\log p(z) = -\tfrac12 \log 2\pi - \frac{z^2}{2}.
  3. Subtract; the log⁡2π\log 2\pi cancels: log⁡q−log⁡p=−12log⁡σ2−(z−μ)22σ2+z22\log q - \log p = -\tfrac12 \log \sigma^2 - \frac{(z-\mu)^2}{2\sigma^2} + \frac{z^2}{2}.
  4. Average under qq, using 𝔼q[(z−μ)2]=σ2\mathbb{E}_q[(z - \mu)^2] = \sigma^2 (definition of variance) and 𝔼q[z2]=μ2+σ2\mathbb{E}_q[z^2] = \mu^2 + \sigma^2 (variance plus squared mean): −12log⁡σ2−12+12(μ2+σ2)-\tfrac12\log\sigma^2 - \tfrac12 + \tfrac12(\mu^2 + \sigma^2).
  5. Collect, and sum over the JJ independent dimensions of a diagonal Gaussian (the KL of independent factors adds):
DKL(𝒩(μ,diag⁡σ2)‖𝒩(0,I))=12∑j=1J(μj2+σj2−1−log⁡σj2).D_{\mathrm{KL}}\big(\mathcal{N}(\mu, \operatorname{diag}\sigma^2) \,\Vert\, \mathcal{N}(0, I)\big) = \frac12 \sum_{j=1}^{J} \big(\mu_j^2 + \sigma_j^2 - 1 - \log \sigma_j^2\big).

Each dimension pays for its mean being away from 0 (μ2\mu^2) and for its spread being anything but 1 (σ2−1−log⁡σ2\sigma^2 - 1 - \log\sigma^2, zero at σ=1\sigma = 1, growing as σ\sigma shrinks or grows). Kingma and Welling print it as 12∑j(1+log⁡σj2−μj2−σj2)\frac12\sum_j(1 + \log\sigma_j^2 - \mu_j^2 - \sigma_j^2), the negative KL, because they maximise.

Worked and checked

μ=(1,−0.5)\mu = (1, -0.5), σ=(0.5,2)\sigma = (0.5, 2): dimension 1 gives 12(1+0.25−1−log⁡0.25)=0.818\tfrac12(1 + 0.25 - 1 - \log 0.25) = 0.818 (the same number as the Information theory page's example), dimension 2 gives 12(0.25+4−1−log⁡4)=0.932\tfrac12(0.25 + 4 - 1 - \log 4) = 0.932; total 1.750 nats. A two-million-sample Monte Carlo average of log⁡q−log⁡p\log q - \log p gives 1.749 (standard error 0.002).

The whole loss, in code

This is the loss the page's VAE was trained with (from src/data/vae.py, PyTorch 2; log⁡σ2\log\sigma^2 is predicted rather than σ\sigma so it can take any real value):

mu, logvar = encoder(x)                      # [batch, J] each
z = mu + torch.exp(0.5 * logvar) * torch.randn_like(mu)   # reparameterised sample
logits = decoder(z)                          # [batch, 784]
rec = F.binary_cross_entropy_with_logits(logits, x, reduction='none').sum(-1)  # -log p(x|z)
kl = 0.5 * (mu**2 + logvar.exp() - 1 - logvar).sum(-1)                          # closed form
loss = (rec + beta * kl).mean()              # beta = 1: minus the ELBO
Two common bugs in this snippet's neighbours
Averaging the reconstruction over pixels (reduction='mean') while summing the KL over dimensions silently multiplies the KL weight by 784: the model then behaves like a heavily over-weighted beta-VAE (see Autoencoders and VAEs) and its samples blur. And the BCE loss on grey-level pixels is not the likelihood of any normalised distribution over grey levels (Loaiza-Ganem and Cunningham 2019, the continuous Bernoulli), so a "log-likelihood" computed that way is not comparable across papers; binarise the data, as here, or use a proper continuous likelihood.
D2. Normalising flows: the change-of-variables formula (derivation)

Idea: start from a simple random variable zz and push it through an invertible function x=f(z)x = f(z). Where ff stretches space, probability thins out; where it squeezes, it piles up. The change-of-variables formula keeps the books.

  1. One dimension, ff increasing: the probability in a small interval is preserved, px(x)|dx|=pz(z)|dz|p_x(x)\,|dx| = p_z(z)\,|dz|.
  2. So px(x)=pz(z)|dzdx|=pz(f−1(x))|dfdz|−1p_x(x) = p_z(z) \left|\frac{dz}{dx}\right| = p_z\big(f^{-1}(x)\big)\, \left|\frac{df}{dz}\right|^{-1}.
  3. In DD dimensions the stretch factor of a small volume is the absolute determinant of the Jacobian matrix ∂f/∂z\partial f/\partial z (Matrix calculus and backprop, section 1; the determinant is the volume scaling of a linear map, Linear algebra for ML). In logs:
log⁡px(x)=log⁡pz(z)−log⁡|det⁡∂f∂z|,z=f−1(x).\log p_x(x) = \log p_z(z) - \log\left|\det \frac{\partial f}{\partial z}\right|, \qquad z = f^{-1}(x).
Two checks

z∼𝒩(0,1)z \sim \mathcal{N}(0,1), x=2z+1x = 2z + 1: at x=3x = 3, z=1z = 1, df/dz=2df/dz = 2, so px(3)=𝒩(1;0,1)/2=0.2420/2=0.121p_x(3) = \mathcal{N}(1; 0, 1)/2 = 0.2420/2 = 0.121; the log-determinant is log⁡2=0.693\log 2 = 0.693. x=ezx = e^{z} (the log-normal): at x=2x = 2, z=ln⁡2z = \ln 2, df/dz=ez=2df/dz = e^z = 2, so px(2)=𝒩(0.693)/2=0.1569p_x(2) = \mathcal{N}(0.693)/2 = 0.1569; counting four million samples falling in [1.99,2.01][1.99, 2.01] gives 0.158.

A normalising flow composes KK such maps, zK=fK∘⋯∘f1(z0)z_K = f_K \circ \dots \circ f_1(z_0), and the log-densities add up (Rezende and Mohamed "Variational Inference with Normalizing Flows", eq. 6 to 7): log⁡qK(zK)=log⁡q0(z0)−∑k=1Klog⁡|det⁡∂fk∂zk−1|\log q_K(z_K) = \log q_0(z_0) - \sum_{k=1}^K \log\left|\det \frac{\partial f_k}{\partial z_{k-1}}\right|. The whole design problem is making that determinant cheap: a general D×DD \times D determinant costs O(D3)O(D^3).

  • Coupling layers (RealNVP, Dinh, Sohl-Dickstein and Bengio 2016): split zz into halves (a,b)(a, b); keep aa; set b′=b⊙es(a)+t(a)b' = b \odot e^{s(a)} + t(a) with any networks s,ts, t. The Jacobian is triangular, so its determinant is the product of the diagonal, exp⁡(∑s(a))\exp(\sum s(a)): one sum. Inverting needs no inverse of ss or tt.
  • Autoregressive flows (IAF, Kingma et al. 2016; MAF): each coordinate depends only on earlier ones, again a triangular Jacobian. IAF used as the VAE's qq is what fixes model B's problem at scale: the approximate posterior can bend and split.
  • Continuous flows: let K→∞K \to \infty with tiny steps, dz/dt=v(z,t)dz/dt = v(z, t). The log-density then changes at the rate −tr⁡(∂v/∂z)-\operatorname{tr}(\partial v/\partial z) (the instantaneous change of variables, Chen et al. 2018, Neural ODEs). Flow matching (D8) trains exactly such a vv, without ever computing the trace during training.
D3. Diffusion: the forward process, its closed form, and two schedules (derivation)

Take a data point x0x_0 (an image; here a 2-D point). The forward process adds a little Gaussian noise TT times (Ho et al. 2020 eq. 2; Sohl-Dickstein et al. 2015 introduced the idea):

q(xt|xt−1)=𝒩(xt; 1−βtxt−1, βtI),t=1,…,T.q(x_t \mid x_{t-1}) = \mathcal{N}\big(x_t;\ \sqrt{1-\beta_t}\, x_{t-1},\ \beta_t I\big), \qquad t = 1, \dots, T.
βt\beta_t
the noise variance added at step tt, from a fixed schedule; Ho et al. use T=1000T = 1000 and βt\beta_t rising linearly from 10−410^{-4} to 0.02.
1−βt\sqrt{1-\beta_t}
a slight shrink of the previous value, so the total variance stays bounded instead of growing.
αt, α‾t\alpha_t,\ \bar\alpha_t
shorthand: αt=1−βt\alpha_t = 1 - \beta_t, and α‾t=∏s=1tαs\bar\alpha_t = \prod_{s=1}^t \alpha_s, the signal fraction left after tt steps (the bar is a product, not an average).

Read it as "xt=αtxt−1+1−αtεtx_t = \sqrt{\alpha_t}\, x_{t-1} + \sqrt{1-\alpha_t}\,\varepsilon_t" with fresh noise εt∼𝒩(0,I)\varepsilon_t \sim \mathcal{N}(0, I) each step: in the VAE language of section 6, this is a reparameterised encoder with no trainable parameters.

The closed form, derived by induction (Ho et al. eq. 4)

  1. Claim: xt=α‾tx0+1−α‾tε‾x_t = \sqrt{\bar\alpha_t}\, x_0 + \sqrt{1 - \bar\alpha_t}\, \bar\varepsilon for a standard Gaussian ε‾\bar\varepsilon. True at t=1t = 1, since α‾1=α1\bar\alpha_1 = \alpha_1.
  2. Assume it for t−1t - 1 and substitute:
    xt=αt(α‾t−1x0+1−α‾t−1ε‾′)+1−αtεtx_t = \sqrt{\alpha_t}\big(\sqrt{\bar\alpha_{t-1}}\, x_0 + \sqrt{1 - \bar\alpha_{t-1}}\, \bar\varepsilon'\big) + \sqrt{1 - \alpha_t}\, \varepsilon_t
    .
  3. The signal part is αtα‾t−1x0=α‾tx0\sqrt{\alpha_t \bar\alpha_{t-1}}\, x_0 = \sqrt{\bar\alpha_t}\, x_0.
  4. The two noise parts are independent zero-mean Gaussians; independent variances add: αt(1−α‾t−1)+(1−αt)=1−αtα‾t−1=1−α‾t\alpha_t(1 - \bar\alpha_{t-1}) + (1 - \alpha_t) = 1 - \alpha_t \bar\alpha_{t-1} = 1 - \bar\alpha_t. A Gaussian with that variance is 1−α‾tε‾\sqrt{1 - \bar\alpha_t}\,\bar\varepsilon. Done:
q(xt|x0)=𝒩(xt; α‾tx0, (1−α‾t)I).q(x_t \mid x_0) = \mathcal{N}\big(x_t;\ \sqrt{\bar\alpha_t}\, x_0,\ (1 - \bar\alpha_t) I\big).

Any noise level in one jump: training never runs the chain, it draws tt and noise and computes xtx_t in one line. If the data has unit variance, so does every xtx_t (α‾t+1−α‾t=1\bar\alpha_t + 1 - \bar\alpha_t = 1): the "variance-preserving" process.

Worked, and checked by running the chain

The root's example (Topic: math, Notation decoder, "Diffusion training loss"): x0=(0.5,−0.2)x_0 = (0.5, -0.2), ε=(1,−0.5)\varepsilon = (1, -0.5), t=200t = 200 on the linear schedule. α‾200=∏s≤200(1−βs)=0.6590\bar\alpha_{200} = \prod_{s \le 200}(1 - \beta_s) = 0.6590, so α‾=0.8118\sqrt{\bar\alpha} = 0.8118, 1−α‾=0.5839\sqrt{1 - \bar\alpha} = 0.5839, and x200=0.8118x0+0.5839ε=(0.9898,−0.4543)x_{200} = 0.8118\,x_0 + 0.5839\,\varepsilon = (0.9898, -0.4543).

Monte Carlo: 200,000 copies of x0x_0 pushed through all 200 single steps, fresh noise each step. Mean (0.4049,−0.1627)(0.4049, -0.1627) against α‾x0=(0.4059,−0.1624)\sqrt{\bar\alpha}\,x_0 = (0.4059, -0.1624) (standard error 0.0013); variance 0.342 against 1−α‾=0.3411 - \bar\alpha = 0.341. After all 1,000 steps: variance 1.001 and 1.007 against 1−4.0×10−51 - 4.0 \times 10^{-5}; the data is gone.

Two schedules. Left: α‾t\bar\alpha_t, the signal fraction left, for the linear schedule (Ho et al.) and the cosine schedule (Nichol and Dhariwal 2021, eq. 17: α‾t=f(t)/f(0)\bar\alpha_t = f(t)/f(0), f(t)=cos2⁡(t/T+0.0081.008⋅π2)f(t) = \cos^2\!\big(\frac{t/T + 0.008}{1.008}\cdot\frac{\pi}{2}\big), βt\beta_t clipped at 0.999). Right: 400 two-moons points at the chosen step, xtx_t drawn from the closed form.

Why a second schedule. On the linear schedule α‾500=0.079\bar\alpha_{500} = 0.079: by the halfway point only 8% of the signal variance is left, and "the latents in the last quarter of the linear schedule are almost purely noise" (Nichol and Dhariwal 2021, section 3.2), so those steps teach little. The cosine schedule keeps α‾500=0.494\bar\alpha_{500} = 0.494 and drops roughly linearly in the middle. A useful single number per step is the signal-to-noise ratio SNR(t)=α‾t/(1−α‾t)\text{SNR}(t) = \bar\alpha_t/(1-\bar\alpha_t), usually as its log λt\lambda_t: linear runs from λ=9.2\lambda = 9.2 to −10.1-10.1, cosine from 10.1 to −12.9-12.9 at t=999t = 999 and −19.8-19.8 at t=1000t = 1000, where the 0.999 clip leaves α‾=2.4×10−9\bar\alpha = 2.4\times 10^{-9}. Kingma et al. 2021 (Variational Diffusion Models) show that in continuous time the ELBO depends on the schedule only through its two end values of SNR; schedules change which noise levels training spends its effort on.

D4. The reverse process and the diffusion ELBO, down to "predict the noise" (eight steps) (derivation)

The model. Generation runs the chain backwards: start from pure noise p(xT)=𝒩(0,I)p(x_T) = \mathcal{N}(0, I) and apply learned Gaussian steps (Ho et al. eq. 1)

pθ(xt−1|xt)=𝒩(xt−1; μθ(xt,t), σt2I),p_\theta(x_{t-1} \mid x_t) = \mathcal{N}\big(x_{t-1};\ \mu_\theta(x_t, t),\ \sigma_t^2 I\big),

with σt2\sigma_t^2 fixed (Ho et al. use βt\beta_t or β~t\tilde\beta_t, below). This is a latent-variable model with latents z=x1:Tz = x_{1:T}, and the forward process of D3 is its q(z|x0)q(z \mid x_0). Reverse steps can be Gaussian because, for small βt\beta_t, the true reverse of a small Gaussian step is itself close to Gaussian (Sohl-Dickstein et al. 2015, citing Feller).

  1. The ELBO, as in section 3 with z=x1:Tz = x_{1:T} (Ho et al. eq. 3):
    −log⁡pθ(x0)≤𝔼q[−log⁡pθ(x0:T)q(x1:T|x0)]=𝔼q[−log⁡p(xT)−∑t≥1log⁡pθ(xt−1|xt)q(xt|xt−1)]=:L-\log p_\theta(x_0) \le \mathbb{E}_q\Big[-\log \frac{p_\theta(x_{0:T})}{q(x_{1:T}\mid x_0)}\Big] = \mathbb{E}_q\Big[-\log p(x_T) - \sum_{t \ge 1} \log \frac{p_\theta(x_{t-1}\mid x_t)}{q(x_t \mid x_{t-1})}\Big] =: L
    . Both chains factorise step by step, so the log of the ratio is a sum.
  2. Turn each forward step around with Bayes' rule. The forward chain is Markov, so q(xt|xt−1)=q(xt|xt−1,x0)q(x_t \mid x_{t-1}) = q(x_t \mid x_{t-1}, x_0), and Bayes' rule gives q(xt|xt−1,x0)=q(xt−1|xt,x0)q(xt|x0)q(xt−1|x0)q(x_t\mid x_{t-1}, x_0) = \frac{q(x_{t-1}\mid x_t, x_0)\, q(x_t \mid x_0)}{q(x_{t-1}\mid x_0)}. Use it for every t≥2t \ge 2.
  3. Telescope. The extra factors q(xt|x0)q(xt−1|x0)\frac{q(x_t\mid x_0)}{q(x_{t-1}\mid x_0)} for t=2..Tt = 2..T multiply to q(xT|x0)q(x1|x0)\frac{q(x_T\mid x_0)}{q(x_1\mid x_0)}: every middle term cancels.
  4. Regroup (Ho et al. eq. 5, derived in their Appendix A):
L=𝔼q[DKL(q(xT|x0)‖p(xT))⏟LT+∑t>1DKL(q(xt−1|xt,x0)‖pθ(xt−1|xt))⏟Lt−1−log⁡pθ(x0|x1)⏟L0].L = \mathbb{E}_q\Big[\underbrace{D_{\mathrm{KL}}\big(q(x_T\mid x_0)\,\Vert\, p(x_T)\big)}_{L_T} + \sum_{t>1} \underbrace{D_{\mathrm{KL}}\big(q(x_{t-1}\mid x_t, x_0)\,\Vert\, p_\theta(x_{t-1}\mid x_t)\big)}_{L_{t-1}} \underbrace{-\log p_\theta(x_0 \mid x_1)}_{L_0}\Big].

LTL_T: how far the fully noised data is from pure noise; no parameters, and tiny (for x0=1x_0 = 1 on the linear schedule, 12(α‾Tx02−α‾T−log⁡(1−α‾T))≈2×10−5\tfrac12(\bar\alpha_T x_0^2 - \bar\alpha_T - \log(1 - \bar\alpha_T)) \approx 2\times10^{-5} nats per dimension). Lt−1L_{t-1}: at every step, the learned reverse step against the true reverse step given the clean data. L0L_0: the final decoder. Every term compares Gaussians, so it has a closed form: no high-variance sampling of the whole chain.

  1. The true reverse step given x0x_0 (Ho et al. eq. 6 to 7). As a function of xt−1x_{t-1}, q(xt−1|xt,x0)∝q(xt|xt−1)q(xt−1|x0)q(x_{t-1}\mid x_t, x_0) \propto q(x_t \mid x_{t-1})\, q(x_{t-1} \mid x_0), a product of two Gaussians in xt−1x_{t-1}. Its exponent is −12[(xt−αtxt−1)2βt+(xt−1−α‾t−1x0)21−α‾t−1]-\tfrac12\Big[\frac{(x_t - \sqrt{\alpha_t}x_{t-1})^2}{\beta_t} + \frac{(x_{t-1} - \sqrt{\bar\alpha_{t-1}}x_0)^2}{1-\bar\alpha_{t-1}}\Big]. Complete the square: the coefficient of xt−12x_{t-1}^2 gives the precision αtβt+11−α‾t−1=1−α‾tβt(1−α‾t−1)\frac{\alpha_t}{\beta_t} + \frac{1}{1-\bar\alpha_{t-1}} = \frac{1 - \bar\alpha_t}{\beta_t(1-\bar\alpha_{t-1})} (using αt(1−α‾t−1)+βt=1−α‾t\alpha_t(1-\bar\alpha_{t-1}) + \beta_t = 1 - \bar\alpha_t); the linear terms give the mean. Result:
q(xt−1|xt,x0)=𝒩(μ~t,β~tI),μ~t=α‾t−1βt1−α‾tx0+αt(1−α‾t−1)1−α‾txt,β~t=1−α‾t−11−α‾tβt.\begin{gathered} q(x_{t-1}\mid x_t, x_0) = \mathcal{N}(\tilde\mu_t, \tilde\beta_t I), \\ \tilde\mu_t = \frac{\sqrt{\bar\alpha_{t-1}}\,\beta_t}{1-\bar\alpha_t}\, x_0 + \frac{\sqrt{\alpha_t}\,(1 - \bar\alpha_{t-1})}{1-\bar\alpha_t}\, x_t, \\ \tilde\beta_t = \frac{1-\bar\alpha_{t-1}}{1-\bar\alpha_t}\,\beta_t . \end{gathered}
At t=200t = 200, linear schedule

μ~200=0.009696x0+0.990095x200\tilde\mu_{200} = 0.009696\, x_0 + 0.990095\, x_{200} and β~200=0.004032\tilde\beta_{200} = 0.004032 (against β200=0.004064\beta_{200} = 0.004064). The same three numbers come out of conditioning the joint Gaussian of (x199,x200)(x_{199}, x_{200}) given x0x_0 by the textbook formula (μ1|2=μ1+Σ12Σ22−1(x2−μ2)\mu_{1|2} = \mu_1 + \Sigma_{12}\Sigma_{22}^{-1}(x_2 - \mu_2)), in src/recompute.py. Given the noisy point, the clean data barely moves the next step: one more reason each step is easy to learn.

  1. KL between Gaussians with the same variance is a squared distance between means: with pθ=𝒩(μθ,σt2I)p_\theta = \mathcal{N}(\mu_\theta, \sigma_t^2 I), Lt−1=𝔼q[12σt2‖μ~t(xt,x0)−μθ(xt,t)‖2]+CL_{t-1} = \mathbb{E}_q\Big[\frac{1}{2\sigma_t^2}\big\|\tilde\mu_t(x_t, x_0) - \mu_\theta(x_t, t)\big\|^2\Big] + C (Ho et al. eq. 8; CC collects the variance terms, which do not depend on θ\theta). So the network should predict μ~t\tilde\mu_t.
  2. Write μ~t\tilde\mu_t in terms of the noise. From D3, x0=(xt−1−α‾tε)/α‾tx_0 = (x_t - \sqrt{1-\bar\alpha_t}\,\varepsilon)/\sqrt{\bar\alpha_t}. Substitute into μ~t\tilde\mu_t. Using α‾t−1/α‾t=1/αt\sqrt{\bar\alpha_{t-1}}/\sqrt{\bar\alpha_t} = 1/\sqrt{\alpha_t}, the coefficient of xtx_t becomes βt+αt(1−α‾t−1)(1−α‾t)αt=1αt\frac{\beta_t + \alpha_t(1-\bar\alpha_{t-1})}{(1-\bar\alpha_t)\sqrt{\alpha_t}} = \frac{1}{\sqrt{\alpha_t}}, and the coefficient of ε\varepsilon becomes −βtαt1−α‾t-\frac{\beta_t}{\sqrt{\alpha_t}\sqrt{1-\bar\alpha_t}}. So (Ho et al. eq. 10) μ~t=1αt(xt−βt1−α‾tε)\tilde\mu_t = \frac{1}{\sqrt{\alpha_t}}\Big(x_t - \frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\varepsilon\Big).
  3. Parameterise the network the same way (Ho et al. eq. 11): μθ(xt,t)=1αt(xt−βt1−α‾tεθ(xt,t))\mu_\theta(x_t, t) = \frac{1}{\sqrt{\alpha_t}}\Big(x_t - \frac{\beta_t}{\sqrt{1-\bar\alpha_t}}\,\varepsilon_\theta(x_t, t)\Big). The xtx_t parts cancel in the difference of means, leaving only the noise:
Lt−1−C=𝔼x0,ε[βt22σt2αt(1−α‾t)×‖ε−εθ(α‾tx0+1−α‾tε, t)‖2]\begin{aligned} L_{t-1} - C = \mathbb{E}_{x_0, \varepsilon}\Big[&\frac{\beta_t^2}{2\sigma_t^2\,\alpha_t\,(1-\bar\alpha_t)} \\ &\times\big\|\varepsilon - \varepsilon_\theta\big(\sqrt{\bar\alpha_t}\,x_0 + \sqrt{1-\bar\alpha_t}\,\varepsilon,\ t\big)\big\|^2\Big] \end{aligned}

(Ho et al. eq. 12)

The last step is a choice, not a derivation. Ho et al. drop the weight in front and sample tt uniformly: Lsimple=𝔼t,x0,ε‖ε−εθ(⋅,t)‖2L_{\text{simple}} = \mathbb{E}_{t, x_0, \varepsilon}\big\|\varepsilon - \varepsilon_\theta(\cdot, t)\big\|^2 (eq. 14). With σt2=βt\sigma_t^2 = \beta_t the dropped weight is βt2αt(1−α‾t)\frac{\beta_t}{2\alpha_t(1-\bar\alpha_t)}:

tt12101002005001000
weight0.500.270.0740.0100.00600.00550.010

The true ELBO puts about 80 times more weight on t=1t = 1 than on t=200t = 200. In Ho et al.'s words, the simplified objective "down-weight[s] loss terms corresponding to small t. These terms train the network to denoise data with very small amounts of noise, so it is beneficial to down-weight them so that the network can focus on more difficult denoising tasks at larger t terms" (section 3.4). So LsimpleL_{\text{simple}} is a reweighted ELBO: better samples, slightly worse likelihood (their Table 1: FID 3.17 against 13.51, test bound 3.75 against 3.70 bits per dimension on CIFAR-10). Later work treats the weighting as a design knob: Kingma and Gao 2023 show that with any monotonic weighting the diffusion objective equals the ELBO of the data with Gaussian noise augmentation.

Go deeper (optional): the DDPM paper page trains four toy DDPMs that differ only in what the network predicts and which loss it uses (its Table 2), with a forward and reverse animation on a Swiss roll and a learned score field; the root's Notation decoder reads eq. 14 symbol by symbol.
D5. Score matching: predicting the noise is estimating a gradient (Tweedie, the SDE and the probability flow ODE) (derivation)

The score of a distribution is the gradient of its log-density with respect to the data, s(x)=∇xlog⁡p(x)s(x) = \nabla_x \log p(x): an arrow at every point, pointing towards higher density. (Not the score of section 5, which was a gradient with respect to parameters; statistics uses the word for both.) Two facts make it useful:

  • It ignores normalisation. If p=p~/Zp = \tilde p/Z, then ∇xlog⁡p=∇xlog⁡p~\nabla_x \log p = \nabla_x \log \tilde p: the intractable constant disappears.
  • It is enough to sample. Langevin dynamics repeats x←x+η2s(x)+ηzx \leftarrow x + \tfrac{\eta}{2}\, s(x) + \sqrt{\eta}\, z with z∼𝒩(0,I)z \sim \mathcal{N}(0, I); for small steps and long runs its samples follow pp (Song and Ermon 2019, eq. 4).

Learning a score without knowing it. Minimising 𝔼‖sθ(x)−∇log⁡p(x)‖2\mathbb{E}\|s_\theta(x) - \nabla\log p(x)\|^2 needs the unknown true score. Two tricks remove it. Hyvärinen 2005 integrated by parts to get an objective with only sθs_\theta and its divergence. Vincent 2011 showed that for noised data the target can be the score of the noising kernel, which is known: denoising score matching. For our kernel q(xt|x0)=𝒩(α‾tx0,(1−α‾t)I)q(x_t\mid x_0) = \mathcal{N}(\sqrt{\bar\alpha_t}x_0, (1-\bar\alpha_t)I):

∇xtlog⁡q(xt|x0)=−xt−α‾tx01−α‾t=−ε1−α‾t.\nabla_{x_t} \log q(x_t \mid x_0) = -\frac{x_t - \sqrt{\bar\alpha_t}x_0}{1-\bar\alpha_t} = -\frac{\varepsilon}{\sqrt{1-\bar\alpha_t}} .

So regressing onto ε\varepsilon is regressing onto the kernel's score times −1−α‾t-\sqrt{1-\bar\alpha_t}, and the minimiser of a squared loss is a conditional mean: εθ∗(xt)=𝔼[ε|xt]\varepsilon_\theta^*(x_t) = \mathbb{E}[\varepsilon \mid x_t], which Vincent's identity turns into the score of the noised marginal:

sθ(xt,t)=−εθ(xt,t)1−α‾t≈∇xtlog⁡qt(xt).s_\theta(x_t, t) = -\frac{\varepsilon_\theta(x_t, t)}{\sqrt{1-\bar\alpha_t}} \approx \nabla_{x_t}\log q_t(x_t).
A case you can check by hand (Tweedie's formula)

Let the data be x0∼𝒩(0,1)x_0 \sim \mathcal{N}(0, 1). Then every xt∼𝒩(0,1)x_t \sim \mathcal{N}(0,1) (variance preserving, D3), with score −xt-x_t. The formula says the ideal noise prediction is ε∗=−1−α‾t⋅(−xt)=1−α‾txt\varepsilon^* = -\sqrt{1-\bar\alpha_t}\cdot(-x_t) = \sqrt{1-\bar\alpha_t}\,x_t. At t=200t = 200: slope 0.5839. A million simulated (x0,ε)(x_0, \varepsilon) pairs, regressing ε\varepsilon on xtx_t by least squares: slope 0.5843.

That is why Ho et al. say their sampler "resembles Langevin dynamics with εθ\varepsilon_\theta as a learned gradient of the data density" (section 3.2): DDPM's reverse step is a scaled score step plus noise. Song et al. 2021 unified the two families in continuous time: the forward process is a stochastic differential equation (SDE) dx=f(x,t)dt+g(t)dwdx = f(x,t)\,dt + g(t)\,dw; its exact time reversal is another SDE that needs only the score, dx=[f−g2∇xlog⁡qt(x)]dt+gdw‾dx = [f - g^2 \nabla_x \log q_t(x)]\,dt + g\, d\bar w (their eq. 6, from Anderson 1982); and a deterministic probability flow ODE, dx=[f−12g2∇xlog⁡qt(x)]dtdx = [f - \tfrac12 g^2\nabla_x \log q_t(x)]\,dt (their eq. 13), has the same marginals at every tt. DDPM discretises the reverse SDE; DDIM, next, is a discretisation of the ODE.

D6. DDIM: the same network, a deterministic sampler that skips steps (derivation)

Song, Meng and Ermon 2020 noticed that LsimpleL_{\text{simple}} only ever uses the marginals q(xt|x0)q(x_t\mid x_0), never the step-to-step chain. Many chains share those marginals, including non-Markovian ones, so a network trained once can be sampled with any of them. Their update (eq. 12), in DDPM's notation:

xt−1=α‾t−1xt−1−α‾tεθ(xt)α‾t⏟predicted x0+1−α‾t−1−σt2εθ(xt)⏟direction pointing to xt+σtεt.x_{t-1} = \sqrt{\bar\alpha_{t-1}}\,\underbrace{\frac{x_t - \sqrt{1-\bar\alpha_t}\,\varepsilon_\theta(x_t)}{\sqrt{\bar\alpha_t}}}_{\text{predicted } x_0} + \underbrace{\sqrt{1-\bar\alpha_{t-1}-\sigma_t^2}\;\varepsilon_\theta(x_t)}_{\text{direction pointing to } x_t} + \sigma_t\,\varepsilon_t .

Guess the clean point from the current one; re-noise that guess to the next, lower noise level, reusing the predicted noise as the direction; optionally add fresh noise. With σt\sigma_t equal to DDPM's posterior spread it is DDPM; with σt=0\sigma_t = 0 it is deterministic, the DDIM sampler, and its steps can skip: use only a subsequence of noise levels (α‾\bar\alpha taken at, say, 20 evenly spaced tt).

Notation trap
The DDIM paper writes αt\alpha_t for what DDPM calls α‾t\bar\alpha_t (the cumulative product). Read any diffusion paper's definition of α\alpha before its equations; the Notation decoder lists more such clashes.
D7. Classifier-free guidance, as a formula (derivation)
  1. Bayes' rule for scores. p(x|c)∝p(c|x)p(x)p(x \mid c) \propto p(c\mid x)\,p(x), so ∇xlog⁡p(x|c)=∇xlog⁡p(x)+∇xlog⁡p(c|x)\nabla_x \log p(x\mid c) = \nabla_x\log p(x) + \nabla_x \log p(c \mid x): the conditional score is the unconditional one plus a classifier's gradient (the normalising constant p(c)p(c) has no xx in it and vanishes).
  2. Turn up the classifier. Sampling with ∇log⁡p(x)+(1+w)∇log⁡p(c|x)\nabla\log p(x) + (1+w)\,\nabla\log p(c\mid x) targets p(x)p(c|x)1+wp(x)\,p(c\mid x)^{1+w}: images the classifier is more sure about. That is classifier guidance (Dhariwal and Nichol 2021), which needs a separate classifier trained on noisy images.
  3. Remove the classifier. Bayes again: ∇log⁡p(c|x)=∇log⁡p(x|c)−∇log⁡p(x)\nabla\log p(c\mid x) = \nabla\log p(x\mid c) - \nabla\log p(x). Substitute:
    ∇log⁡p(x)+(1+w)(∇log⁡p(x|c)−∇log⁡p(x))=(1+w)∇log⁡p(x|c)−w∇log⁡p(x)\nabla\log p(x) + (1+w)\big(\nabla\log p(x\mid c) - \nabla\log p(x)\big) = (1+w)\nabla\log p(x\mid c) - w\,\nabla\log p(x)
    .
  4. Write it with noise predictions (s=−ε/1−α‾s = -\varepsilon/\sqrt{1-\bar\alpha}, D5) and you have Ho and Salimans 2022, eq. 6:
ε~θ(xt,c)=(1+w)εθ(xt,c)−wεθ(xt,⌀).\tilde\varepsilon_\theta(x_t, c) = (1+w)\,\varepsilon_\theta(x_t, c) - w\,\varepsilon_\theta(x_t, \varnothing).

Run the network twice, with the condition and with an empty condition ⌀\varnothing, and extrapolate past the conditional prediction, away from the unconditional one. One network does both: during training the condition is replaced by ⌀\varnothing with some probability (15% for the two-moons toy on Diffusion from zero). w=0w = 0 is plain conditional sampling.

Two conventions for the same knob
Libraries usually write ε⌀+s(εc−ε⌀)\varepsilon_\varnothing + s\,(\varepsilon_c - \varepsilon_\varnothing), so s=1+ws = 1 + w. Hugging Face diffusers' Stable Diffusion pipeline defaults to guidance_scale = 7.5, which is w=6.5w = 6.5 in the paper's notation (pipeline_stable_diffusion.py, v0.35.1).
D8. Flow matching: the conditional loss and why it learns the marginal velocity (Lipman et al., Theorem 2) (derivation)

The path. Pair a data point x0x_0 with a noise sample ε\varepsilon and join them by a straight line: xt=(1−t)x0+tεx_t = (1-t)\,x_0 + t\,\varepsilon, t∈[0,1]t \in [0, 1] (Esser et al. 2024 (Stable Diffusion 3), eq. 13; Liu, Gong and Liu 2022, rectified flow). Along that line the velocity is constant, dxtdt=ε−x0\frac{dx_t}{dt} = \varepsilon - x_0.

The loss (conditional flow matching, Lipman et al. 2023):

ℒCFM(θ)=𝔼t∼U[0,1], x0, ε‖vθ(xt,t)−(ε−x0)‖2.\mathcal{L}_{\text{CFM}}(\theta) = \mathbb{E}_{t \sim U[0,1],\ x_0,\ \varepsilon}\,\big\|v_\theta(x_t, t) - (\varepsilon - x_0)\big\|^2 .
  1. Many lines pass through the same point xx at time tt. The best single answer for a squared loss is their average direction, the marginal velocity v∗(x,t)=𝔼[ε−x0|xt=x]v^*(x,t) = \mathbb{E}[\varepsilon - x_0 \mid x_t = x].
  2. Lipman et al.'s Theorem 2: the conditional loss above and the (intractable) loss against v∗v^* differ by a constant, so they have the same gradients. We regress on single lines and learn the average.
  3. The ODE dx/dt=v∗(x,t)dx/dt = v^*(x, t) moves the whole noise distribution at t=1t = 1 onto the data distribution at t=0t = 0 (the marginals of the straight-line paths are preserved). Generate by integrating backwards from t=1t = 1: Euler steps x←x−1Svθ(x,t)x \leftarrow x - \tfrac1S v_\theta(x, t).

It is the same family as diffusion: xtx_t is a scaled data point plus scaled Gaussian noise, so a velocity prediction converts to a noise prediction (εˆ=xt+(1−t)v\hat\varepsilon = x_t + (1-t)\,v) or a clean-data prediction (xˆ0=xt−tv\hat x_0 = x_t - t\,v). What changes is the path (straight in tt rather than variance-preserving) and the target (velocity rather than noise), and with them which errors are cheap.

Conventions differ: Lipman et al. put noise at t=0t = 0 and data at t=1t = 1 (their eq. 22 to 23, with a small σmin⁡\sigma_{\min}); Stable Diffusion 3 and this page put data at t=0t = 0. Couplings, reflow and solvers are on Flow matching and rectified flow.

8. The measured runs, and where these ideas sit in real models

This page trained three models whose runs teach the models more than the maths; each now sits on the page that owns it:

  • The MNIST VAE (2-D latent, 30 epochs: training curves of the two terms, test numbers, latent map, decoded grid, reconstructions) is a closed block in section 3 of Autoencoders and VAEs; its importance-weighted bound and gap split stay here (sections 3 and 4).
  • The β\beta sweep (five 16-D MNIST VAEs, best log-likelihood near β=1\beta = 1, half the dimensions dead at β=8\beta = 8) is a closed block in section 5 of Autoencoders and VAEs.
  • The two tiny 2-D diffusion and flow networks (noised then generated back, step positions, straightness, guidance, the sampler lab you can run) are closed blocks in sections 5 and 6 of Diffusion from zero.
Where these ideas sit in real models, dated (provenance)
Date (arXiv v1 or announcement)SystemWhat from this page it uses
Dec 2013VAEELBO, reparameterisation, Gaussian KL (sections 3, 5, 6)
Nov 2017VQ-VAEDiscrete latents with a learned prior, straight-through gradients; avoids posterior collapse (section 6; measured on Autoencoders and VAEs). Discrete image and audio tokenisers descend from it.
Jun 2020DDPMForward process, ELBO, LsimpleL_{\text{simple}} (D3, D4)
Dec 2021Latent diffusion (Stable Diffusion)A KL-regularised autoencoder (a VAE with a small KL weight) compresses images; diffusion runs in its latent space (section 6)
Apr 2022DALL-E 2 (unCLIP)Two diffusion stages: a prior that generates a CLIP image embedding from the caption, a decoder that generates the image from it
May 2022ImagenText-conditioned pixel diffusion with a frozen T5 text encoder
Jul 2022Classifier-free guidanceD7; used by essentially every text-to-image system since
Dec 2022DiTReplaces the U-Net denoiser with a transformer on latent patches
Mar 2024Stable Diffusion 3Rectified flow (D8) with a multimodal transformer, up to 8B parameters
1 Aug 2024FLUX.1 (Black Forest Labs)"a hybrid architecture of multimodal and parallel diffusion transformer blocks and scaled to 12B parameters", built on flow matching
Oct 2024Movie Gen (Meta)A 30B-parameter transformer for video trained with the Flow Matching objective
Feb 2025LLaDADiffusion for text: a masking forward process and a transformer reverse process, trained on "a likelihood lower bound"; 8B parameters
Jul 2026DiffusionGemmaGemma 4 26B A4B converted from autoregressive to discrete diffusion, about 20 tokens per forward pass (paper page)

The pattern: the VAE survives as the compressor in front of nearly every image and video generator; the generator itself moved from DDPM's noise prediction to flow-matching velocity with transformer backbones; and diffusion is being tried for text, where the latents are masked tokens rather than Gaussian noise. Topic: generative-and-multimodal compares these systems (its Model map); this page owns the maths they share.

9. Common mistakes

Each one opens; the first five are about the ELBO itself, the rest about the diffusion and flow derivations of section 7.

Using the wrong direction of KL for variational inference
VI minimises DKL(q‖p(z|x))D_{\mathrm{KL}}(q \Vert p(z\mid x)), the average under qq. The other direction would need samples from the posterior. The direction is why VI underestimates spread (section 4) and picks one mode (section 3, model B).
Reading the ELBO as the log-likelihood
It is a lower bound with an unknown gap. On the MNIST VAE the encoder's ELBO was 8.2 nats below the true log⁡p(x)\log p(x) (section 4). Compare models with an importance-weighted estimate at stated KK (or exact quadrature when the latent is tiny), on the same data and binarisation.
Mixing sum and mean between the two loss terms
Mean over pixels for reconstruction and sum over latent dimensions for the KL is a hidden beta of 784 on MNIST. Sum both over dimensions, then average over the batch (D1).
The KL formula with log⁡σ\log\sigma where it wants log⁡σ2\log\sigma^2
12(μ2+σ2−1−log⁡σ2)\tfrac12(\mu^2 + \sigma^2 - 1 - \log\sigma^2): if the network outputs log⁡σ\log\sigma, the last term is 2log⁡σ2\log\sigma and σ2=e2log⁡σ\sigma^2 = e^{2\log\sigma}. Getting it wrong still trains, to the wrong objective. Check against a Monte Carlo estimate, as D1 does.
Diagnosing posterior collapse from the total loss
Look at the KL per latent dimension: a dimension with KL near 0 for every input is unused (the MNIST β\beta sweep on Autoencoders and VAEs, section 5: 8 of 16 at β=8\beta = 8). The total loss can look fine.
α\alpha means α‾\bar\alpha in some papers
DDPM: αt=1−βt\alpha_t = 1 - \beta_t, α‾t\bar\alpha_t the product. DDIM: αt\alpha_t is the product. VDM and others use αt,σt\alpha_t, \sigma_t for the signal and noise scales. Read the definitions first.
Time running the other way
Diffusion and Stable Diffusion 3 put data at t=0t = 0; Lipman et al.'s flow matching puts noise at t=0t = 0. The velocity's sign flips with it.
Two guidance scales with the same name
The paper's ww and the libraries' s=1+ws = 1 + w (D7). "Guidance 7.5" is w=6.5w = 6.5.
Dividing by α‾t\sqrt{\bar\alpha_t} near the end of the cosine schedule
With βt\beta_t clipped at 0.999 the cosine schedule ends at α‾1000=2.4×10−9\bar\alpha_{1000} = 2.4\times10^{-9}, and the predicted x0=(xt−1−α‾εˆ)/α‾x_0 = (x_t - \sqrt{1-\bar\alpha}\,\hat\varepsilon)/\sqrt{\bar\alpha} multiplies the network's error by about 20,000. On the two-moons toy of Diffusion from zero (section 5), 20-step DDIM on that schedule put 1.2% of 600 samples on the data until the predicted x0x_0 was clipped to the data range ([−3,3][-3, 3]) and the noise re-derived from the clipped value; with that fix, 95.3%. Image samplers clip to [−1,1][-1, 1] for the same reason.
Treating LsimpleL_{\text{simple}} as the ELBO
It drops the per-step weights (D4): the true bound weighs t=1t = 1 about 80 times more than t=200t = 200. Likelihood numbers need the weighted bound.
Mixing up the two "scores"
Section 5's score is ∇ϕlog⁡qϕ(z)\nabla_\phi \log q_\phi(z), a gradient with respect to parameters, averaging to zero. D5's score is ∇xlog⁡p(x)\nabla_x \log p(x), a gradient with respect to the data. The link to noise prediction is s=−ε/1−α‾ts = -\varepsilon/\sqrt{1 - \bar\alpha_t}, with that minus sign.