Quant Memo
Advanced

Variational Inference

A way to approximate a hard Bayesian posterior almost instantly by finding the simplest, easy-to-describe distribution that's closest to it — trading exactness for speed when a full MCMC run is too slow to be useful.

Prerequisites: Bayes' Theorem, Gibbs Sampling

Gibbs sampling and other MCMC methods get you an exact posterior, eventually — but "eventually" can mean hours or days for a model with millions of parameters, like a large ranking or recommendation model updated every trading day. Sometimes you need an answer in seconds, and you're willing to trade some accuracy for it. Variational inference is that trade: instead of drawing samples that gradually paint a picture of the true posterior, it picks a family of simple, easy-to-work-with distributions — independent normals, say — and directly optimizes to find the member of that family closest to the true posterior. No sampling, no waiting for a chain to converge — just an optimization problem, which is usually much faster to solve.

An analogy: fitting a rug to an oddly-shaped room

Imagine the true posterior is the exact, irregular floor plan of a room — full of alcoves and curves that no simple shape captures perfectly. MCMC is like carefully placing thousands of tiles across the whole floor, one by one, until their arrangement traces the true shape as closely as you like — accurate, but slow. Variational inference instead asks: "what's the best-fitting simple rectangular rug I can lay down, chosen from a catalog of rectangles, that covers as much of this room as well as possible?" You'll never get the alcoves exactly right, and the rug you pick is guaranteed to be simpler than the room — but you get an answer to "roughly what does this room look like" in the time it takes to measure four corners, not the time it takes to lay a thousand tiles.

true posterior (irregular) closest Gaussian
The true posterior (red, irregular) is approximated by the best-fitting member of a simple family — here, a single Gaussian (dashed). Variational inference searches within the simple family for the member minimizing the gap to the truth; it never recovers detail the family can't represent, like the true distribution's lobes.

The method, one symbol at a time

Let θ\theta be the parameters and p(θdata)p(\theta \mid \text{data}) the true (intractable) posterior. Choose a family of simpler distributions q(θ;ϕ)q(\theta; \phi) ("q of theta, indexed by phi") — for instance, a normal distribution, where ϕ\phi ("phi") stacks together its mean and variance. Variational inference finds the ϕ\phi that makes qq closest to pp, where "closest" is measured by the Kullback-Leibler divergence:

ϕ=argminϕ KL(q(θ;ϕ)  p(θdata)).\phi^{*} = \arg\min_{\phi}\ \text{KL}\big(q(\theta;\phi)\ \|\ p(\theta \mid \text{data})\big) .

In words: search over every candidate distribution in the simple family, and pick the one, ϕ\phi^*, that has the smallest KL divergence — a way of scoring how much probability mass one distribution puts where the other doesn't — to the true posterior. Because the true posterior itself is unknown (that's the whole problem), you can't compute the KL divergence directly. The trick is that minimizing it is mathematically equivalent to maximizing a different, computable quantity called the evidence lower bound (ELBO):

ELBO(ϕ)=Eq[lnp(data,θ)]Eq[lnq(θ;ϕ)].\text{ELBO}(\phi) = E_{q}\big[\ln p(\text{data}, \theta)\big] - E_{q}\big[\ln q(\theta;\phi)\big] .

In words: the ELBO rewards qq for putting probability mass where the data and prior jointly say it's likely (the first term), and separately rewards qq for staying spread out and uncertain rather than collapsing to a single point (the second term, an entropy bonus) — maximizing this quantity over ϕ\phi is a standard optimization problem, solvable with the same gradient-based tools used to train any other statistical model, and it provably pushes qq toward pp without ever needing pp itself.

A common simplifying choice, mean-field variational inference, assumes qq factorizes into independent pieces, one per parameter: q(θ1,,θk)=q1(θ1)qk(θk)q(\theta_1, \dots, \theta_k) = q_1(\theta_1)\cdots q_k(\theta_k). In words: assume the approximating distribution treats every parameter as independent of every other, which makes the optimization tractable but throws away any true correlation between parameters — a specific, known cost of the approximation, not a hidden one.

Variational inference turns "find the posterior" into "solve an optimization problem": pick a simple distribution family, and directly search for the member closest to the true posterior by maximizing the ELBO. It is fast because it's optimization, not sampling — and it is approximate for exactly the same reason: it can only ever return something as simple as the family you chose.

