Variational inference

Also known as: VI · variational Bayes

On this page 7

Variational inference (VI), also called variational Bayes, is a family of methods that approximates an intractable posterior distribution with a simpler, tractable distribution chosen by optimization. Within probabilistic models in artificial intelligence, it replaces the exact computation of the posterior with a search over a restricted variational family, selecting the member that is closest to the true posterior in Kullback-Leibler divergence.

The central idea is to turn inference into optimization. Instead of drawing samples as Markov chain Monte Carlo does, variational inference adjusts the parameters of an approximating distribution until an objective, the evidence lower bound (ELBO), stops improving. This makes it fast and scalable to large datasets and deep models, at the price of a systematic approximation error.

How variational inference works

Variational inference starts from a model with observed data x and latent variables z, where the posterior p(z | x) requires the marginal likelihood p(x), an integral that is usually impossible to compute exactly. The method introduces an approximating distribution q(z), indexed by variational parameters, and minimizes the divergence KL(q(z) || p(z | x)).

Because that divergence itself contains the unknown p(x), the method maximizes an equivalent objective. The log evidence decomposes as log p(x) = ELBO(q) + KL(q || p), and since the divergence is never negative, the ELBO is a lower bound on the log marginal likelihood. Maximizing the ELBO therefore minimizes the divergence to the posterior.

The ELBO can be written as the expected log joint probability under q plus the entropy of q. The first term rewards placing mass where the model explains the data well; the entropy term prevents the approximation from collapsing onto a single point.

The main components of a variational inference procedure are summarized below.

ComponentRoleTypical choice
Variational familySet of candidate approximationsFactorized Gaussians, normalizing flows
ObjectiveQuantity to maximizeEvidence lower bound
DivergenceMeasure of approximation errorReverse KL divergence KL(q || p)
OptimizerUpdates variational parametersCoordinate ascent, stochastic gradient methods
Gradient estimatorEstimates ELBO gradientsReparameterization or score function estimator
Components of a variational inference procedure

Main variants of variational inference

Variational inference has evolved from closed-form coordinate updates for conjugate models to black-box, gradient-based methods that work with neural networks. The variants differ in how they choose the family and how they compute gradients.

VariantKey ideaTypical use
Mean-field VILatent variables treated as independent in qTopic models, mixture models
Coordinate ascent VIClosed-form updates for each factor in turnConditionally conjugate exponential family models
Stochastic VINoisy natural gradients from data minibatchesVery large corpora and datasets
Black-box VIMonte Carlo gradient estimates for any modelProbabilistic programming systems
Amortized inferenceA neural encoder predicts variational parametersVariational autoencoders
Structured VIKeeps selected dependencies between variablesTime series, hierarchical models
Major variational inference variants

The mean-field approximation is the classic starting point because it makes updates simple, but it ignores correlations. Normalizing flows and full-covariance Gaussians enrich the family at higher computational cost, and the reparameterization trick made low-variance gradients practical for continuous latent variables.

Variational inference compared with other inference methods

Variational inference is one of several approximate inference strategies, and its main competitor is Markov chain Monte Carlo. The choice is a trade-off between speed and asymptotic accuracy.

MethodStrengthWeakness
Variational inferenceFast, scalable, easy convergence monitoringBiased; tends to underestimate variance
Markov chain Monte CarloAsymptotically exact samplesSlow on large data, hard to diagnose mixing
Laplace approximationCheap Gaussian around the modePoor for skewed or multimodal posteriors
Expectation propagationMinimizes forward KL locally, often better calibratedCan fail to converge
Maximum a posteriori estimationSingle point estimate, very cheapNo uncertainty information
Comparison of approximate inference methods

A key technical distinction concerns the direction of the divergence. Variational inference minimizes the reverse KL divergence, which is mode-seeking: it penalizes q for placing mass where p is small, so the approximation usually concentrates on one mode and underestimates posterior uncertainty. Expectation propagation uses the forward direction, which is mass-covering.

Where variational inference is used

Variational inference is the default inference engine for large latent variable models. In latent Dirichlet allocation, it fits topic models to millions of documents. In variational autoencoders, amortized variational inference trains an encoder and a decoder jointly by maximizing the ELBO.

It also underpins many Bayesian neural networks, where a Gaussian distribution over each weight provides a measure of epistemic uncertainty, and probabilistic programming languages offer automatic variational inference so that practitioners can fit custom models without deriving updates by hand. Gaussian process models use sparse variational methods with inducing points to scale beyond tens of thousands of observations.

Because the ELBO is a bound on log p(x), it also serves as an approximate criterion for model comparison. Practitioners compare ELBO values across model variants, such as different numbers of topics or mixture components, although a tighter bound in one model can distort the comparison when the variational families differ in quality. Variational methods are equally common in streaming and online settings, where parameters must be updated as new data arrive without revisiting the full history.

Limitations and practical pitfalls

Variational inference gives an answer quickly, but that answer is only as good as the variational family. A converged ELBO does not prove that the approximation is accurate, so practitioners should validate results against MCMC on smaller subsets or with simulation-based calibration checks.

SymptomLikely causeRemedy
Overconfident credible intervalsMean-field family ignores correlationsUse full-rank or flow-based families
Noisy or diverging ELBOHigh-variance gradient estimatesReparameterization, control variates, smaller step size
Latent variables ignored by decoderPosterior collapse in amortized modelsKL annealing, weaker decoders
Different results across runsNon-convex objective with local optimaMultiple restarts, better initialization
Common problems in variational inference

Another subtle issue is the amortization gap: an encoder network may not find the optimal variational parameters for every data point, so amortized inference can be less accurate than per-example optimization even within the same family.

Put simply

Some questions in statistics have exact answers that are too hard to compute. Variational inference takes a shortcut. It picks a simple shape that is easy to work with. Then it bends and stretches that shape until it fits the true answer as closely as possible.

Imagine tracing a complicated coastline with a flexible ruler. The ruler cannot follow every rock and inlet. It still gives a useful outline, and it gives it quickly. The catch is that the outline can look more certain than reality.

In practice

A news archive team wants to organize 2 million articles into themes such as politics, sport and science. They fit a latent Dirichlet allocation model with 200 topics. Running Gibbs sampling on the full archive would take days, so they use stochastic variational inference with minibatches of 1,000 articles.

Each minibatch updates the topic estimates with a small, decreasing step size. The ELBO stabilizes after a few passes over the data, and training finishes in a few hours on a single server. Editors review the top words of each topic and confirm that most themes are coherent. The team then spot-checks a sample of 20,000 articles with MCMC and finds similar topics, which confirms that the faster approximation is good enough for search and recommendation.