AI Wiki中文/EN

The ELBO: a bound, its gap and a misleading sample

证据下界

Derive the posterior-KL gap and calculate examples where a Monte Carlo estimate crosses the evidence.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Why introduce a lower bound?

Consider a teaching model that explains an observation using a hidden variable. You observe xx, but not the zz chosen when generating it. Evaluating the model requires combining all possible explanations, rather than selecting one favorable zz. Sum over a discrete variable or integrate over a continuous one. The marginal probability or density pθ(x)p_\theta(x) is called the evidence; the word does not mean proof that the model is correct.

pθ(x)=∫pθ(x,z) dz,pθ(z∣x)=pθ(x,z)pθ(x).p_\theta(x)=\int p_\theta(x,z)\,dz,\qquad p_\theta(z\mid x)=\frac{p_\theta(x,z)}{p_\theta(x)}.

The integral is often the obstacle. The joint pθ(x,z)p_\theta(x,z) may be easy to evaluate while its marginal is difficult, making the normalized posterior difficult too. An auxiliary distribution q(z∣x)q(z\mid x) with tractable sampling and density evaluation lets us optimize an evidence lower bound, or ELBO. We choose qq as an approximation; it is not another name for the true posterior. AEVB Section 2 organizes learning around this construction; Section 4.1 of the early Rezende paper also moves from a marginal integral to a variational objective.

Start with conditional probability and KL divergence. This article explains the bound, its equality condition and its estimated values. A particular encoder architecture belongs to the VAE article.

Exact discrete and Gaussian examples compare the bound, posterior gap and sampled values that can cross the evidence.
Exact discrete and Gaussian examples compare the bound, posterior gap and sampled values that can cross the evidence.

The gap explains the inequality

Fix one observation xx. Assume positive, finite evidence and normalized qq, initially with finite expectations and KL. Define:

L(q,θ;x)=Eq[log⁡pθ(x,z)−log⁡q(z∣x)].\mathcal L(q,\theta;x)=\mathbb E_q[\log p_\theta(x,z)-\log q(z\mid x)].

Write the joint as posterior times evidence, splitting log⁡pθ(x,z)\log p_\theta(x,z) inside the expectation. The term log⁡pθ(x)\log p_\theta(x) does not depend on zz, so it can leave the expectation. Rearranging gives:

log⁡pθ(x)−L=Eq ⁣[log⁡q(z∣x)pθ(z∣x)]=DKL(q∥pθ(z∣x))≥0.\log p_\theta(x)-\mathcal L=\mathbb E_q\!\left[\log\frac{q(z\mid x)}{p_\theta(z\mid x)}\right]=D_{\rm KL}(q\Vert p_\theta(z\mid x))\ge0.

The KL direction runs from qq to the true posterior. Nonnegativity puts the ELBO below log evidence; in the finite case, equality requires the distributions to agree almost everywhere. Equality does not establish that the generative model fits the data. It removes the posterior-approximation gap within that model. This identity corresponds to AEVB Equations 1–2.

Alternatively, split the joint into likelihood and prior:

L=Eq[log⁡pθ(x∣z)]−DKL(q(z∣x)∥p(z)).\mathcal L=\mathbb E_q[\log p_\theta(x\mid z)]-D_{\rm KL}(q(z\mid x)\Vert p(z)).

The first term evaluates the observation under explanations sampled from qq. The second constrains how far the approximate posterior departs from the prior. This prior KL differs from the true-posterior KL above. Reducing the prior KL need not reduce the posterior gap, since the reconstruction term and generative model can change too. AEVB Equation 3 gives this decomposition.

A discrete calculation by hand

For a fixed xx, let the joint masses of two latent states be 0.1 and 0.4; the remaining probability belongs to other observations. Choose uniform qq:

j=(0.1,0.4),q=(0.5,0.5),Z=0.5,L=12log⁡0.2+12log⁡0.8=log⁡0.4.j=(0.1,0.4),\quad q=(0.5,0.5),\quad Z=0.5,\quad\mathcal L=\tfrac12\log0.2+\tfrac12\log0.8=\log0.4.

