Probability

Variational Inference

Variational inference turns posterior inference into optimization over a tractable family: maximize the ELBO, and the remaining gap is KL(q || posterior).

status: reviewimportance: importantdifficulty 4/5math: graduateread: 20mlive demo

Concept Structure

Variational Inference

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

4prerequisites
1next concepts
5related links

Learner Contract

What this page should let you do.

You are here becauseVariational inference turns posterior inference into optimization over a tractable family: maximize the ELBO, and the remaining gap is KL(q || posterior).

This Probability concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.

By the end4/4 sections ready | runnable code expected | live demo

Explain the mechanism, trace the main notation, and test one prediction in the live demo.

Do this firstIntuition

Read the intuition before the notation; the math should name a mechanism you already felt.

Then go nextVariational Autoencoders

Follow this edge after making one prediction here; the next page should reuse the result, not restart the route.

Test the linkManipulate one control and predict the visible change.Then continue to Variational Autoencoders

Claim/source review status

Substantive review recorded

1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.
Claims1/1 reviewed
Sources5 cited
Codeattached
Demolive
Reviewed2026-07-02
Updatedpage 2026-07-02

Learning item flow

4/4 sections readyAsk about thisResearch room
ConceptVariational InferenceProbability
5 sources attachedLocal snapshot ready
concept:probability/variational-inference
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

Bayesian inference gives the object we want:

p(zx),p(z\mid x),

the posterior distribution over hidden variables zz after observing data xx.

The trouble is that this posterior often requires a sum or integral over many hidden configurations. In a realistic latent-variable model, exact posterior inference can be the expensive part.

Variational inference changes the question. Instead of asking for the exact posterior, it asks:

Which distribution inside a tractable family is closest to the posterior?

Call that tractable distribution q(z)q(z). It might be a fully factorized mean-field distribution, a Gaussian with diagonal covariance, or a neural network that predicts distribution parameters. The family is the bargain. It makes optimization possible, but it also decides what kinds of uncertainty can be represented.

The core learning move is to watch the gap:

logp(x)=L(q)+KL(q(z)p(zx)).\log p(x) = \mathcal L(q) + \mathrm{KL}\big(q(z)\,\|\,p(z\mid x)\big).

The left side, logp(x)\log p(x), is the log evidence or marginal log likelihood. The first term, L(q)\mathcal L(q), is the evidence lower bound (ELBO). The second term is the price of approximation. If qq can match the true posterior, the KL gap is zero. If the family cannot express the posterior, the gap remains.

This is why variational inference is not "Bayes, but faster" in a casual sense. It is posterior inference turned into optimization, with a visible approximation contract.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

Let xx be observed data and let zz be latent. A latent-variable model specifies a joint density or mass function

pθ(x,z)=pθ(xz)p(z),p_\theta(x,z)=p_\theta(x\mid z)p(z),

where θ\theta are model parameters. The exact posterior is

pθ(zx)=pθ(x,z)pθ(x).p_\theta(z\mid x)=\frac{p_\theta(x,z)}{p_\theta(x)}.

The evidence is the normalizer

pθ(x)=zpθ(x,z),p_\theta(x)=\sum_z p_\theta(x,z),

or an integral when zz is continuous. This sum is often the hard object.

Choose a variational distribution q(z)q(z) from a family Q\mathcal Q. The ELBO is

L(q)=Eq(z)[logpθ(x,z)logq(z)].\mathcal L(q) = \mathbb E_{q(z)} \left[ \log p_\theta(x,z)-\log q(z) \right].

Equivalently,

L(q)=Eq[logpθ(x,z)]+H(q),\mathcal L(q) = \mathbb E_q[\log p_\theta(x,z)] + H(q),

where H(q)=Eq[logq(z)]H(q)=-\mathbb E_q[\log q(z)] is entropy. A good variational distribution must put mass on high-joint-probability latent states, but it is also rewarded for keeping enough entropy when that helps the bound.

Now derive the gap. Start from the reverse KL to the exact posterior:

KL(q(z)pθ(zx))=Eq[logq(z)logpθ(zx)].\mathrm{KL}\big(q(z)\,\|\,p_\theta(z\mid x)\big) = \mathbb E_q \left[ \log q(z)-\log p_\theta(z\mid x) \right].

Use logpθ(zx)=logpθ(x,z)logpθ(x)\log p_\theta(z\mid x)=\log p_\theta(x,z)-\log p_\theta(x):

