Skip to content
AIAI Wranglers

8 Variational Inference

Every probabilistic model with latent variables poses the same fundamental question: given observed data 𝒙, what can we say about the hidden variables 𝒛? Answering this question means computing the posterior distribution p(𝒛|𝒙). In simple models such as the Gaussian mixture model of Chapter ch:gmm, the posterior factorises into a short list of responsibilities p(zi=k|𝒙i;θ), each available in closed form. But in the deep latent-variable models that drive modern generative AI, including variational autoencoders (Chapter ch:vae), hierarchical VAEs, and diffusion models (Chapter ch:diffusion), the posterior is a high-dimensional, intricately correlated distribution that no closed-form expression can capture.

Variational inference (VI) resolves this impasse by reframing inference as optimisation: instead of computing p(𝒛|𝒙) exactly, we search over a tractable family 𝒬 for the member q(𝒛) closest to the true posterior. The “closeness” is measured by Kullback–Leibler divergence, and the optimisation target is the evidence lower bound (ELBO), the same quantity we met briefly in the EM algorithm (Section sec:gmm:elbo).

This chapter develops variational inference from first principles. We begin with motivation (Section Introduction and Motivation), revisit the asymmetry of KL divergence (Section KL Divergence Revisited), derive the ELBO in depth (Section The Evidence Lower Bound), build the classical mean-field framework (Section Mean-Field Variational Inference), and present the coordinate ascent algorithm (Section Coordinate Ascent Variational Inference). File B of this chapter continues with stochastic variational inference, amortised inference, and the reparameterisation trick that powers VAEs.

Historical Note.

Variational inference has roots in three disciplines. In physics, the mean-field approximation originated with Pierre Curie (1895) and Pierre-Ernest Weiss (1907), who approximated interacting spin systems by replacing many-body interactions with an effective average field. In information theory, Kullback and Leibler (1951) [1] formalised the divergence that serves as the loss function. In statistics and machine learning, the modern formulation crystallised in the 1990s through the work of Hinton and van Camp (1993), Waterhouse, MacKay, and Robinson (1996), and especially Jordan, Ghahramani, Jaakkola, and Saul (1999) [2], who unified these threads into a general framework for approximate Bayesian inference. The ELBO itself echoes the Gibbs–Bogoliubov variational free energy of statistical mechanics, closing a circle that spans more than a century.

Introduction and Motivation

The Central Problem: Posterior Inference

Consider a latent-variable model specified by a prior p(𝒛) and a likelihood p(𝒙|𝒛). The joint density is p(𝒙,𝒛)=p(𝒛)p(𝒙|𝒛), and Bayes' theorem gives the posterior (Bayes)p(𝒛|𝒙)=p(𝒙,𝒛)p(𝒙)=p(𝒛)p(𝒙|𝒛)p(𝒛)p(𝒙|𝒛)d𝒛. The denominator p(𝒙)=p(𝒙,𝒛)d𝒛 is the marginal likelihood (or evidence). Computing it requires integrating the joint density over the entire latent space, a sum over KN configurations for a GMM with N data points, or an integral over m for a continuous latent space.

Example 1 (Posterior Intractability in Practice).

  1. Gaussian mixture model (K components, N points): The posterior p(𝒛1:N|𝒙1:N) involves a sum over KN joint assignments, exponential in N. The EM algorithm sidesteps this by factorising over data points, but this factorisation is a special feature of the GMM.

  2. Bayesian neural network: The posterior over weights p(𝒘|𝒟) is a distribution in |𝒘| shaped by the nonlinear likelihood. Even for a small network with 104 weights, this integral is hopelessly high-dimensional.

  3. Variational autoencoder: The posterior p(𝒛|𝒙) for a single image involves integrating over a latent space m with m typically 64512. The nonlinear decoder makes the integral analytically intractable.

  4. Latent Dirichlet allocation: The posterior over topic assignments for a corpus of D documents with vocabulary size V and K topics has no closed form.

The difficulty is not merely practical but fundamental:

Proposition 1 (Hardness of Exact Inference).

Computing the marginal likelihood p(𝒙) (and hence the posterior) is #P-hard for general graphical models [3]. Even approximate inference to within a constant factor is NP-hard in the worst case.

This hardness result means that no algorithm can solve arbitrary inference problems efficiently, and we must accept approximations. Two great families of approximate inference have emerged:

  1. Markov chain Monte Carlo (MCMC): construct a Markov chain whose stationary distribution is p(𝒛|𝒙) and collect samples. MCMC is asymptotically exact (given infinite time, the samples converge to the true posterior), but convergence diagnostics are difficult, and the method can be prohibitively slow for large datasets.

  2. Variational inference (VI): choose a tractable family 𝒬 and find the member q𝒬 closest to the posterior. VI is biased (the optimum q generally differs from the true posterior) but fast: it inherits the scalability of optimisation, including stochastic gradient methods.

The Inference Landscape

Figure fig:vi:landscape provides a bird's-eye view of inference methods, organised by their accuracy–speed trade-off.

The inference landscape. Exact methods (green) are limited to models with special structure (trees, small treewidth). MCMC methods (purple) are asymptotically exact but slow. Variational methods (blue) trade some accuracy for speed and scalability. Modern approaches such as normalising-flow VI blur the boundary between VI and MCMC.

The Core Idea: Inference as Optimisation

Key Idea.

Inference = Optimisation. Instead of computing p(𝒛|𝒙) analytically or sampling from it, variational inference posits a family of tractable distributions 𝒬={qϕ(𝒛):ϕΦ} and solves the optimisation problem q(𝒛)=arg minq𝒬𝖣KL(q(𝒛)p(𝒛|𝒙)). This converts an integration problem (hard) into a search problem (tractable with gradient-based methods). The quality of the approximation depends on the richness of the family 𝒬.

Remark 1 (Why “Variational”?).

The name variational comes from the calculus of variations, the branch of mathematics concerned with optimising functionals, that is, functions of functions. Here we optimise the KL divergence, which is a functional of the distribution q. When 𝒬 is a nonparametric family (e.g. all distributions that factorise in a certain way), the optimisation is genuinely variational: we take functional derivatives and set them to zero, exactly as in classical mechanics when deriving the Euler–Lagrange equations.

Road Map

The remainder of this chapter is organised as follows.

  1. Section KL Divergence Revisited: KL Divergence Revisited. We examine the crucial asymmetry between forward and reverse KL, which determines why VI uses the reverse direction.

  2. Section The Evidence Lower Bound: The Evidence Lower Bound. We derive the ELBO from multiple perspectives and explore its decompositions.

  3. Section Mean-Field Variational Inference: Mean-Field VI. We introduce the fully factorised approximation and derive the optimal factors via functional optimisation.

  4. Section Coordinate Ascent Variational Inference: Coordinate Ascent VI. We present the classical CAVI algorithm and apply it to Bayesian Gaussian mixture models.

  5. File B continues with stochastic VI, amortised inference, and connections to VAEs (Chapter ch:vae) and diffusion models (Chapter ch:diffusion).

Insight.

The ELBO is the universal currency of deep generative models. Whether you are training a VAE (Chapter ch:vae), a hierarchical VAE, or deriving the variational diffusion objective (Section sec:diff:vdm:elbo), the ELBO appears as the central objective. Mastering its derivation and decompositions in this chapter will pay dividends across the rest of the book.

Why Posterior Inference Matters

Before diving into the technical machinery, let us emphasise why computing, or approximating, the posterior p(𝒛|𝒙) is so important. The posterior answers three distinct questions:

  1. What do the latent variables look like? In a mixture model, the posterior p(zi|𝒙i) tells us which cluster generated each observation. In a topic model, it tells us which topics are present in each document. In a VAE, it tells us the latent “code” that summarises each data point.

  2. How uncertain are we? Bayesian posteriors quantify uncertainty. The posterior p(𝒘|𝒟) of a neural network's weights tells us not just the best-guess parameters but how confident we should be. This is crucial for safety-critical applications (medical diagnosis, autonomous driving) and for active learning (where we query the most uncertain inputs).

  3. How do we learn model parameters? In the EM framework (Chapter ch:gmm), the E-step requires the posterior p(𝒛|𝒙;θ). In VAEs, the approximate posterior qϕ(𝒛|𝒙) appears in the ELBO gradient. Posterior inference is not just a downstream task; it is integral to training.

Example 2 (The Posterior in Real Applications).

  • Medical imaging (VAE): A radiologist feeds a chest X-ray into a VAE. The approximate posterior qϕ(𝒛|𝒙) compresses the image into a latent code 𝒛. The spread of this posterior indicates how ambiguous the image is; a blurry or atypical scan produces a wider posterior, flagging it for human review.

  • Recommendation systems (matrix factorisation): The posterior over user and item latent factors quantifies our uncertainty about each user's preferences, allowing the system to recommend items that are both likely to be enjoyed and informative for reducing uncertainty.

  • Drug discovery (Bayesian optimisation): The posterior over a surrogate model's parameters drives the acquisition function that selects the next molecule to synthesise. Overconfident posteriors lead to premature exploitation; underconfident posteriors lead to wasteful exploration.

Remark 2 (The Inference–Learning Duality).

There is a deep duality between inference and learning:

  • Inference holds the model fixed and reasons about the latent variables: p(𝒛|𝒙;θ).

  • Learning holds the latent variables fixed (or marginalised) and adjusts the model: θ=arg maxθlogp(𝒙;θ).

In the EM algorithm and in variational inference, these two problems are solved alternately: inference updates the latent variables, learning updates the parameters. The ELBO provides the objective for both.

KL Divergence Revisited

The KL divergence was introduced in Chapter ch:divergences (Definition def:kl) and appeared naturally in the ELBO decomposition for GMMs (Proposition prop:ll:decompose). In this section we examine a subtlety that is central to variational inference: the two directions of KL divergence behave very differently, and choosing the “wrong” direction would make VI impractical.

Recap: KL Divergence

Recall that for two continuous distributions with densities p and q on d, the KL divergence from q to p is (DEF)𝖣KL(qp)=q(𝒛)logq(𝒛)p(𝒛)d𝒛=𝔼q[logq(𝒛)p(𝒛)]. By Gibbs' inequality (Theorem thm:gibbs), 𝖣KL(qp)0 with equality if and only if q=p almost everywhere. Crucially, KL divergence is asymmetric: 𝖣KL(qp)𝖣KL(pq) in general.

Forward vs. Reverse KL

Let p(𝒛) denote the target distribution (in our setting, p(𝒛|𝒙)) and q(𝒛) the approximation. The two directions of KL divergence optimise very different objectives.

Definition 1 (Forward and Reverse KL).

  • The forward KL (or inclusive KL, moment-projection, M-projection) minimises (FWD KL)𝖣KL(pq)=𝔼p[logp(𝒛)q(𝒛)]=𝖧(p)𝔼p[logq(𝒛)].

  • The reverse KL (or exclusive KL, information-projection, I-projection) minimises (REV KL)𝖣KL(qp)=𝔼q[logq(𝒛)p(𝒛)]=𝖧(q)𝔼q[logp(𝒛)].

The terms “inclusive” and “exclusive” hint at the qualitative difference, which we now make precise.

Proposition 2 (Behaviour of Forward and Reverse KL).

Let p be the target and q the approximation.

  1. Forward KL is zero-avoiding (mode-covering): Wherever p(𝒛)>0, the term p(𝒛)log(p(𝒛)/q(𝒛)) in the forward KL blows up if q(𝒛)0. Hence the optimal q must place mass everywhere p does, even if this means spreading mass into low-density regions.

  2. Reverse KL is zero-forcing (mode-seeking): Wherever q(𝒛)>0, the term q(𝒛)log(q(𝒛)/p(𝒛)) blows up if p(𝒛)0. Hence the optimal q avoids placing mass where p is small, even if this means ignoring entire modes of p.

Proof.

  1. For any 𝒛0 with p(𝒛0)>0, the integrand in the forward KL contains p(𝒛0)logp(𝒛0)q(𝒛0)+ as q(𝒛0)0. Thus the minimum-KL solution q must satisfy q(𝒛)>0 whenever p(𝒛)>0: it covers all modes.

  2. For any 𝒛0 with q(𝒛0)>0, the reverse KL integrand contains q(𝒛0)logq(𝒛0)p(𝒛0)+ as p(𝒛0)0. Thus the minimum-KL solution must satisfy q(𝒛)=0 whenever p(𝒛)=0: it avoids regions of zero target density and typically selects a single mode.

Visualising the Asymmetry

The following figure is perhaps the single most important illustration for understanding variational inference.

Fitting a single Gaussian q to a bimodal target p. (a) Forward KL (𝖣KL(pq)): the optimal q is a broad Gaussian covering both modes, placing density in the valley between them. (b) Reverse KL (𝖣KL(qp)): the optimal q is a narrow Gaussian concentrating on a single mode, ignoring the other entirely.

Why Reverse KL for Variational Inference

Given the mode-seeking behaviour of the reverse KL, one might ask: isn't the forward KL a better choice, since it covers all modes? The answer is no, for a pragmatic but decisive reason.

Proposition 3 (Computational Feasibility of the Two Directions).

Let p=p(𝒛|𝒙) be the intractable posterior and q=q(𝒛) the approximation.

  1. Forward KL requires 𝔼p(𝒛|𝒙)[logq(𝒛)], an expectation under the intractable posterior p(𝒛|𝒙). We cannot compute this without already knowing the posterior.

  2. Reverse KL requires 𝔼q(𝒛)[logp(𝒛|𝒙)], an expectation under the tractable approximation q(𝒛). We can compute (or estimate via Monte Carlo) this expectation because sampling from q is easy.

Proof.

Expanding the forward KL: 𝖣KL(p(𝒛|𝒙)q(𝒛))=𝔼p(𝒛|𝒙)[logp(𝒛|𝒙)logq(𝒛)]. This requires sampling from or integrating over p(𝒛|𝒙), which is precisely what we cannot do.

Expanding the reverse KL: 𝖣KL(q(𝒛)p(𝒛|𝒙))=𝔼q(𝒛)[logq(𝒛)logp(𝒛|𝒙)]. All expectations are under q, which we control. Moreover, we will show in Section The Evidence Lower Bound that minimising this quantity is equivalent to maximising the ELBO, which only requires evaluating the joint logp(𝒙,𝒛), not the intractable posterior.

Insight.

Forward KL needs the truth; reverse KL only needs your guess. The forward KL 𝖣KL(pq) takes expectations under the unknown target p, an apparent chicken-and-egg problem. The reverse KL 𝖣KL(qp) takes expectations under the known approximation q, which we designed to be easy to sample from. This computational asymmetry, not any preference for mode-seeking behaviour, is the primary reason variational inference uses the reverse KL.

Worked Example: Gaussian Approximation to a Mixture

To build intuition, let us compute both KL divergences explicitly for a toy problem.

Example 3 (Both KL Directions for a Mixture).

Let the target be a symmetric mixture of two unit-variance Gaussians: p(z)=12𝒩(z|μ0,1)+12𝒩(z|+μ0,1),μ0=3. We approximate p with a single Gaussian q(z)=𝒩(z|m,s2).

Forward KL. Since 𝖣KL(pq)=𝖧(p)𝔼p[logq(z)], and the entropy 𝖧(p) is independent of q, minimising over (m,s2) amounts to maximising 𝔼p[logq(z)]=12log(2πs2)12s2𝔼p[(zm)2]. By symmetry of p, the optimal mean is m=0. Using 𝔼p[z2]=1+μ02=10 (since 𝖵arp(z)=1+μ02=10 and 𝔼p[z]=0), the optimal variance is s2=𝔼p[(z0)2]=10. Hence qfwd(z)=𝒩(0,10), a very broad Gaussian straddling both modes, placing significant density in the valley at z=0 where p(z)0.

Reverse KL. We minimise 𝖣KL(qp)=𝔼q[logq(z)]𝔼q[logp(z)]. The term 𝔼q[logp(z)] is a log-sum-exp that cannot be computed in closed form, but we can optimise it numerically. Due to the mode-seeking property, gradient descent initialised near z=+μ0 converges to qrev(z)𝒩(3,1), a tight Gaussian sitting on one mode and ignoring the other entirely.

Summary. qfwd=𝒩(0,10)mode-coveringvs.qrev𝒩(3,1)mode-seeking. The forward KL fit has the correct mean but wildly overestimates the variance. The reverse KL fit captures one mode precisely but misses the other.

Properties of KL Divergence

For completeness, we collect the key properties that will be used throughout.

