Latent Variable Models and the Evidence Lower Bound
Imagine you have a dataset of handwritten digits. You want a model that explains why each image looks the way it does. A "7" might vary in slant, stroke width, and size. These are hidden factors that combine to produce pixels. If you could recover these factors, you could generate new digits. You could also denoise corrupted ones, or measure how well your model fits reality. This is the promise of a latent variable model: assume every observed data point was generated from some unobserved cause . Then learn the machinery that connects the two. The trouble is that scoring how good such a model is requires computing the marginal likelihood . For any interesting model — one where is high-dimensional or the generative process is a neural network — this integral has no closed form. It also has no efficient exact algorithm. This is not a minor inconvenience. It sits at the center of why generative modeling with latent variables is hard. It also explains why fields as different as Bayesian statistics, variational physics, and deep learning converged on the same mathematical trick. That trick is the evidence lower bound (ELBO). Instead of computing the intractable marginal likelihood directly, introduce an auxiliary distribution over the latent variables. Then optimize a tractable lower bound on . The gap between the bound and the truth is exactly a KL divergence. So tightening the bound and inferring the latents become the same optimization. This single inequality — dressed up in different notation — underlies variational inference in statistics, mean-field methods in physics, expectation-maximization in classical machine learning. Later, it also underlies the variational autoencoder in deep learning. This article derives the ELBO from first principles. It shows the algorithmic recipe for optimizing it. It proves the bound is correct and explains when it is tight. It also traces a worked numerical example, so the abstract inequality becomes concrete arithmetic. It closes with the historical lineage of the idea. Finally, it previews how deep networks turn this classical bound into a trainable, backpropagatable objective.
- Latent variable models posit hidden causes behind observed data , via a joint .
- The marginal likelihood is generally intractable — no closed form, no efficient exact computation.
- Variational inference sidesteps this by introducing a tractable approximate posterior over latents.
- The ELBO is a lower bound on ; maximizing it simultaneously fits the model and infers the latents.
- The gap between and the ELBO equals — the bound is tight iff equals the true posterior.
- This exact bound, generalized with neural networks for and , becomes the training objective for Variational Autoencoders.
Because the true posterior over latent causes is intractable, we optimize a computable lower bound on the data likelihood whose slack is exactly the approximation error in our guess of that posterior.
The idea
A latent variable model describes data through a joint distribution , where is observed, is an unobserved (latent) variable, is a prior over latents, and is the generative or "decoder" distribution parameterized by . The model explains data by imagining that nature first draws a hidden cause , then generates the visible conditioned on it. Fitting the model means choosing to make observed data likely under this story, i.e., maximizing the marginal likelihood (also called the evidence):
For discrete this is a sum instead of an integral, but the difficulty is the same: the integral marginalizes out every possible explanation for the data, weighted by how plausible that explanation is. When is a simple conjugate distribution (e.g., linear-Gaussian), this integral can sometimes be solved in closed form. But when is parameterized by a neural network, the integral has no analytic solution, and its dimension (over all possible ) makes numerical quadrature or naive Monte Carlo hopelessly slow — this is precisely the intractable marginal likelihood problem. A related, equally intractable object is the posterior over latents given data, , which tells you which hidden causes plausibly generated a specific observation. Since it is defined using , if the evidence is intractable, so is the exact posterior. Variational inference solves both problems at once: introduce a tractable family of distributions , indexed by parameters , meant to approximate the true posterior. Then derive a bound on that only requires expectations under , never under the true posterior. That bound is the Evidence Lower BOund, or ELBO.
Deriving the ELBO. Start from the log marginal likelihood and introduce by multiplying and dividing inside the integral:
Because is concave, Jensen's inequality lets us move the log inside the expectation, only decreasing the value:
This quantity is the ELBO. It is fully tractable whenever we can sample from , evaluate its density, and evaluate and — all mild requirements satisfied by simple parametric families like Gaussians. Two equivalent rewritings expose its meaning:
which balances explaining well against staying close to the prior, and
which reveals the exact gap between the true evidence and the bound: it is the KL divergence from our approximate posterior to the true posterior. Since KL divergence is always non-negative, this immediately re-derives the inequality and, more importantly, tells us how to close the gap: choose to make as close as possible to .
How it works
The practical recipe alternates — or jointly performs via gradient ascent — two goals: improve the generative model and improve the approximate posterior , both by maximizing the same scalar objective, the ELBO, summed (or averaged) over the dataset.
Step-by-step mechanism: 1. Choose a prior , typically simple (e.g., standard normal ), fixed or learned. 2. Choose a generative (decoder) family , e.g., a neural network mapping to the parameters of a distribution over (Gaussian mean/variance for continuous , Bernoulli logits for binary ). 3. Choose a variational (encoder) family , e.g., a neural network mapping to the mean and variance of a diagonal Gaussian over . 4. For each data point (or minibatch), estimate the ELBO:
- Sample (or use a closed-form expectation when possible).
- Compute — the reconstruction log-likelihood.
- Compute — closed-form when both are Gaussian.
- Combine: .
5. Ascend the gradient of with respect to both and (this requires differentiating through the sampling step — the reparameterization trick, foreshadowing the Variational Autoencoder). 6. Repeat over the dataset until convergence; at convergence, defines a good generative model and approximates the true posterior for any . This is the modern, amortized, gradient-based version. A classical, non-amortized ancestor is Expectation-Maximization (EM), which alternates fully solving for (the E-step, setting exactly when tractable) and then maximizing over (the M-step) — both steps are coordinate ascent on the exact same ELBO objective. ``` ALGORITHM: ELBO-based training of a latent variable model (variational EM, amortized) Input: dataset D = {x_1, ..., x_N} prior p(z) decoder p_theta(x | z) # neural network, params theta encoder q_phi(z | x) # neural network, params phi learning rate eta, number of steps T Initialize theta, phi randomly for step = 1 to T: sample minibatch B = {x_1, ..., x_m} from D grad_theta = 0 grad_phi = 0 for each x in B:
# --- variational step: get an approximate posterior sample --- (mu, sigma) = encoder_forward(phi, x) # e.g. Gaussian params epsilon ~ N(0, I) # reparameterization noise z = mu + sigma * epsilon # differentiable sample
# --- evaluate the ELBO for this point --- recon_ll = log p_theta(x | z) # decoder log-likelihood kl_term = KL( N(mu, sigma^2) || p(z) ) # closed form if p(z)=N(0,I) elbo_x = recon_ll - kl_term
# --- backpropagate through both terms --- grad_theta += d(elbo_x) / d(theta) grad_phi += d(elbo_x) / d(phi) # flows through z via reparameterization theta = theta + eta grad_theta / m # gradient ASCENT on ELBO phi = phi + eta grad_phi / m return theta, phi ``` The key subtlety in this pseudocode is that is drawn via with fixed as external randomness, rather than sampled directly as . This reparameterization makes a deterministic, differentiable function of and noise, so gradients can flow from the ELBO back into the encoder — without it, `grad_phi` could not be computed by ordinary backpropagation, only by higher-variance estimators like REINFORCE.
Complexity & correctness
Correctness — why the inequality holds and what "tight" means. The derivation used only two facts: the algebraic identity (valid wherever ), and Jensen's inequality for the concave function , which states for any positive random variable , with equality iff is almost surely constant. Applying this with gives the ELBO inequality, and equality holds exactly when is constant in — which happens precisely when , i.e. when (the true posterior). This matches the second derivation exactly: the gap is , with equality iff the two distributions are identical (KL divergence is zero iff its two arguments coincide almost everywhere). So the ELBO is not an ad hoc approximation — it is provably a lower bound for any valid probability distribution , and the slack is a well-understood, non-negative quantity that vanishes exactly when inference is perfect. This also explains why maximizing the ELBO over alone (holding fixed) performs correct approximate inference: since does not depend on , increasing can only be achieved by decreasing the KL gap. And maximizing over pushes up a valid lower bound on the true log-likelihood, so (unlike, say, maximizing a heuristic surrogate) improving the ELBO is guaranteed to improve a certified floor on how well the model explains the data.
Complexity. Let be the dimensionality of , and suppose the encoder and decoder are neural networks with parameters and floating-point operations per forward pass.
- Exact marginal likelihood (baseline, for contrast): computing exactly by numerical integration over a grid costs for grid points per dimension — exponential in , intractable for beyond a handful of dimensions. This is the problem the ELBO exists to avoid.
- ELBO estimation (Monte Carlo, one sample): — one encoder forward pass to get 's parameters, one sample of (cost , negligible next to ), one decoder forward pass to get , and, when and the prior are both Gaussian, a closed-form KL term costing only arithmetic operations (no sampling needed for that piece). Crucially this cost does not grow with exponentially — it is linear in network size, independent of how the exponential-integral difficulty would have scaled.
- Gradient computation: backpropagation through encoder and decoder costs the same order as the forward pass, , by the standard reverse-mode differentiation argument (each op is differentiated once).
- Per training step overall: for a minibatch of size ; memory: for parameters plus stored activations for backpropagation, exactly as in standard supervised deep learning.
- Variance of the estimate: because is stochastic, the ELBO estimate from a single sample is a Monte Carlo estimator with some variance; more samples of reduce variance at cost for samples, trading compute for lower-variance gradients — a tunable, not a fundamental, tradeoff.
Honest tradeoffs. The ELBO purchases tractability at the price of an approximation gap that is rarely known exactly in practice (we cannot compute the true posterior to check how tight our bound is). A poorly chosen family — e.g., a diagonal Gaussian approximating a true posterior that is highly multimodal or correlated — can leave a large, uncorrectable gap no matter how well is optimized within that family; this is a model-mismatch limitation, not an optimization failure. Richer variational families (normalizing flows, hierarchical ) shrink the gap but increase computational cost per step.
Worked example
Consider a toy one-dimensional latent variable model so every term can be computed by hand. Let the prior be standard normal, . Let the decoder be a fixed linear-Gaussian model, (mean , variance ) — chosen simple so we can also compute the true posterior for comparison, to see the ELBO gap concretely. Suppose we observe .
Step 1 — the true posterior (ground truth, for checking). Since prior and likelihood are conjugate Gaussians, . Completing the square in gives a Gaussian posterior with
So the true posterior is . (In a real deep model we would not have this in closed form — this is exactly why we need .)
Step 2 — suppose our variational family is Gaussian and, before training, the encoder outputs a poor guess (close to the prior, badly off the true posterior).
Step 3 — compute the ELBO terms with this bad guess. Draw ; take the mean-value estimate for illustration (in practice we'd sample and/or use closed forms where possible).
- Reconstruction term: .
- KL term (closed form for two Gaussians vs ):
- ELBO estimate: .
Step 4 — repeat with a better guess, (matching the true posterior exactly), using :
- Reconstruction term: .
- KL term: .
- ELBO estimate: .
Step 5 — check against the true log-evidence. For this linear-Gaussian model, (since , gives ):
| Quantity | Bad () | Good () | True |
|---|---|---|---|
| ELBO estimate | — | ||
| True log-evidence | |||
| Bound valid? () | violated by point-estimate approximation (expected: MC sampling / Jensen bias) | holds | — |
(Note: because we used single point evaluations at the mean instead of a proper Monte Carlo expectation, the "bad " row's ELBO estimate of exceeding reflects estimator noise/bias from skipping the expectation, not a violation of the theorem — with true expectations taken analytically, both values are guaranteed , and the good- case, using the exact posterior, gives exactly, since the KL gap is exactly zero there.) This subtlety itself is instructive: it shows why in practice we must be careful about Monte Carlo variance when reporting or comparing ELBO values, and why using the exact posterior as collapses the bound to equality — exactly as the correctness argument predicted.
Common pitfalls & traps
| Pitfall | Why it happens | Consequence |
|---|---|---|
| Forgetting the KL term is a divergence to the prior, not to the true posterior | Confusing the two KLs in the two ELBO decompositions | Misinterpreting what regularizes the latent space during training |
| Treating the ELBO gap as always small | Assuming a simple family is "good enough" | Silent underestimation of ; latent codes may not reflect the true posterior geometry |
| Sampling without reparameterization when gradients w.r.t. are needed | Sampling breaks the differentiable computation graph | Gradients for the encoder cannot be computed by standard backpropagation |
| Using only one Monte Carlo sample and reporting the ELBO as if exact | High variance from single-sample estimates, especially early in training | Noisy or misleading likelihood comparisons across models |
| Comparing ELBO values across models with different families as if comparing directly | ELBO in general; gap sizes differ across models | A model with a worse fit but a better/richer can appear to "win" spuriously |
Pioneers & history
The mathematics of bounding an intractable integral via a variational distribution has roots in statistical physics — mean-field approximations for the free energy of interacting systems — and was imported into statistics and machine learning through the lens of variational inference and the closely related Expectation-Maximization algorithm.
Origins · 1 minRichard S. Sutton and how this was discovered
Where this matters
The ELBO is the training objective behind Variational Autoencoders, which power generative image models, molecular design pipelines, anomaly detection systems, and representation-learning backbones across industry. It underlies topic models like Latent Dirichlet Allocation, where variational inference (an ELBO maximization) is the standard scalable fitting algorithm for millions of documents. In Bayesian deep learning, ELBO-style objectives approximate posteriors over network weights for uncertainty quantification in medical imaging and autonomous systems. Probabilistic programming languages (Pyro, Stan's variational mode, TensorFlow Probability) implement generic ELBO optimizers so practitioners can plug in custom generative models without deriving inference by hand. The same bound, generalized to sequences of latents, appears in state-space models for time series and in diffusion-adjacent hierarchical latent variable models, making the ELBO one of the most reused mathematical objects connecting classical statistics to modern deep generative modeling, alongside foundational tools like KL Divergence and Bayes' Rule.
Ask the tutor: How does the reparameterization trick concretely enable gradient-based optimization of the ELBO in a Variational Autoencoder?
Is the ELBO just an approximation, or is it a mathematically guaranteed bound?
It is a guaranteed bound, not a heuristic approximation. The derivation uses only an algebraic identity (multiplying and dividing by ) and Jensen's inequality applied to the concave logarithm function, both of which hold for any valid probability distributions involved — no assumptions about the model family are needed. This means for any choice of , is provably true; what varies is only how tight the bound is, governed by the KL divergence between and the true posterior. So while the value of the ELBO underestimates the true likelihood, the inequality itself is exact mathematics, not an approximation.
Why not just compute the true posterior p(z|x) exactly instead of approximating it with q(z|x)?
Computing exactly requires knowing , the very intractable integral that motivated variational inference in the first place — so exact posterior computation and exact marginal likelihood computation are two faces of the same intractability. In special cases (conjugate exponential-family models like linear-Gaussian systems) the posterior is available in closed form, and there variational inference is unnecessary. But once the generative model is a nonlinear neural network, no conjugacy holds, the posterior can be arbitrarily complex (multimodal, correlated), and no closed form exists — forcing an approximation strategy like variational inference or Monte Carlo sampling methods.
How is the ELBO related to Expectation-Maximization (EM)?
EM is a special case of ELBO maximization where, in the E-step, is set to the exact true posterior whenever that is tractable (making the KL gap exactly zero and the bound tight), and in the M-step, is updated to maximize the resulting tight ELBO. Modern amortized variational inference generalizes this by restricting to a parametric family (e.g., Gaussian encoders) when the true posterior is intractable, accepting a nonzero KL gap in exchange for tractability. Both methods are coordinate ascent on the exact same objective function — the ELBO — differing only in whether the E-step can be solved exactly or must itself be approximated.
Why does the ELBO decompose into a reconstruction term and a KL-to-prior term, and what does each mean intuitively?
Algebraically, , and taking the expectation under turns the second term into . Intuitively, the reconstruction term rewards latent samples that let the decoder assign high probability to the actual observed — it wants the model to explain the data well. The KL term penalizes the encoder for drifting far from the prior, acting as a regularizer that keeps the latent space well-structured and prevents the model from encoding as an arbitrarily specific, non-generalizing code. Training balances these two competing pressures.
Does a higher ELBO always mean a better generative model?
Not necessarily, and this is a subtle but important caveat. The ELBO is a lower bound on , and the gap depends on how well approximates the true posterior for that particular . Two models with identical true log-likelihoods can have different ELBOs if their posteriors are easier or harder for the chosen family to approximate — a model whose true posterior happens to be close to Gaussian will show a smaller gap than one with a highly multimodal posterior, even if the second model fits the data equally well. So the ELBO should be interpreted as a joint measure of model fit and inference quality, and comparisons across differently-structured families should be made cautiously.
What role does the choice of variational family for q(z|x) play in practice?
The family of determines how tight the ELBO can possibly become, independent of how well is optimized. A simple family, such as a diagonal (mean-field) Gaussian, is cheap to sample from and yields closed-form KL terms against a Gaussian prior, but cannot represent correlations or multimodality in the true posterior, capping how small the KL gap can get. Richer families — full-covariance Gaussians, mixtures, or normalizing flows applied to a base distribution — can shrink the gap further at increased computational and implementation cost. Choosing this family is therefore a direct tradeoff between tractability/speed and the tightness of the bound, and is one of the main design decisions inherited by later architectures such as the Variational Autoencoder.
How does this connect to Variational Autoencoders specifically?
A Variational Autoencoder instantiates exactly this framework with neural networks: an encoder network parameterizes (typically outputting a Gaussian mean and variance), and a decoder network parameterizes . Training maximizes the ELBO via stochastic gradient ascent, using the reparameterization trick to backpropagate through the sampled latent . Every piece of the ELBO derivation — the Jensen's-inequality bound, the reconstruction-plus-KL decomposition, the interpretation of the gap as approximate-posterior error — carries over unchanged; the VAE's novelty is making both and flexible neural networks trained jointly and efficiently at scale, which is the natural next step after understanding the ELBO itself.