KL(qpθ(zx))=Eq[logq(z)logpθ(x,z)+logpθ(x)]=logpθ(x)Eq[logpθ(x,z)logq(z)]=logpθ(x)L(q).\begin{aligned} \mathrm{KL}\big(q\,\|\,p_\theta(z\mid x)\big) &= \mathbb E_q[\log q(z)-\log p_\theta(x,z)+\log p_\theta(x)] \\ &= \log p_\theta(x) - \mathbb E_q[\log p_\theta(x,z)-\log q(z)] \\ &= \log p_\theta(x)-\mathcal L(q). \end{aligned}

So

logpθ(x)=L(q)+KL(qpθ(zx)).\log p_\theta(x) = \mathcal L(q) + \mathrm{KL}\big(q\,\|\,p_\theta(z\mid x)\big).

Because KL divergence is nonnegative,

L(q)logpθ(x).\mathcal L(q)\le \log p_\theta(x).

This is also Jensen's inequality in disguise:

logpθ(x)=logzq(z)pθ(x,z)q(z)zq(z)logpθ(x,z)q(z)=L(q),\log p_\theta(x) = \log \sum_z q(z)\frac{p_\theta(x,z)}{q(z)} \ge \sum_z q(z)\log \frac{p_\theta(x,z)}{q(z)} = \mathcal L(q),

assuming q(z)>0q(z)>0 only where the ratio is well-defined.

Mean-field variational inference chooses a factorized family such as

q(z1,,zm)=j=1mqj(zj).q(z_1,\ldots,z_m)=\prod_{j=1}^m q_j(z_j).

This can make coordinate updates tractable: optimize one factor qjq_j while holding the others fixed. The cost is representational. If the posterior has strong dependence or multiple separated modes, a simple qq family may fit only one part of it.

The direction of KL matters. The usual ELBO identity minimizes KL(qp)\mathrm{KL}(q\,\|\,p), often called exclusive or reverse KL in this context. With a restricted family, it can prefer a sharp approximation around one mode rather than spreading mass through a low-probability region between modes. That is a feature of the objective, not a bug in the arithmetic.

Amortized variational inference changes how qq is produced. Instead of optimizing separate variational parameters for every xx, a network predicts them:

qϕ(zx).q_\phi(z\mid x).

That is the bridge to variational autoencoders. The general idea here is still the same: optimize an ELBO, inspect the KL gap, and remember what the variational family can and cannot express.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
import numpy as np

z = np.array([-2, -1, 0, 1, 2])
log_joint = np.array([-2.9, -0.62, -3.9, -0.78, -2.4])

candidates = {
    "one_mode": np.array([0.06, 0.78, 0.11, 0.04, 0.01]),
    "covers_both": np.array([0.14, 0.24, 0.24, 0.24, 0.14]),
    "wrong_center": np.array([0.05, 0.18, 0.54, 0.18, 0.05]),
}

def logsumexp(v):
    m = v.max()
    return m + np.log(np.exp(v - m).sum())

log_px = logsumexp(log_joint)
posterior = np.exp(log_joint - log_px)

def score(q):
    expected_joint = np.sum(q * log_joint)
    entropy = -np.sum(q * np.log(q))
    elbo = expected_joint + entropy
    gap = log_px - elbo
    kl = np.sum(q * (np.log(q) - np.log(posterior)))
    return expected_joint, entropy, elbo, gap, kl

print("posterior:", np.round(posterior, 3).tolist())
print("log evidence:", round(log_px, 3))

for name, q in candidates.items():
    ej, h, elbo, gap, kl = score(q)
    print(name, "ELBO", round(elbo, 3), "gap", round(gap, 3), "KL", round(kl, 3))

The code mirrors the identity. log_px is exact because this toy latent space has only five states. Each candidate qq gets an expected joint score, an entropy reward, an ELBO, and a KL gap. The printed gap and KL match because

logp(x)L(q)=KL(qp(zx)).\log p(x)-\mathcal L(q)=\mathrm{KL}(q\|p(z\mid x)).
04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

The lab below hides the posterior and the ELBO ledger until you commit.

Choose a latent posterior case, inspect the candidate qq distributions, and predict which candidate has the highest ELBO. After reveal, compare three things:

  1. the exact posterior p(zx)p(z\mid x);
  2. the ELBO ledger for each qq;
  3. the gap logp(x)L(q)\log p(x)-\mathcal L(q).

