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.
elboWhy introduce a lower bound?
Consider a teaching model that explains an observation using a hidden variable. You observe , but not the chosen when generating it. Evaluating the model requires combining all possible explanations, rather than selecting one favorable . Sum over a discrete variable or integrate over a continuous one. The marginal probability or density is called the evidence; the word does not mean proof that the model is correct.
The integral is often the obstacle. The joint may be easy to evaluate while its marginal is difficult, making the normalized posterior difficult too. An auxiliary distribution with tractable sampling and density evaluation lets us optimize an evidence lower bound, or ELBO. We choose 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.
The gap explains the inequality
Fix one observation . Assume positive, finite evidence and normalized , initially with finite expectations and KL. Define:
Write the joint as posterior times evidence, splitting inside the expectation. The term does not depend on , so it can leave the expectation. Rearranging gives:
The KL direction runs from 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:
The first term evaluates the observation under explanations sampled from . 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 , let the joint masses of two latent states be 0.1 and 0.4; the remaining probability belongs to other observations. Choose uniform :
Log evidence is approximately −0.693147, the ELBO is −0.916291, and the gap is . The true posterior is . Choosing it makes the bound tight.
Check supports separately. If , it omits the second state, which has positive posterior mass, yet the bound is finite: , with gap . Thus covering the entire posterior support is not necessary for a finite lower bound. Conversely, positive 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 samples, the following estimator is unbiased; the lower-bound inequality does not constrain each realization:
In the discrete example a single draw returns either or . The second value, about −0.223144, exceeds log evidence −0.693147. The expectation remains . 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 , and , where is variance. Expanding the expected squared residual gives:
The in the reconstruction term comes from . Replacing by its mean and dropping this contribution is incorrect. Adding Gaussian variables and completing the square give the true marginal and posterior:
At , the posterior has mean 0.8 and variance 0.2. Check the gap using the KL from a general to that posterior:
Here 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 fixed and assuming valid interchange of differentiation and integration, the generative-parameter gradient is:
If also depends on the parameter being optimized, the fixed- formula cannot be reused unchanged. Its parameter gradient can instead use reparameterization or a score-function estimator. Alternately improving 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 time for latent states and space in this vectorized implementation. The scalar Gaussian formulas take constant time. In a general model, an -sample estimate requires joint and 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 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
- With joint masses , which makes the ELBO equal log evidence? Does that establish a correct data distribution?
Answer: The model’s true posterior is , 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.
- Calculate the bound and gap for . Why is the calculation valid despite omitting a possible state?
Answer: The bound is , log evidence is , and the gap is . The only state with positive mass also has positive joint mass, so the expectation is finite. The omitted state contributes zero.
- Under uniform , what is the probability that two independent samples both select the second state? Does their average exceed log evidence?
Answer: The probability is . Both terms are , leaving an average . Two samples do not guarantee a lower bound on each realization.
- At , compare with .
Answer: The first matches both posterior mean and variance and has zero gap. The second matches only the mean, giving KL . 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?
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
- Auto-Encoding Variational Bayes (v11): bound and reparameterization
Diederik P. Kingma; Max Welling · 2022 - 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:
- Auto-Encoding Variational Bayes (v11): bound and reparameterization · Read Sections2.2–2.4 and3, Equations1–10/Algorithm1; inspected PDF pages3 and5. First submitted2013-12-20; v11 dated2022-12-10. No full appendices or benchmark replication.
- Stochastic Back-propagation and Variational Inference in Deep Latent Gaussian Models (v1) · Read Section3 Gaussian derivatives/coordinate transforms and4.1 bound opening; inspected PDF page3. v1 dated2014-01-16, whose title differs from the final PMLR paper. No full appendix or experiment review.
Related topics