Log evidence is approximately −0.693147, the ELBO is −0.916291, and the gap is log⁡1.25≈0.223144\log1.25\approx0.223144. The true posterior is (0.2,0.8)(0.2,0.8). Choosing it makes the bound tight.

Check supports separately. If q=(1,0)q=(1,0), it omits the second state, which has positive posterior mass, yet the bound is finite: L=log⁡0.1\mathcal L=\log0.1, with gap log⁡5\log5. Thus covering the entire posterior support is not necessary for a finite lower bound. Conversely, positive qq mass where the joint is zero gives ELBO minus infinity and KL plus infinity. At zero evidence, the conditional posterior is undefined. The program handles these cases separately rather than disguising infinities as ordinary numbers.

A sampled estimate can cross the evidence

Training often replaces the expectation with a sample average. With SS samples, the following estimator is unbiased; the lower-bound inequality does not constrain each realization:

L^S=1S∑s=1Slog⁡pθ(x,zs)q(zs∣x),zs∼q,E[L^S]=L.\widehat{\mathcal L}_S=\frac1S\sum_{s=1}^{S}\log\frac{p_\theta(x,z_s)}{q(z_s\mid x)},\quad z_s\sim q,\quad\mathbb E[\widehat{\mathcal L}_S]=\mathcal L.

In the discrete example a single draw returns either log⁡0.2\log0.2 or log⁡0.8\log0.8. The second value, about −0.223144, exceeds log evidence −0.693147. The expectation remains log⁡0.4\log0.4. Averaging independent samples reduces variance, but no fixed finite sample count thereby guarantees staying below the evidence on every run. AEVB Section 2.3 distinguishes the bound from its estimator; training logs require the same distinction.

A continuous example with an exact posterior

Let z∼N(0,1)z\sim\mathcal N(0,1), x∣z∼N(z,τ2)x\mid z\sim\mathcal N(z,\tau^2) and q=N(m,v)q=\mathcal N(m,v), where v>0v>0 is variance. Expanding the expected squared residual gives:

Eqlog⁡p(x∣z)=−12[log⁡(2πτ2)+(x−m)2+vτ2],DKL(q∥p(z))=12(m2+v−1−log⁡v).\mathbb E_q\log p(x\mid z)=-\frac12\left[\log(2\pi\tau^2)+\frac{(x-m)^2+v}{\tau^2}\right],\quad D_{\rm KL}(q\Vert p(z))=\frac12(m^2+v-1-\log v).

The vv in the reconstruction term comes from Eq(z−m)2\mathbb E_q(z-m)^2. Replacing zz by its mean and dropping this contribution is incorrect. Adding Gaussian variables and completing the square give the true marginal and posterior:

p(x)=N(x;0,1+τ2),p(z∣x)=N ⁣(z;x1+τ2,τ21+τ2).p(x)=\mathcal N(x;0,1+\tau^2),\qquad p(z\mid x)=\mathcal N\!\left(z;\frac{x}{1+\tau^2},\frac{\tau^2}{1+\tau^2}\right).

At x=1,τ2=0.25x=1,\tau^2=0.25, the posterior has mean 0.8 and variance 0.2. Check the gap using the KL from a general qq to that posterior:

DKL(N(m,v)∥N(m∗,v∗))=12[log⁡v∗v+v+(m−m∗)2v∗−1].D_{\rm KL}(\mathcal N(m,v)\Vert\mathcal N(m_*,v_*))=\frac12\left[\log\frac{v_*}{v}+\frac{v+(m-m_*)^2}{v_*}-1\right].

Here m∗,v∗m_*,v_* are the true posterior parameters. The program verifies that this KL equals independently computed log evidence minus ELBO. The tractable posterior is a deliberate checking device; complex latent-variable models need not admit the same closed-form integration. Continuous models use densities, which can exceed one, so log density may be positive.

Using the bound for optimization

For independent observations, their ELBOs are usually summed or averaged; specify which scale is used. Holding qq fixed and assuming valid interchange of differentiation and integration, the generative-parameter gradient is:

∇θL=Eq[∇θlog⁡pθ(x,z)]when q is held fixed and differentiation is valid.\nabla_\theta\mathcal L=\mathbb E_q[\nabla_\theta\log p_\theta(x,z)]\quad\text{when }q\text{ is held fixed and differentiation is valid}.

