Variational inference I: the ELBO, mean field and CAVI
Variational inference turns integration into optimization: it seeks the distribution closest to the posterior in a tractable family by maximizing the ELBO, the same EM bound from m12 with q restricted to a family. We study mean field and its consequences, coordinate ascent (CAVI), closed updates in conjugate-exponential models and variational EM, with Bayesian Gaussian mixtures and LDA as complete examples.
After this lesson you can
- Formulate inference as ELBO optimization and compare it with Laplace, EP and MCMC in bias, cost and scalability.
- Measure the ELBO-to-log-evidence gap and explain the effect of KL(q ‖ p) direction from m07 on variational dispersion.
- Derive the optimal mean-field factor update, log q_j* = E_{-j}[log p] + constant.
- Implement CAVI for a Bayesian Gaussian mixture and LDA, testing ELBO monotonicity.
- Prove that mean field underestimates variances in a correlated Gaussian.
Before you start
- 14Latent variable modelGlobal and local latent variablesLatent Dirichlet allocationEM for graphical models via expected sufficient statisticsMultivariate conjugate priors (Normal-gamma, Normal-Wishart)Laplace approximationMarkov blanket
- 12EM lower boundGaussian mixture model
- 07Forward versus reverse KL
- 05Exponential familyConjugate priors
Turning integration into optimization
A posterior may be easy to write and hard to normalize. Laplace approximates it around a mode; EP matches factor moments; MCMC and the particle filter use samples and have Monte Carlo error. Variational inference offers another compromise: choose a manageable family, search it for a nearby distribution and accept that the chosen shape can introduce bias. There is no universal winner: cost, geometry, dimension and required accuracy matter.
For data and latents , let be a density whose support is contained in that of . Variational inference maximizes the evidence lower bound (ELBO)
in a family . If and integrals exist, the exact identity is
It follows by substituting and using that integrates to one. KL is nonnegative, so ELBO is a lower bound; maximizing it is equivalent to minimizing that KL for fixed data and model. This is the same EM bound, but is restricted to a tractable family. ELBO improvement does not imply evidence changed: only the gap may have shrunk.
The figure’s model is and with . Its posterior has two curved regions: both two positive signs and two negative signs explain the product. Evidence is integrated in one dimension using ; displayed solutions were obtained by optimizing ELBO from multiple starts. The mixture uses two equal-weight components with common covariance; its entropy is integrated by order-40 Gauss-Hermite, also checked with orders 20, 60 and 80. Numbers are found solutions and numerical quadratures, not a global-optimum certificate. Model and approximation parameters are in the figure data.
This cell recalculates evidence and ELBO with found parameters rounded to eight decimals. Mixture entropy is not the average of component entropies: integrate under the mixture itself. The two components are symmetric in this solution.
import numpy as np
from scipy.integrate import quad
from numpy.polynomial.hermite import hermgauss
y_obs, noise = 2., .4
def evidence_integrand(a):
var=a*a+noise**2
return np.exp(-a*a/2)/np.sqrt(2*np.pi)*np.exp(-y_obs*y_obs/(2*var))/np.sqrt(2*np.pi*var)
logZ=np.log(quad(evidence_integrand,-np.inf,np.inf,epsabs=1e-12)[0])
def expected_log_joint(m,S):
a,b=m; va,vb=S[0,0],S[1,1]; c=S[0,1]
eab=a*b+c
ea2b2=a*a*b*b+a*a*vb+b*b*va+4*a*b*c+va*vb+2*c*c
return -np.log(2*np.pi)-.5*(a*a+b*b+va+vb)-.5*(np.log(2*np.pi*noise**2)+(y_obs*y_obs-2*y_obs*eab+ea2b2)/noise**2)
nodes,w=hermgauss(40)
z=np.stack(np.meshgrid(nodes,nodes,indexing='ij'),axis=-1).reshape(-1,2)*np.sqrt(2)
weights=np.outer(w,w).ravel()/np.pi
def mixture_bound(means,S):
L=np.linalg.cholesky(S); norm=-np.log(2*np.pi)-np.log(np.diag(L)).sum()
eqlogq=0.
for m in means:
[email protected]
logps=[]
for other in means:
diff=np.linalg.solve(L,(points-other).T).T
logps.append(norm-.5*np.sum(diff*diff,axis=1))
logq=np.logaddexp.reduce(np.stack(logps),axis=0)-np.log(len(means))
eqlogq+=np.dot(weights,logq)/len(means)
return np.mean([expected_log_joint(m,S) for m in means])-eqlogq
mf_mean=np.array([1.32664985,1.32664993]); mf_cov=np.diag([.0800000053,.0800000218])
full_mean=np.array([1.38060500,1.38060503]); full_cov=np.array([[.15001258,-.10804141],[-.10804141,.15001259]])
for name,means,S in [('campo medio',[mf_mean],mf_cov),('completa',[full_mean],full_cov),('mezcla',[full_mean,-full_mean],full_cov)]:
bound=mixture_bound(means,S)
print(name,'ELBO',round(bound,4),'KL',round(logZ-bound,4))
print('log evidencia',round(logZ,4))Direction matters. When minimizing , placing mass of where has almost no density is costly; a unimodal family may prefer one mode and omit another. This is a tendency dependent on problem and family, not a theorem that every variational approximation always underestimates all uncertainty. Even an approximation with high ELBO can be poor for a particular decision quantity.
Mean field and coordinates
A mean-field family factors . Independence is a restriction of the approximation, not necessarily the model. Hold every factor except fixed and define . Then
if the integral is finite. The proof is direct: ELBO terms depending on are , equivalent to a constant minus with . KL is minimized at zero. This underlies coordinate ascent variational inference (CAVI): update one factor, then another, and repeat. An exact update does not decrease ELBO, but the joint problem can have local maxima.
For a Gaussian posterior , the update of factor has precision and mean . At a fixed point means solve , so if , but each variance remains . By the Schur complement, that conditional variance does not exceed marginal .
With correlation , each factor variance is , although each true marginal has variance 1. The optimal KL in this example is . The conclusion holds for this Gaussian mean field and that KL; it does not establish that a more general family cannot overestimate some variance.
In conjugate exponential models, expectations of sufficient statistics from other factors are added to the prior’s natural parameters. Conditionals have the same family as the updated factor. The Markov blanket identifies which joint terms affect each factor: others disappear into the normalization constant.
Mixtures: responsibilities and pruning
Consider components, , , and , with known. Use . For responsibilities and ,
The update of normalizes exponentials of . Term integrates mean uncertainty; replacing it with a single point gives another approximation. A small Dirichlet prior favors sparse concentrations but does not guarantee recovering the true number of groups.
Data are 40 samples from each of three isotropic Gaussians centered at , and , with standard deviation 0.35 and seed 7. The inferred model uses 10 components, , and ; asymmetric initialization uses seed 3. The value of is a model assumption, distinct from generating variance . In this run three weights remain dominant; the smallest ELBO increase is of rounding order. The figure comes from the lab below.
In a complete Bayesian mixture, precisions are also unknown. With a Normal-Wishart prior for , updates add weighted counts and statistics to the prior; uses digammas and likelihood uses . The lab calculates the complete ELBO, including the cost of weight and Normal-Wishart factors, not just likelihood. Solutions can depend on initialization and prior.
Variational EM and topic models
Variational EM alternates approximate optimization of with a model-parameter update that increases the same ELBO. In exact EM the E-step uses the exact posterior and the bound touches log likelihood; with mean field the gap may remain positive. An ELBO increase each step does not mean each ELBO is evidence or a global maximum is reached.
In LDA, with fixed topics and document prior , approximation and leads to
These equations alternate until convergence. With unknown topics as parameters, the M-step normalizes expected word counts by topic; random topics require additional factors and prior terms. Topic names are interchangeable: when comparing two fits, align components before measuring their difference. The original work of Blei, Ng and Jordan develops variational inference and EM for LDA.
Bethe free energy offers another variational approximation over local marginals and consistency constraints. On trees it connects with exact message passing; with cycles it can have multiple stationary points and loopy message passing has no general convergence guarantee. It is not the same mean-field ELBO: the family and entropy approximation change.
Lab: mixture with known covariance
The following code generates the figure’s data and runs mean-field updates. ELBO sums expected likelihood and categorical term and subtracts KLs of Dirichlet and Gaussian factors from their priors. We measure monotonicity after each complete cycle, not after an initialization that is not a coordinate update.
import numpy as np
from scipy.special import digamma, gammaln, logsumexp
def make_data():
rg = np.random.default_rng(7)
centers = np.array([[-2.,0.],[2.,0.],[0.,2.5]])
return np.vstack([c+rg.normal(0,.35,(40,2)) for c in centers])
def elbo_known(X,r,alpha,m,s2,alpha0=.1,tau2=9.,noise2=.16):
n,d=X.shape; k=r.shape[1]
elogpi=digamma(alpha)-digamma(alpha.sum())
kl_dir=gammaln(alpha.sum())-gammaln(alpha).sum()-gammaln(k*alpha0)+k*gammaln(alpha0)+np.sum((alpha-alpha0)*elogpi)
kl_mean=.5*np.sum((d*s2+np.sum(m*m,axis=1))/tau2-d+d*np.log(tau2/s2))
assignment=np.sum(r*(elogpi[None,:]-np.log(np.maximum(r,1e-300))))
residual=np.sum((X[:,None,:]-m[None,:,:])**2,axis=2)+d*s2[None,:]
likelihood=np.sum(r*(-.5*d*np.log(2*np.pi*noise2)-residual/(2*noise2)))
return likelihood+assignment-kl_dir-kl_mean
def cavi_known(X,K=10,steps=60):
rg=np.random.default_rng(3); n,d=X.shape
starts=X[rg.choice(n,K,replace=False)]
logits=-np.sum((X[:,None,:]-starts[None,:,:])**2,axis=2)/(.8**2)
r=np.exp(logits-logsumexp(logits,axis=1,keepdims=True))
history=[]
for _ in range(steps+1):
counts=r.sum(axis=0); alpha=.1+counts
s2=1/(1/9+counts/.16); m=s2[:,None]*(r.T@X)/.16
history.append(elbo_known(X,r,alpha,m,s2))
log_r=digamma(alpha)[None,:]-digamma(alpha.sum())-.5*(np.sum((X[:,None,:]-m[None,:,:])**2,axis=2)+d*s2[None,:])/.16
r=np.exp(log_r-logsumexp(log_r,axis=1,keepdims=True))
return alpha,m,np.array(history)
X=make_data()
alpha,m,history=cavi_known(X)
print('ELBO inicial y final',round(history[0],4),round(history[-1],4))
print('mínimo incremento',np.diff(history).min())
print('pesos finales',np.round(alpha/alpha.sum(),4))
assert np.all(np.diff(history)>-1e-9)Initialization uses distinct centers taken from data. The 0.01 display threshold is a convention for counting dominant components, not literal deletion: with a proper Dirichlet prior remaining expected weights stay positive.
Lab: complete Normal-Wishart
Precision is now unknown. We use the Normal-Wishart convention . For each component, , , and
The cell separately calculates observation, assignment, weight and Normal-Wishart terms. For nearly zero , division by its sum is protected; quantities it multiplies also tend to zero. Wishart normalization uses , the multivariate gamma.
from scipy.special import multigammaln
from scipy.linalg import cho_solve, cho_factor
def kl_dir(alpha,alpha0):
k=len(alpha); elog=digamma(alpha)-digamma(alpha.sum())
return gammaln(alpha.sum())-gammaln(alpha).sum()-gammaln(k*alpha0)+k*gammaln(alpha0)+np.sum((alpha-alpha0)*elog)
def log_wishart_norm(W,nu):
d=W.shape[0]
return -.5*nu*d*np.log(2)-.5*nu*np.linalg.slogdet(W)[1]-multigammaln(nu/2,d)
def nw_update(X,r,m0,beta0,W0,nu0,alpha0):
n,d=X.shape; k=r.shape[1]
N=r.sum(axis=0); beta=beta0+N; nu=nu0+N; alpha=alpha0+N
m=(beta0*m0[None,:]+r.T@X)/beta[:,None]
W=[]; prior_prec=np.linalg.solve(W0,np.eye(d))
for j in range(k):
mean=(r[:,j,None]*X).sum(axis=0)/max(N[j],1e-300)
xc=X-mean; scatter=(r[:,j,None]*xc).T@xc; delta=mean-m0
invW=prior_prec+scatter+(beta0*N[j]/beta[j])*np.outer(delta,delta)
W.append(cho_solve(cho_factor(invW,lower=True),np.eye(d)))
return alpha,beta,nu,m,np.array(W)
def nw_elbo(X,r,params,m0,beta0,W0,nu0,alpha0):
alpha,beta,nu,m,W=params; n,d=X.shape; k=r.shape[1]
elogpi=digamma(alpha)-digamma(alpha.sum())
prior_inv=np.linalg.solve(W0,np.eye(d))
assignment=np.sum(r*(elogpi[None,:]-np.log(np.maximum(r,1e-300))))
likelihood=0.; normalwishart=0.
for j in range(k):
elogdet=sum(digamma((nu[j]+1-i)/2) for i in range(1,d+1))+d*np.log(2)+np.linalg.slogdet(W[j])[1]
delta=X-m[j]; quad=np.einsum('ni,ij,nj->n',delta,W[j],delta)
likelihood+=.5*np.sum(r[:,j]*(elogdet-d*np.log(2*np.pi)-d/beta[j]-nu[j]*quad))
q_inv=np.linalg.solve(W[j],np.eye(d))
wish=log_wishart_norm(W0,nu0)-log_wishart_norm(W[j],nu[j])+.5*(nu0-nu[j])*elogdet-.5*nu[j]*np.trace((prior_inv-q_inv)@W[j])
dm=m[j]-m0
normal=.5*d*np.log(beta0/beta[j])+.5*d-.5*beta0*(d/beta[j]+nu[j]*dm@W[j]@dm)
normalwishart+=wish+normal
return likelihood+assignment-kl_dir(alpha,alpha0)+normalwishart
def cavi_nw(X,K=10,steps=60):
n,d=X.shape; rg=np.random.default_rng(3)
starts=X[rg.choice(n,K,replace=False)]
logits=-np.sum((X[:,None,:]-starts[None,:,:])**2,axis=2)/(.8**2)
r=np.exp(logits-logsumexp(logits,axis=1,keepdims=True))
m0=np.zeros(d); beta0=1.; nu0=d+2.; W0=.3*np.eye(d); alpha0=.1
history=[]
for _ in range(steps+1):
params=nw_update(X,r,m0,beta0,W0,nu0,alpha0)
alpha,beta,nu,m,W=params
history.append(nw_elbo(X,r,params,m0,beta0,W0,nu0,alpha0))
log_r=np.empty((n,K))
for j in range(K):
elogdet=sum(digamma((nu[j]+1-i)/2) for i in range(1,d+1))+d*np.log(2)+np.linalg.slogdet(W[j])[1]
delta=X-m[j]; quad=np.einsum('ni,ij,nj->n',delta,W[j],delta)
log_r[:,j]=digamma(alpha[j])-digamma(alpha.sum())+.5*(elogdet-d/beta[j]-nu[j]*quad)
r=np.exp(log_r-logsumexp(log_r,axis=1,keepdims=True))
return params,np.array(history)
params,bounds=cavi_nw(X)
print('ELBO inicial y final',round(bounds[0],4),round(bounds[-1],4))
print('mínimo incremento',np.diff(bounds).min())
print('pesos',np.round(params[0]/params[0].sum(),4))
assert np.all(np.diff(bounds)>-1e-9)Compare with the professional implementation, aligning dominant centers. The scikit-learn prior covariance_prior corresponds here to and a finite Dirichlet mixture is used. Do not expect equality for different initializations or conventions; this comparison checks one configuration, not a general proof.
from sklearn.mixture import BayesianGaussianMixture
from scipy.optimize import linear_sum_assignment
sk=BayesianGaussianMixture(n_components=10,weight_concentration_prior_type='dirichlet_distribution',weight_concentration_prior=.1,mean_precision_prior=1.,mean_prior=np.zeros(2),degrees_of_freedom_prior=4.,covariance_prior=np.eye(2)/.3,max_iter=1000,tol=1e-7,reg_covar=0.,random_state=3).fit(X)
weights=params[0]/params[0].sum(); own=np.flatnonzero(weights>.01); other=np.flatnonzero(sk.weights_>.01)
cost=np.linalg.norm(params[3][own,None,:]-sk.means_[None,other,:],axis=2)
rows,cols=linear_sum_assignment(cost)
print('convergió sklearn',sk.converged_,'componentes activas',len(own),len(other))
print('distancias de centros alineados',np.round(cost[rows,cols],8))Lab: LDA on the m14-l09 corpus
We use exactly the m14-l09 generator: 250 documents of 60 words, 3 topics, vocabulary 12, seed 2026 and symmetric priors , . This is a synthetic corpus with known true topics, not real document text. The module is available to download lda_corpus.py; the first cell reproduces it so the lab works in an independent session.
"""Corpus LDA sintético reproducible para m14-l09, l18 y l22."""
import numpy as np
def synthetic_lda(seed=2026, n_docs=250, n_words=60, n_topics=3,
n_vocab=12, alpha=.3, beta=.12):
"""Devuelve (conteos, theta, temas, asignaciones, palabras).
Temas: (K,V); theta: (D,K); asignaciones y palabras: (D,N).
Los temas y proporciones se generan de priors Dirichlet simétricos,
cada palabra tiene su propio tema, y las filas de conteos suman N.
"""
if min(n_docs,n_words,n_topics,n_vocab)<1 or alpha<=0 or beta<=0:
raise ValueError('tamaños y concentraciones deben ser positivos')
rng=np.random.default_rng(seed)
topics=rng.dirichlet(np.full(n_vocab,beta),size=n_topics)
theta=rng.dirichlet(np.full(n_topics,alpha),size=n_docs)
assignments=np.empty((n_docs,n_words),dtype=int)
words=np.empty_like(assignments)
counts=np.zeros((n_docs,n_vocab),dtype=int)
for d in range(n_docs):
assignments[d]=rng.choice(n_topics,size=n_words,p=theta[d])
for n,z in enumerate(assignments[d]):
words[d,n]=rng.choice(n_vocab,p=topics[z])
counts[d]=np.bincount(words[d],minlength=n_vocab)
return counts,theta,topics,assignments,wordsIn CAVI we maintain , and probabilities shared across all appearances of word in document . Update
The second method performs variational EM with topics as point parameters: the E-step updates and with , and the M-step normalizes expected counts by topic. It introduces no prior in the M-step; hence its bound and the CAVI bound with Dirichlet topic prior belong to different objectives and must not be directly compared as evidence. Each local update iterates to tolerance or 100 steps. ELBO includes corresponding entropies and Dirichlet constants.
import numpy as np
from scipy.special import digamma,gammaln,logsumexp
from scipy.optimize import linear_sum_assignment
from sklearn.decomposition import LatentDirichletAllocation
counts,theta,truth,z,words=synthetic_lda()
D,V=counts.shape;K=3;alpha=.3;beta=.12
def elog_dir(x):return digamma(x)-digamma(x.sum(axis=-1,keepdims=True))
def dir_prior_minus_q(q,a):
k=q.shape[-1];e=elog_dir(q)
lp=gammaln(k*a)-k*gammaln(a)+(a-1)*e.sum(axis=-1)
lq=gammaln(q.sum(axis=-1))-gammaln(q).sum(axis=-1)+((q-1)*e).sum(axis=-1)
return (lp-lq).sum()
def local_update(counts,elog_beta,gamma,steps=100):
for _ in range(steps):
logphi=elog_dir(gamma)[:,None,:]+elog_beta.T[None,:,:]
logphi-=logsumexp(logphi,axis=2,keepdims=True);phi=np.exp(logphi)
next_gamma=alpha+np.einsum('dv,dvk->dk',counts,phi)
if np.max(np.abs(next_gamma-gamma))<1e-7:gamma=next_gamma;break
gamma=next_gamma
logphi=elog_dir(gamma)[:,None,:]+elog_beta.T[None,:,:]
logphi-=logsumexp(logphi,axis=2,keepdims=True)
return gamma,np.exp(logphi)
def lda_elbo(gamma,phi,elog_beta,lam=None):
terms=elog_dir(gamma)[:,None,:]+elog_beta.T[None,:,:]-np.log(np.maximum(phi,1e-300))
value=dir_prior_minus_q(gamma,alpha)+np.sum(counts[:,:,None]*phi*terms)
if lam is not None:value+=dir_prior_minus_q(lam,beta)
return value
def initialize(method):
rng=np.random.default_rng(17);gamma=np.full((D,K),alpha+counts.sum(1)[:,None]/K)
if method=='cavi':
lam=beta+rng.gamma(1,30,size=(K,V));elog=elog_dir(lam)
else:
topics=rng.dirichlet(np.ones(V),size=K);elog=np.log(topics)
return {'method':method,'gamma':gamma,'elog':elog,'history':[]}
def advance(state,steps=10):
for _ in range(steps):
gamma,phi=local_update(counts,state['elog'],state['gamma'])
suff=np.einsum('dv,dvk->kv',counts,phi)
if state['method']=='cavi':
lam=beta+suff;elog=elog_dir(lam);topics=lam/lam.sum(axis=1,keepdims=True)
value=lda_elbo(gamma,phi,elog,lam)
else:
topics=np.maximum(suff,1e-300);topics/=topics.sum(axis=1,keepdims=True);elog=np.log(topics)
value=lda_elbo(gamma,phi,elog)
state.update(gamma=gamma,elog=elog,topics=topics)
state['history'].append(value)
def match(a,b):
cost=np.abs(a[:,None,:]-b[None,:,:]).sum(axis=2)
i,j=linear_sum_assignment(cost)
return j,cost[i,j]
cavi=initialize('cavi');em=initialize('em')
print('corpus',counts.shape,'tokens',counts.sum(),'prior alpha',alpha,'beta',beta)Four blocks of ten steps let us observe the trajectory. Both initializations use the same seed, but families and objectives differ. Expected monotonicity assumes exact updates; finite calculations can have small differences from tolerance and rounding.
advance(cavi);advance(em)
print('CAVI, EM',cavi['history'][-1],em['history'][-1])advance(cavi);advance(em)
print('CAVI, EM',cavi['history'][-1],em['history'][-1])advance(cavi);advance(em)
print('CAVI, EM',cavi['history'][-1],em['history'][-1])advance(cavi);advance(em)
for name,s in [('CAVI',cavi),('EM',em)]:
h=np.array(s['history'])
print(name,'ELBO inicial y final',h[0],h[-1],'mínimo incremento',np.diff(h).min())Compare topics by distance, aligning permutations via Hungarian assignment. Since generating topics are known in this simulation, we can also measure error against them. The sklearn comparison uses the same matrix and priors for Bayesian LDA; its initialization and optimization differ.
sk=LatentDirichletAllocation(n_components=K,doc_topic_prior=alpha,topic_word_prior=beta,
learning_method='batch',max_iter=40,random_state=17,n_jobs=1).fit(counts)
sk_topics=sk.components_/sk.components_.sum(axis=1,keepdims=True)
for name,state in [('CAVI',cavi),('EM',em)]:
print(name,'L1 por tema frente a generador',match(truth,state['topics'])[1])
print(name,'L1 por tema frente a sklearn',match(sk_topics,state['topics'])[1])
print('iteraciones sklearn',sk.n_iter_,'perplejidad de entrenamiento',sk.bound_)Displayed perplexity is training perplexity, not an out-of-sample result. Topic labels are interchangeable, and small error in this single simulation does not establish general recovery or superiority of a method.
Exercises
Step 1 of 3. Which part of ELBO depends on ?
Step 1 of 3. What is the optimal factor variance?
gmm_elbo(x, r, alpha, m, s2, alpha0, tau2, noise2) for the lesson's mixture of Gaussian means and Dirichlet weights with scalar data. r has shape (n,k), alpha, m and s2 have length k; alpha0, tau2 and noise2 are positive scalars. Return the complete ELBO.def gmm_elbo(x, r, alpha, m, s2, alpha0, tau2, noise2):
passSummary
- Mean field turns each step into a factor update; exact CAVI does not decrease ELBO, though it can converge to a local maximum.
- In correlated Gaussians the optimal factor has conditional variance at most the marginal. This conclusion does not cover every family.
- In mixtures and LDA, responsibilities and expected statistics connect inference with EM. ELBO helps monitor the algorithm but does not automatically replace evidence.