Proposition 4 (Properties of KL Divergence).

  1. Non-negativity (Gibbs' inequality): 𝖣KL(qp)0, with equality iff q=p a.e.

  2. Asymmetry: 𝖣KL(qp)𝖣KL(pq) in general.

  3. Not a metric: The triangle inequality does not hold.

  4. Invariance under invertible transformations: If 𝒛=f(𝒛) with f a diffeomorphism, then 𝖣KL(q𝒛p𝒛)=𝖣KL(q𝒛p𝒛).

  5. Additivity for independent distributions: If q(𝒛)=jqj(zj) and p(𝒛)=jpj(zj), then 𝖣KL(qp)=j𝖣KL(qjpj).

  6. Chain rule: 𝖣KL(q(𝒛1,𝒛2)p(𝒛1,𝒛2))=𝖣KL(q(𝒛1)p(𝒛1))+𝔼q(𝒛1)[𝖣KL(q(𝒛2|𝒛1)p(𝒛2|𝒛1))].

Proof of (d).

Let 𝒛=f(𝒛). Under the change of variables, q𝒛(𝒛)=q𝒛(f1(𝒛))|detJf1(𝒛)|, and similarly for p. The Jacobian factors cancel in the ratio: 𝖣KL(q𝒛p𝒛)=q𝒛(𝒛)logq𝒛(𝒛)p𝒛(𝒛)d𝒛=q𝒛(𝒛)logq𝒛(𝒛)p𝒛(𝒛)d𝒛=𝖣KL(q𝒛p𝒛). This invariance is central to normalising flows, where the latent space is transformed through a chain of diffeomorphisms.

Remark 3 (Looking Ahead: Other Divergences in VI).

The restriction to reverse KL is a design choice, not a law of nature. Replacing it with other divergences yields different algorithms:

  • α-divergence VI [4]: interpolates between forward and reverse KL using Rényi's α-divergence.

  • Stein variational gradient descent (SVGD): uses the kernelised Stein discrepancy, combining the flexibility of particles with the speed of optimisation.

  • χ2-divergence VI: gives tighter bounds on the marginal likelihood at the cost of higher variance gradients.

Each choice trades off bias, variance, and computational cost in different ways. We focus on the reverse KL because it leads directly to the ELBO.

The Evidence Lower Bound

The evidence lower bound (ELBO) is the central object of variational inference. It is simultaneously:

  • a lower bound on the log-evidence logp(𝒙),

  • the objective function that VI maximises,

  • a bridge between the intractable posterior and the tractable approximation.

We derive it from two complementary perspectives and then explore its multiple decomposition forms, each of which highlights a different aspect of the inference–learning trade-off.

Derivation Route 1: Jensen's Inequality

Theorem 1 (ELBO via Jensen's Inequality).

For any distribution q(𝒛) over the latent variables, (Jensen)logp(𝒙)𝔼q(𝒛)[logp(𝒙,𝒛)q(𝒛)]=def(q). The quantity (q) is called the evidence lower bound (ELBO).

Proof.

Start from the marginal likelihood and introduce q: (Step1)logp(𝒙)=logp(𝒙,𝒛)d𝒛=logq(𝒛)p(𝒙,𝒛)q(𝒛)d𝒛q(𝒛)logp(𝒙,𝒛)q(𝒛)d𝒛=𝔼q(𝒛)[logp(𝒙,𝒛)q(𝒛)]=(q). The inequality in is Jensen's inequality applied to the concave function log(): log(𝔼[Y])𝔼[logY] for any positive random variable Y.

Remark 4 (Jensen's Gap).

The gap between logp(𝒙) and (q) is sometimes called Jensen's gap. From our second derivation (below), we will see that this gap is exactly 𝖣KL(q(𝒛)p(𝒛|𝒙)), the KL divergence from the approximation to the true posterior. Jensen's inequality is tight (gap =0) if and only if the random variable inside the expectation is constant almost surely, which happens when q(𝒛)=p(𝒛|𝒙).

Derivation Route 2: KL Decomposition

The second derivation is more revealing: it shows exactly where the gap comes from and why maximising the ELBO is equivalent to minimising the reverse KL divergence.

Theorem 2 (ELBO Gap Identity).

For any distribution q(𝒛), (GAP)logp(𝒙)=(q)+𝖣KL(q(𝒛)p(𝒛|𝒙)). Equivalently, (GAP ALT)(q)=logp(𝒙)𝖣KL(q(𝒛)p(𝒛|𝒙)).

Proof.

Expand the KL divergence between q(𝒛) and the true posterior p(𝒛|𝒙): (Step1)𝖣KL(q(𝒛)p(𝒛|𝒙))=𝔼q[logq(𝒛)p(𝒛|𝒙)]=𝔼q[logq(𝒛)logp(𝒙,𝒛)p(𝒙)]=𝔼q[logq(𝒛)logp(𝒙,𝒛)]+logp(𝒙)=(q)+logp(𝒙). In we used Bayes' theorem p(𝒛|𝒙)=p(𝒙,𝒛)/p(𝒙); in the term logp(𝒙) exits the expectation because it does not depend on 𝒛. Rearranging gives .

This is the same decomposition we encountered for GMMs in Proposition prop:ll:decompose (equation ), now stated in full generality. The identity has three immediate consequences:

Corollary 1 (Consequences of the ELBO Gap Identity).

  1. Lower bound: Since 𝖣KL0, we have (q)logp(𝒙) for all q.

  2. Maximising the ELBO minimising the KL: Since logp(𝒙) is constant with respect to q, arg maxq𝒬(q)=arg minq𝒬𝖣KL(q(𝒛)p(𝒛|𝒙)).

  3. Tightness: The bound is tight ((q)=logp(𝒙)) if and only if 𝖣KL(q(𝒛)p(𝒛|𝒙))=0, i.e. q(𝒛)=p(𝒛|𝒙) a.e.

Key Idea.

The ELBO links three quantities. The log-evidence logp(𝒙) decomposes into the ELBO (q) (what we can compute and optimise) plus the KL divergence 𝖣KL(qp(𝒛|𝒙)) (the approximation error we are trying to minimise). Since logp(𝒙) is fixed, pushing one up pushes the other down.

Three Decompositions of the ELBO

The ELBO can be written in several equivalent forms, each emphasising a different interpretation.

Proposition 5 (Three Faces of the ELBO).

For any variational distribution q(𝒛), the ELBO admits the following equivalent decompositions: (Form1)(q)=𝔼q[logp(𝒙,𝒛)]energy+𝖧(q)entropy=𝔼q[logp(𝒙|𝒛)]reconstruction𝖣KL(q(𝒛)p(𝒛))regularisation=logp(𝒙)evidence𝖣KL(q(𝒛)p(𝒛|𝒙))gap where 𝖧(q)=𝔼q[logq(𝒛)] is the entropy of q.

Proof.

Form 1: Expand the definition directly: (q)=𝔼q[logp(𝒙,𝒛)logq(𝒛)]=𝔼q[logp(𝒙,𝒛)]+𝖧(q). Form 2: Factor the joint as p(𝒙,𝒛)=p(𝒙|𝒛)p(𝒛): (q)=𝔼q[logp(𝒙|𝒛)+logp(𝒛)logq(𝒛)]=𝔼q[logp(𝒙|𝒛)]𝔼q[logq(𝒛)p(𝒛)]=𝔼q[logp(𝒙|𝒛)]𝖣KL(q(𝒛)p(𝒛)). Form 3: This is a restatement of the ELBO gap identity .

Each form provides a different lens:

  1. Energy + Entropy (Form 1): This is the classical variational free energy formulation from statistical physics. Maximising balances fitting the model (low energy = high 𝔼q[logp(𝒙,𝒛)]) against spreading out (high entropy 𝖧(q)).

  2. Reconstruction Regularisation (Form 2): This is the form most commonly used in VAEs (Section sec:vae:elbo). The first term rewards q for concentrating on latent configurations that explain the data well; the KL term penalises q for deviating from the prior, acting as a regulariser.

  3. Evidence Gap (Form 3): This shows the ELBO as the log-evidence minus an approximation error. It is the most conceptually transparent form but the least computationally useful, since logp(𝒙) is unknown.

Three faces of the ELBO. All three expressions are algebraically identical. The arrows indicate the algebraic steps connecting them. Form 1 connects to statistical physics, Form 2 to VAE training, and Form 3 to the quality of posterior approximation.

Worked Example: ELBO for a Gaussian Model

To solidify understanding, we compute the ELBO in closed form for a simple conjugate model.

Example 4 (ELBO for a Univariate Gaussian with Known Variance).

Suppose we observe x1,,xNiid𝒩(μ,σ2) with known variance σ2 and wish to infer the mean μ with a Gaussian prior μ𝒩(μ0,σ02).

True posterior (for reference). By conjugacy, the posterior is Gaussian: (TRUE Posterior)p(μ|x1:N)=𝒩(μ|μN,σN2),σN2=(1σ02+Nσ2)1,μN=σN2(μ0σ02+Nxσ2), where x=1Ni=1Nxi.

Variational approximation. Let q(μ)=𝒩(μ|m,s2) with free parameters (m,s2). We compute the ELBO using Form 2: (m,s2)=𝔼q[i=1Nlogp(xi|μ)]reconstruction𝖣KL(q(μ)p(μ))regularisation.

Reconstruction term. 𝔼q[i=1Nlogp(xi|μ)]=𝔼q[N2log(2πσ2)12σ2i=1N(xiμ)2]=N2log(2πσ2)12σ2i=1N[(xim)2+s2]=N2log(2πσ2)12σ2[Ns2+i(xim)2], using 𝔼q[(xiμ)2]=(xim)2+s2.

KL term. Using the formula for KL between univariate Gaussians (Proposition prop:kl-gaussian-1d): 𝖣KL(q(μ)p(μ))=logσ0s+s2+(mμ0)22σ0212.

Optimal variational parameters. Setting m=0 and s2=0, we obtain m=μN,s2=σN2. The variational approximation recovers the exact posterior! This is expected: when the true posterior lies within the variational family 𝒬 (here, the family of all Gaussians), the ELBO is maximised at q=p(μ|x1:N) and the KL gap vanishes.

Remark 5 (Conjugacy and Tightness).

Example Example 4 is special: the true posterior is Gaussian, so a Gaussian variational family can capture it exactly. In most models of interest (VAEs, Bayesian neural networks, topic models), the true posterior is not in 𝒬, and the ELBO is strictly below logp(𝒙). The gap 𝖣KL(qp(𝒛|𝒙)) measures the price we pay for using a tractable approximation.

Tightness of the ELBO

Proposition 6 (ELBO Tightness Condition).

The ELBO is tight, (q)=logp(𝒙), if and only if q(𝒛)=p(𝒛|𝒙) almost everywhere. Consequently:

  1. If p(𝒛|𝒙)𝒬, then the optimal ELBO equals the log-evidence.

  2. If p(𝒛|𝒙)𝒬, then the ELBO gap is minq𝒬𝖣KL(qp(𝒛|𝒙))>0, and the ELBO underestimates logp(𝒙).

The ELBO as a Training Objective

In practice, the ELBO is used not only for inference (optimising q) but also for learning (optimising model parameters θ). When the model has parameters θ (e.g. a neural network decoder), we maximise the ELBO jointly over q and θ: (Joint)maxθ,q𝒬(θ,q)=maxθ,q𝒬𝔼q(𝒛)[logpθ(𝒙,𝒛)q(𝒛)]. This is the principle behind the VAE objective (Section sec:vae:elbo): the encoder parameterises qϕ, the decoder parameterises pθ, and both are optimised jointly via stochastic gradient ascent on the ELBO.

Example 5 (ELBO as a Lower Bound: Numerical Illustration).

Consider the conjugate model from Example Example 4 with N=5 observations x=(1.2,0.8,1.5,1.1,0.9), prior μ𝒩(0,4), and known variance σ2=1.

The exact log-evidence can be computed: p(𝒙)=i=15𝒩(xi|μ,1)𝒩(μ|0,4)dμ=(2π)5/2(2π4)1/2(2πσN2)1/2exp(12ixi2+12μN2σN2). With x=1.1, σN2=(1/4+5)1=4/210.190, and μN=σN25x=(4/21)5.51.048: logp(𝒙)7.14.

Now consider three variational approximations q(μ)=𝒩(m,s2):

Approximation(m,s2)(q)𝖣KL(qp(μ|𝒙))
Optimal q(1.048,0.190)7.140
Wide q(1.048,1.0)7.750.61
Off-centre q(0,0.190)9.912.77
The optimal q recovers the exact log-evidence (as expected for a conjugate model). The wide approximation pays a moderate penalty; the off-centre approximation pays a large penalty, confirming that both the mean and variance of q matter.

Connection to Statistical Physics

Remark 6 (The ELBO as Variational Free Energy).

In statistical physics, a system at inverse temperature β has a Helmholtz free energy F=ETS, where E is the internal energy, T=1/β is the temperature, and S is the entropy. The Gibbs–Bogoliubov inequality states that for any trial distribution q, F𝔼q[E(𝒛)]T𝖧(q)=defFvar(q), with equality when q is the Boltzmann distribution q(𝒛)=exp(βE(𝒛))/Z.

Setting β=1 and identifying E(𝒛)=logp(𝒙,𝒛), we see that Fvar(q)=(q). Thus maximising the ELBO is equivalent to minimising the variational free energy, the same principle that physicists have used since Gibbs (1902) and Bogoliubov (1958).

The ELBO and the Exponential Family

When the model p(𝒙,𝒛) belongs to the exponential family, the ELBO and its gradients take particularly clean forms. This is the setting where classical (non-stochastic) variational inference is most naturally derived.

Definition 2 (Exponential Family).

A distribution p(𝒛|𝜼) is in the exponential family with natural parameter 𝜼 if its density can be written as (Expfam)p(𝒛|𝜼)=h(𝒛)exp{𝜼𝖳𝒕(𝒛)A(𝜼)}, where 𝒕(𝒛) is the vector of sufficient statistics, A(𝜼)=logh(𝒛)exp(𝜼𝖳𝒕(𝒛))d𝒛 is the log-partition function, and h(𝒛) is the base measure.

Proposition 7 (ELBO Gradient for Exponential-Family Models).

If q(𝒛)=q(𝒛|𝝀) is in the exponential family with natural parameters 𝝀, then (Expfam GRAD)𝝀=𝝀2A(𝝀)(𝔼q[𝒛logp(𝒙,𝒛)]𝝀). At the optimum, 𝝀 satisfies a fixed-point equation involving the expected sufficient statistics of the complete-data distribution under q.

Remark 7 (Conjugate Models Are Especially Nice).

When the model p(𝒙,𝒛) is conditionally conjugate (each complete conditional p(zj|𝒛j,𝒙) belongs to the exponential family), the mean-field optimal factor qj from Theorem thm:vi:mf:optimal is guaranteed to be in the same exponential family. This means:

  1. The functional form of each qj is known a priori (Gaussian, Gamma, Dirichlet, etc.).

  2. The update reduces to computing the natural parameters of qj, which are expectations of sufficient statistics.

  3. No numerical optimisation is needed within each coordinate step, only moment computations.

This is why the BGMM example in Section Extended Example: CAVI for Bayesian Gaussian Mixture Models works so cleanly: the Dirichlet–Categorical and Gaussian–Gaussian conjugacies ensure all updates are in closed form.

The ELBO in Deep Generative Models

Remark 8 (Forward References: ELBO Across the Book).

The ELBO appears in many guises throughout this book:

  • GMMs (Section sec:gmm:elbo): the EM algorithm performs coordinate ascent on the ELBO with a discrete latent variable.

  • VAEs (Section sec:vae:elbo): the ELBO decomposes into reconstruction + KL, optimised jointly over encoder ϕ and decoder θ via the reparameterisation trick.

  • Diffusion models (Section sec:diff:vdm:elbo): the ELBO for a Markov chain of latent variables decomposes into a sum of local KL terms, one per diffusion step.

  • Hierarchical VAEs: the ELBO extends to multiple layers of latent variables, with the KL chain rule yielding a telescoping sum.

In every case, the ELBO serves the same dual purpose: it provides a tractable training objective and a measure of model quality.

Mean-Field Variational Inference

The ELBO gap identity (Theorem Theorem 2) tells us to maximise (q) over a variational family 𝒬. But which family? The choice of 𝒬 determines both the quality of the approximation and the difficulty of the optimisation. The simplest and historically most important choice is the mean-field family, in which the variational distribution factorises completely over the latent variables.

The Mean-Field Assumption

Definition 3 (Mean-Field Variational Family).

Let 𝒛=(z1,z2,,zJ) be a partition of the latent variables into J groups (each zj may itself be a vector). The mean-field variational family is the set of distributions that factorise as (MF)𝒬MF={q(𝒛)=j=1Jqj(zj)|each qj is a valid density}. Each factor qj(zj) is called a variational factor and is optimised independently. No parametric form is assumed for the factors; they are determined by the optimisation.

Historical Note.

The mean-field idea originated in the physics of magnetism. Pierre-Ernest Weiss (1907) proposed that each spin in a ferromagnet experiences an effective “mean field” generated by the average of all other spins, rather than interacting with each one individually. This Curie–Weiss theory replaced a many-body problem with a single-body problem in an effective field, exactly the strategy of mean-field VI. The extension to general probabilistic models was formalised by Jordan et al. (1999) [2], who recognised that the same decoupling principle applies to any graphical model.

The mean-field assumption is drastic: by forcing q(𝒛)=jqj(zj), we ignore all correlations between the groups z1,,zJ. If the true posterior has strong dependencies between latent variables, as it often does, this introduces bias. But the payoff is computational: the optimal factors have a remarkably simple form.

Optimal Mean-Field Factors

Theorem 3 (Optimal Mean-Field Update).

Under the mean-field assumption q(𝒛)=j=1Jqj(zj), the ELBO is maximised with respect to a single factor qj, holding all others qj={qk:kj} fixed, when (Optimal)logqj(zj)=𝔼qj[logp(𝒙,𝒛)]+const, where 𝔼qj denotes the expectation with respect to all variational factors except qj: 𝔼qj[]=(kjqk(zk))()kjdzk. Equivalently, (Optimal EXP)qj(zj)exp{𝔼qj[logp(𝒙,𝒛)]}.

Proof.

We isolate the dependence of the ELBO on qj. Write q(𝒛)=qj(zj)kjqk(zk) and expand: (Proof Expand)(q)=q(𝒛)logp(𝒙,𝒛)q(𝒛)d𝒛=qj(zj)[kjqk(zk)logp(𝒙,𝒛)kjdzk]dzjqj(zj)logqj(zj)dzjkjqk(zk)logqk(zk)dzk. The last line (entropies of other factors) is constant with respect to qj. Define p~(zj)=𝔼qj[logp(𝒙,𝒛)]. The terms involving qj are: (Proof KL)[j]=qj(zj)p~(zj)dzjqj(zj)logqj(zj)dzj+const. Define q^(zj)exp{p~(zj)}. Then [j]=qjlogq^dzj+logZq^qjlogqjdzj+const=𝖣KL(qjq^)+logZq^+const, where Zq^ is the normalisation constant of q^. Since 𝖣KL0, the maximum is attained at qj=q^, i.e. qj(zj)exp{𝔼qj[logp(𝒙,𝒛)]}.

Remark 9 (Functional Optimisation).

Theorem Theorem 3 is a result from the calculus of variations: we optimise the functional with respect to the function qj, with no parametric assumption on qj. The optimal qj is determined entirely by the model's joint distribution p(𝒙,𝒛) and the current values of the other factors. In practice, if the model is in the exponential family, the optimal qj belongs to a recognisable parametric family (Gaussian, Gamma, Dirichlet, etc.), and the update reduces to computing its natural parameters.

Example: Mean-Field for the Ising Model

The Ising model is the prototypical example from statistical physics.

Example 6 (Mean-Field Ising Model).

Consider a lattice of N binary spins zi{1,+1} with pairwise interactions: p(𝒛)=1Zexp((i,j)Jijzizj+i=1Nhizi), where is the set of edges (e.g. nearest neighbours on a grid), Jij are coupling strengths, hi are external fields, and Z is the (intractable) partition function.

Mean-field approximation. Assume q(𝒛)=i=1Nqi(zi), where each qi is a Bernoulli distribution parameterised by mi=𝔼qi[zi][1,1].

By Theorem Theorem 3: logqi(zi)=𝔼qi[(i,j)Jijzizj+hizi]+const=zi(j𝒩(i)Jijmj+hi)+const, where 𝒩(i) are the neighbours of spin i and mj=𝔼qj[zj]. Normalising: mi=tanh(j𝒩(i)Jijmj+hi). Each spin's magnetisation is determined by the average magnetisation of its neighbours, the “mean field” that gives the method its name.

Mean-field decoupling for the Ising model. Left: The exact model has pairwise interactions (edges) between neighbouring spins. Right: The mean-field approximation replaces interactions with an effective field, making all spins independent. Each spin zi is parameterised by its mean magnetisation mi.

Example: Mean-Field for a Bivariate Gaussian

Before tackling a full model, let us see mean-field VI in action on the simplest possible example: a two-dimensional Gaussian.

Example 7 (Mean-Field for a Correlated Bivariate Gaussian).

Let p(z1,z2)=𝒩((00),(1ρρ1)) with |ρ|<1. We apply the mean-field factorisation q(z1,z2)=q1(z1)q2(z2).

Optimal q1. By Theorem Theorem 3: logq1(z1)=𝔼q2[logp(z1,z2)]+const=𝔼q2[12(1ρ2)(z122ρz1z2+z22)]+const=12(1ρ2)(z122ρz1𝔼q2[z2])+const. Let μ2=𝔼q2[z2]. Completing the square: q1(z1)=𝒩(ρμ2,1ρ2).

Optimal q2. By symmetry: q2(z2)=𝒩(ρμ1,1ρ2).

Fixed point. The coupled system μ1=ρμ2 and μ2=ρμ1 has the unique solution μ1=μ2=0 (since |ρ|<1). Hence: q(z1,z2)=𝒩(z1|0,1ρ2)𝒩(z2|0,1ρ2).

What is lost? The marginal means are correct (μ1=μ2=0), but the marginal variances are 1ρ2 instead of the true value 1. The mean-field approximation underestimates the marginal variances, and of course sets the covariance to zero. The KL gap is 𝖣KL(qp)=log(1ρ2)+(1ρ2)1+ρ2+(1ρ2)1=log(1ρ2)ρ2. As |ρ|1, this gap diverges; the mean-field approximation becomes arbitrarily poor for strongly correlated variables.

This simple example encapsulates the core trade-off of mean-field VI: tractability (independent factors) versus fidelity (capturing correlations).

Example: Mean-Field for Bayesian Linear Regression

We now apply mean-field VI to a workhorse statistical model.

Example 8 (Mean-Field Bayesian Linear Regression).

Consider the Bayesian linear regression model: (Prior TAU)τGamma(a0,b0),𝒘𝒩(0,τ1I),yi|𝒘,τ𝒩(𝒘𝖳𝒙i,τ1),i=1,,N, where τ is the noise precision, 𝒘d is the weight vector, and {(𝒙i,yi)}i=1N are training pairs.

Mean-field factorisation. We posit q(𝒘,τ)=q𝒘(𝒘)qτ(τ), a complete factorisation between weights and precision.

Optimal factor for 𝒘. By Theorem Theorem 3: logq𝒘(𝒘)=𝔼qτ[logp(𝒚,𝒘,τ)]+const=𝔼qτ[τ2i=1N(yi𝒘𝖳𝒙i)2τ2𝒘𝖳𝒘]+const=τ2[𝒘𝖳(i=1N𝒙i𝒙i𝖳+I)𝒘2𝒘𝖳i=1Nyi𝒙i]+const, where τ=𝔼qτ[τ]. This is a quadratic form in 𝒘, so q𝒘(𝒘)=𝒩(𝒘|𝒎𝒘,𝑺𝒘) with (QW)𝑺𝒘=τ1(i=1N𝒙i𝒙i𝖳+I)1,𝒎𝒘=τ𝑺𝒘i=1Nyi𝒙i.

Optimal factor for τ. Similarly: logqτ(τ)=𝔼q𝒘[logp(𝒚,𝒘,τ)]+const=(a01)logτb0τ+N+d2logττ2𝔼q𝒘[i=1N(yi𝒘𝖳𝒙i)2+𝒘𝖳𝒘]+const. This is the log-density of a Gamma distribution: qτ(τ)=Gamma(τ|aN,bN) with (QTAU)aN=a0+N+d2,bN=b0+12𝔼q𝒘[i=1N(yi𝒘𝖳𝒙i)2+𝒘𝖳𝒘]. The expectation in bN uses 𝔼q𝒘[𝒘𝖳𝑨𝒘]=𝒎𝒘𝖳𝑨𝒎𝒘+trace(𝑨𝑺𝒘).

Key observation. The optimal q𝒘 depends on τ (from qτ), and the optimal qτ depends on moments of q𝒘. Neither can be computed independently: we must iterate, updating one factor while holding the other fixed. This is the coordinate ascent algorithm of Section Coordinate Ascent Variational Inference.

Mean-Field vs. Exact Posterior

The mean-field approximation decouples the latent variables, which means it cannot represent posterior correlations. The following figure illustrates this concretely.

The mean-field approximation ignores posterior correlations. Left: The true posterior has a tilted elliptical shape, indicating correlation between z1 and z2. Right: The mean-field approximation q(z1)q(z2) is constrained to axis-aligned ellipses, losing the off-diagonal structure.

Caution.

Mean field ignores correlations. The mean-field approximation q(𝒛)=jqj(zj) sets all posterior covariances between different groups to zero: 𝖢ovq(zj,zk)=0 for jk. This can cause:

  1. Underestimation of posterior variance in individual variables (the marginal qj may be too narrow because it cannot “borrow” uncertainty from correlated variables).

  2. Poor uncertainty quantification in downstream tasks that depend on joint distributions (e.g. predictive intervals).

  3. Overconfident predictions in Bayesian models where parameter correlations are important (e.g. multicollinear regression).

When correlations are critical, consider structured VI (e.g. block mean-field, Gaussian with full covariance, or normalising-flow families) at the cost of harder optimisation.

Structured Variational Families

Proposition 8 (Mean-Field Is Dominated by Structured Approximations).

Let 𝒬MF𝒬S𝒬all, where 𝒬S is a structured family that preserves some dependencies. Then maxq𝒬MF(q)maxq𝒬S(q)logp(𝒙). A richer variational family always yields a tighter (or equal) ELBO, at the cost of harder optimisation.

Proof.

Since 𝒬MF𝒬S, the maximum over the larger set is at least as large. The upper bound logp(𝒙) follows from the ELBO gap identity.

Remark 10 (Beyond Mean Field).

Common structured families include:

  • Block mean-field: Group related variables and allow correlations within blocks: q(𝒛)=q1(𝒛block1)q2(𝒛block2)

  • Gaussian with full covariance: q(𝒛)=𝒩(𝒛|𝒎,𝑺) with 𝑺 a full (or low-rank + diagonal) covariance matrix.

  • Normalising-flow families: Transform a simple base distribution through a sequence of invertible maps, allowing q to capture complex dependencies.

  • Amortised inference: Use a neural network qϕ(𝒛|𝒙) to map each observation to its own approximate posterior, the approach of VAEs (Definition def:vae:vae).

Each choice moves up the accuracy–cost trade-off curve of Figure fig:vi:landscape.

Coordinate Ascent Variational Inference

The optimal mean-field updates of Theorem Theorem 3 give us the best factor qj when all other factors are held fixed. But each update depends on the moments of the other factors, creating a system of coupled equations. The natural solution is to iterate: update each factor in turn, cycling through all J groups. This is the coordinate ascent variational inference (CAVI) algorithm.

The CAVI Algorithm

Algorithm 1 (Coordinate Ascent Variational Inference (CAVI)).

Input: Model p(𝒙,𝒛), data 𝒙, partition 𝒛=(z1,,zJ).

Output: Variational factors q1(z1),,qJ(zJ).

Initialise: Set each factor qj(0)(zj) to a reasonable initialisation (e.g. random, prior, or moment-matched).

for t=1,2,3, until convergence:

  1. for j=1,2,,J: enumerate[(a)]

  2. Compute the expected log-joint under all factors except qj: logqj(t)(zj)𝔼qj(t)[logp(𝒙,𝒛)]+const.

  3. Normalise qj(t) to obtain a valid density.

  4. Extract the sufficient statistics / moments of qj(t) needed by other updates. enumerate

  5. Compute (t)=(q(t)) to monitor convergence.

  6. if |(t)(t1)|<ϵ, stop.

Monotonic Convergence

Theorem 4 (CAVI Monotonically Increases the ELBO).

Each CAVI update (updating a single factor qj while holding others fixed) increases (q), or leaves it unchanged if qj is already optimal. Consequently, the sequence (0),(1),(2), is non-decreasing.

Proof.

From the proof of Theorem Theorem 3, the ELBO restricted to qj (with all other factors fixed) is [j](qj)=𝖣KL(qjq^j)+constqj, where q^j(zj)exp{𝔼qj[logp(𝒙,𝒛)]}. The CAVI update sets qj=q^j, achieving 𝖣KL=0 and thus maximising [j]. Since =[j]+constqj, the full ELBO cannot decrease.

Since the ELBO is bounded above by logp(𝒙), the monotone bounded sequence converges.

Remark 11 (Local Optima).

CAVI is guaranteed to converge to a local maximum (or saddle point) of the ELBO, not necessarily the global maximum. The ELBO landscape for mean-field VI is generally non-convex, even when the model is in the exponential family. In practice:

  • Multiple random initialisations are used, and the run with the highest final ELBO is selected.

  • The initialisation can significantly affect both the speed of convergence and the quality of the solution.

  • For mixture models, the symmetry of the model means that permuting cluster labels gives equivalent solutions (the “label-switching” problem).

Extended Example: CAVI for Bayesian Gaussian Mixture Models

We now develop a complete CAVI algorithm for the Bayesian Gaussian mixture model (BGMM), the canonical example in variational inference. This extends the EM algorithm of Chapter ch:gmm by placing priors on all parameters and performing fully Bayesian inference.

Example 9 (Bayesian Gaussian Mixture Model - Full Specification).

Generative model. For K components in d with N observations: (PI)𝝅Dirichlet(α0,,α0),𝝁k𝒩(𝒎0,β01I),k=1,,K,ziCategorical(𝝅),i=1,,N,𝒙i|zi=k𝒩(𝝁k,σ2I),i=1,,N, where we use isotropic covariances σ2I (known) for simplicity. The latent variables are 𝒛=(𝝅,𝝁1:K,z1:N).

Joint log-density. (Joint)logp(𝒙,𝒛)=logp(𝝅)+k=1Klogp(𝝁k)+i=1N[logp(zi|𝝅)+logp(𝒙i|zi,𝝁1:K)].

Variational factorisation. We use the mean-field factorisation: (MF)q(𝝅,𝝁1:K,z1:N)=q(𝝅)k=1Kq(𝝁k)i=1Nq(zi).

We now derive each optimal factor using Theorem Theorem 3.

Update for q(zi): Cluster Assignments

The terms in logp(𝒙,𝒛) that involve zi are logp(zi|𝝅) and logp(𝒙i|zi,𝝁1:K). By Theorem Theorem 3: (Z Update)logq(zi=k)=𝔼qzi[logπk+log𝒩(𝒙i|𝝁k,σ2I)]+const=𝔼q(𝝅)[logπk]+𝔼q(𝝁k)[log𝒩(𝒙i|𝝁k,σ2I)]+const. Define the “responsibility” parameters: (RHO)ρikexp{𝔼[logπk]12σ2𝔼q(𝝁k)[𝒙i𝝁k2]}, normalised so that kρik=1. These are the variational analogue of the EM responsibilities (Section sec:gmm:em).

The expectations needed are:

  • 𝔼[logπk]: the digamma function, computed from the Dirichlet factor q(𝝅).

  • 𝔼q(𝝁k)[𝒙i𝝁k2]=𝒙i𝒎k2+trace(𝑺k), where 𝒎k,𝑺k are the mean and covariance of q(𝝁k).

Update for q(𝝁k): Cluster Means

The terms involving 𝝁k are logp(𝝁k) and the likelihood terms for all 𝒙i assigned to cluster k: (MU LOG)logq(𝝁k)=𝔼q𝝁k[logp(𝝁k)+i=1N𝟙[zi=k]log𝒩(𝒙i|𝝁k,σ2I)]+const=β02𝝁k𝒎0212σ2i=1Nρik𝒙i𝝁k2+const. Completing the square in 𝝁k, this is Gaussian: (Q MU)q(𝝁k)=𝒩(𝝁k|𝒎k,𝑺k), with (MU Params)𝑺k=(β0I+Nkσ2I)1,𝒎k=𝑺k(β0𝒎0+1σ2i=1Nρik𝒙i), where Nk=i=1Nρik is the effective number of points assigned to cluster k. This is a precision-weighted average of the prior mean 𝒎0 and the data centroid 𝒙k=1Nkiρik𝒙i.

Update for q(𝝅): Mixing Weights

The terms involving 𝝅 are logp(𝝅) (the Dirichlet prior) and ilogp(zi|𝝅): (PI LOG)logq(𝝅)=𝔼q𝝅[(α01)klogπk+i=1Nk=1K𝟙[zi=k]logπk]+const=k=1K(α01+Nk)logπk+const. This is the log-density of a Dirichlet distribution: (Q PI)q(𝝅)=Dirichlet(α0+N1,,α0+NK). The expected log-mixing weights needed by the zi-update are: (Elogpi)𝔼[logπk]=ψ(α0+Nk)ψ(k=1K(α0+Nk)), where ψ() is the digamma function ψ(x)=ddxlogΓ(x).

Summary of CAVI Updates

Algorithm 2 (CAVI for Bayesian GMM).

Input: Data {𝒙1,,𝒙N}d, number of components K, hyperparameters α0,𝒎0,β0,σ2.

Initialise: Set ρik=1/K for all i,k (or use k-means).

repeat:

  1. Update q(𝝅): Compute Nk=iρik and set αk=α0+Nk for each k. Compute 𝔼[logπk] via .

  2. Update q(𝝁k) for k=1,,K: Compute 𝒎k and 𝑺k via .

  3. Update q(zi) for i=1,,N: Compute ρik via and normalise.

  4. Compute ELBO (t) (see below).

until |(t)(t1)|<ϵ.

Computing the ELBO for Monitoring

To monitor convergence, we must evaluate the ELBO (q)=𝔼q[logp(𝒙,𝒛)]𝔼q[logq(𝒛)] at each iteration. Using the mean-field factorisation :

(ELBO FULL)=𝔼q[logp(𝝅)]𝔼q[logq(𝝅)]Dirichlet terms+k=1K(𝔼q[logp(𝝁k)]𝔼q[logq(𝝁k)])Gaussian mean terms+i=1N(𝔼q[logp(zi|𝝅)]+𝔼q[logp(𝒙i|zi,𝝁1:K)]𝔼q[logq(zi)])data terms.

Each term involves expectations of log-densities under their respective variational factors, all of which are available in closed form for exponential-family models:

  • Dirichlet terms: 𝔼[logp(𝝅)]𝔼[logq(𝝅)] involves the difference of two Dirichlet log-normalisation constants plus digamma expectations.

  • Gaussian mean terms: 𝔼[logp(𝝁k)]𝔼[logq(𝝁k)]=𝖣KL(q(𝝁k)p(𝝁k)), computable via the closed-form KL between Gaussians (Proposition prop:kl-gaussian-mv).

  • Data terms: 𝔼[logp(zi|𝝅)]=kρik𝔼[logπk]; the reconstruction term uses 𝔼[𝒙i𝝁k2]=𝒙i𝒎k2+trace(𝑺k); the entropy of q(zi) is kρiklogρik.

CAVI Iterations: A Visual Example

CAVI iterations for a Bayesian GMM with K=3 on 2D data. Left: After initialisation, cluster means 𝒎k are poorly placed and uncertainty circles (dashed) are wide. Centre: By iteration 5, the means migrate toward the data clusters and uncertainty shrinks. Right: By iteration 10, the algorithm has converged: each cluster mean sits at the centre of its assigned points (colour-coded), and the posterior uncertainty is small.

Comparison with EM

CAVI for the Bayesian GMM bears a striking resemblance to EM for the frequentist GMM (Chapter ch:gmm). The following table makes the correspondence explicit.

AspectEM (frequentist GMM)CAVI (Bayesian GMM)
ParametersPoint estimates θ={πk,𝝁k,𝚺k}Distributions q(𝝅),q(𝝁k)
E-stepCompute γik=p(zi=k|𝒙i;θ)Update q(zi): ρik via
M-stepMaximise Q(θ,θ(t)) over θUpdate q(𝝅), q(𝝁k)
ObjectiveLog-likelihood (θ)ELBO (q)
UncertaintyNone (point estimate)Full posterior over all parameters
OverfittingCan overfit with large KAutomatic regularisation via prior
K selectionRequires BIC/AICAutomatic pruning (empty clusters)
Side-by-side comparison of EM and CAVI for Gaussian mixture models.
EM vs. CAVI as coordinate ascent. Both algorithms alternate between updating latent-variable distributions and model parameters. EM uses point estimates; CAVI maintains full distributions. CAVI generalises EM: when the variational family is restricted to delta functions for the parameters and free distributions for the assignments, CAVI reduces to EM.

Proposition 9 (EM as a Special Case of CAVI).

If the variational family for the parameters is restricted to point masses q(θ)=δ(θθ^), then CAVI reduces to the EM algorithm:

  1. The q(zi) update becomes the E-step (computing responsibilities under the current θ^).

  2. The q(θ) “update” becomes the M-step (finding the θ^ that maximises the expected complete-data log-likelihood).

Proof.

With q(θ)=δ(θθ^), the expected log-joint 𝔼qzi[logp(𝒙,𝒛)] evaluated at θ=θ^ gives the same responsibilities as the E-step. Maximising the ELBO over θ^ with fixed q(z) is equivalent to maximising 𝔼q(z)[logp(𝒙,z;θ)], which is the M-step objective Q(θ,θ(t)).

Practical Considerations

Remark 12 (Initialisation Strategies).

Good initialisation is critical for CAVI:

  1. k-means initialisation: Run k-means on the data and use the cluster assignments to initialise ρik. This is the most common strategy.

  2. Random initialisation: Draw ρik from a Dirichlet distribution and normalise. Repeat with multiple random seeds.

  3. Prior initialisation: Set variational parameters to the prior hyperparameters. This is conservative but can be slow to converge.

  4. Spectral initialisation: Use the leading eigenvectors of the data matrix for initial cluster structure.

Remark 13 (Convergence Diagnostics).

In practice, CAVI convergence is monitored by tracking the ELBO across iterations. Additional diagnostics include:

  • Checking that the ELBO is monotonically non-decreasing (any decrease indicates a bug).

  • Monitoring the change in variational parameters between iterations.

  • For mixture models, tracking the effective number of clusters Keff=#{k:Nk>ϵ}.

Typical convergence occurs in 10100 iterations for well-initialised models, though this depends on the model complexity and data size.

Remark 14 (CAVI as Message Passing).

The CAVI updates have an elegant interpretation as message passing on the graphical model. Each factor qj sends “messages” (its sufficient statistics) to the factors it interacts with through the joint distribution. This perspective, formalised as variational message passing (VMP) [5], allows automatic derivation of CAVI updates for any conjugate exponential-family model. Software packages such as Infer.NET and Edward implement this paradigm.

CAVI and Natural Gradients

There is an elegant connection between the CAVI coordinate updates and the natural gradient of information geometry.

Proposition 10 (CAVI Performs Natural Gradient Ascent).

When each factor qj belongs to an exponential family with natural parameters 𝜼j, the CAVI update 𝜼j(t+1)=arg max𝜼j(qj(;𝜼j),qj(t)) is equivalent to a natural gradient step with unit step size: (Natgrad)𝜼j(t+1)=𝜼j(t)+𝑭j1𝜼j|𝜼j(t), where 𝑭j is the Fisher information matrix of qj. In the natural parameterisation, 𝑭j1𝜼j simplifies, and the update becomes a direct replacement of natural parameters.

This connection is important because it explains why CAVI converges rapidly in practice: natural gradients account for the curvature of the distribution space and take optimally large steps. It also paves the way for stochastic natural-gradient methods, where we replace the full-data sufficient statistics with mini-batch estimates, the basis of stochastic variational inference (SVI), covered in File B.

Predictive Distribution

After convergence, the variational approximation can be used for prediction. For the Bayesian GMM, the predictive density for a new observation 𝒙 is:

(Predictive)p(𝒙|𝒙1:N)p(𝒙|𝒛)q(𝒛)d𝒛=k=1K𝔼q[πk]𝒩(𝒙|𝝁k,σ2I)q(𝝁k)d𝝁k.

Since both the likelihood and q(𝝁k) are Gaussian, the inner integral is available in closed form:

(Predictive Closed)𝒩(𝒙|𝝁k,σ2I)𝒩(𝝁k|𝒎k,𝑺k)d𝝁k=𝒩(𝒙|𝒎k,σ2I+𝑺k).

The predictive distribution is therefore itself a Gaussian mixture kπk𝒩(𝒎k,σ2I+𝑺k) with πk=𝔼q[πk]=(α0+Nk)/k(α0+Nk). Notice that the predictive covariance σ2I+𝑺k is larger than the noise covariance σ2I: the additional term 𝑺k captures our epistemic uncertainty about the cluster mean. As N, 𝑺k0 and the predictive distribution converges to the plug-in estimate, and the Bayesian and frequentist answers agree asymptotically.

Remark 15 (Model Comparison via the ELBO).

Since the ELBO lower-bounds logp(𝒙), it can serve as a proxy for Bayesian model comparison. Given two models 1 and 2, we prefer the one with the higher optimised ELBO: 1=maxq𝒬11(q)vs.2=maxq𝒬22(q). This is an automatic, principled alternative to BIC/AIC that naturally penalises model complexity through the KL regularisation term. For the BGMM, this approach can determine the number of clusters K without cross-validation: simply run CAVI for several values of K and select the K with the highest ELBO.

Limitations of CAVI

Caution.

When CAVI falls short. Despite its elegance, classical CAVI has significant limitations:

  1. Requires conjugacy: The optimal factor qjexp{𝔼qj[logp(𝒙,𝒛)]} is only tractable when the model is conjugate exponential family. Non-conjugate models require approximations within each update.

  2. Does not scale to large datasets: Each update sweeps over all N data points. For N=106, this is prohibitively expensive.

  3. Mean-field bias: The factorised approximation ignores posterior correlations, which may be severe.

  4. Local optima: The non-convex ELBO landscape means results depend on initialisation.

  5. No amortisation: Each new data point requires re-running the full optimisation, and there is no way to “generalise” the inference to unseen inputs.

These limitations motivate the development of stochastic variational inference (which scales to large data), black-box VI (which handles non-conjugate models), and amortised VI (which generalises across data points), all of which are covered in File B of this chapter. The amortised approach leads directly to the VAE (Chapter ch:vae).

Exercises

Exercise 1 (ELBO Derivation).

  1. Derive the ELBO via Jensen's inequality, starting from logp(𝒙)=logp(𝒙,𝒛)d𝒛.

  2. Derive the ELBO via the KL decomposition, starting from 𝖣KL(q(𝒛)p(𝒛|𝒙)).

  3. Show that the two derivations yield the same expression.

  4. Under what condition is the bound tight?

Exercise 2 (Forward vs. Reverse KL).

Let p(z)=12𝒩(z|3,1)+12𝒩(z|3,1) and q(z)=𝒩(z|m,s2).

  1. Find the optimal (m,s2) minimising 𝖣KL(pq) analytically.

  2. Argue that the optimal (m,s2) minimising 𝖣KL(qp) concentrates on one mode. Use gradient descent to find the solution numerically.

  3. Plot both approximations and the target. Which captures the “shape” of p better? Which captures a “mode” better?

  4. For what kinds of downstream tasks would you prefer the forward KL approximation? The reverse?

Exercise 3 (ELBO for a Poisson Model).

Consider the model λGamma(a,b) and xi|λPoisson(λ) for i=1,,N.

  1. Write the joint log-density logp(x1:N,λ).

  2. Let q(λ)=Gamma(α,β). Compute the ELBO (α,β) in closed form.

  3. Find the optimal (α,β) by setting gradients to zero. Verify that these recover the exact posterior parameters (since the model is conjugate).

  4. Compute the ELBO at the optimum and verify that it equals logp(x1:N).

Exercise 4 (Mean-Field for a Bivariate Gaussian).

Let p(z1,z2)=𝒩((00),(1ρρ1)) with |ρ|<1.

  1. Apply the mean-field factorisation q(z1,z2)=q1(z1)q2(z2).

  2. Using Theorem Theorem 3, derive the optimal q1 and q2. Show that they are Gaussian with the correct marginal means and variances.

  3. Compute 𝖣KL(qp) as a function of ρ. What happens as |ρ|1?

  4. Plot the contours of p, q, and their difference for ρ=0,0.5,0.9.

Exercise 5 (CAVI for Bayesian Linear Regression).

Implement CAVI for the Bayesian linear regression model of Example Example 8.

  1. Generate synthetic data from y=2x13x2+ϵ with ϵ𝒩(0,1), N=100, d=2.

  2. Initialise q(𝒘) and q(τ) and run CAVI for 50 iterations. Plot the ELBO vs. iteration.

  3. Compare the variational posterior means 𝔼q[𝒘] with the true values (2,3) and with the MLE 𝒘^.

  4. Plot the marginal posteriors q(w1) and q(w2) and compare with the exact Bayesian posterior (available in closed form for this conjugate model).

  5. Vary N{10,50,200,1000} and describe how the posterior concentrates as N grows.

Exercise 6 (CAVI for Bayesian GMM).

Implement the CAVI algorithm for the Bayesian GMM (Algorithm Algorithm 2).

  1. Generate 300 data points from a mixture of 3 Gaussians in 2.

  2. Run CAVI with K=5 (intentionally over-specified). Plot the ELBO vs. iteration and the cluster assignments at convergence.

  3. Observe that some clusters become “empty” (Nk0). How does the Dirichlet prior encourage this automatic pruning?

  4. Compare the converged cluster means 𝒎k and effective counts Nk with the EM solution.

  5. Repeat with different initialisations. How sensitive is the solution?

Exercise 7 (ELBO Monotonicity).

  1. Prove that each coordinate update in CAVI increases (or maintains) the ELBO.

  2. Show that the ELBO is bounded above by logp(𝒙).

  3. Conclude that CAVI converges.

  4. Give an example where CAVI converges to a local (non-global) maximum.

Exercise 8 (Stein Variational Gradient Descent).

SVGD [6] represents the variational distribution as a set of particles {𝒛1,,𝒛M} updated by 𝒛m𝒛m+ϵϕ^(𝒛m),ϕ^(𝒛)=1Mm=1M[k(𝒛m,𝒛)𝒛mlogp(𝒛m|𝒙)+𝒛mk(𝒛m,𝒛)], where k is a positive-definite kernel.

  1. Explain why the first term in ϕ^ drives particles toward high-density regions of the posterior.

  2. Explain why the second term (the “repulsive” term) prevents particles from collapsing to a single point.

  3. In the limit M=1, show that SVGD reduces to gradient ascent on logp(𝒛|𝒙) (i.e. MAP inference).

  4. Compare SVGD with mean-field VI: which can represent multimodal posteriors?

Exercise 9 (Importance-Weighted ELBO).

The standard ELBO uses a single-sample estimate. The importance-weighted ELBO (IWAE bound) [7] draws S samples from q: S=𝔼𝒛1,,𝒛Sq[log1Ss=1Sp(𝒙,𝒛s)q(𝒛s)].

  1. Show that 1= (the standard ELBO).

  2. Use Jensen's inequality to show that SS+1logp(𝒙) for all S. (Hint: the log of an average is at most the average of logs.)

  3. Show that limSS=logp(𝒙).

  4. Discuss the trade-off: more samples give a tighter bound but increase computational cost. When might S>1 be worthwhile?

Remark 16 (Summary and Looking Ahead).

In this chapter we have developed the foundations of variational inference:

  • Section KL Divergence Revisited: The asymmetry of KL divergence (forward KL is mode-covering, reverse KL is mode-seeking) and the computational reason that VI uses the reverse direction.

  • Section The Evidence Lower Bound: The ELBO, derived via Jensen's inequality and the KL decomposition, with three equivalent forms (energy + entropy, reconstruction regularisation, evidence gap).

  • Section Mean-Field Variational Inference: The mean-field assumption, which yields optimal factors via functional optimisation at the cost of ignoring posterior correlations.

  • Section Coordinate Ascent Variational Inference: The CAVI algorithm, which iterates mean-field updates to convergence, with a complete worked example for Bayesian GMMs.

Classical CAVI is limited to conjugate exponential-family models and does not scale to large datasets or deep generative models. File B addresses these limitations through stochastic variational inference (mini-batch updates), black-box variational inference (score function and reparameterisation gradients), and amortised inference (neural network encoders). The amortised approach connects directly to the VAE (Chapter ch:vae), where the encoder qϕ(𝒛|𝒙) plays the role of the variational distribution and the ELBO is maximised end-to-end with the reparameterisation trick.

Exponential Families and Conjugacy

The coordinate ascent updates derived in the previous section, while general in principle, become especially clean and computationally attractive when the model belongs to the exponential family. This is no accident: exponential families possess a rich algebraic structure that interacts beautifully with the KL divergence and the ELBO. In this section we formalise this structure and show why exponential families occupy a privileged position in variational inference.

The Exponential Family

Definition 4 (Exponential Family).

A parametric family of distributions is an exponential family if every member can be written in the form (Recap)p(𝒙;𝜼)=h(𝒙)exp{𝜼𝖳T(𝒙)A(𝜼)}, where:

  • 𝜼s is the natural parameter (also called the canonical parameter).

  • T(𝒙)s is the vector of sufficient statistics.

  • h(𝒙)0 is the base measure, independent of 𝜼.

  • A(𝜼)=logh(𝒙)exp{𝜼𝖳T(𝒙)}d𝒙 is the log-partition function (also called the cumulant function), which ensures normalisation.

The set Ω={𝜼s:A(𝜼)<} is the natural parameter space.

The exponential family encompasses nearly every distribution encountered in introductory statistics: the Gaussian, Bernoulli, Poisson, exponential, gamma, beta, Dirichlet, multinomial, Wishart, and von Mises–Fisher distributions are all members. Notable exceptions include the uniform distribution on [0,θ] (whose support depends on the parameter), the Cauchy distribution (no sufficient statistic of fixed dimension), and mixture distributions (sums of exponentials are not exponentials).

The representation may look abstract, but its power lies in the properties of the log-partition function A. The function A(𝜼) acts as a “generating function” for the moments of T(𝒙): each derivative of A produces a higher moment.

Theorem 5 (Properties of the Log-Partition Function).

Let p(𝒙;𝜼) be a member of an exponential family with log-partition function A(𝜼). Then:

  1. A(𝜼) is convex in 𝜼.

  2. The mean of the sufficient statistics is given by the gradient: (MEAN)𝜼A(𝜼)=𝔼p(𝒙;𝜼)[T(𝒙)].

  3. The covariance of the sufficient statistics is given by the Hessian: (COV)𝜼2A(𝜼)=𝖢ovp(𝒙;𝜼)[T(𝒙)].

Proof.

Part 1. Write A(𝜼)=logh(𝒙)e𝜼𝖳T(𝒙)d𝒙. This is the logarithm of a sum (integral) of convex functions of 𝜼 (exponentials are convex), hence convex (log-sum-exp is convex; see the appendix on convex analysis).

Part 2. Differentiate A under the integral sign: 𝜼A(𝜼)=T(𝒙)h(𝒙)e𝜼𝖳T(𝒙)d𝒙h(𝒙)e𝜼𝖳T(𝒙)d𝒙=T(𝒙)p(𝒙;𝜼)d𝒙=𝔼[T(𝒙)].

Part 3. Differentiating once more: 𝜼2A(𝜼)=T(𝒙)T(𝒙)𝖳p(𝒙;𝜼)d𝒙(T(𝒙)p(𝒙;𝜼)d𝒙)(T(𝒙)p(𝒙;𝜼)d𝒙)𝖳=𝔼[T(𝒙)T(𝒙)𝖳]𝔼[T(𝒙)]𝔼[T(𝒙)]𝖳=𝖢ov[T(𝒙)]. Since a covariance matrix is positive semi-definite, the Hessian of A is positive semi-definite, confirming convexity.

Example 10 (The Gaussian as an Exponential Family).

A univariate Gaussian 𝒩(x;μ,σ2) can be rewritten: p(x;μ,σ2)=12πσ2exp{(xμ)22σ2}=12πexp{μσ2x12σ2x2μ22σ212logσ2}. Identifying the components:

  • Natural parameters: 𝜼=(η1,η2)=(μ/σ2,1/(2σ2)).

  • Sufficient statistics: T(x)=(x,x2).

  • Base measure: h(x)=1/2π.

  • Log-partition function: A(𝜼)=η12/(4η2)12log(2η2).

One can verify that A/η1=μ=𝔼[x] and A/η2=μ2+σ2=𝔼[x2], as promised by Theorem 5.

Example 11 (The Bernoulli as an Exponential Family).

The Bernoulli distribution p(x;π)=πx(1π)1x for x{0,1} can be rewritten: p(x;π)=exp{xlogπ+(1x)log(1π)}=(1π)exp{xlogπ1π}. Identifying the components:

  • Natural parameter: η=logπ1π (the log-odds or logit).

  • Sufficient statistic: T(x)=x.

  • Base measure: h(x)=1.

  • Log-partition function: A(η)=log(1+eη)=softplus(η).

We can verify: A(η)=σ(η)=π=𝔼[x], where σ is the logistic sigmoid, and A(η)=σ(η)(1σ(η))=π(1π)=𝖵ar[x].

Remark 17 (Mean Parameters and Natural Parameters).

The mapping 𝝁mean=A(𝜼) sends natural parameters to mean parameters 𝝁mean=𝔼[T(𝒙)]. Because A is convex (Theorem 5), this mapping is monotone and, for minimal exponential families (where the sufficient statistics are not linearly dependent), it is a bijection. The inverse mapping 𝜼=(A)1(𝝁mean) is available via the convex conjugate A(𝝁mean)=sup𝜼{𝜼𝖳𝝁meanA(𝜼)}.

This duality between natural and mean parameters is the foundation of the information geometry of exponential families, and it plays a key role in the natural gradient methods discussed in Stochastic Variational Inference.

The KL divergence between two members of the same exponential family has a particularly elegant form: (KL)𝖣KL(p(𝒙;𝜼1)p(𝒙;𝜼2))=A(𝜼2)A(𝜼1)(𝜼2𝜼1)𝖳A(𝜼1). This is the Bregman divergence generated by A, a connection that provides geometric insight into variational inference as projection onto the variational family with respect to this divergence.

Conjugate Priors

When building Bayesian models, a natural question is: can we choose a prior so that the posterior has the same functional form as the prior? If so, the posterior update becomes a simple parameter update rather than a change of distributional family.

Definition 5 (Conjugate Prior).

Let p(𝒙|𝜽) be a likelihood from an exponential family. A prior p(𝜽) is conjugate to this likelihood if, for any observation 𝒙, the posterior p(𝜽|𝒙)p(𝒙|𝜽)p(𝜽) belongs to the same family as the prior.

When the likelihood belongs to an exponential family with natural parameter 𝜽 and sufficient statistics T(𝒙), a conjugate prior can always be constructed: (FORM)p(𝜽;𝝌,ν)=1Z(𝝌,ν)exp{𝝌𝖳𝜽νA(𝜽)}, where 𝝌 and ν>0 are hyperparameters, and Z(𝝌,ν) is the normalising constant. After observing data 𝒙1,,𝒙N, the posterior is (Posterior)p(𝜽|𝒙1:N;𝝌,ν)exp{(𝝌+i=1NT(𝒙i))𝖳𝜽(ν+N)A(𝜽)}, which is the same family with updated hyperparameters 𝝌=𝝌+iT(𝒙i) and ν=ν+N. The posterior simply “adds” the observed sufficient statistics to the prior pseudo-observations.

Common conjugate pairs. Each arrow connects a prior distribution (left, blue) to its conjugate likelihood (right, green). Observing data updates the prior hyperparameters by adding sufficient statistics, and no change of distributional family is needed.

CAVI in Exponential Family Models

We now connect exponential families to the coordinate ascent variational inference (CAVI) algorithm developed in the previous section. The payoff is remarkable: for models in which every complete conditional belongs to an exponential family, the optimal mean-field factors have closed-form natural parameter updates.

Theorem 6 (Optimal Mean-Field Factor for Exponential Family Complete Conditionals).

Suppose the complete conditional of latent variable zj given all others is an exponential family: (Conditional)p(zj|𝒛j,𝒙)=h(zj)exp{𝜼j(𝒛j,𝒙)𝖳T(zj)A(𝜼j(𝒛j,𝒙))}. Then the optimal mean-field variational factor is in the same exponential family: (Optimal)q(zj)h(zj)exp{𝔼q(𝒛j)[𝜼j(𝒛j,𝒙)]𝖳T(zj)}. That is, the optimal variational natural parameter is the expected natural parameter of the complete conditional, where the expectation is taken under the current variational distribution over all other variables: (Natparam)𝜼j=𝔼q(𝒛j)[𝜼j(𝒛j,𝒙)].

Proof.

Recall from the CAVI derivation that the optimal q(zj) satisfies logq(zj)=𝔼q(𝒛j)[logp(zj,𝒛j,𝒙)]+const. Since only the terms in logp that involve zj matter, and the complete conditional absorbs all such terms: logq(zj)=𝔼q(𝒛j)[logp(zj|𝒛j,𝒙)]+const=𝔼q(𝒛j)[𝜼j(𝒛j,𝒙)𝖳T(zj)A(𝜼j(𝒛j,𝒙))+logh(zj)]+const=𝔼q(𝒛j)[𝜼j(𝒛j,𝒙)]𝖳T(zj)+logh(zj)+const. The term A(𝜼j(𝒛j,𝒙)) does not depend on zj and is absorbed into the constant. Exponentiating gives q(zj)h(zj)exp{𝔼[𝜼j]𝖳T(zj)}, which is an exponential family distribution with natural parameter 𝜼j=𝔼q(𝒛j)[𝜼j(𝒛j,𝒙)].

Example 12 (Conjugate Updates: Normal–Normal Model).

Consider a simple model with known variance σ2: a Gaussian prior on the mean μ and Gaussian observations: (Model)μ𝒩(μ0,σ02),xi|μiid𝒩(μ,σ2),i=1,,N. The complete conditional of μ given the data is p(μ|x1,,xN)=𝒩(μ|μN,σN2), where (Posterior)1σN2=1σ02+Nσ2,μNσN2=μ0σ02+i=1Nxiσ2. In this simple case the posterior is exact (no approximation needed), but the structure illustrates the general pattern: the natural parameter of the posterior is the sum of the prior natural parameter and the data natural parameter. In the Gaussian case, the natural parameter is η=μ/σ2 (the precision-weighted mean), and we see that the posterior natural parameter is ηN=η0+ixi/σ2, the prior pseudo-data plus the actual data, exactly as predicts.

Insight.

Why exponential families are special for VI. Exponential families enjoy three properties that make variational inference tractable and elegant:

  1. Closed-form CAVI updates. The optimal mean-field factor belongs to the same family as the complete conditional, and its natural parameter is simply an expectation (Theorem 6). No optimisation subroutine is needed.

  2. Moment–parameter duality. The gradient of A(𝜼) maps natural parameters to mean parameters (Theorem 5), providing a bijection between two coordinate systems, each useful for different computations.

  3. Finite-dimensional sufficient statistics. The entire dataset 𝒙1,,𝒙N is summarised by iT(𝒙i), which is crucial for the scalable methods we develop next.

When any of these properties fails (for example, when the model has non-conjugate factors), the elegant closed-form updates break down, motivating the more general techniques in sec:vi:bbvi,sec:vi:reparam.

The Variational EM Algorithm

In sec:gmm:em we introduced the Expectation–Maximisation (EM) algorithm for fitting models with latent variables. Recall the two steps:

  • E-step: compute the posterior over latent variables, p(𝒛|𝒙;θ).

  • M-step: maximise the expected complete-data log-likelihood Q(θ,θ(t)) with respect to the model parameters θ.

For GMMs, the E-step is tractable: the posterior over the cluster assignments zi factorises and each factor is a categorical distribution (the “responsibilities”). But for more complex models (topic models, deep latent variable models, models with continuous high-dimensional latent spaces) the exact posterior p(𝒛|𝒙;θ) is intractable. What do we do?

The answer is the Variational EM algorithm: replace the exact E-step with a variational E-step that finds an approximate posterior within a tractable family 𝒬.

To understand why the exact E-step becomes intractable, consider a topic model with K topics and a document of N words. The posterior over topic assignments requires marginalising over all KN possible configurations, an exponential sum that no closed-form trick can simplify. In a deep latent variable model, the decoder is a neural network, and the posterior involves inverting this nonlinear mapping, and there is no hope of a closed form. Variational EM sidesteps these difficulties by approximating the posterior rather than computing it exactly.

Historical Note.

The variational EM framework was developed and popularised in the mid-1990s and early 2000s, with foundational contributions by Jordan et al. [2] and Winn and Bishop [5], who developed the VIBES (Variational Inference for Bayesian Networks) software that automated variational updates for conjugate exponential family models. The application to LDA by Blei et al. [8] demonstrated that variational methods could scale to real-world text corpora, sparking widespread adoption in machine learning.

From EM to Variational EM

Recall the ELBO decomposition (from the previous sections): (Decomp)logp(𝒙;θ)=𝔼q(𝒛)[logp(𝒙,𝒛;θ)q(𝒛)](q,θ)(ELBO)+𝖣KL(q(𝒛)p(𝒛|𝒙;θ)). In standard EM, the E-step sets q(𝒛)=p(𝒛|𝒙;θ(t)), making the KL term zero and the ELBO equal to the log-evidence. In variational EM, we cannot set q to the exact posterior; instead, we maximise the ELBO over a restricted family q𝒬:

Definition 6 (Variational E-step and M-step).

  • VE-step (variational E-step): holding θ fixed at θ(t), find (Vestep)q(t+1)=arg maxq𝒬(q,θ(t)). This is equivalent to minimising 𝖣KL(qp(𝒛|𝒙;θ(t))) over 𝒬.

  • VM-step (variational M-step): holding q fixed at q(t+1), update the model parameters: (Vmstep)θ(t+1)=arg maxθ(q(t+1),θ). Since the entropy 𝖧[q(t+1)] does not depend on θ, this reduces to θ(t+1)=arg maxθ𝔼q(t+1)[logp(𝒙,𝒛;θ)].

Algorithm 3 (Variational EM Algorithm).

  1. Initialise model parameters θ(0) and variational parameters λ(0)
  2. for t=0,1,2, until convergence
  3. VE-step: optimise variational parameters λ(t+1)arg maxλ(qλ,θ(t)) Approximate posterior
  4. VM-step: optimise model parameters θ(t+1)arg maxθ(qλ(t+1),θ) Fit generative model
  5. Evaluate (qλ(t+1),θ(t+1)) and check for convergence

Theorem 7 (Monotonic Convergence of Variational EM).

Each iteration of Variational EM increases the ELBO: (Monotone)(q(t+1),θ(t+1))(q(t+1),θ(t))(q(t),θ(t)). Since the ELBO is bounded above by logp(𝒙;θ) (which itself is bounded for well-defined models), the sequence {(q(t),θ(t))}t0 converges.

Proof.

The first inequality (q(t+1),θ(t))(q(t),θ(t)) follows because the VE-step maximises over q while holding θ(t) fixed, so the new q(t+1) achieves an ELBO at least as large as the old q(t). The second inequality (q(t+1),θ(t+1))(q(t+1),θ(t)) follows because the VM-step maximises over θ while holding q(t+1) fixed. Each step is a (block) coordinate ascent on the ELBO, and since the ELBO is bounded above, the sequence converges.

Variational EM as coordinate ascent on the ELBO. Blue vertical arrows (VE-step): optimise q holding θ fixed. Orange horizontal arrows (VM-step): optimise θ holding q fixed. Each step increases the ELBO, and the iterates converge to a local maximum.

Remark 18 (Connection to Standard EM).

When the variational family 𝒬 is unrestricted (i.e., all valid distributions), the VE-step recovers the exact posterior q(𝒛)=p(𝒛|𝒙;θ(t)), and Variational EM reduces to standard EM\@. The difference is entirely in the restriction of 𝒬: mean-field assumptions, parametric families, or amortised inference networks.

The restriction has two consequences. First, the ELBO at convergence will generally be lower than the true log-likelihood; the gap equals the KL divergence between the best approximation in 𝒬 and the true posterior. Second, the VM-step may converge to a different θ than standard EM would, because the objective being maximised (the ELBO with an approximate q) differs from the exact expected complete-data log-likelihood. Despite this, Variational EM often finds good solutions in practice, and it is the only option when the exact E-step is intractable.

Example: Variational EM for Latent Dirichlet Allocation

Latent Dirichlet Allocation (LDA) is the canonical application of Variational EM [8]. It is a topic model that discovers latent “topics” (distributions over words) from a corpus of documents.

The generative model. For a corpus of D documents, each with Nd words, and K latent topics:

  1. For each topic k=1,,K: draw a word distribution 𝜷kDirichlet(𝜼), where 𝜷kΔV1 (the (V1)-simplex over a vocabulary of V words).

  2. For each document d=1,,D: enumerate

  3. Draw topic proportions 𝜽dDirichlet(𝜶).

  4. For each word position n=1,,Nd: enumerate

  5. Draw a topic assignment zdnCategorical(𝜽d).

  6. Draw a word wdnCategorical(𝜷zdn). enumerate enumerate

The posterior p(𝜽1:D,𝒛1:D,𝜷1:K|𝒘1:D;𝜶,𝜼) is intractable because the Dirichlet–categorical conjugacy is broken by the coupling through the topic assignments zdn.

The mean-field approximation. The standard variational approximation uses a fully factorised family: (MF)q(𝜽1:D,𝒛1:D,𝜷1:K)=k=1Kq(𝜷k|𝝀k)d=1D[q(𝜽d|𝜸d)n=1Ndq(zdn|𝝓dn)], where q(𝜷k|𝝀k)=Dirichlet(𝝀k), q(𝜽d|𝜸d)=Dirichlet(𝜸d), and q(zdn|𝝓dn)=Categorical(𝝓dn).

Example 13 (Variational EM for LDA).

VE-step. Applying CAVI with exponential family structure (Theorem 6), the updates cycle through the local variational parameters: (PHI)ϕdnkexp{𝔼q[logθdk]+𝔼q[logβk,wdn]},γdk=αk+n=1Ndϕdnk, where 𝔼q[logθdk]=Ψ(γdk)Ψ(jγdj) uses the digamma function Ψ()=ddxlogΓ(x).

VM-step. The global topic–word parameters are updated as: (Lambda)λkv=ηv+d=1Dn=1Ndϕdnk𝟙[wdn=v]. This aggregates the expected topic assignment across all documents: λkv counts how many times word v is (softly) assigned to topic k, plus the prior pseudo-count ηv.

The computational cost of each VE-step is O(DNK), where N is the average document length: we must update 𝝓dnk for each of the DN word positions and K topics. For a corpus of D=106 documents with average length N=200 and K=100 topics, a single VE-step touches 2×1010 variational parameters.

Moreover, the VE-step must be iterated to convergence (cycling through the 𝝓 and 𝜸 updates multiple times) before performing a single VM-step. This makes each iteration of Variational EM extremely expensive for large corpora.

The VM-step aggregates information from all documents to update the global topic parameters. This full-data sweep is the computational bottleneck that motivates the stochastic methods of the next section.

Remark 19 (Sparsity in LDA).

In practice, the 𝝓dnk updates are sparse: for most word–topic pairs, ϕdnk0. Exploiting this sparsity can significantly speed up each VE-step iteration, but it does not change the fundamental O(D) scaling with the number of documents.

Stochastic Variational Inference

Coordinate ascent variational inference (CAVI) and Variational EM both require a full pass over the dataset in every iteration. For the LDA example, each VE-step touches every word in every document. When the corpus grows from thousands to millions of documents, this becomes a crippling bottleneck: the cost of a single iteration scales linearly in the dataset size N, and many iterations are needed for convergence.

The insight of Stochastic Variational Inference (SVI) [20] is both natural and powerful: subsample the data and use noisy but unbiased gradient estimates to update the global variational parameters. This brings the per-iteration cost down from O(N) to O(1) (independent of dataset size), at the price of noisier updates that nonetheless converge to the same optimum.

Local and Global Latent Variables

The key structural assumption in SVI is a distinction between two types of latent variables.

Definition 7 (Local and Global Variables).

In a latent variable model with data 𝒙1,,𝒙N:

  • Local (latent) variables 𝒛i are associated with a single data point 𝒙i. There are N sets of local variables, one per observation.

  • Global (latent) variables 𝜷 are shared across all data points. They govern the overall structure of the model.

The joint model factorises as: (Model)p(𝒙1:N,𝒛1:N,𝜷)=p(𝜷)i=1Np(𝒙i,𝒛i|𝜷).

In LDA, the topic–word distributions 𝜷1:K are global variables (shared across all documents), while the topic proportions 𝜽d and topic assignments zdn are local to document d. In a Gaussian mixture model, the component parameters (𝝁k,𝚺k,πk) are global, and the cluster assignments zi are local.

The mean-field variational distribution mirrors this decomposition: (MF)q(𝒛1:N,𝜷)=q(𝜷|𝝀)i=1Nq(𝒛i|𝝓i), where 𝝀 are the global variational parameters and 𝝓i are the local variational parameters for data point i.

The SVI Algorithm

The ELBO for the model decomposes as: (ELBO)(𝝀,𝝓1:N)=𝔼q[logp(𝜷)]𝔼q[logq(𝜷)]+i=1N(𝔼q[logp(𝒙i,𝒛i|𝜷)]𝔼q[logq(𝒛i)]). The sum over N data points is the bottleneck. The SVI strategy proceeds in three steps:

  1. Subsample a minibatch {1,,N} of size B.

  2. Local step: for each i, optimise 𝝓i to convergence (using the current global parameters 𝝀). This is typically cheap, often one CAVI update per local variable.

  3. Global step: form the stochastic natural gradient of the ELBO with respect to 𝝀 and take a step.

The stochastic gradient is constructed by scaling the minibatch contribution: (GRAD)^𝝀=𝝀𝔼q[logp(𝜷)logq(𝜷)]+NBi𝝀(𝔼q[logp(𝒙i,𝒛i|𝜷)]𝔼q[logq(𝒛i)]). The factor N/B rescales the minibatch contribution to be an unbiased estimate of the full-data sum.

For conjugate exponential family models, the global update takes a particularly elegant form. After computing the locally optimal 𝝓i for each i, the intermediate global natural parameter is (Intermediate)𝝀^=𝝀prior+NBit(𝒙i,𝝓i), where 𝝀prior encodes the prior's contribution and t(𝒙i,𝝓i) are the expected sufficient statistics from data point i under the optimised local distribution. The global update is then a convex combination (weighted average) of the old parameters and this intermediate estimate: (Update)𝝀(t+1)=(1ρt)𝝀(t)+ρt𝝀^, where ρt(0,1] is the step size (learning rate) at iteration t.

Algorithm 4 (Stochastic Variational Inference).

  1. Initialise global variational parameters 𝝀(0)
  2. Set step size schedule ρt=(τ+t)κ with κ(0.5,1], τ0
  3. for t=0,1,2,
  4. Sample a minibatch {1,,N} uniformly, ||=B
  5. for each i Local step
  6. Optimise local parameters: 𝝓iarg max𝝓i(𝝀(t),𝝓i)
  7. Compute intermediate global parameter: 𝝀^𝝀prior+NBit(𝒙i,𝝓i) Global step
  8. Update: 𝝀(t+1)(1ρt)𝝀(t)+ρt𝝀^

Why Natural Gradients?

A crucial but subtle point in the SVI algorithm is that the global update uses the natural gradient rather than the ordinary (Euclidean) gradient. To understand why, consider the geometry of the variational parameter space.

The ordinary gradient 𝝀 gives the steepest ascent direction in Euclidean space; it assumes that a unit step in any direction of 𝝀 produces an equally significant change. But for probability distributions, this is misleading: a change Δλ=0.01 in the mean of a Gaussian has a very different effect from the same change in the log-variance.

The natural gradient corrects for this by measuring distances in the space of distributions rather than parameters. It is defined as: (Natgrad)~𝝀=𝑭(𝝀)1𝝀, where 𝑭(𝝀)=𝔼q𝝀[𝝀logq𝝀(𝒛)(𝝀logq𝝀(𝒛))𝖳] is the Fisher information matrix.

For exponential families, a remarkable simplification occurs: when the variational parameters are the natural parameters 𝜼, the Fisher information matrix is 𝑭=2A(𝜼), and the natural gradient update in natural parameter space takes the simple form of the convex combination . This is why SVI works in natural parameter space, where the natural gradient is “built in” to the update rule.

Remark 20 (Natural vs. Euclidean Gradients).

In practice, natural gradient updates converge significantly faster than ordinary gradient updates for VI, because they account for the curvature of the KL divergence landscape. Ordinary gradient descent can take many small steps in high-curvature directions while overshooting in low-curvature directions; the natural gradient normalises step sizes appropriately across all directions. We will explore natural gradients in more depth in the next chapter section.

Convergence Guarantees

The step size schedule must satisfy the classical Robbins–Monro conditions [9]: (Robbins)t=1ρt=andt=1ρt2<. The first condition ensures that the step sizes are large enough to reach any point in parameter space (no matter how far the initialisation is from the optimum). The second condition ensures that the noise in the stochastic gradient is eventually averaged out. The schedule ρt=(τ+t)κ satisfies both conditions when κ(0.5,1].

Theorem 8 (Convergence of SVI).

Under the following conditions:

  1. The model–variational family pair yields an ELBO (𝝀) (with local variables optimised out) that has a unique global optimum 𝝀.

  2. The stochastic natural gradient ^𝝀 is an unbiased estimate of the true natural gradient with bounded variance.

  3. The step sizes satisfy the Robbins–Monro conditions .

Then the SVI iterates converge to the global optimum: 𝝀(t)𝝀 almost surely as t.

More generally, when the ELBO has multiple local optima, SVI converges to a local optimum of the ELBO.

Proof sketch.

The update has the form of a stochastic approximation scheme: 𝝀(t+1)=𝝀(t)+ρt(𝝀^𝝀(t)). This is a Robbins–Monro recursion with the expected update pointing towards the optimum of the ELBO (since 𝔼[𝝀^]=𝝀 at convergence for the single-optimum case). The conditions on ρt ensure that the iterates eventually overcome the noise (first condition) without accumulating too much variance (second condition). The result then follows from the classical Robbins–Monro theorem.

Convergence of batch CAVI vs. stochastic variational inference (SVI) as a function of wall-clock time. On a small dataset (N=104, solid lines), both converge, but SVI is faster. On a large dataset (N=106, dashed lines), batch CAVI barely makes progress in the same time budget, while SVI converges nearly as fast as before, since its per-iteration cost is independent of N.

Example: SVI for Online Topic Modelling

Example 14 (SVI for LDA with Streaming Documents).

Consider applying SVI to the LDA model from Example 13. The global variables are the topic–word distributions 𝜷1:K with variational parameters 𝝀1:K (each 𝝀kV). The local variables are the per-document topic proportions 𝜽d and word-level topic assignments zdn, with variational parameters 𝜸d and 𝝓dn.

In each SVI iteration:

  1. Sample a minibatch of B documents.

  2. Local step: for each d, iterate the CAVI updates to convergence, obtaining 𝝓dn and 𝜸d.

  3. Global step: compute the intermediate topic parameters: λ^kv=ηv+DBdn=1Ndϕdnk𝟙[wdn=v], and update λkv(t+1)=(1ρt)λkv(t)+ρtλ^kv.

Because only the documents in are processed, a single SVI iteration on a corpus of D=107 documents costs the same as on a corpus of D=103 documents (given the same minibatch size B). This makes it possible to learn topic models from web-scale text corpora in a streaming fashion: new documents can be incorporated as they arrive, without revisiting old ones.

Key Idea.

Subsample Data, Scale Gradients. The core principle of SVI is simple: replace the expensive full-data gradient with a cheap, noisy, but unbiased estimate computed from a small minibatch. The stochastic approximation theory of Robbins and Monro [9] guarantees convergence, provided the step sizes decay at the right rate. This is the same principle that makes stochastic gradient descent (SGD) work for training neural networks, applied here to variational inference.

The limitation of SVI is that it still requires model-specific derivations: the practitioner must work out the conjugate structure, derive the natural gradient, and implement the local and global updates by hand. The next two sections remove this limitation.

Black-Box Variational Inference

Stochastic variational inference (Stochastic Variational Inference) brought scalability to VI, but it required the practitioner to derive model-specific update equations, exploiting conjugate exponential family structure to obtain closed-form natural gradients. What if the model is not conjugate? What if the likelihood involves a neural network, or the prior is non-standard? In such cases, the elegant closed-form updates of SVI simply do not exist.

Black-Box Variational Inference (BBVI) [21] attacks this problem head-on: it provides a gradient estimator for the ELBO that works for any model and any variational family, requiring only the ability to

  1. sample from the variational distribution q𝝀(𝒛), and

  2. evaluate logp(𝒙,𝒛) and logq𝝀(𝒛) at the sampled points.

No conjugacy, no exponential family structure, no model-specific derivations. The price? Variance, which we must work hard to control.

The Score Function Estimator

The foundation of BBVI is the score function estimator, also known as the REINFORCE trick or the log-derivative trick [22]. It provides a way to differentiate an expectation with respect to the parameters of the distribution being averaged over.

Lemma 1 (Score Function Identity).

Let q𝝀(𝒛) be a distribution parameterised by 𝝀, and let f(𝒛) be any function (not depending on 𝝀). Then: (Identity)𝝀𝔼q𝝀(𝒛)[f(𝒛)]=𝔼q𝝀(𝒛)[f(𝒛)𝝀logq𝝀(𝒛)].

Proof.

Starting from the definition of the expectation and exchanging the gradient and integral (justified under mild regularity conditions): 𝝀𝔼q𝝀[f(𝒛)]=𝝀f(𝒛)q𝝀(𝒛)d𝒛=f(𝒛)𝝀q𝝀(𝒛)d𝒛=f(𝒛)q𝝀(𝒛)𝝀q𝝀(𝒛)q𝝀(𝒛)d𝒛=f(𝒛)q𝝀(𝒛)𝝀logq𝝀(𝒛)d𝒛=𝔼q𝝀[f(𝒛)𝝀logq𝝀(𝒛)]. The key step is the “log-derivative trick”: q/q=logq, which rewrites the gradient of q as q times the gradient of logq, allowing us to bring q back inside the expectation.

The quantity 𝝀logq𝝀(𝒛) is called the score function of q; it measures how sensitive the log-density is to changes in the parameters at a given point 𝒛.

Applying this identity to the ELBO gradient requires care. Write (𝝀)=𝔼q𝝀[logp(𝒙,𝒛)logq𝝀(𝒛)] and note that logq𝝀(𝒛) itself depends on 𝝀 both through the expectation (the distribution we average over) and through the integrand (the log-density being evaluated). The full gradient is: (Fullgrad)𝝀=𝝀𝔼q𝝀[logp(𝒙,𝒛)logq𝝀(𝒛)]=𝔼q𝝀[(logp(𝒙,𝒛)logq𝝀(𝒛))𝝀logq𝝀(𝒛)]𝔼q𝝀[𝝀logq𝝀(𝒛)]=0. The first term applies the score function identity (Lemma 1) to the full ELBO integrand. The second term arises from differentiating logq𝝀(𝒛) as part of the integrand; it vanishes because 𝔼q[𝝀logq𝝀(𝒛)]=𝝀q𝝀(𝒛)d𝒛=𝝀q𝝀(𝒛)d𝒛=𝝀1=0. This yields the key result:

(GRAD)𝝀(𝝀)=𝔼q𝝀(𝒛)[𝝀logq𝝀(𝒛)(logp(𝒙,𝒛)logq𝝀(𝒛))].

This is an expectation under q𝝀, so we can estimate it with Monte Carlo: (MC)^𝝀=1Ss=1S𝝀logq𝝀(𝒛(s))(logp(𝒙,𝒛(s))logq𝝀(𝒛(s))),𝒛(s)q𝝀.

This estimator is unbiased: its expectation equals the true gradient 𝝀. Crucially, it requires no knowledge of the model structure beyond the ability to evaluate logp(𝒙,𝒛); the model is treated as a “black box.”

Caution.

The variance problem. The score function estimator is unbiased but can have enormous variance. The score function 𝝀logq𝝀(𝒛) fluctuates wildly across samples, and when multiplied by the (also fluctuating) quantity logp(𝒙,𝒛)logq𝝀(𝒛), the product can vary over many orders of magnitude. In practice, using the raw estimator with S=1 sample produces gradient estimates so noisy that optimisation fails to make progress.

Variance reduction is not optional; it is essential for BBVI to work.

Variance Reduction

Three classical techniques bring the variance of the score function estimator under control.

Control Variates

Definition 8 (Control Variate).

A control variate for estimating 𝔼[f(𝒛)] is a random variable h(𝒛) with known expectation 𝔼[h(𝒛)]=μh. Instead of estimating 𝔼[f(𝒛)] directly, we estimate (CV)𝔼[f(𝒛)c(h(𝒛)μh)]=𝔼[f(𝒛)], where c is a scalar coefficient. The estimator is unbiased for any c, but its variance depends on c: (VAR)𝖵ar[fc(hμh)]=𝖵ar[f]2c𝖢ov[f,h]+c2𝖵ar[h].

If h is positively correlated with f, choosing c>0 reduces the variance. The optimal coefficient that minimises is: (Optimal)c=𝖢ov[f,h]𝖵ar[h]. In practice, c is estimated from the samples themselves.

For BBVI, a common choice is the baseline approach: subtract a scalar b (an estimate of the mean reward) from the “reward” signal logp(𝒙,𝒛)logq𝝀(𝒛) in the gradient estimate . This does not change the expected gradient (since 𝔼q[𝝀logq𝝀(𝒛)]=0, a standard property of the score function), but can dramatically reduce variance.

Rao–Blackwellization

If some latent variables can be integrated out analytically, doing so always reduces variance (by the Rao–Blackwell theorem). For example, if 𝒛=(𝒛1,𝒛2) and the expectation over 𝒛2 can be computed in closed form, we should compute it analytically and only use Monte Carlo for 𝒛1. This is model-specific but can yield large variance reductions.

Optimal Baseline Derivation

For the BBVI gradient estimator, consider subtracting a baseline b: (Baseline)^𝝀=1Ss=1S𝝀logq𝝀(𝒛(s))(logp(𝒙,𝒛(s))logq𝝀(𝒛(s))b). The variance of a single-sample estimator (for each component j of 𝝀) is 𝖵ar[g^j]=𝔼[(sj(𝒛)(f(𝒛)b))2](𝔼[sj(𝒛)f(𝒛)])2, where sj(𝒛)=logq𝝀(𝒛)/λj and f(𝒛)=logp(𝒙,𝒛)logq𝝀(𝒛). Minimising over b yields: (Optbaseline)bj=𝔼[sj(𝒛)2f(𝒛)]𝔼[sj(𝒛)2]. This is the optimal per-component baseline. In practice, a single scalar baseline (averaged across components) is often used for simplicity.

The BBVI Algorithm

Algorithm 5 (Black-Box VI with Control Variates).

  1. Initialise variational parameters 𝝀(0), learning rate α
  2. for t=0,1,2,
  3. Draw S samples: 𝒛(1),,𝒛(S)q𝝀(t)
  4. Evaluate f(s)=logp(𝒙,𝒛(s))logq𝝀(t)(𝒛(s)) for each s
  5. Compute score functions: 𝒔(s)=𝝀logq𝝀(t)(𝒛(s)) for each s
  6. Estimate baseline: b^j=s(sj(s))2f(s)s(sj(s))2 for each component j
  7. Compute gradient estimate: 𝒈^=1Ss=1S𝒔(s)(𝒇(s)𝒃^) is element-wise
  8. Update: 𝝀(t+1)𝝀(t)+α𝒈^ Or use Adam / other optimiser

Gradient Variance: Score Function vs. Reparameterization

Comparison of gradient estimator variance during optimisation. The raw score function estimator (REINFORCE) has variance several orders of magnitude higher than the reparameterisation trick. Adding a control variate (baseline) helps substantially, but the reparameterisation trick, when applicable, remains the gold standard for low variance.

The figure reveals the fundamental tension in BBVI: the score function estimator is maximally general (works for any model and any variational family) but has high variance. The reparameterisation trick (next section) has much lower variance but requires the variational distribution to support a differentiable reparameterisation. For models where the reparameterisation trick applies, it is almost always preferred.

To quantify the difference: in a typical 50-dimensional latent space model, the score function estimator can have variance 103105 times larger than the reparameterised estimator. With S=1 sample, the score function estimator often produces gradient estimates whose signal-to-noise ratio is below 1, making optimisation impractical. The reparameterised estimator typically achieves a signal-to-noise ratio above 10 even with a single sample, enabling practical training with minibatch sizes of 32–128.

This variance gap is the primary reason that the VAE (ch:vae) uses the reparameterisation trick rather than the score function estimator. For discrete latent variables, where reparameterisation is not available, the variance of BBVI remains a major challenge and an active area of research.

Example 15 (BBVI for Bayesian Logistic Regression).

Consider Bayesian logistic regression with a Gaussian prior on the weights: 𝒘𝒩(0,σ02𝑰),yi|𝒙i,𝒘Bernoulli(σ(𝒘𝖳𝒙i)),i=1,,N, where σ(a)=1/(1+ea) is the logistic sigmoid. The posterior p(𝒘|𝒙1:N,𝒚1:N) has no closed form because the Gaussian prior is not conjugate to the Bernoulli likelihood with a logistic link.

We use a mean-field Gaussian variational family: q𝝀(𝒘)=𝒩(𝒘|𝝁,diag(𝝈2)) with 𝝀=(𝝁,log𝝈). CAVI does not apply (no conjugate exponential family structure).

Using BBVI, each iteration:

  1. Draws S samples 𝒘(s)q𝝀.

  2. Evaluates f(𝒘(s))=logp(𝒚|𝑿,𝒘(s))+logp(𝒘(s))logq𝝀(𝒘(s)).

  3. Computes the score 𝝀logq𝝀(𝒘(s)) (available in closed form for Gaussians).

  4. Forms the gradient estimate with the optimal baseline and updates 𝝀.

No model-specific derivations beyond specifying logp(𝒙,𝒘) are needed. However, as we shall see in the next section, since the Gaussian family supports reparameterisation, we can do much better.

The Reparameterization Trick

The score function estimator is general but noisy. In this section we develop a dramatically better gradient estimator for the important special case when the variational distribution admits a differentiable reparameterisation, meaning we can express samples from q𝝓(𝒛) as a deterministic, differentiable transformation of parameter-free noise.

The reparameterisation trick is the technical engine behind the Variational Autoencoder (VAE, ch:vae). It was independently discovered by two groups in 2013–2014, and its impact on the field cannot be overstated: it made end-to-end training of deep latent variable models practical for the first time.

Separating Randomness from Parameters

The fundamental difficulty in computing 𝝓𝔼q𝝓(𝒛)[f(𝒛)] is that the distribution we are averaging over depends on the parameters 𝝓. When we draw 𝒛q𝝓, the randomness is entangled with the parameters, so we cannot take the gradient inside the expectation directly.

The reparameterisation trick untangles this by expressing the random variable 𝒛 as a deterministic function of 𝝓 and a parameter-free noise variable 𝝐.

Definition 9 (Reparameterisation).

A distribution q𝝓(𝒛) admits a reparameterisation if there exists:

  • a base distribution p(𝝐) that does not depend on 𝝓, and

  • a differentiable function g𝝓:dd such that

(DEF)𝒛=g𝝓(𝝐),𝝐p(𝝐)𝒛q𝝓(𝒛).

The reparameterisation converts a stochastic computation (draw from q𝝓) into a deterministic computation applied to fixed noise. This seemingly simple change has profound consequences: because g𝝓 is deterministic and differentiable, standard backpropagation can compute 𝝓 through the entire computation, including through the “sampling” step.

The most important example is the Gaussian reparameterisation: (Gauss)𝒛𝒩(𝝁,diag(𝝈2))𝒛=𝝁+𝝈𝝐,𝝐𝒩(0,𝑰), where 𝝓=(𝝁,𝝈) and denotes element-wise multiplication. The noise 𝝐 is drawn from a standard Gaussian that does not depend on 𝝓; all the parameter-dependence is in the deterministic transformation g𝝓(𝝐)=𝝁+𝝈𝝐.

The Reparameterised Gradient

With the reparameterisation, the expectation transforms: (Transform)𝔼q𝝓(𝒛)[f(𝒛)]=𝔼p(𝝐)[f(g𝝓(𝝐))]. Now the distribution p(𝝐) inside the expectation does not depend on 𝝓, so we can freely move the gradient inside: (GRAD)𝝓𝔼q𝝓[f(𝒛)]=𝝓𝔼p(𝝐)[f(g𝝓(𝝐))]=𝔼p(𝝐)[𝝓f(g𝝓(𝝐))]. The gradient now flows through f and through g𝝓 via the chain rule: (Chain)𝝓f(g𝝓(𝝐))=𝒛f(𝒛)|𝒛=g𝝓(𝝐)𝝓g𝝓(𝝐).

Theorem 9 (Reparameterised Gradient Estimator).

If q𝝓(𝒛) admits a reparameterisation 𝒛=g𝝓(𝝐), 𝝐p(𝝐), then (Estimator)𝝓𝔼q𝝓[f(𝒛)]=𝔼p(𝝐)[𝒛f(𝒛)𝝓g𝝓(𝝐)], and the Monte Carlo estimator (MC)^𝝓=1Ss=1S𝒛f(𝒛(s))𝝓g𝝓(𝝐(s)),𝝐(s)p(𝝐),𝒛(s)=g𝝓(𝝐(s)), is unbiased and, for smooth f, has substantially lower variance than the score function estimator .

Proof.

The unbiasedness follows directly from : the Monte Carlo estimator is the sample mean of 𝝓f(g𝝓(𝝐)), whose expectation under p(𝝐) equals 𝝓𝔼q𝝓[f(𝒛)].

To build intuition for the lower variance, compare what information each estimator uses. The score function estimator computes f(𝒛)𝝓logq𝝓(𝒛): it multiplies the function value f(𝒛) (a scalar that can be large and fluctuating) by the score of the variational distribution. The estimator treats f as a “reward” signal; it knows the value of f at the sampled point but not how f would change if 𝒛 moved slightly.

The reparameterised estimator computes 𝒛f(𝒛)𝝓g𝝓(𝝐): it uses the gradient of f with respect to 𝒛, which is a local linear approximation of f's landscape. This “pathwise” information is far more informative: it tells us not just the value of f but the direction in which f increases.

More formally, the variance reduction can be understood through the Rao–Blackwell theorem: the reparameterised estimator effectively conditions on more information (the local gradient structure of f) than the score function estimator, and conditioning always reduces variance. A detailed variance comparison can be found in [10].

For the Gaussian case, the reparameterised ELBO gradient has an especially clean form. With q𝝓(𝒛)=𝒩(𝝁,diag(𝝈2)) and the reparameterisation 𝒛=𝝁+𝝈𝝐: (Gradmu)𝝁=𝔼𝝐[𝒛f(𝒛)],𝝈=𝔼𝝐[𝒛f(𝒛)𝝐], where f(𝒛)=logp(𝒙,𝒛)logq𝝓(𝒛). These gradients are straightforward to compute via automatic differentiation, requiring only a forward pass (to evaluate f) and a backward pass (to compute 𝒛f) through the model.

Computational Graph Perspective

The reparameterisation trick has an elegant interpretation in terms of computational graphs, which is how automatic differentiation frameworks (PyTorch, JAX) implement it in practice.

The reparameterisation trick as a computational graph transformation. Left: Sampling 𝒛q𝝓 creates a stochastic node that blocks gradient flow, since we cannot backpropagate through a random sampling operation. Right: After reparameterisation, the randomness is isolated in 𝝐p(𝝐) (a fixed distribution), and 𝒛=g𝝓(𝝐) is a deterministic, differentiable function of 𝝓. Gradients flow freely along the dashed red arrows via standard backpropagation.

Reparameterisable Distributions

Not every distribution admits a simple reparameterisation. The following table summarises the most commonly used reparameterisable families.

llll@ DistributionParameters 𝝓Base noise p(𝝐)Transformation g𝝓(𝝐)
Gaussian 𝒩(𝝁,diag(𝝈2))𝝁,𝝈𝒩(0,𝑰)𝝁+𝝈𝝐
[4pt] Full-cov. Gaussian 𝒩(𝝁,𝚺)𝝁,𝑳𝒩(0,𝑰)𝝁+𝑳𝝐
[4pt] Log-normal LogNormal(μ,σ2)μ,σ𝒩(0,1)exp(μ+σϵ)
[4pt] Exponential Exp(λ)λUniform(0,1)log(ϵ)/λ
[4pt] Gamma Gamma(α,β)α,βvia shape augmentationimplicit
[4pt] von Mises–Fisher vMF(𝝁,κ)𝝁,κrejection samplingHouseholder transform
Common reparameterisable distributions. For each family, we give the base noise distribution p(𝝐) and the deterministic transformation g𝝓(𝝐).

Remark 21 (Discrete Distributions).

Discrete distributions (e.g., categorical, Bernoulli) do not admit a differentiable reparameterisation, because the sampling operation involves discrete jumps. Approaches such as the Gumbel-Softmax trick and the straight-through estimator provide biased but useful approximations; we discuss these in Extensions: Handling Non-Reparameterisable Distributions below.

Reparameterisation with Full Covariance

Example 16 (Cholesky Reparameterisation for Multivariate Gaussian).

For a variational distribution q𝝓(𝒛)=𝒩(𝒛|𝝁,𝚺) with full covariance 𝚺d×d, we parameterise 𝚺 via its Cholesky factor: 𝚺=𝑳𝑳𝖳, where 𝑳 is lower-triangular with positive diagonal entries. The reparameterisation is: (Cholesky)𝒛=𝝁+𝑳𝝐,𝝐𝒩(0,𝑰). Then 𝒛𝒩(𝝁,𝑳𝑳𝖳)=𝒩(𝝁,𝚺) as desired. The variational parameters are 𝝓=(𝝁,𝑳), with 𝝁d and 𝑳 having d(d+1)/2 free parameters (lower-triangular entries).

The gradients are: 𝒛𝝁=𝑰,𝒛Lij=𝒆iϵjfor ij, where 𝒆i is the i-th standard basis vector. These gradients are propagated through f(𝒛) via standard backpropagation, enabling end-to-end gradient-based optimisation of the ELBO with respect to both 𝝁 and 𝑳.

Connection to Pathwise Gradients

The reparameterisation trick is an instance of a more general idea known as pathwise gradients (or pathwise derivatives) in the operations research and stochastic simulation literature. The key insight is the same: when we can express a random quantity as a deterministic function of a parameter and independent randomness, we can differentiate through the function.

In the notation of stochastic optimisation, for a performance measure J(𝝓)=𝔼[f(𝒛)] where 𝒛 depends on 𝝓:

  • The score function approach (likelihood ratio method) differentiates the measure under which we average.

  • The pathwise approach differentiates the sample path g𝝓(𝝐) directly.

When both are available, the pathwise approach typically has lower variance because it exploits the local geometry of f (via 𝒛f), while the score function approach only uses information about the density q𝝓.

Historical Note.

The reparameterisation trick for variational inference was independently proposed by Kingma and Welling [11] (in the context of the VAE) and by Rezende, Mohamed, and Wierstra [10] (in the context of deep latent Gaussian models), both published in 2014. The underlying idea of pathwise differentiation is much older, appearing in the operations research literature under names like “infinitesimal perturbation analysis” and “pathwise sensitivity analysis.” The contribution of Kingma–Welling and Rezende–Mohamed–Wierstra was to recognise that this classical idea, combined with amortised inference and neural network decoders, could unlock scalable training of deep generative models.

Extensions: Handling Non-Reparameterisable Distributions

For distributions that do not admit exact reparameterisation, most notably discrete distributions, several approximations have been developed:

  • Gumbel–Softmax / Concrete relaxation. Replace a categorical variable with a continuous relaxation using Gumbel noise: (Gumbel)zk=exp((logπk+gk)/τ)jexp((logπj+gj)/τ),gkGumbel(0,1), where τ>0 is a temperature parameter. As τ0, the samples approach one-hot vectors (hard categorical); for τ>0, the samples are continuous and differentiable in log𝝅.

  • Straight-through estimator. Use the discrete samples in the forward pass but pretend the rounding operation is the identity in the backward pass. This introduces bias but works surprisingly well in practice.

  • RELAX and other hybrid estimators. Combine the score function estimator with a learned control variate based on a continuous relaxation, achieving lower variance than either approach alone.

Remark 22 (When to Use Which Gradient Estimator).

As a practical guide:

  • Continuous latent variables with standard families (Gaussian, log-normal, etc.): use the reparameterisation trick. This is the default in modern VI frameworks.

  • Discrete latent variables: use the score function estimator with variance reduction, or the Gumbel–Softmax relaxation if a biased but low-variance gradient is acceptable.

  • Mixture of continuous and discrete: reparameterise the continuous part, use score function for the discrete part (Rao–Blackwellisation).

  • Complex, non-standard distributions: consider implicit reparameterisation or learned surrogates.

Amortized Variational Inference

All the variational inference methods we have seen so far (CAVI, SVI, BBVI, reparameterised VI) share a common pattern: for each data point 𝒙i, we must optimise variational parameters 𝝓i to approximate the posterior p(𝒛|𝒙i). When the dataset contains N data points, this means solving N separate optimisation problems, each requiring multiple gradient steps.

For a dataset of modest size, this is feasible. But what happens when N=106 or N=108? And what about new data points not seen during training; do we need to run optimisation from scratch for each one?

Amortized inference answers both questions with a single idea: instead of optimising 𝝓i separately for each 𝒙i, train a shared function (typically a neural network) that maps any 𝒙 directly to the variational parameters 𝝓 in a single forward pass.

From Per-Instance to Amortized

Definition 10 (Amortized Inference).

In amortized variational inference, the variational distribution for a data point 𝒙 is parameterised as (DEF)qψ(𝒛|𝒙)=q(𝒛;fψ(𝒙)), where fψ:𝒳Φ is an inference network (also called an encoder or recognition network) with parameters ψ, and Φ is the space of variational parameters (e.g., means and variances of a Gaussian).

For example, if q(𝒛;𝝓)=𝒩(𝒛|𝝁,diag(𝝈2)), then the inference network outputs fψ(𝒙)=(𝝁(𝒙),log𝝈(𝒙)), a mean vector and a log-standard-deviation vector, both computed from 𝒙 via a neural network with shared parameters ψ.

The key insight is one of cost amortisation:

1.3

Per-instance VIAmortized VI
Parameters𝝓1,,𝝓N (one per data point)ψ (shared)
Cost per new 𝒙O(optimisation steps)O(1) forward pass
Trainingoptimise each 𝝓i separatelytrain fψ once

Once fψ is trained, computing the approximate posterior for a new data point 𝒙new (never seen during training) requires only a single forward pass through the network, with no iterative optimisation. This is the “amortisation”: the cost of learning to do inference is paid once during training, and then inference for any input is essentially free.

The term “amortisation” comes from accounting: a large upfront cost (training the network) is spread over many future uses (inference for each data point). Just as a factory invests in machinery that produces many units cheaply, amortised inference invests in a neural network that produces many approximate posteriors cheaply.

Remark 23 (Amortised Inference in the Brain).

There is a fascinating analogy to biological perception. When you see a face, you do not solve an optimisation problem from scratch to infer the 3D shape, lighting, and identity; your visual cortex has been “trained” (through years of visual experience) to map retinal images directly to perceptual interpretations. This is amortised inference in the brain: the cost of learning is paid during development, and perception at test time is fast and feedforward. The Helmholtz machine, a precursor to the VAE proposed by Hinton and Dayan in the 1990s, was explicitly motivated by this analogy.

The Amortised ELBO

The ELBO for amortized inference over a dataset {𝒙1,,𝒙N} is: (ELBO)(ψ,θ)=i=1N𝔼qψ(𝒛|𝒙i)[logpθ(𝒙i,𝒛)logqψ(𝒛|𝒙i)], where θ denotes the generative model parameters. We maximise jointly over ψ (inference network) and θ (generative model) using stochastic gradient ascent, with the reparameterisation trick (The Reparameterization Trick) to estimate the gradients through the sampling.

The Amortization Gap

Amortised inference trades optimality for speed. A single neural network cannot perfectly approximate the optimal variational parameters for every possible input, so it must generalise across inputs, and this generalisation introduces a systematic approximation error.

Definition 11 (Amortization Gap).

The amortization gap for data point 𝒙i is the difference between the optimal per-instance ELBO and the amortised ELBO: (Amortgap)Δi=max𝝓i(𝝓i,θ;𝒙i)(fψ(𝒙i),θ;𝒙i)0.

Proposition 11 (Amortised ELBO is Looser).

The amortised ELBO is bounded above by the per-instance optimal ELBO: (Bound)(fψ(𝒙i),θ;𝒙i)max𝝓i(𝝓i,θ;𝒙i)logpθ(𝒙i), with the first inequality strict whenever fψ(𝒙i) does not equal the per-instance optimal 𝝓i. The total amortization gap for the dataset is Δ=i=1NΔi.

Proof.

The per-instance ELBO (𝝓,θ;𝒙i) is maximised at 𝝓i=arg max𝝓(𝝓,θ;𝒙i). The amortised ELBO evaluates this objective at 𝝓=fψ(𝒙i), which in general differs from 𝝓i. Since 𝝓i is the maximiser, (fψ(𝒙i),θ;𝒙i)(𝝓i,θ;𝒙i). The second inequality holds because the ELBO is always a lower bound on the log-evidence.

The amortization gap has several sources:

  • Limited network capacity. The inference network fψ may not be expressive enough to represent the mapping 𝒙𝝓(𝒙) exactly. For example, if the optimal mapping is highly nonlinear but fψ is a shallow network, it will approximate poorly in some regions of input space.

  • Training data coverage. The network is trained on a finite dataset and must generalise to unseen inputs. In regions of input space poorly represented in the training data, the amortised parameters may be suboptimal.

  • Multi-modality. If the true posterior is multi-modal for some inputs, the mean-field Gaussian output of a standard inference network cannot capture this structure, regardless of network capacity.

In practice, the amortization gap is typically small for well-designed models: less than a few nats per data point. It can be diagnosed by comparing the amortised ELBO against a locally refined ELBO (as in semi-amortised inference, below).

Semi-Amortized Inference

A natural compromise between per-instance optimisation and full amortisation is semi-amortized inference: use the amortised output fψ(𝒙) as an initialisation for a few steps of local iterative refinement. This combines the speed of amortisation (a good initialisation in one forward pass) with the accuracy of per-instance optimisation (a few gradient steps close the amortization gap).

Concretely:

  1. Compute 𝝓(0)=fψ(𝒙) via the inference network.

  2. For j=1,,J (typically J=520): 𝝓(j)=𝝓(j1)+α𝝓(𝝓,θ;𝒙)|𝝓=𝝓(j1).

  3. Use 𝝓(J) as the final variational parameters.

This can be seen as “test-time compute” for inference: spending more computation per data point to get a tighter ELBO.

Amortization and VAEs

Per-instance variational inference (left) versus amortized variational inference (right). Left: each data point 𝒙i requires a separate optimisation trajectory to find its optimal variational parameters 𝝓i. Right: a single inference network fψ maps any data point to variational parameters in one forward pass. The amortised approach is the architecture of the VAE encoder (ch:vae).

The connection to Variational Autoencoders (ch:vae) is now immediate. In a VAE:

  • The generative model pθ(𝒙|𝒛)p(𝒛) is a deep latent variable model with a neural network decoder.

  • The approximate posterior qψ(𝒛|𝒙) is amortised via a neural network encoder (the inference network).

  • The ELBO is optimised jointly over ψ and θ using the reparameterisation trick from The Reparameterization Trick.

Thus the VAE encoder is precisely an amortised inference network: it implements fψ(𝒙)=(𝝁ψ(𝒙),log𝝈ψ(𝒙)), mapping each input 𝒙 to the parameters of a Gaussian approximate posterior in a single forward pass.

Insight.

Amortization: Pay Once, Infer Forever. Amortised inference invests computation during training to learn a mapping from data to posteriors. Once trained, inference for any new data point, even one never seen before, costs only a single forward pass through the network. This is the key enabler that makes variational inference practical for large-scale deep generative models.

The tradeoff is the amortisation gap: the inference network cannot be optimal for every input. In practice, this gap is small for well-trained models with sufficiently expressive encoder architectures, and it can always be reduced by semi-amortised refinement.

Example: Amortized Inference for a Latent Variable Model

Example 17 (Amortised Inference for a Simple Generative Model).

Consider the following latent variable model for 1D data: z𝒩(0,1),x|z𝒩(w2σ(w1z+b1)+b2,σx2), where σ() is the sigmoid function and θ=(w1,b1,w2,b2,σx) are the generative model parameters.

Per-instance approach. For each xi, we would initialise μi,σi and run gradient ascent on (μi,σi;xi)=𝔼q[logp(xi,z)]+𝖧[q]. With N=10,000 data points and 100 gradient steps per point, this requires 106 gradient evaluations per epoch.

Amortised approach. Define an inference network fψ(x)=(μψ(x),logσψ(x)) as a small MLP (e.g., two hidden layers with 64 units). The ELBO becomes: (ψ,θ)=i=1N𝔼ϵ𝒩(0,1)[logpθ(xi|μψ(xi)+σψ(xi)ϵ)+logp(μψ(xi)+σψ(xi)ϵ)logqψ(z|xi)]. In each training step, we sample a minibatch of data points, draw one noise sample ϵ per data point (reparameterisation trick), compute the ELBO gradient with respect to (ψ,θ) jointly, and update. After training, fψ(xnew) instantly produces the approximate posterior for any new x.

The Road to Deep Generative Models

Let us pause and survey the path we have traversed in this chapter. We began with the fundamental inference problem: computing the posterior p(𝒛|𝒙). We formulated variational inference as an optimisation problem, minimising 𝖣KL(qp) over a tractable family, and derived the ELBO as the objective.

The journey from classical to modern VI can be summarised as a sequence of generalisations, each removing a limitation of the previous method:

1.3

MethodLimitation RemovedRemaining Limitation
CAVI(starting point)Requires full data pass; conjugate models only
Variational EMSeparates inference from parameter learningStill requires full data pass
SVISubsamples data for scalabilityRequires conjugate exponential families
BBVIWorks for any model (score function gradient)High variance gradients
ReparameterisationLow-variance gradientsRequires differentiable reparameterisation
Amortised VIO(1) inference per data pointAmortisation gap

The combination of amortised inference, the reparameterisation trick, and stochastic minibatch training gives us the VAE (ch:vae), the first practical framework for training deep latent variable models at scale. In the next sections, we push further: normalizing flows enrich the variational family beyond mean-field Gaussians, importance-weighted bounds tighten the ELBO, and natural gradients exploit the geometry of the variational distribution for faster convergence.

Remark 24 (The Variational Inference Toolkit).

A practitioner choosing a VI method should consider:

  1. Is the model conjugate? If yes, CAVI or SVI give fast, closed-form updates.

  2. Is the dataset large? If yes, use stochastic methods (SVI, BBVI, or reparameterised VI with minibatches).

  3. Is the variational distribution reparameterisable? If yes, use the reparameterisation trick for low-variance gradients. If not (e.g., discrete latent variables), use BBVI with variance reduction.

  4. Do you need inference for new data at test time? If yes, use amortised inference (an inference network).

  5. Is the mean-field assumption too restrictive? If yes, consider normalising flows or structured variational families (covered in the next sections).

Modern probabilistic programming frameworks such as Pyro (built on PyTorch) and NumPyro (built on JAX) implement all of these methods, allowing the practitioner to mix and match components as needed.

Normalizing Flows for Richer Posteriors

The variational families considered so far (mean-field factorizations, Mean-Field Variational Inference; exponential-family conditionals, Exponential Families and Conjugacy; and even full-covariance Gaussians) impose strong structural assumptions on the approximate posterior. A mean-field Gaussian, for instance, can never capture correlations between latent dimensions, while a full-covariance Gaussian cannot represent multimodality or skewness. When the true posterior p(𝒛|𝒙) exhibits such features, these families introduce an irreducible approximation gap: the ELBO remains strictly below logp(𝒙) regardless of optimization quality.

Normalizing flows address this limitation by constructing rich, flexible variational families through the composition of simple invertible transformations. The core idea is deceptively simple: start with a tractable base distribution q0(𝒛0) (e.g., a standard Gaussian) and transform it through a sequence of invertible maps to obtain a complex distribution capable of matching intricate posterior geometries.

Change of Variables via Invertible Maps

Let f:dd be a smooth, invertible (i.e., diffeomorphic) mapping. If 𝒛0q0(𝒛0) and 𝒛=f(𝒛0), then the density of 𝒛 is given by the change of variables formula: (COV)q(𝒛)=q0(f1(𝒛))|detf1𝒛|=q0(𝒛0)|detf𝒛0|1. Taking logarithms yields the key identity: (LOG COV)logq(𝒛)=logq0(𝒛0)log|detf𝒛0|. The Jacobian determinant |det(f/𝒛0)| measures how f locally stretches or compresses volume, adjusting the density accordingly.

Composing Flows

A single invertible transformation may not be expressive enough. The power of normalizing flows comes from composition: given a sequence of K diffeomorphisms f1,f2,,fK, define (FLOW Chain)𝒛K=(fKfK1f1)(𝒛0),𝒛0q0(𝒛0). By iterating the change-of-variables formula, the log-density of the final iterate 𝒛K decomposes as: (FLOW LOG Density)logqK(𝒛K)=logq0(𝒛0)k=1Klog|detfk𝒛k1| where 𝒛k=fk(𝒛k1) for k=1,,K. Each transformation fk may have its own learnable parameters.

Key Idea.

Flows trade computation for expressiveness. Each invertible layer adds O(d) to O(d3) computational cost (depending on the architecture) but strictly increases the capacity of the variational family. With enough layers, flows can in principle approximate any distribution, offering a systematic way to close the approximation gap in the ELBO.

ELBO with Normalizing Flows

Substituting the flow density into the standard ELBO (The Evidence Lower Bound), we obtain: (FLOW ELBO)flow=𝔼q0(𝒛0)[logp(𝒙,𝒛K)logq0(𝒛0)+k=1Klog|detfk𝒛k1|]=𝔼q0[logp(𝒙,𝒛K)]joint likelihood+𝖧[q0]base entropy+𝔼q0[k=1Klog|det𝑱k|]volume correction, where 𝑱k=deffk/𝒛k1 is the Jacobian of the k-th transformation. The first term encourages the transformed samples to land in high-probability regions under the model; the second and third terms together represent the entropy of the flow distribution, preventing collapse.

Since 𝒛K is a deterministic function of 𝒛0, all expectations are over q0: we sample 𝒛0q0, push it through the flow, and evaluate the objective. Gradients flow back through the entire chain via the reparameterization trick (The Reparameterization Trick).

Planar Flows

The simplest flow architecture, introduced by Rezende and Mohamed [23], uses planar transformations: (Planar)f(𝒛)=𝒛+𝒖h(𝒘𝒛+b), where 𝒖,𝒘d, b, and h is a smooth activation function (typically tanh). This transformation adds a perturbation in the direction 𝒖 whose magnitude depends on the projection of 𝒛 onto 𝒘. Geometrically, it contracts or expands the density along hyperplanes {𝒛:𝒘𝒛+b=const}.

The key computational advantage of planar flows is the efficient Jacobian determinant.

Proposition 12 (Planar Flow Jacobian).

The Jacobian determinant of the planar transformation is: (Planar DET)detf𝒛=1+h(𝒘𝒛+b)𝒖𝒘, which can be computed in O(d) time.

Proof.

The Jacobian matrix of f is f𝒛=𝑰d+h(𝒘𝒛+b)𝒖𝒘. This has the form 𝑰+𝒂𝒃 with 𝒂=h(𝒘𝒛+b)𝒖 and 𝒃=𝒘. By the matrix determinant lemma, det(𝑰+𝒂𝒃)=1+𝒃𝒂=1+h(𝒘𝒛+b)𝒘𝒖.

For the transformation to be invertible, we require det(f/𝒛)0, which imposes the constraint h(𝒘𝒛+b)𝒖𝒘>1. When h=tanh, this is enforced by reparameterizing 𝒖 so that 𝒖𝒘1+log(1+e𝒖𝒘) [23].

Radial Flows

While planar flows warp the density along hyperplanes, radial flows create contractions and expansions around a reference point 𝒛0d: (Radial)f(𝒛)=𝒛+βα+r(𝒛)(𝒛𝒛0),r(𝒛)=𝒛𝒛02, where α>0 and β are scalar parameters. The Jacobian determinant can likewise be computed in O(d): (Radial DET)detf𝒛=(1+βα+r)d1(1+βα+rβr(α+r)2). Radial flows are naturally suited to creating or removing modes, since they can concentrate or disperse density radially.

Beyond Simple Flows

Planar and radial flows have limited per-layer expressiveness (each adds only a single degree of freedom to the density shape). In practice, many layers are needed for complex posteriors. More powerful architectures have been developed that achieve a better balance between expressiveness and computational cost:

  1. RealNVP (Dinh et al. [12]): uses affine coupling layers with triangular Jacobians, yielding O(d) determinant computation and exact inversion.

  2. Masked Autoregressive Flows (MAF) (Papamakarios et al. [13]): autoregressive transformations with triangular Jacobians. Density evaluation is efficient but sampling requires sequential passes.

  3. Inverse Autoregressive Flows (IAF) (Kingma et al. [14]): the inverse of MAF, enabling efficient sampling at the cost of slower density evaluation, which is ideal for variational inference where sampling is the bottleneck.

We defer a comprehensive treatment of these architectures to the normalizing flows chapter; here we focus on flows as a tool for enriching variational posteriors.

A normalizing flow transforms a simple base distribution (standard Gaussian, left) through successive invertible maps into increasingly complex distributions. After K=4 planar flows, the resulting density can capture multimodality.

Example 18 (Flow Posterior for a Banana Distribution).

Consider the “banana-shaped” posterior that arises in many hierarchical models, characterized by strong nonlinear correlations. A standard Gaussian q(𝒛)=𝒩(𝒛;𝝁,𝚺) cannot capture the curvature, leading to a poor ELBO.

Applying K=8 planar flows with tanh activations to a diagonal Gaussian base: 𝒛0𝒩(𝝁,diag(𝝈2)),𝒛k=𝒛k1+𝒖ktanh(𝒘k𝒛k1+bk),k=1,,8, with jointly optimized parameters {𝝁,𝝈,𝒖k,𝒘k,bk}k=18, the flow posterior successfully captures the nonlinear correlation structure. The ELBO gap, measured against a long-run MCMC estimate of logp(𝒙), decreases from 3.2 nats (diagonal Gaussian) to 0.15 nats (8-layer flow).

Proposition 13 (Universal Approximation of Flows).

Let p be a continuous target density on d with finite second moments, and let q0=𝒩(0,𝑰). For any ϵ>0, there exists a finite composition of smooth invertible maps f=fKf1 such that the resulting density qK satisfies 𝖣KL(pqK)<ϵ.

The proof relies on the fact that smooth diffeomorphisms are dense in the space of measure-preserving maps (in the appropriate topology) [24]. In practice, the number of layers K required may be large, and optimization may not find the global optimum, so the approximation guarantee is primarily of theoretical interest.

Insight.

Flows as systematic bias reduction. In the variational inference framework, the approximation error 𝖣KL(qp(|𝒙)) has two components: approximation error (the best q in the family is still far from p) and optimization error (we fail to find the best q). Normalizing flows directly attack the approximation error by enlarging the variational family, at the cost of increasing the optimization challenge.

Importance Weighted Bounds

An orthogonal strategy for tightening the ELBO does not change the variational family at all but instead uses multiple samples from q to form a tighter lower bound on logp(𝒙). The importance weighted autoencoder (IWAE) bound, introduced by Burda et al. [7], achieves this through a simple application of importance sampling.

The IWAE Objective

Draw k independent samples 𝒛(1),,𝒛(k) from q(𝒛|𝒙) and define the importance weights: (IW Weights)w()=p(𝒙,𝒛())q(𝒛()|𝒙),=1,,k. The importance weighted ELBO with k samples is: (IWAE Bound)kIWAE=𝔼[log1k=1kw()]=𝔼[log1k=1kp(𝒙,𝒛())q(𝒛()|𝒙)] where the expectation is over 𝒛(1),,𝒛(k)iidq(𝒛|𝒙). Note that 1IWAE recovers the standard ELBO.

The Tightness Hierarchy

The central theoretical result for the IWAE bound is that more importance samples always yield a tighter bound.

Theorem 10 (IWAE Tightness Hierarchy).

For any k1: (IWAE Hierarchy)1IWAEkIWAEk+1IWAElogp(𝒙). Moreover, kIWAElogp(𝒙) as k.

Proof.

Upper bound. Each importance weight satisfies 𝔼q[w()]=q(𝒛|𝒙)p(𝒙,𝒛)q(𝒛|𝒙)d𝒛=p(𝒙), so 𝔼[1kw()]=p(𝒙). By Jensen's inequality (since log is concave): kIWAE=𝔼[log1k=1kw()]log𝔼[1k=1kw()]=logp(𝒙).

Monotonicity. Write wk=1k=1kw() and wk+1=1k+1=1k+1w(). We can express wk+1 as a mixture: wk+1=kk+1wk+1k+1w(k+1). Since log is concave, we have for any realization: logwk+1kk+1logwk+1k+1logw(k+1). Taking expectations and using the fact that the samples are exchangeable, we get 𝔼[logw(k+1)]=1, whence: k+1kk+1k+1k+11kk+1k+1k+1k=k, where the last inequality uses k1 (which holds by induction, with the base case k=1 being trivial).

Consistency. By the strong law of large numbers, wk𝔼q[w]=p(𝒙) almost surely, so logwklogp(𝒙) a.s. Dominated convergence (the log is bounded above by logp(𝒙) and the lower bound follows from integrability of w) gives klogp(𝒙).

Bias Analysis

A Taylor expansion reveals the rate at which the IWAE bound approaches logp(𝒙): (IWAE BIAS)kIWAE=logp(𝒙)12k𝖵arq[w](𝔼q[w])2+O(k2). Thus the gap closes at rate O(1/k), and the gap itself is proportional to the relative variance of the importance weights. If q is close to p(𝒛|𝒙), the weights are nearly constant, the variance is small, and even moderate k suffices.

The Signal-to-Noise Ratio Problem

While increasing k tightens the bound, Rainforth et al. [25] discovered a surprising counterpoint: the gradient signal for the inference network (encoder) deteriorates as k grows.

Theorem 11 (SNR Degradation).

Let ϕ denote the parameters of the inference network qϕ(𝒛|𝒙). The signal-to-noise ratio of the IWAE gradient estimator for ϕ satisfies: (IWAE SNR)SNRϕ(k)=|𝔼[ϕk]|𝖵ar[ϕk]=O(1k)as k.

This result reveals a fundamental tension:

  1. Tighter bound: larger k reduces the gap to logp(𝒙), helping the generative model pθ;

  2. Noisier encoder gradient: larger k reduces the SNR for ϕ, hurting the inference network qϕ.

Caution.

More importance samples tighten the bound but may hurt the encoder. Using a very large k in the IWAE objective produces a tighter bound on logp(𝒙), which benefits the decoder/generative model. However, the encoder gradients become increasingly dominated by noise, potentially leading to a poorly trained inference network. In practice, moderate values (k=5 to 50) often work best.

Gradient Computation

The gradient of the IWAE objective with respect to both model parameters θ and inference parameters ϕ can be written using self-normalized importance weights: (IWAE GRAD)k=𝔼[=1kw~()logw()],where w~()=w()m=1kw(m) are the normalized importance weights. This shows that the IWAE gradient is a weighted combination of per-sample ELBO gradients, with weights proportional to the importance ratios.

Tucker et al. [26] proposed the doubly reparameterized gradient estimator, which modifies the gradient computation to reduce variance without increasing bias. The key insight is to stop gradients through the normalized weights w~() while still obtaining an unbiased estimator, achieving better SNR properties for the encoder.

The IWAE bound with k importance samples provides a progressively tighter lower bound on the log-evidence logp(𝒙). The standard ELBO (k=1) converges to a value well below logp(𝒙), while IWAE bounds with k=5 and k=50 converge closer to the true value. However, the encoder gradient SNR decreases with k (Theorem 11).

Stein Variational Gradient Descent

All methods discussed so far represent the approximate posterior through a parametric distribution qλ(𝒛). An entirely different philosophy is to represent the posterior as a collection of particles {𝒛i}i=1n that are iteratively transported toward high-probability regions of p(𝒛|𝒙) while maintaining diversity. Stein Variational Gradient Descent (SVGD), introduced by Liu and Wang [6], achieves this by combining ideas from Stein's method, kernel methods, and variational inference into an elegant, deterministic update rule.

Stein's Identity and the Stein Operator

The foundation of SVGD is Stein's identity, which characterizes a distribution p through an integral condition involving its score function 𝒛logp(𝒛).

Definition 12 (Stein Operator).

Let p be a smooth density on d and let 𝝓:dd be a smooth vector-valued test function. The Stein operator 𝒜p applied to 𝝓 is: (Stein Operator)𝒜p𝝓(𝒛)=𝒛logp(𝒛)𝝓(𝒛)+𝒛𝝓(𝒛), where 𝒛𝝓=j=1dϕj/zj denotes the divergence.

Lemma 2 (Stein's Identity).

If p is a smooth density on d and 𝝓:dd is a smooth test function such that p(𝒛)𝝓(𝒛)0 as 𝒛 (boundary condition), then: (Stein Identity)𝔼p[trace(𝒜p𝝓(𝒛))]=0.

Proof.

Expanding the trace: 𝔼p[trace(𝒜p𝝓)]=p(𝒛)[𝒛logp(𝒛)𝝓(𝒛)+𝒛𝝓(𝒛)]d𝒛=[𝒛p(𝒛)𝝓(𝒛)+p(𝒛)𝒛𝝓(𝒛)]d𝒛=𝒛[p(𝒛)𝝓(𝒛)]d𝒛, where we used logp=p/p and the product rule for divergence. By the divergence theorem, this integral equals the boundary flux p𝝓𝒏^dS, which vanishes by the boundary condition.

The crucial observation is that Stein's identity holds for 𝝓 drawn from any sufficiently regular function class. If 𝔼q[trace(𝒜p𝝓)]0 for some 𝝓, then qp. This motivates using the maximum violation as a discrepancy measure.

Kernelized Stein Discrepancy

To obtain a tractable discrepancy, we restrict 𝝓 to lie in a reproducing kernel Hilbert space (RKHS) with kernel k:d×d.

Definition 13 (Kernelized Stein Discrepancy).

The kernelized Stein discrepancy (KSD) between q and p is: (KSD)𝕊(q,p)=max𝝓,𝝓1{𝔼q[trace(𝒜p𝝓(𝒛))]}2.

By the representer theorem in RKHS, the optimal test function admits a closed-form solution: (KSD Optimal)𝝓()𝔼q[k(𝒛,)𝒛logp(𝒛)+𝒛k(𝒛,)]. This function 𝝓 represents the direction of steepest descent for the KL divergence 𝖣KL(qp) in the space of distributions, as measured by the RKHS norm.

The SVGD Update Rule

Given n particles {𝒛i}i=1n representing the current approximation to p(𝒛|𝒙), SVGD updates them simultaneously: (SVGD Update)𝒛i𝒛i+ϵ𝝓^(𝒛i),𝝓^(𝒛i)=1nj=1n[k(𝒛j,𝒛i)𝒛jlogp(𝒛j|𝒙)+𝒛jk(𝒛j,𝒛i)] where ϵ>0 is the step size. The update has a beautiful interpretation as the sum of two forces:

  1. Attractive force: 1njk(𝒛j,𝒛i)𝒛jlogp(𝒛j|𝒙) drives each particle toward high-probability regions, weighted by kernel similarity. When k(𝒛j,𝒛i) is large (particles are close), particle i is strongly influenced by the gradient at particle j.

  2. Repulsive force: 1nj𝒛jk(𝒛j,𝒛i) pushes particles apart, preventing them from collapsing onto a single mode. For an RBF kernel k(𝒛,𝒛)=exp(𝒛𝒛2/(2h2)), this term pushes 𝒛i away from nearby particles.

Remark 25.

When n=1, the repulsive term vanishes and SVGD reduces to standard gradient ascent on logp(𝒛|𝒙), yielding a MAP estimate. The multi-particle nature of SVGD is essential for representing uncertainty.

Algorithm 6.

SVGD Algorithm

  1. Input: Target score 𝒛logp(𝒛|𝒙) (up to a constant), kernel k, step sizes {ϵt}, number of particles n.

  2. Initialize: {𝒛i(0)}i=1nq0(𝒛) (e.g., q0=𝒩(0,𝑰)).

  3. For t=0,1,2, until convergence: enumerate[(a)]

  4. Compute the kernel matrix: Kij=k(𝒛j(t),𝒛i(t)) for all i,j.

  5. Compute the score at each particle: 𝒈j=𝒛jlogp(𝒛j(t)|𝒙).

  6. For each particle i, compute the SVGD direction: 𝝓^(𝒛i(t))=1nj=1n[Kij𝒈j+𝒛jk(𝒛j(t),𝒛i(t))].

  7. Update: 𝒛i(t+1)=𝒛i(t)+ϵt𝝓^(𝒛i(t)). enumerate

  8. Return: particles {𝒛i(T)}i=1n.

SVGD particles evolving from a Gaussian initialization (left) to approximate a bimodal target distribution (orange contours). The attractive force drives particles toward the modes, while the repulsive force ensures both modes are covered with appropriate particle density.

Theoretical Foundation

The SVGD update can be understood as a discretization of a continuous gradient flow on the space of probability distributions.

Theorem 12 (SVGD as KL Gradient Flow).

In the limit of infinitely many particles (n) and infinitesimal step size (ϵ0), SVGD implements the gradient flow of 𝖣KL(qp) in the space of probability distributions, as measured in the RKHS norm. Specifically, the density qt of the particles at time t evolves according to: (SVGD Gradient FLOW)qtt=(qt𝝓qt), where 𝝓qt is the optimal RKHS perturbation , and this dynamics decreases 𝖣KL(qtp) at the fastest rate among all perturbations of unit RKHS norm.

This theorem connects SVGD to the theory of Wasserstein gradient flows, providing a rigorous justification for the particle updates. In practice, the finite-particle approximation introduces bias, and the quality of the approximation depends on both the number of particles and the choice of kernel.

Comparison with MCMC

SVGD occupies an interesting middle ground between variational inference and Markov chain Monte Carlo (MCMC):

PropertyVI (parametric)SVGDMCMC
UpdatesDeterministicDeterministicStochastic
RepresentationParameters λParticles {𝒛i}Samples {𝒛i}
MultimodalityDifficultNaturalNatural
ConvergenceOptimizationOptimizationMixing
Asymptotic biasYes (family)No()No
()In the infinite-particle limit. Finite-particle SVGD has variance collapse issues.

Example 19 (Bayesian Logistic Regression with SVGD).

Consider binary classification with 𝒙id, yi{0,1}, and a logistic likelihood: p(yi=1|𝒙i,𝒘)=σ(𝒘𝒙i),p(𝒘)=𝒩(0,α1𝑰). The unnormalized log-posterior is: logp(𝒘|𝑿,𝒚)i=1N[yilogσ(𝒘𝒙i)+(1yi)log(1σ(𝒘𝒙i))]α2𝒘2. SVGD with n=100 particles and an RBF kernel k(𝒘,𝒘)=exp(𝒘𝒘2/(2h2)), where h is set to the median pairwise distance (the median heuristic), provides both a point prediction (particle mean) and uncertainty estimates (particle spread) without any parametric assumptions on the posterior shape.

Insight.

SVGD: the best of both worlds. SVGD combines the computational efficiency of variational methods (deterministic updates, no rejection steps) with the flexibility of particle-based methods (no parametric assumptions, natural handling of multimodality). The kernel controls the trade-off: a wide kernel encourages exploration, while a narrow kernel promotes exploitation.

Natural Gradient Variational Inference

Standard gradient-based optimization of the ELBO treats the variational parameters 𝝀 as living in Euclidean space: the steepest-ascent direction is simply 𝝀. But 𝝀 parameterizes a probability distribution q𝝀, and Euclidean geometry is a poor match for the space of distributions. Two parameter vectors 𝝀 and 𝝀+𝜹 that are close in Euclidean norm may correspond to distributions that are far apart in KL divergence, and vice versa.

The natural gradient [27] resolves this mismatch by equipping the parameter space with the Fisher information metric, the unique Riemannian metric that respects the geometry of probability distributions.

The Fisher Information Matrix

Definition 14 (Fisher Information Matrix).

The Fisher information matrix of a parametric family {q𝝀} is: (Fisher)𝑭(𝝀)=𝔼q𝝀[𝝀logq𝝀(𝒛)(𝝀logq𝝀(𝒛))]=𝔼q𝝀[𝝀2logq𝝀(𝒛)].

The Fisher matrix 𝑭 is positive semidefinite and, for regular models, positive definite. It defines a local inner product 𝒖,𝒗𝑭=𝒖𝑭𝒗 on the parameter space, making it a Riemannian manifold.

For exponential families (Exponential Families and Conjugacy) with natural parameters 𝜼, the Fisher matrix has a particularly elegant form: (Fisher Expfam)𝑭(𝜼)=2A(𝜼), the Hessian of the log-partition function. Since A is convex, 𝑭 is always positive semidefinite, confirming its role as a metric.

The Natural Gradient

Definition 15 (Natural Gradient).

The natural gradient of a function (𝝀) with respect to the Fisher information metric is: (DEF)~𝝀=𝑭(𝝀)1𝝀.

The natural gradient is the solution to the constrained optimization problem: find the direction 𝜹 that maximizes the linear approximation 𝜹 subject to a fixed step in KL divergence: (Natgrad Constrained)~=arg max𝜹𝜹s.t.𝜹𝑭𝜹ϵ2. This ensures that each step moves a fixed “distance” in the space of distributions, not in the space of parameters.

Theorem 13 (Parameterization Invariance).

The natural gradient is invariant under smooth reparameterization. If 𝝀=g(𝝃) for a diffeomorphism g, then the natural gradient update 𝝀t+1=𝝀t+ϵ~𝝀 and the corresponding update in 𝝃-coordinates produce identical trajectories in distribution space.

Proof.

Under the reparameterization 𝝀=g(𝝃), the Fisher matrix transforms as 𝑭𝝃=𝑱𝑭𝝀𝑱, where 𝑱=g/𝝃 is the Jacobian. The Euclidean gradient transforms as 𝝃=𝑱𝝀. Therefore: 𝑭𝝃1𝝃=(𝑱𝑭𝑱)1𝑱=𝑱1𝑭1(𝑱)1𝑱=𝑱1~𝝀. Mapping back: 𝑱~𝝃=~𝝀, confirming that the induced distribution update is identical.

Euclidean gradient (left) versus natural gradient (right) on an objective with elongated contours. The Euclidean gradient points perpendicular to the contour (steepest ascent in parameter space) but zigzags along the valley. The natural gradient, rescaled by the inverse Fisher matrix, points more directly toward the optimum by accounting for the curvature of the statistical manifold.

Natural Gradient for Exponential Families

For variational families in the exponential family, the natural gradient has a remarkably simple form. Let 𝒎=𝔼q𝜼[T(𝒛)]=A(𝜼) denote the mean parameters. Since 𝑭(𝜼)=2A(𝜼)=𝒎/𝜼, the natural gradient update in natural parameters is: (Natgrad Expfam)𝜼t+1=𝜼t+ρt𝑭(𝜼t)1𝜼=𝜼t+ρt𝒎, where 𝒎 is the gradient with respect to the mean parameters. This is the natural gradient expressed purely in terms of mean-parameter gradients, with no explicit matrix inversion required.

The Bayesian Learning Rule

For conjugate exponential-family models with prior p(𝒛)exp(𝜼0T(𝒛)) and likelihood contributions p(𝒙i|𝒛)exp(𝜼i(𝒛)T(𝒛)), the natural gradient update takes the form of the Bayesian learning rule [28]: (BLR)𝜼t+1=(1ρt)𝜼t+ρt(𝜼0+N𝔼qt[𝒎logp(𝒙i|𝒛)]) where 𝒙i is a randomly selected data point and N is the dataset size. This has a beautiful interpretation: at each step, the natural parameters are a weighted average of the current estimate and a target formed by combining the prior natural parameters with a scaled stochastic estimate of the data contribution.

Remark 26.

The connection to SVI (Stochastic Variational Inference) is now transparent: SVI performs exactly this update. The Robbins–Monro step sizes in SVI are not merely a convergence trick; they arise naturally from the requirement of taking natural gradient steps on the ELBO. SVI was “accidentally” doing the right thing all along.

Practical Methods

Computing the full Fisher matrix is O(p2) in the number of parameters p, which is prohibitive for large models. Several practical approximations have been developed:

  1. Diagonal Fisher: Approximate 𝑭diag(𝑭), reducing storage and inversion to O(p). This is equivalent to using per-parameter adaptive step sizes.

  2. KFAC (Kronecker-factored approximate curvature): For neural networks, approximate the Fisher as a Kronecker product of smaller matrices, one per layer.

  3. VOGN (Variational Online Gauss-Newton): A natural-gradient method for Bayesian neural networks that maintains a diagonal Gaussian posterior q(𝒘)=𝒩(𝝁,diag(𝝈2)) over weights [15].

The Bethe Free Energy and Belief Propagation

We now step back from gradient-based optimization and examine variational inference from a broader, unifying perspective. The variational principle for inference, developed systematically by Wainwright and Jordan [29], reveals that essentially all approximate inference methods, including mean field, belief propagation, expectation propagation, and more, can be understood as different approximations to a single optimization problem. This perspective provides deep insight into why methods work (or fail) and suggests principled ways to design new ones.

The Exact Variational Principle

Consider an undirected graphical model (Markov random field) with potential functions ψs(𝒛s) for nodes s and ψst(𝒛s,𝒛t) for edges (s,t)E of a graph G=(V,E). The joint distribution is: (MRF)p(𝒛;𝜽)=1Z(𝜽)exp(𝜽T(𝒛)), where 𝜽 collects all natural parameters and T(𝒛) collects the sufficient statistics. The log-partition function A(𝜽)=logZ(𝜽) is the central quantity of interest, since marginals and expectations follow from its derivatives.

The exact variational principle expresses A as a convex optimization problem via conjugate duality: (Exact Variational)A(𝜽)=sup𝝁{𝜽𝝁+𝖧(𝝁)} where is the marginal polytope (the set of all valid marginal vectors realizable by some distribution) and 𝖧(𝝁) is the entropy written as a function of the marginals. The supremum is attained at 𝝁=𝔼p[T(𝒛)], the exact marginals.

This formulation is exact but intractable in general: (i) the marginal polytope has exponentially many constraints, and (ii) the entropy 𝖧(𝝁) has no closed-form expression in terms of marginals for general graphs.

Mean Field as Inner Approximation

Mean-field VI (Mean-Field Variational Inference) can be recast in this framework as making two approximations:

  1. Inner bound on : restrict to product distributions, which gives a subset MF. Since we optimize over a smaller set, we obtain a lower bound on A(𝜽).

  2. Exact entropy: the entropy of a product distribution factorizes as 𝖧MF=s𝖧(τs), which is exact for the product family.

The mean-field approximation is thus: (MF Variational)AMF(𝜽)=sup𝝉MF{𝜽𝝉+sV𝖧(τs)}A(𝜽). The bound is tight only when the true distribution is itself a product (i.e., the graph has no edges).

Belief Propagation and the Bethe Approximation

Belief propagation (BP) takes the opposite approach to mean field, making approximations in a different direction:

  1. Outer relaxation of : replace the marginal polytope with the local polytope: (Local Polytope)(G)={𝝉0|zsτs(zs)=1,zsτst(zs,zt)=τt(zt)(s,t)E}, which enforces only pairwise marginalization consistency. We always have (G)(G); equality holds if and only if G is a tree.

  2. Bethe entropy approximation: replace the exact entropy with the Bethe entropy: (Bethe Entropy)𝖧Bethe(𝝉)=sV𝖧(τs)(s,t)E𝖨(τst), where 𝖧(τs) is the marginal entropy of node s and 𝖨(τst)=𝖧(τs)+𝖧(τt)𝖧(τst) is the mutual information of edge (s,t).

Definition 16 (Bethe Free Energy).

The Bethe free energy is the negative of the Bethe variational objective: (Bethe FREE Energy)FBethe(𝝉)=𝜽𝝉𝖧Bethe(𝝉). The Bethe approximation to the log-partition function is: (Bethe Approx)ABethe(𝜽)=sup𝝉(G){𝜽𝝉+𝖧Bethe(𝝉)}.

Unlike the mean-field bound, the Bethe approximation is neither an upper nor a lower bound on A(𝜽) in general. However, it can be much more accurate than mean field, especially for graphs with weak interactions or high connectivity.

BP Fixed Points and the Bethe Variational Problem

The connection between message-passing algorithms and variational methods is made precise by the following foundational result.

Theorem 14 (BP Fixed Points = Bethe Stationary Points).

The fixed points of the loopy belief propagation algorithm are in one-to-one correspondence with the stationary points of the Bethe variational problem over the local polytope (G).

Proof sketch.

Write the Lagrangian of the Bethe variational problem with multipliers enforcing the local consistency constraints in (G). Setting partial derivatives to zero yields stationarity conditions of the form: τs(zs)exp(θs(zs))t𝒩(s)mts(zs), where mts are the Lagrange multipliers, and: mts(zs)ztexp(θst(zs,zt))τt(zt)u𝒩(t)smut(zt). These are precisely the BP message update equations. Conversely, any BP fixed point defines pseudo-marginals τs,τst that satisfy the stationarity conditions of the Bethe problem.

Exactness on Trees

Corollary 2 (BP is Exact on Trees).

If G is a tree (acyclic graph), then:

  1. The local polytope equals the marginal polytope: (G)=(G).

  2. The Bethe entropy equals the exact entropy: 𝖧Bethe=𝖧.

  3. BP converges to the unique fixed point, which yields the exact marginals.

This explains the remarkable success of BP on tree-structured models [16] and provides insight into why “loopy” BP (applied to graphs with cycles) often works well in practice: many real-world graphical models have locally tree-like structure.

The variational inference landscape. Exact inference corresponds to optimizing over the true marginal polytope with exact entropy. Mean field uses an inner approximation (MF) with exact entropy for product distributions, yielding a lower bound. Belief propagation uses an outer relaxation () with the approximate Bethe entropy, yielding neither a bound in general. Structured VI methods interpolate between these extremes.

Beyond Bethe: Region-Based Methods

The Bethe approximation uses pairwise interactions. The Kikuchi hierarchy [30] generalizes this to larger regions (clusters of variables), leading to tighter entropy approximations at higher computational cost. The corresponding message-passing algorithms are called generalized belief propagation (GBP). The k-th level of the Kikuchi hierarchy uses regions of up to k variables and recovers the exact entropy when k equals the treewidth of the graph.

Historical Note.

From Pearl's messages to variational free energies. Judea Pearl introduced belief propagation for tree-structured graphical models in 1988 [16], where it provides exact inference. The algorithm was soon applied heuristically to loopy graphs with surprising empirical success. The variational interpretation, connecting BP fixed points to the Bethe free energy, was established by Yedidia, Freeman, and Weiss [17] in 2001, placing loopy BP on firm theoretical footing and opening the door to principled generalizations.

Insight.

All approximate inference methods are variational. The Wainwright–Jordan framework reveals that mean field, belief propagation, expectation propagation, and even MCMC (in a limiting sense) are all solving versions of the same variational problem sup𝝉{𝜽𝝉+𝖧~(𝝉)}; they simply differ in (i) the feasible set (inner or outer approximation to ) and (ii) the entropy approximation 𝖧~. Understanding this unifying structure is essential for choosing and designing inference algorithms.

Variational Inference in Modern Generative Models

Variational inference is not merely a classical technique for approximate Bayesian computation; it is the mathematical engine powering the most successful generative models of the modern era. Variational autoencoders, diffusion models, and even aspects of large language model alignment all rest on variational principles developed in this chapter. We now trace these connections explicitly, demonstrating how the abstract machinery of the ELBO, reparameterization, and amortized inference manifests in concrete generative architectures.

Variational Autoencoders

The variational autoencoder (VAE, ch:vae) is perhaps the most direct application of variational inference. A deep latent variable model specifies: (VAE Model)pθ(𝒙,𝒛)=p(𝒛)pθ(𝒙|𝒛),p(𝒛)=𝒩(0,𝑰),pθ(𝒙|𝒛)=𝒩(𝝁θ(𝒛),𝝈θ2(𝒛)), where 𝝁θ and 𝝈θ2 are neural networks. The true posterior pθ(𝒛|𝒙) is intractable, so we introduce an amortized variational distribution: (VAE Encoder)qϕ(𝒛|𝒙)=𝒩(𝝁ϕ(𝒙),diag(𝝈ϕ2(𝒙))).

The VAE training objective is precisely the ELBO: (VAE ELBO)(θ,ϕ;𝒙)=𝔼qϕ(𝒛|𝒙)[logpθ(𝒙|𝒛)]𝖣KL(qϕ(𝒛|𝒙)p(𝒛)). The first term is the expected reconstruction quality; the second is the KL regularizer pushing the approximate posterior toward the prior (see sec:vae:elbo for a detailed derivation).

Key VI innovations in VAEs.

  1. Amortized inference: Rather than optimizing separate variational parameters 𝝀i for each data point 𝒙i, the encoder qϕ(𝒛|𝒙) shares parameters ϕ across all data points. This introduces an amortization gap: the amortized posterior may be suboptimal for any individual 𝒙i, but this enables O(1) inference at test time.

  2. Reparameterization: The reparameterization trick (The Reparameterization Trick) makes the ELBO differentiable with respect to ϕ, enabling joint optimization of encoder and decoder.

  3. β-VAE: The modified objective β=𝔼q[logpθ(𝒙|𝒛)]β𝖣KL(qϕp) with β>1 encourages disentangled representations at the cost of reconstruction quality.

  4. VQ-VAE: Replaces the continuous latent space with discrete codes using vector quantization and the straight-through estimator, sidestepping the KL term entirely.

Diffusion Models as Hierarchical VAEs

Diffusion models (ch:diffusion) can be viewed as hierarchical VAEs with T layers of latent variables [31]. The forward (noising) process defines the variational distribution: (DIFF Forward)q(𝒙1:T|𝒙0)=t=1Tq(𝒙t|𝒙t1),q(𝒙t|𝒙t1)=𝒩(1βt𝒙t1,βt𝑰), while the reverse (generative) process is: (DIFF Reverse)pθ(𝒙0:T)=p(𝒙T)t=1Tpθ(𝒙t1|𝒙t),p(𝒙T)=𝒩(0,𝑰).

The variational lower bound (sec:diff:vdm:elbo) decomposes as: (DIFF VLB)logpθ(𝒙0)𝖣KL(q(𝒙T|𝒙0)p(𝒙T))prior matchingt=2T𝖣KL(q(𝒙t1|𝒙t,𝒙0)pθ(𝒙t1|𝒙t))consistency terms+𝔼q[logpθ(𝒙0|𝒙1)]reconstruction. Crucially, each consistency term is a KL divergence between two Gaussians: the true posterior q(𝒙t1|𝒙t,𝒙0) (available in closed form via Bayes' rule, see thm:diff:elbo-first) and the learned reverse pθ(𝒙t1|𝒙t), making each term analytically tractable.

Remark 27.

The simplified objective used in practice (noise prediction loss) corresponds to a reweighted VLB where the per-timestep weights are uniform rather than the SNR(t)-dependent weights arising from the true VLB. This reweighting improves sample quality at the cost of not optimizing a valid lower bound.

Bayesian Neural Networks

In a Bayesian neural network, we place a prior p(𝑾) over the weights and seek the posterior p(𝑾|𝒟). Variational inference approximates this with qϕ(𝑾), typically a factorized Gaussian: (BNN)qϕ(𝑾)=l=1Lij𝒩(Wij(l);μij(l),(σij(l))2).

Bayes by Backprop (Blundell et al. [32]) optimizes the ELBO: (Bayes Backprop)(ϕ)=𝔼qϕ(𝑾)[logp(𝒟|𝑾)]𝖣KL(qϕ(𝑾)p(𝑾)), using the reparameterization trick: Wij=μij+σijϵij with ϵij𝒩(0,1).

Point-estimate neural network (left) versus Bayesian neural network with variational posterior (right). In the Bayesian version, each weight is a distribution q(wij)=𝒩(μij,σij2) rather than a point value, enabling principled uncertainty quantification through the predictive distribution p(𝒚|𝒙,𝒟)=𝔼q(𝑾)[p(𝒚|𝒙,𝑾)].

MC-Dropout as implicit VI. Gal and Ghahramani [33] showed that applying dropout at test time (MC-Dropout) is equivalent to approximate variational inference with a specific variational distribution: each weight is either present (with its trained value) or absent (zeroed out), with Bernoulli probability determined by the dropout rate. This provides a practical uncertainty estimate requiring no architectural changes, only keeping dropout active during prediction and averaging over multiple forward passes.

VI and Large Language Models

Variational principles appear in modern large language models in several contexts:

  1. KL regularization in RLHF: Reinforcement learning from human feedback [18] maximizes reward subject to a KL penalty 𝖣KL(πθπref) that prevents the policy πθ from deviating too far from a reference model πref. This is structurally identical to the ELBO, with the reward playing the role of the log-likelihood and the KL penalty playing the role of the regularizer.

  2. Latent reasoning models: Some approaches to improving LLM reasoning introduce latent “thought” variables 𝒛 and optimize a variational bound on logp(𝒚|𝒙)𝔼q(𝒛|𝒙,𝒚)[logp(𝒚|𝒙,𝒛)]𝖣KL(qp(𝒛|𝒙)), using variational EM to alternately improve the thought generator and the output model.

The Generative Model Family Tree

The generative model family tree showing how variational inference connects major model families. GMMs use the EM algorithm (a special case of variational EM); VAEs use amortized ELBO optimization; diffusion models optimize a hierarchical variational lower bound; and Bayesian neural networks maintain posterior distributions over weights.

tab:vi:modern-summary summarizes how VI concepts manifest across modern generative model families.

ModelVariational familyELBO variantKey innovation
GMM (ch:gmm)Categorical + GaussiansStandard ELBOEM algorithm
VAE (ch:vae)Amortized GaussianStandard ELBOReparameterization
β-VAEAmortized GaussianWeighted KLDisentanglement
VQ-VAEDiscrete codesCommitment lossStraight-through
Diffusion (ch:diffusion)Fixed forward processHierarchical VLBNoise prediction
BNNFactorized GaussianStandard ELBOBayes by Backprop
LLM (RLHF)Policy πθRewardKLKL regularization
Variational inference across modern generative models.

Practical Guide and Open Problems

We conclude the chapter with practical guidance for applying variational inference and a survey of open research directions.

Choosing the Right VI Method

The choice of VI algorithm depends on the model structure, dataset size, and desired posterior quality. fig:vi:decision-flowchart provides a decision guide.

Decision flowchart for selecting a variational inference method. Conjugate models admit CAVI (small data) or SVI (large data). Non-conjugate models use black-box VI or the reparameterization trick, with normalizing flows when a richer posterior is needed, and SVGD when parametric assumptions are undesirable.

Diagnostics

Monitoring VI convergence and quality requires attention to several indicators:

  1. ELBO monitoring: Plot the ELBO across iterations. A plateau indicates convergence (but possibly to a local optimum). Sudden drops suggest numerical issues.

  2. Posterior predictive checks: Sample 𝒛q(𝒛), generate synthetic data 𝒙p(𝒙|𝒛), and compare distributional properties with the observed data. Systematic discrepancies reveal model or approximation inadequacies.

  3. Comparison to MCMC on small problems: On low-dimensional subproblems or subsets of data, run MCMC to obtain ground-truth posterior summaries. Compare VI marginals, means, and variances to MCMC estimates. Large discrepancies indicate the variational family is too restrictive.

  4. Gradient variance monitoring: For BBVI (Black-Box Variational Inference), monitor the variance of gradient estimates. Excessively high variance indicates the need for better control variates or larger mini-batches.

Common Pitfalls

  1. Mode collapse in mean-field: Mean-field VI minimizes the reverse KL 𝖣KL(qp), which is mode-seeking: the optimizer concentrates q on a single mode of a multimodal posterior, ignoring others entirely.

  2. Poor initialization: CAVI and gradient-based methods can converge to poor local optima. Multiple random restarts or initialization from simpler models (e.g., initializing from the prior) can mitigate this.

  3. Posterior collapse in VAEs: When the decoder is too powerful, the model learns to ignore the latent variables entirely, with qϕ(𝒛|𝒙)p(𝒛) for all 𝒙 (see sec:vae:collapse).

  4. Gradient variance in BBVI: The score-function gradient estimator (Black-Box Variational Inference) can have extremely high variance, making optimization impractical without careful variance reduction via control variates and baselines.

  5. Underestimated uncertainty: Variational posteriors, especially mean-field ones, systematically underestimate posterior variance. This can lead to overconfident predictions in downstream tasks.

Open Research Directions

Despite decades of development, variational inference remains an active area of research with several important open problems:

  1. Tighter bounds without SNR degradation: The IWAE bound (Importance Weighted Bounds) tightens monotonically in k but degrades encoder gradients. Designing bounds that are simultaneously tight and provide high-quality gradients for all model components remains open.

  2. Better structured variational families: Beyond mean-field and normalizing flows, what are the “right” variational families that balance expressiveness, computational cost, and optimization difficulty? Structured mean-field approaches that exploit graphical model structure are promising but underexplored for deep models.

  3. VI for discrete structures: Most VI methods assume continuous latent variables. Extending reparameterization-style tricks to discrete latent variables (beyond Gumbel-Softmax) remains challenging, with implications for program synthesis, combinatorial optimization, and symbolic reasoning.

  4. Scaling VI to trillion-parameter models: As models grow to hundreds of billions or trillions of parameters, maintaining even a diagonal Gaussian posterior requires doubling the parameter count. Efficient representations of uncertainty at this scale are needed.

  5. Connections to optimal transport: Wasserstein distances and optimal transport maps offer alternative geometries for measuring the discrepancy between q and p. Replacing KL divergence with Wasserstein-type objectives leads to different algorithms with potentially better properties for multimodal posteriors.

Exercises

Exercise 10 (KL Divergence between Gaussians ).

Let p=𝒩(μ1,σ12) and q=𝒩(μ2,σ22) be univariate Gaussians.

  1. Show that the KL divergence is: 𝖣KL(qp)=logσ1σ2+σ22+(μ2μ1)22σ1212.

  2. Verify that 𝖣KL(qp)=0 if and only if μ1=μ2 and σ1=σ2.

  3. Generalize to d-dimensional Gaussians p=𝒩(𝝁1,𝚺1) and q=𝒩(𝝁2,𝚺2).

Exercise 11 (Forward vs Reverse KL ).

Let p(z)=12𝒩(z;3,1)+12𝒩(z;3,1) be a symmetric bimodal mixture.

  1. Find the Gaussian q=𝒩(μ,(σ)2) that minimizes 𝖣KL(qp) (reverse KL, used in VI). Hint: argue by symmetry and mode-seeking behavior that there are two local optima plus a saddle point.

  2. Find the Gaussian q=𝒩(μ,(σ)2) that minimizes 𝖣KL(pq) (forward KL). Show that μ=0 and (σ)2=10.

  3. Explain qualitatively why the reverse KL selects a single mode while the forward KL covers both modes. Which behavior is preferable for approximate inference?

Exercise 12 (Deriving the ELBO from Jensen's Inequality ).

Starting from the marginal likelihood p(𝒙)=p(𝒙,𝒛)d𝒛 and an arbitrary distribution q(𝒛):

  1. Multiply and divide by q(𝒛) inside the integral.

  2. Apply Jensen's inequality to obtain logp(𝒙)𝔼q[logp(𝒙,𝒛)logq(𝒛)].

  3. Identify when equality holds.

Exercise 13 (Deriving the ELBO from KL Decomposition ).

  1. Starting from the definition of 𝖣KL(q(𝒛)p(𝒛|𝒙)), show that: logp(𝒙)=𝔼q[logp(𝒙,𝒛)logq(𝒛)]ELBO+𝖣KL(q(𝒛)p(𝒛|𝒙)).

  2. Explain why this immediately implies that the ELBO is a lower bound on logp(𝒙).

Exercise 14 (ELBO Tightness ).

Using the decomposition from Exercise Exercise 13, prove that the ELBO equals logp(𝒙) if and only if q(𝒛)=p(𝒛|𝒙) almost everywhere. Explain why this means the gap between the ELBO and logp(𝒙) measures the quality of the variational approximation.

Exercise 15 (Mean-Field Optimal Factor ).

Consider the joint distribution p(z1,z2)exp(12[z12+z22+z1z2]) and the mean-field factorization q(z1,z2)=q1(z1)q2(z2).

  1. Derive the optimal q1(z1) holding q2 fixed, using the mean-field update logqj(zj)=𝔼qj[logp(𝒛)]+const.

  2. Show that q1 is Gaussian. Find its mean and variance.

  3. By symmetry, write down q2 and verify that the mean-field approximation underestimates the correlation between z1 and z2.

Exercise 16 (CAVI for Bayesian Linear Regression ).

Consider the model yi=𝒘𝒙i+ϵi, ϵi𝒩(0,τ1), with priors 𝒘𝒩(0,α1𝑰) and τGamma(a0,b0).

  1. Derive the CAVI update for q(𝒘)=𝒩(𝝁w,𝚺w).

  2. Derive the CAVI update for q(τ)=Gamma(an,bn).

  3. Write pseudocode for the full CAVI algorithm.

Exercise 17 (CAVI for Bayesian GMM ).

Consider a Bayesian Gaussian mixture model with K=3 components: p(𝒙i|zi=k)=𝒩(𝝁k,𝑰), p(zi=k)=πk, with priors 𝝁k𝒩(𝒎0,s02𝑰) and 𝝅Dirichlet(α01).

  1. Write down the complete-data log-likelihood.

  2. Derive the CAVI update for q(zi) (a categorical distribution over components).

  3. Derive the CAVI update for q(𝝁k) (a Gaussian).

  4. Derive the CAVI update for q(𝝅) (a Dirichlet).

  5. Explain how these updates relate to the EM algorithm for GMMs (ch:gmm).

Exercise 18 (CAVI Monotonically Increases the ELBO ).

Prove that each coordinate update in CAVI (Algorithm 1) does not decrease the ELBO. Hint: Show that the CAVI update for factor qj solves arg maxqj(q1,,qj,,qM), and that replacing qj with its optimum can only increase .

Exercise 19 (Gradient of the Log-Partition Function ).

Let p(𝒛;𝜼)=h(𝒛)exp(𝜼T(𝒛)A(𝜼)) be an exponential family distribution.

  1. Show that 𝜼A(𝜼)=𝔼p[T(𝒛)].

  2. Show that 𝜼2A(𝜼)=𝖢ovp[T(𝒛)].

  3. Conclude that A is convex.

Exercise 20 (Natural Parameter Updates for Conjugate Models ).

Consider a Bayesian model with likelihood p(𝒙|θ) from an exponential family with sufficient statistic T(𝒙) and a conjugate prior p(θ)exp(𝜼0T(θ)ν0A(θ)).

  1. Show that the posterior p(θ|𝒙1:N) is in the same family with updated natural parameters.

  2. Express the updated parameters in terms of 𝜼0, ν0, and the data sufficient statistics.

  3. Interpret the prior parameters (𝜼0,ν0) as “pseudo-observations.”

Exercise 21 (Variational EM for a Latent Factor Model ).

Consider the model 𝒙i=𝑾𝒛i+𝝐i with 𝒛i𝒩(0,𝑰k), 𝝐i𝒩(0,σ2𝑰d), and 𝑾d×k.

  1. Write down the ELBO for this model with q(𝒛i)=𝒩(𝒎i,𝑺i).

  2. VE-step: Derive the optimal q(𝒛i) for fixed 𝑾,σ2.

  3. VM-step: Derive the updates for 𝑾 and σ2 for fixed q.

  4. Show that this recovers probabilistic PCA in the limit.

Exercise 22 (SVI Natural Gradient for LDA ).

In Latent Dirichlet Allocation, each document d has topic proportions 𝜽dDirichlet(𝜶) and each word wdn is drawn from topic zdnCategorical(𝜽d) with word distribution 𝜷zdn.

  1. Write down the complete-data log-likelihood.

  2. Identify the global and local variational parameters.

  3. Derive the noisy natural gradient update for the global parameter 𝝀 (the Dirichlet parameter of the variational distribution over topics).

  4. Verify that the SVI update has the form of (BLR).

Exercise 23 (Robbins–Monro Convergence ).

Consider the stochastic approximation iteration λt+1=λt+ρtgt, where 𝔼[gt|λt]=(λt) and the step sizes satisfy tρt=, tρt2<.

  1. Explain intuitively why both conditions are necessary: ρt= ensures we can reach any point; ρt2< ensures the noise averages out.

  2. Verify that ρt=tα satisfies both conditions for α(12,1].

  3. For the quadratic case (λ)=12(λλ)2 with gt=(λtλ)+ϵt and ϵt𝒩(0,σ2), prove that λtλ in mean square.

Exercise 24 (Score Function Has Zero Expectation ).

Let qϕ(𝒛) be a smooth parametric density. Prove that 𝔼qϕ[ϕlogqϕ(𝒛)]=0. Hint: Differentiate qϕ(𝒛)d𝒛=1 with respect to ϕ and exchange differentiation and integration.

Exercise 25 (BBVI Gradient for Logistic Regression ).

Consider Bayesian logistic regression with p(yi=1|𝒙i,𝒘)=σ(𝒘𝒙i) and prior 𝒘𝒩(0,𝑰).

  1. Write down the ELBO with qϕ(𝒘)=𝒩(𝝁,diag(𝝈2)).

  2. Derive the score function (REINFORCE) gradient estimator for 𝝁.

  3. Derive the reparameterized gradient estimator.

  4. Discuss the expected variance of each estimator.

Exercise 26 (Optimal Control Variate Coefficient ).

Given a gradient estimator g^ and a control variate c with 𝔼[c]=0, the variance-reduced estimator is g^b=g^bc.

  1. Show that g^b is unbiased for any b.

  2. Derive the optimal coefficient b=𝖢ov(g^,c)/𝖵ar(c) that minimizes 𝖵ar(g^b).

  3. Show that the resulting variance reduction is 𝖵ar(g^b)=(1ρ2)𝖵ar(g^), where ρ is the correlation between g^ and c.

Exercise 27 (Reparameterization Trick for Gaussian ).

Let qϕ(z)=𝒩(μ,σ2) with ϕ=(μ,σ). Compute ϕ𝔼qϕ[z2]:

  1. Analytically, using 𝔼[z2]=μ2+σ2.

  2. Via the reparameterization trick with z=μ+σϵ, ϵ𝒩(0,1).

  3. Verify that both methods give the same result.

Exercise 28 (Gumbel-Softmax Density ).

The Gumbel-Softmax distribution with temperature τ>0 and log-probabilities 𝜶K assigns density to 𝒚ΔK1 (the simplex) via: p(𝒚;𝜶,τ)=(K1)!τK1k=1K[αkykτ1](k=1Kαkykτ)K,αk=eαk.

  1. Verify that as τ0, the samples approach one-hot vectors (categorical samples).

  2. Show that the density is well-defined on the simplex (integrates to 1).

  3. Explain why the Gumbel-Softmax provides a continuous relaxation of categorical variables that enables the reparameterization trick.

Exercise 29 (Planar Flow Jacobian Determinant ).

For the planar flow f(𝒛)=𝒛+𝒖h(𝒘𝒛+b):

  1. Compute the Jacobian matrix f/𝒛.

  2. State the matrix determinant lemma: for any 𝑨d×d invertible and 𝒖,𝒗d, det(𝑨+𝒖𝒗)=(1+𝒗𝑨1𝒖)det(𝑨).

  3. Use the lemma to derive the result det(f/𝒛)=1+h(𝒘𝒛+b)𝒖𝒘.

  4. What constraint on 𝒖 and 𝒘 is needed to ensure invertibility when h=tanh?

Exercise 30 (IWAE Bound is Tighter than ELBO ).

  1. Show that the standard ELBO is 1IWAE (the special case k=1).

  2. Using Jensen's inequality and the concavity of log, prove that 12.

  3. Generalize: show kk+1 for all k1.

  4. Construct a simple example (e.g., p(x,z) being jointly Gaussian, q(z|x)=𝒩(0,1)) and numerically compute 1,5,50 to verify the hierarchy.

Exercise 31 (Stein's Identity for Smooth Distributions ).

Let p(z) be a smooth density on with p(z)0 as |z|.

  1. Prove the univariate Stein identity: 𝔼p[f(z)+f(z)(logp(z))]=0 for smooth f with p(z)f(z)0 at the boundaries.

  2. Verify the identity for p=𝒩(0,1) and f(z)=z.

  3. Extend the proof to d using the divergence theorem.

Exercise 32 (SVGD with the RBF Kernel ).

Consider SVGD with the RBF kernel k(𝒛,𝒛)=exp(𝒛𝒛2/(2h2)).

  1. Compute 𝒛k(𝒛,𝒛) explicitly.

  2. Write out the full SVGD update for this kernel.

  3. Interpret the repulsive term geometrically: show that it pushes particle 𝒛i away from nearby particles 𝒛j with a force proportional to (𝒛i𝒛j)/h2.

  4. Explain the role of the bandwidth h. What happens when h is very large? Very small?

Exercise 33 (Natural Gradient for Diagonal Gaussian ).

Let the variational family be qϕ(𝒛)=𝒩(𝝁,diag(𝝈2)) with ϕ=(𝝁,𝝈).

  1. Compute the Fisher information matrix 𝑭(ϕ). Show that it is block-diagonal between 𝝁 and 𝝈.

  2. Derive the natural gradient of an objective (ϕ) with respect to 𝝁 and 𝝈.

  3. Show that the natural gradient with respect to 𝝁 equals the Euclidean gradient scaled by diag(𝝈2): per-parameter adaptive step sizes.

  4. Compare to the Adam optimizer [19]: what similarities and differences do you observe?

Exercise 34 (BP is Exact on Trees ).

Consider a tree-structured graphical model G=(V,E) with pairwise potentials.

  1. Show that for a tree, any collection of pairwise-consistent marginals (τs,τst) satisfying zsτst(zs,zt)=τt(zt) corresponds to a valid joint distribution. (This proves (G)=(G) for trees.)

  2. Show that for a tree, the Bethe entropy 𝖧Bethe=s𝖧(τs)(s,t)𝖨(τst) equals the exact joint entropy 𝖧(τ). Hint: Use the chain rule for entropy along the tree edges.

  3. Conclude that BP computes exact marginals on trees.

Exercise 35 (Diffusion Variational Lower Bound ).

For a diffusion model with T steps:

  1. Starting from logpθ(𝒙0)𝔼q[logpθ(𝒙0:T)logq(𝒙1:T|𝒙0)], derive the decomposition into prior matching, consistency, and reconstruction terms ((DIFF VLB)).

  2. Show that each consistency term 𝖣KL(q(𝒙t1|𝒙t,𝒙0)pθ(𝒙t1|𝒙t)) is a KL between two Gaussians and derive its closed-form expression.

  3. Explain why the forward process q is not learned (unlike in a standard VAE) and how this simplifies optimization.

Exercise 36 (Mean-Field vs Structured VI on a Chain ).

Consider a Markov chain p(z1,z2,z3)=p(z1)p(z2|z1)p(z3|z2) where each zi{0,1}, with p(z1=1)=0.5, p(zi+1=zi)=0.9.

  1. Compute the exact marginals p(zi=1) for i=1,2,3.

  2. Apply mean-field VI with q(z1,z2,z3)=iqi(zi) and derive the CAVI updates. Run them to convergence and report the resulting marginals.

  3. Apply structured VI with q(z1,z2,z3)=q(z1)q(z2,z3) and derive the updates. Compare the resulting marginals with the mean-field solution.

  4. Quantify the approximation error of each method using total variation distance.

Exercise 37 (Implement CAVI for a Bayesian GMM ).

Write detailed pseudocode for CAVI applied to the Bayesian GMM from Exercise Exercise 17, including:

  1. Initialization strategy (e.g., from k-means or random).

  2. The update loop, specifying the order of updates for q(zi), q(𝝁k), and q(𝝅).

  3. ELBO computation for convergence monitoring.

  4. A clear specification of all expectations needed (e.g., 𝔼q(𝝁k)[𝝁k] and 𝔼q(𝝁k)[𝝁k𝝁k]).

Exercise 38 (The Amortization Gap ).

  1. Define the amortization gap as the difference between the amortized ELBO (using qϕ(𝒛|𝒙)) and the per-instance optimal ELBO (optimizing qi(𝒛) separately for each 𝒙i).

  2. Construct a simple example where the amortization gap is nonzero. Hint: consider a model where p(𝒛|𝒙) changes qualitatively for different 𝒙 values (e.g., the posterior is unimodal for some 𝒙 and bimodal for others), and the encoder cannot represent both shapes.

  3. Discuss strategies for reducing the amortization gap (e.g., iterative amortized inference, semi-amortized inference).

Exercise 39 (KL Minimization Equals ELBO Maximization ).

  1. Show that for a fixed model p(𝒙,𝒛) and observed data 𝒙: arg minq𝒬𝖣KL(q(𝒛)p(𝒛|𝒙))=arg maxq𝒬(q).

  2. Explain why this equivalence is important: we can optimize the ELBO (which requires only the joint p(𝒙,𝒛)) instead of the KL (which requires the intractable posterior p(𝒛|𝒙)).

  3. Does this equivalence hold when 𝒬 is the set of all distributions? What is the solution in that case?

0.60.5pt

The exercises above span the full range of variational inference topics covered in this chapter. Exercises 1–5 test foundational understanding of KL divergence and the ELBO\@; Exercises 6–9 develop fluency with mean-field and CAVI\@; Exercises 10–14 cover exponential families, SVI, and stochastic optimization; Exercises 15–19 address gradient estimation and the reparameterization trick; Exercises 20–21 treat normalizing flows and importance weighting; Exercises 22–24 develop SVGD and natural gradient methods; and Exercises 25–30 connect VI to graphical models, diffusion models, and modern practice.

References

  1. On information and sufficiency

    Solomon Kullback, Richard A Leibler

    The annals of mathematical statistics, vol. 22, no. 1, pp. 79-86 · 1951

    BibTeX
    @article{kullback1951information,
      title={On information and sufficiency},
      author={Kullback, Solomon and Leibler, Richard A},
      journal={The annals of mathematical statistics},
      volume={22},
      number={1},
      pages={79--86},
      year={1951},
      publisher={Institute of Mathematical Statistics}
    }

    Journal article

  2. An Introduction to Variational Methods for Graphical Models

    Michael I. Jordan, Zoubin Ghahramani, Tommi S. Jaakkola, Lawrence K. Saul

    Machine Learning, vol. 37, no. 2, pp. 183-233 · 1999

    BibTeX
    @article{jordan1999introduction,
      title={An Introduction to Variational Methods for Graphical Models},
      author={Jordan, Michael I. and Ghahramani, Zoubin and Jaakkola, Tommi S. and Saul, Lawrence K.},
      journal={Machine Learning},
      volume={37},
      number={2},
      pages={183--233},
      year={1999}
    }

    Journal article

  3. The Computational Complexity of Probabilistic Inference using Bayesian Belief Networks

    Gregory F. Cooper

    Artificial Intelligence, vol. 42, no. 2--3, pp. 393-405 · 1990

    BibTeX
    @article{cooper1990computational,
      title={The Computational Complexity of Probabilistic Inference using {Bayesian} Belief Networks},
      author={Cooper, Gregory F.},
      journal={Artificial Intelligence},
      volume={42},
      number={2--3},
      pages={393--405},
      year={1990}
    }

    Journal article

  4. Divergence Measures and Message Passing

    Tom Minka

    Microsoft Research Technical Report · 2005

    BibTeX
    @inproceedings{minka2005divergence,
      title={Divergence Measures and Message Passing},
      author={Minka, Tom},
      booktitle={Microsoft Research Technical Report},
      year={2005}
    }

    Conference paper

  5. Variational Message Passing

    John Winn, Christopher M. Bishop

    Journal of Machine Learning Research, vol. 6, pp. 661-694 · 2005

    BibTeX
    @article{winn2005variational,
      title={Variational Message Passing},
      author={Winn, John and Bishop, Christopher M.},
      journal={Journal of Machine Learning Research},
      volume={6},
      pages={661--694},
      year={2005}
    }

    Journal article

  6. Stein Variational Gradient Descent: A General Purpose Bayesian Inference Algorithm

    Qiang Liu, Dilin Wang

    Advances in Neural Information Processing Systems (NeurIPS), pp. 2378-2386 · 2016

    BibTeX
    @inproceedings{liu2016stein,
      title={Stein Variational Gradient Descent: A General Purpose {B}ayesian Inference Algorithm},
      author={Liu, Qiang and Wang, Dilin},
      booktitle={Advances in Neural Information Processing Systems (NeurIPS)},
      pages={2378--2386},
      year={2016}
    }

    Conference paper

  7. Importance Weighted Autoencoders

    Yuri Burda, Roger Grosse, Ruslan Salakhutdinov

    International Conference on Learning Representations (ICLR) · 2016

    BibTeX
    @inproceedings{burda2016importance,
      title={Importance Weighted Autoencoders},
      author={Burda, Yuri and Grosse, Roger and Salakhutdinov, Ruslan},
      booktitle={International Conference on Learning Representations (ICLR)},
      year={2016}
    }

    Conference paper

  8. Variational Inference: A Review for Statisticians

    David M. Blei, Alp Kucukelbir, Jon D. McAuliffe

    Journal of the American Statistical Association, vol. 112, no. 518, pp. 859-877 · 2017

    BibTeX
    @article{blei2017variational,
      title={Variational Inference: A Review for Statisticians},
      author={Blei, David M. and Kucukelbir, Alp and McAuliffe, Jon D.},
      journal={Journal of the American Statistical Association},
      volume={112},
      number={518},
      pages={859--877},
      year={2017}
    }

    Journal article

  9. A stochastic approximation method

    H. Robbins, S. Monro

    The Annals of Mathematical Statistics, pp. 400-407 · 1951

    BibTeX
    @Article{robbins1951stochastic,
      Title                    = {A stochastic approximation method},
      Author                   = {Robbins, H. and Monro, S.},
      Journal                  = {The Annals of Mathematical Statistics},
      Year                     = {1951},
      Pages                    = {400--407},
      Publisher                = {JSTOR}
    }

    Journal article

  10. Stochastic Backpropagation and Approximate Inference in Deep Generative Models

    Danilo Jimenez Rezende, Shakir Mohamed, Daan Wierstra

    International Conference on Machine Learning, pp. 1278-1286 · 2014

    BibTeX
    @inproceedings{rezende2014stochastic,
      title={Stochastic Backpropagation and Approximate Inference in Deep Generative Models},
      author={Rezende, Danilo Jimenez and Mohamed, Shakir and Wierstra, Daan},
      booktitle={International Conference on Machine Learning},
      pages={1278--1286},
      year={2014}
    }

    Conference paper

  11. Auto-Encoding Variational Bayes

    Diederik P Kingma, Max Welling

    International Conference on Learning Representations · 2014

    BibTeX
    @inproceedings{kingma2013auto,
      title={Auto-Encoding Variational {B}ayes},
      author={Kingma, Diederik P and Welling, Max},
      booktitle={International Conference on Learning Representations},
      year={2014}
    }

    Conference paper

  12. Density Estimation using Real-NVP

    Laurent Dinh, Jascha Sohl-Dickstein, Samy Bengio

    Proceedings of the International Conference on Learning Representations (ICLR) · 2017

    BibTeX
    @inproceedings{dinh2017density,
      title={Density Estimation using {Real-NVP}},
      author={Dinh, Laurent and Sohl-Dickstein, Jascha and Bengio, Samy},
      booktitle={Proceedings of the International Conference on Learning Representations (ICLR)},
      year={2017}
    }

    Conference paper

  13. Masked Autoregressive Flow for Density Estimation

    George Papamakarios, Theo Pavlakou, Iain Murray

    Advances in Neural Information Processing Systems, pp. 2338-2347 · 2017

    BibTeX
    @inproceedings{papamakarios2017masked,
      title={Masked Autoregressive Flow for Density Estimation},
      author={Papamakarios, George and Pavlakou, Theo and Murray, Iain},
      booktitle={Advances in Neural Information Processing Systems},
      pages={2338--2347},
      year={2017}
    }

    Conference paper

  14. Improved Variational Inference with Inverse Autoregressive Flow

    Diederik P. Kingma, Tim Salimans, Rafal Jozefowicz, Xi Chen, Ilya Sutskever, Max Welling

    Advances in Neural Information Processing Systems, pp. 4743-4751 · 2016

    BibTeX
    @inproceedings{kingma2016improved,
      title={Improved Variational Inference with Inverse Autoregressive Flow},
      author={Kingma, Diederik P. and Salimans, Tim and Jozefowicz, Rafal and Chen, Xi and Sutskever, Ilya and Welling, Max},
      booktitle={Advances in Neural Information Processing Systems},
      pages={4743--4751},
      year={2016}
    }

    Conference paper

  15. Practical Deep Learning with Bayesian Principles

    Kazuki Osawa, Siddharth Swaroop, Mohammad Emtiyaz Khan, Anirudh Jain, Runa Eschenhagen, Richard E. Turner, Rio Henning

    Advances in Neural Information Processing Systems (NeurIPS) · 2019

    BibTeX
    @inproceedings{osawa2019practical,
      title={Practical Deep Learning with {Bayesian} Principles},
      author={Osawa, Kazuki and Swaroop, Siddharth and Khan, Mohammad Emtiyaz and Jain, Anirudh and Eschenhagen, Runa and Turner, Richard E. and Henning, Rio},
      booktitle={Advances in Neural Information Processing Systems (NeurIPS)},
      year={2019}
    }

    Conference paper

  16. Probabilistic Reasoning in Intelligent Systems: Networks of Plausible Inference

    Judea Pearl

    Morgan Kaufmann · 1988

    BibTeX
    @book{pearl1988probabilistic,
      title={Probabilistic Reasoning in Intelligent Systems: Networks of Plausible Inference},
      author={Pearl, Judea},
      publisher={Morgan Kaufmann},
      year={1988}
    }

    Book

  17. Understanding Belief Propagation and Its Generalizations

    Jonathan S Yedidia, William T Freeman, Yair Weiss

    Exploring Artificial Intelligence in the New Millennium, vol. 8, pp. 236-239 · 2003

    BibTeX
    @article{yedidia2003understanding,
      title={Understanding Belief Propagation and Its Generalizations},
      author={Yedidia, Jonathan S and Freeman, William T and Weiss, Yair},
      journal={Exploring Artificial Intelligence in the New Millennium},
      volume={8},
      pages={236--239},
      year={2003}
    }

    Journal article

  18. Training Language Models to Follow Instructions with Human Feedback

    Long Ouyang, Jeffrey Wu, Xu Jiang, Diogo Almeida, Carroll Wainwright, Pamela Mishkin, Chong Zhang, Sandhini Agarwal, et al.

    Advances in Neural Information Processing Systems, vol. 35, pp. 27730-27744 · 2022

    BibTeX
    @article{ouyang2022training,
      title={Training Language Models to Follow Instructions with Human Feedback},
      author={Ouyang, Long and Wu, Jeffrey and Jiang, Xu and Almeida, Diogo and Wainwright, Carroll and Mishkin, Pamela and Zhang, Chong and Agarwal, Sandhini and Slama, Katarina and Ray, Alex and others},
      journal={Advances in Neural Information Processing Systems},
      volume={35},
      pages={27730--27744},
      year={2022}
    }

    Journal article

  19. Adam: A Method for Stochastic Optimization

    Diederik P. Kingma, Jimmy Ba

    Proceedings of the International Conference on Learning Representations (ICLR) · 2015

    BibTeX
    @article{kingma2015adam,
      title={Adam: A Method for Stochastic Optimization},
      author={Kingma, Diederik P. and Ba, Jimmy},
      journal={Proceedings of the International Conference on Learning Representations (ICLR)},
      year={2015}
    }

    Journal article

  20. Stochastic Variational Inference

    Matthew D. Hoffman, David M. Blei, Chong Wang, John Paisley

    Journal of Machine Learning Research, vol. 14, pp. 1303-1347 · 2013

    BibTeX
    @article{hoffman2013stochastic,
      title={Stochastic Variational Inference},
      author={Hoffman, Matthew D. and Blei, David M. and Wang, Chong and Paisley, John},
      journal={Journal of Machine Learning Research},
      volume={14},
      pages={1303--1347},
      year={2013}
    }

    Journal article

  21. Black Box Variational Inference

    Rajesh Ranganath, Sean Gerrish, David M. Blei

    Proceedings of the International Conference on Artificial Intelligence and Statistics (AISTATS), pp. 814-822 · 2014

    BibTeX
    @inproceedings{ranganath2014black,
      title={Black Box Variational Inference},
      author={Ranganath, Rajesh and Gerrish, Sean and Blei, David M.},
      booktitle={Proceedings of the International Conference on Artificial Intelligence and Statistics (AISTATS)},
      pages={814--822},
      year={2014}
    }

    Conference paper

  22. Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning

    Ronald J. Williams

    Machine Learning, vol. 8, no. 3--4, pp. 229-256 · 1992

    BibTeX
    @article{williams1992simple,
      title={Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning},
      author={Williams, Ronald J.},
      journal={Machine Learning},
      volume={8},
      number={3--4},
      pages={229--256},
      year={1992}
    }

    Journal article

  23. Variational Inference with Normalizing Flows

    Danilo Jimenez Rezende, Shakir Mohamed

    International Conference on Machine Learning, pp. 1530-1538 · 2015

    BibTeX
    @inproceedings{rezende2015variational,
      title={Variational Inference with Normalizing Flows},
      author={Rezende, Danilo Jimenez and Mohamed, Shakir},
      booktitle={International Conference on Machine Learning},
      pages={1530--1538},
      year={2015}
    }

    Conference paper

  24. Triangular Transformations of Measures

    Vladimir I. Bogachev, Alexander V. Kolesnikov, Kirill V. Medvedev

    Sbornik: Mathematics, vol. 196, no. 3, pp. 309-335 · 2005

    BibTeX
    @article{bogachev2005triangular,
      title={Triangular Transformations of Measures},
      author={Bogachev, Vladimir I. and Kolesnikov, Alexander V. and Medvedev, Kirill V.},
      journal={Sbornik: Mathematics},
      volume={196},
      number={3},
      pages={309--335},
      year={2005}
    }

    Journal article

  25. Tighter Variational Bounds are Not Necessarily Better

    Tom Rainforth, Adam R. Kosiorek, Tuan Anh Le, Chris J. Maddison, Maximilian Igl, Frank Wood, Yee Whye Teh

    Proceedings of the International Conference on Machine Learning (ICML), pp. 4277-4285 · 2018

    BibTeX
    @inproceedings{rainforth2018tighter,
      title={Tighter Variational Bounds are Not Necessarily Better},
      author={Rainforth, Tom and Kosiorek, Adam R. and Le, Tuan Anh and Maddison, Chris J. and Igl, Maximilian and Wood, Frank and Teh, Yee Whye},
      booktitle={Proceedings of the International Conference on Machine Learning (ICML)},
      pages={4277--4285},
      year={2018}
    }

    Conference paper

  26. Doubly Reparameterized Gradient Estimators for Monte Carlo Objectives

    George Tucker, Dieterich Lawson, Shixiang Gu, Chris J. Maddison

    International Conference on Learning Representations (ICLR) · 2019

    BibTeX
    @inproceedings{tucker2019doubly,
      title={Doubly Reparameterized Gradient Estimators for {M}onte {C}arlo Objectives},
      author={Tucker, George and Lawson, Dieterich and Gu, Shixiang and Maddison, Chris J.},
      booktitle={International Conference on Learning Representations (ICLR)},
      year={2019}
    }

    Conference paper

  27. Natural Gradient Works Efficiently in Learning

    Shun-ichi Amari

    Neural Computation, vol. 10, no. 2, pp. 251-276 · 1998

    BibTeX
    @article{amari1998natural,
      title={Natural Gradient Works Efficiently in Learning},
      author={Amari, Shun-ichi},
      journal={Neural Computation},
      volume={10},
      number={2},
      pages={251--276},
      year={1998}
    }

    Journal article

  28. The Bayesian Learning Rule

    Mohammad Emtiyaz Khan, Haavard Rue

    Journal of Machine Learning Research, vol. 24, no. 281, pp. 1-46 · 2023

    BibTeX
    @article{khan2021bayesian,
      title={The {Bayesian} Learning Rule},
      author={Khan, Mohammad Emtiyaz and Rue, H{\aa}vard},
      journal={Journal of Machine Learning Research},
      volume={24},
      number={281},
      pages={1--46},
      year={2023}
    }

    Journal article

  29. Graphical Models, Exponential Families, and Variational Inference

    Martin J. Wainwright, Michael I. Jordan

    Foundations and Trends in Machine Learning, vol. 1, no. 1--2, pp. 1-305 · 2008

    BibTeX
    @article{wainwright2008graphical,
      title={Graphical Models, Exponential Families, and Variational Inference},
      author={Wainwright, Martin J. and Jordan, Michael I.},
      journal={Foundations and Trends in Machine Learning},
      volume={1},
      number={1--2},
      pages={1--305},
      year={2008}
    }

    Journal article

  30. Constructing Free-Energy Approximations and Generalized Belief Propagation Algorithms

    Jonathan S. Yedidia, William T. Freeman, Yair Weiss

    IEEE Transactions on Information Theory, vol. 51, no. 7, pp. 2282-2312 · 2005

    BibTeX
    @article{yedidia2005constructing,
      title={Constructing Free-Energy Approximations and Generalized Belief Propagation Algorithms},
      author={Yedidia, Jonathan S. and Freeman, William T. and Weiss, Yair},
      journal={IEEE Transactions on Information Theory},
      volume={51},
      number={7},
      pages={2282--2312},
      year={2005}
    }

    Journal article

  31. Variational Diffusion Models

    Diederik Kingma, Tim Salimans, Ben Poole, Jonathan Ho

    Advances in Neural Information Processing Systems, vol. 34, pp. 21696-21707 · 2021

    BibTeX
    @inproceedings{kingma2021variational,
      title={Variational Diffusion Models},
      author={Kingma, Diederik and Salimans, Tim and Poole, Ben and Ho, Jonathan},
      booktitle={Advances in Neural Information Processing Systems},
      volume={34},
      pages={21696--21707},
      year={2021}
    }

    Conference paper

  32. Weight Uncertainty in Neural Networks

    Charles Blundell, Julien Cornebise, Koray Kavukcuoglu, Daan Wierstra

    Proceedings of the International Conference on Machine Learning (ICML), pp. 1613-1622 · 2015

    BibTeX
    @inproceedings{blundell2015weight,
      title={Weight Uncertainty in Neural Networks},
      author={Blundell, Charles and Cornebise, Julien and Kavukcuoglu, Koray and Wierstra, Daan},
      booktitle={Proceedings of the International Conference on Machine Learning (ICML)},
      pages={1613--1622},
      year={2015}
    }

    Conference paper

  33. Dropout as a Bayesian Approximation: Representing Model Uncertainty in Deep Learning

    Yarin Gal, Zoubin Ghahramani

    Proceedings of the International Conference on Machine Learning (ICML), pp. 1050-1059 · 2016

    BibTeX
    @inproceedings{gal2016dropout,
      title={Dropout as a {B}ayesian Approximation: Representing Model Uncertainty in Deep Learning},
      author={Gal, Yarin and Ghahramani, Zoubin},
      booktitle={Proceedings of the International Conference on Machine Learning (ICML)},
      pages={1050--1059},
      year={2016}
    }

    Conference paper