If qq also depends on the parameter being optimized, the fixed-qq formula cannot be reused unchanged. Its parameter gradient can instead use reparameterization or a score-function estimator. Alternately improving qq and the generative parameters can improve the bound without guaranteeing a global optimum. A rising bound also need not mean a rising true likelihood on every step, because the posterior gap can change simultaneously.

Compute the evidence, bound and gap separately

Save the program as elbo.py and run it with Python 3.12 and NumPy 1.26.4. No data download is required. Discrete examples allow at most 64 latent states; Gaussian means and variances have explicit bounds. The returned gap is calculated as KL rather than merely subtracting the two objectives, enabling a cross-check of the identity.

"""Exact, bounded ELBO examples; natural logarithms, not a data benchmark."""
import json
import numpy as np


def discrete(joint, q):
    """joint is p(x,z) for one fixed discrete observation x."""
    joint, q = np.asarray(joint, float), np.asarray(q, float)
    if (joint.ndim != 1 or joint.shape != q.shape or not 1 <= joint.size <= 64
            or not np.isfinite(joint).all() or not np.isfinite(q).all()
            or (joint < 0).any() or (q < 0).any()
            or not np.isclose(q.sum(), 1, atol=1e-12, rtol=0)
            or not 0 < joint.sum() <= 1):
        raise ValueError('Expected finite joint masses and normalized q, with positive evidence <= 1.')
    evidence = float(joint.sum())
    active = q > 0
    if np.any(joint[active] == 0):
        return dict(log_evidence=float(np.log(evidence)), elbo=None, gap=None,
                    reason='ELBO is -infinity and KL is +infinity: q puts mass on impossible z.')
    terms = np.log(joint[active]) - np.log(q[active])
    bound = float(q[active] @ terms)
    kl = float(q[active] @ (np.log(q[active]) - np.log(joint[active] / evidence)))
    return dict(log_evidence=float(np.log(evidence)), elbo=bound, gap=kl,
                single_sample_terms=terms.tolist())


def gaussian(x=1., mean=0., variance=1., noise_variance=.25):
    """z~N(0,1), x|z~N(z,tau²), q=N(mean,variance); densities may exceed 1."""
    values = np.array([x, mean, variance, noise_variance])
    if (not np.isfinite(values).all() or max(abs(x), abs(mean)) > 20
            or not 1e-6 <= variance <= 100 or not 1e-6 <= noise_variance <= 100):
        raise ValueError('Use bounded means and strictly positive, bounded variances.')
    tau = noise_variance
    posterior_mean, posterior_variance = x / (1 + tau), tau / (1 + tau)
    reconstruction = -.5 * (np.log(2 * np.pi * tau) + ((x - mean)**2 + variance) / tau)
    kl_prior = .5 * (mean**2 + variance - 1 - np.log(variance))
    bound = reconstruction - kl_prior
    log_evidence = -.5 * (np.log(2 * np.pi * (1 + tau)) + x*x / (1 + tau))
    kl_posterior = .5 * (np.log(posterior_variance / variance)
                        + (variance + (mean - posterior_mean)**2) / posterior_variance - 1)
    return dict(elbo=float(bound), log_evidence=float(log_evidence),
                reconstruction=float(reconstruction), kl_prior=float(kl_prior),
                gap=float(kl_posterior), posterior_mean=posterior_mean,
                posterior_variance=posterior_variance)


def demo():
    return dict(loose=discrete([.1, .4], [.5, .5]), tight=discrete([.1, .4], [.2, .8]),
                restricted=discrete([.1, .4], [1, 0]),
                impossible=discrete([0, .5], [.5, .5]),
                gaussian_loose=gaussian(), gaussian_tight=gaussian(mean=.8, variance=.2))


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2, allow_nan=False))

The discrete calculation takes O(K)O(K) time for KK latent states and O(K)O(K) space in this vectorized implementation. The scalar Gaussian formulas take constant time. In a general model, an SS-sample estimate requires SS joint and qq density evaluations; their costs depend on the models and cannot be inferred from this closed-form example.

Companion checks compare hand calculations, 24-point Gaussian integration and parameter grids, and exercise zero evidence, impossible support, nonfinite inputs and a sampled violation. Passing establishes these bounded examples, not a numerical-accuracy guarantee for arbitrary models.