Use the two-mode case as the main warning. A broad qq has more entropy, but it also puts mass through a low-joint-probability bridge. Under KL(qp)\mathrm{KL}(q\|p), the one-mode approximation can win even though it misses the other explanation.

Then switch to the tight case. When the family contains a good approximation, the KL gap nearly disappears. That contrast is the mechanism.

Live Concept Demo

Explore Variational Inference

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 4/5graduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Variational Inference should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

Variational inference turns posterior inference into optimization over a tractable family: maximize the ELBO, and the remaining gap is KL(q || posterior).

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Variational Inference should make visible.

Visual Inquiry

Make the image answer a mathematical question

Variational inference turns posterior inference into optimization over a tractable family: maximize the ELBO, and the remaining gap is KL(q || posterior).

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Variational Inference easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

course-notes · 2026CS228 Notes: Variational InferenceStanford CS228

Supports VI as inference-as-optimization, KL(q||p), the variational lower bound/ELBO, reverse-KL support behavior, mean-field families, and coordinate-ascent intuition.

Open source
paper · 2017Variational Inference: A Review for StatisticiansBlei, Kucukelbir, and McAuliffe

Review source for VI as approximating difficult posterior densities by optimizing within a chosen family using KL divergence, with mean-field and stochastic-optimization context.

Open source
book · 2016Deep Learning, Chapter 19: Approximate InferenceGoodfellow, Bengio, and Courville

Deep-learning textbook anchor for approximate inference, variational methods, KL direction, and mean-field caveats.

Open source
book · 2023Probabilistic Machine Learning: Advanced TopicsKevin P. Murphy

Broad probabilistic-ML reference for modern approximate inference and the relationship between variational and Monte Carlo inference.

Open source
course-notes · 2019Deep Generative Models Notes: Variational AutoencodersStanford CS236-style course notes

Supports the latent-variable ELBO, the KL gap to the true posterior, black-box VI, amortized VI, and the VAE bridge.

Open source

Claim Review

Variational inference turns posterior inference into optimization over a tractable family: maximize the ELBO, and the remaining gap is KL(q || posterior).

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources5 references

cs228-variational-inference-notes, blei-2017-vi-review, goodfellow-2016-deep-learning-inference, murphy-2023-probml-advanced, cs236-vae-notes

Local checks4 local checks

Use equations, runnable code, and demos to check whether the source support is operational.

Substantively reviewedVariational inference chooses a tractable family q(z), optimizes the ELBO E_q[log p(x,z)-log q(z)], and leaves an approximation gap exactly equal to KL(q(z)||p(z|x)) for the chosen posterior target.Claim metadata: source checked

The sources support the ELBO identity, family-restricted approximation, reverse-KL objective, mean-field coordinate optimization context, stochastic/amortized VI bridge, and the caveat that optimization/family choices control the returned approximation.

Sources: CS228 Notes: Variational Inference, Variational Inference: A Review for Statisticians, Deep Learning, Chapter 19: Approximate Inference, Probabilistic Machine Learning: Advanced Topics, Deep Generative Models Notes: Variational AutoencodersFinite discrete witness only; excludes continuous estimators, structured/collapsed/flow VI, convergence guarantees, and calibration.A bounded review summary is present; still check caveats and exact reference scope.

Checked CS228 for VI as optimization over a family, KL(q||p), the variational lower bound/ELBO, reverse-KL support behavior, and mean-field coordinate ascent; checked Blei et al. for the family-plus-KL optimization framing and caveats; checked CS236-style notes for latent-variable ELBO, KL gap, black-box VI, amortized VI, and VAE bridge. GPT Pro publication critique remains pending.

Reviewer: codex-local-source-review; reviewed 2026-07-02

Practice Loop

Try the idea before it explains itself

Variational inference turns posterior inference into optimization over a tractable family: maximize the ELBO, and the remaining gap is KL(q || posterior).

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Variational Inference.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded research drawerClose
ConceptVariational InferenceProbability

Research Room

Attach the question to a claim, equation, code, or demo

Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptProbability

Variational Inference

Attached question

What is the smallest example that makes Variational Inference click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays in this browser, attached to the selected learning item.

No local draft saved.
Evidence to inspect
  • References to inspect: attached references on this page.
  • Definition, prerequisite, and contrast concept links
  • The equation or runnable code that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Variational Inference Selected item key: recorded for copy. Context: Probability Page anchor: recorded for copy. Open question: What is the smallest example that makes Variational Inference click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

View it in context
concept/concept-notebook/probability/variational-inference concept:probability/variational-inference