Worked example 1: approximating a skewed posterior with a Gaussian

Suppose the true posterior for a win-rate parameter (from few observed wins, hence right-skewed, as in the credible-intervals page) is Beta(3,39)\text{Beta}(3, 39), with true mean 3/42=0.07143/42 = 0.0714 and true variance 3×39422×43=11775852=0.00154\dfrac{3 \times 39}{42^2 \times 43} = \dfrac{117}{75852} = 0.00154 (standard deviation 0.0393\approx 0.0393). A mean-field variational fit restricted to Gaussians would match these first two moments as closely as the optimization allows, landing near qN(0.071, 0.00154)q^* \approx N(0.071,\ 0.00154). Compare the two: the true Beta posterior gives essentially zero probability to negative win rates (it's naturally bounded at 0), but the Gaussian approximation, being symmetric and unbounded, assigns roughly Pr(θ<0)=Φ(0.071/0.0393)=Φ(1.81)3.5%\Pr(\theta<0) = \Phi(-0.071/0.0393) = \Phi(-1.81) \approx 3.5\% probability to an impossible negative win rate. That 3.5% is not a computational error — it is the family-choice error worked example flagged in the analogy: the rug is a rectangle, the room has a curve, and no amount of optimizing the rectangle's position fixes that mismatch.

Worked example 2: ELBO improving over iterations

A simplified gradient-based fit tracks the ELBO across iterations as it climbs toward its maximum: iteration 1, ELBO=142.3\text{ELBO} = -142.3; iteration 10, ELBO=98.7\text{ELBO} = -98.7; iteration 50, ELBO=81.2\text{ELBO} = -81.2; iteration 200, ELBO=80.9\text{ELBO} = -80.9; iteration 500, ELBO=80.9\text{ELBO} = -80.9 (unchanged to one decimal). The ELBO rising and then flattening out is the direct, computable signal that qq has converged to the best approximation available within its family — you never see the true posterior or the KL divergence directly, but watching the ELBO plateau is the standard, practical stopping rule, exactly analogous to watching a training loss curve flatten when fitting any other model by gradient descent.

Distribution · normal
-0.010.070.15μvalue →
Within ±1σ 68.3%mean μ 0.07std σ 0.04

The bell curve above is the shape the Gaussian variational family is restricted to — no matter how well the optimization runs, the fitted approximation can only ever look like this shape, symmetric and unbounded, never the true skewed, bounded Beta posterior underneath it.

What this means in practice

  • Large-scale Bayesian models in production — recommendation systems, topic models, large hierarchical models refit daily — typically use variational inference or its stochastic variant precisely because MCMC's per-update cost is too high to run on a daily cadence at that scale.
  • Variational posteriors systematically understate uncertainty. The KL divergence used above penalizes qq heavily for putting mass where pp has none, which pushes the fitted qq to be narrower than the truth, especially under mean-field independence assumptions — a known, directional bias, not a random error, so credible intervals built from a variational posterior tend to be too tight.
  • Choose the family to match what you actually need. If you only need the posterior mean, the family-mismatch cost in worked example 1 barely matters; if you need an accurate tail probability (a VaR-style question), the mismatch can be the whole ballgame.
  • Compare to MCMC on a small version of the problem first. Before trusting a variational fit at production scale, validate it against exact Gibbs or Metropolis-Hastings samples on a scaled-down version where both are feasible to run.

The classic confusion: treating a variational posterior's reported uncertainty (its variance, its credible interval) with the same confidence as an MCMC-derived one. Because the KL divergence direction used in standard variational inference specifically penalizes qq for overspreading relative to pp, but under-penalizes qq for underspreading, the optimization is systematically biased toward overconfident, too-narrow approximations — worked example 1's 0.0393 standard deviation happened to match the truth by construction of the example, but in real fits with correlated parameters and mean-field independence assumptions, the variational posterior's spread is routinely much too small. Treat a variational credible interval as a plausible lower bound on your true uncertainty, not a substitute for it.

Related concepts

Practice in interviews

Further reading

  • Blei, Kucukelbir & McAuliffe (2017), Journal of the American Statistical Association
  • Bishop, Pattern Recognition and Machine Learning, ch. 10
ShareTwitterLinkedIn