What the bound does not establish

The approximation family limits tightness. Even its best qq may fail to represent the true posterior. A shared neural encoder adds constraints across observations; finishing training does not establish that each observation has its best within-family approximation.

ELBOs with different observation spaces, likelihood variances or sum/mean conventions should not be ranked directly. Changing the coefficient of the prior KL changes the original posterior-gap identity. Classification accuracy and visual quality require their own evaluations; the ELBO evaluates the specified probabilistic objective.

Four questions with calculable answers

  1. With joint masses (0.1,0.4)(0.1,0.4), which qq makes the ELBO equal log evidence? Does that establish a correct data distribution?

Answer: The model’s true posterior is q=(0.2,0.8)q=(0.2,0.8), giving zero KL. It removes the posterior-approximation gap without establishing that the generative model is correct. An incorrect generative model also has an exact posterior.

  1. Calculate the bound and gap for q=(1,0)q=(1,0). Why is the calculation valid despite omitting a possible state?

Answer: The bound is log⁡0.1\log0.1, log evidence is log⁡0.5\log0.5, and the gap is log⁡5\log5. The only state with positive qq mass also has positive joint mass, so the expectation is finite. The omitted state contributes zero.

  1. Under uniform qq, what is the probability that two independent samples both select the second state? Does their average exceed log evidence?

Answer: The probability is 0.52=0.250.5^2=0.25. Both terms are log⁡0.8\log0.8, leaving an average log⁡0.8>log⁡0.5\log0.8>\log0.5. Two samples do not guarantee a lower bound on each realization.

  1. At x=1,τ2=0.25x=1,\tau^2=0.25, compare m=0.8,v=0.2m=0.8,v=0.2 with m=0.8,v=1m=0.8,v=1.

Answer: The first matches both posterior mean and variance and has zero gap. The second matches only the mean, giving KL [log⁡0.2+5−1]/2≈1.195281[\log0.2+5-1]/2\approx1.195281. Predicting the appropriate center does not eliminate an error in distribution width.

Original sources and version boundaries

Kingma and Welling’s AEVB gives the posterior-KL decomposition in Section 2.2 and estimators in Section 2.3. Its first preprint was submitted on 2013-12-20; this reading uses v11 dated 2022-12-10. The revision date is not the method’s origin date. Rezende and colleagues’ v1, submitted on 2014-01-16, introduces the bound from the marginal integral in Section 4.1; its title differs from the final PMLR version.

This article relies on those method sections, without claiming a full appendix review or image-experiment replication. Continue with variational inference for approximation families and optimization, then the VAE and reparameterization entries in this volume’s catalogue.

Make a prediction, then check

Must every sampled ELBO estimate stay below log evidence?

Choose one answer

Learning objectives

  • Derive the bound and identify its equality condition.
  • Handle zeros and mismatched supports.
  • Separate expectations from sampled estimates.
  • Compute discrete and Gaussian posterior gaps.

Prerequisites & connections

Explore related knowledge →

References

  1. Auto-Encoding Variational Bayes (v11): bound and reparameterization
    Diederik P. Kingma; Max Welling · 2022
  2. Stochastic Back-propagation and Variational Inference in Deep Latent Gaussian Models (v1)
    Danilo Jimenez Rezende; Shakir Mohamed; Daan Wierstra · 2014

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-13 · Single AI author checked AEVB v11 posterior-KL identity and estimator sections plus Rezende v1 bound opening. Ten paired equations and four explained exercises; exact discrete and Gaussian gaps, support restrictions, impossible events and finite-sample bound violations. Fixed-q derivative conditions stated.

  • Verified hand-computed discrete bounds and zero/missing support,24-point Gaussian integration, posterior-gap parameter grids, sample-average counterexamples and variance-mismatch exercise answers.
  • Four computed SVGs per topic bind the exact bilingual MDX. The four-topic group passed15 numeric/geometry checks and24 isolated language/width cases with four fallback fonts; eight representative screenshots were actually inspected. VAE heading changed from draw to estimate; original figures preserved, data unchanged. Literal-prose AST checked before freezing. Full article-page acceptance is separate; no independent human review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.