Variational inference II: stochastic, black-box and amortized
To scale to large datasets and nonconjugate models, variational inference becomes stochastic. We study SVI with natural gradients, score-function and reparameterization Monte Carlo estimators and their variance reduction, ADVI transformations to unconstrained space, expressive variational families and amortized inference underlying VAEs.
After this lesson you can
- Derive minibatch SVI with natural gradients in conjugate-exponential models.
- Derive score-function and reparameterization estimators and compare their variance.
- Implement BBVI with control variates and reparameterization for Bayesian logistic regression.
- Apply ADVI with bijective transformations and Jacobian correction.
- Explain amortized inference, the amortization gap and the role of flows as variational families.
Before you start
- 14Variational inferenceMean-field approximationVariational inference in conjugate-exponential modelsBayesian logistic regressionGlobal and local latent variables
- 06Stochastic gradient descentAdamRobbins-Monro stochastic approximationNatural gradient
- 09Reverse-mode automatic differentiation
- 05Fisher informationFisher information matrix
- 04Change of variables for densities
When a full pass is too expensive
Coordinate ascent variational inference needs expectations under all factors. With millions of observations or a nonconjugate likelihood, each step may be too expensive or lack closed form. The solution is to estimate gradients with minibatches and samples, without confusing estimator noise with the posterior uncertainty being calculated.
Stochastic variational inference (SVI) exploits global and local latent structure. In a conjugate exponential model, the optimal global natural parameter combines the prior with a sum of local statistics. A uniform minibatch of size provides an unbiased estimate of that sum when multiplied by . If local factors correspond to the current global state, the natural update has the form
The natural gradient uses the inverse Fisher metric to measure distributional changes; in this family geometry cancels curvature and leaves the difference . The estimate is not automatically unbiased if local factors are stale or examples are sampled with unequal probabilities without correction. With , classical Robbins-Monro rate conditions and hold for . Additional assumptions on gradients, noise and stability are needed; these alone do not guarantee finding the global optimum.
The figure generates observations , with a fixed seed; it uses prior and sampling with replacement per minibatch. It evaluates exact gap on the entire dataset. The trajectory is noisy because updates depend on minibatches, even though that gap evaluation is not. A finite 250-step interval does not prove asymptotic convergence; a rate too small can leave the state far from optimum and a large rate leaves appreciable fluctuations.
Two Monte Carlo gradients
For , with support independent of and under conditions permitting interchange of derivative and integral,
This is the score-function estimator, also called likelihood-ratio trick or REINFORCE. It does not need to differentiate with respect to and also works for discrete latents. But variance can be high. Since , a constant independent of the sample can be subtracted from without changing expectation.
For score coordinate , the constant minimizing is if the denominator is positive. It follows by differentiating the second moment with respect to . Estimating it with an independent pilot preserves conditional unbiasedness; using the same batch to fit and apply the baseline can introduce bias. Other control variates and variance-reduction techniques exist; none always dominates.
If with from a distribution independent of , and differentiation under expectation and the chain rule are justified, the reparameterization gradient (pathwise) is
For , , gradients of with respect to and are and . If the integrand also explicitly depends on , add its direct derivative. For Gaussian ELBO it is convenient to differentiate entropy analytically, as in the lab.
The simulation uses 5000 standard normals with a fixed seed and represents gradients with respect to of with . For the quadratic, the optimal baseline is ; for sine it is . For step , the true gradient is : the step’s ordinary derivative is zero almost everywhere, but interchanging it with expectation misses the moving boundary. This precisely violates the assumptions above.
Transforming support: ADVI
ADVI transforms constrained latents to free coordinates, places a diagonal or full Gaussian there and optimizes ELBO with autodifferentiation. If is bijective, change of variables requires
Equivalently, the induced density in original space is . For , the Jacobian is . Omitting it is not a mere change of plot scale: it changes density and the optimized objective.
For the simplex of three probabilities use two free coordinates and . In coordinates the determinant is . Three logits without fixing a reference are not bijective: adding the same constant leaves the simplex unchanged. The figure shows an independent normal in and approximates the integral on a grid; numerical error may grow near boundaries.
More expressivity and amortization
A full Gaussian captures correlation but not necessarily multimodality. Mixtures and normalizing flows expand the family: if with invertible transforms,
Greater expressivity can reduce the best attainable KL if the family contains the old one, but costs more to optimize and does not ensure that best value is reached. Rezende and Mohamed develop variational flows with evaluable transformation Jacobians.
Amortized inference learns a shared function predicting variational parameters for each observation, instead of optimizing a local factor from scratch per datum. For a fixed family, total gap separates into approximation gap, between posterior and best family member, and amortization gap, between that best member and the encoder output. This assumes ideal optimization of the individual member; finite implementation can also have optimization error. Semi-amortization starts from the encoder output and refines per-datum parameters. Cremer and colleagues study both sources in VAEs.
Automatic guides in Pyro and NumPyro build diagonal or full families and transform constrained supports. A full guide can capture correlations but costs more and remains approximate; checking predictives and sensitivity to family is part of inference.
Lab: Bayesian logistic regression and BBVI from scratch
This independent experiment checks estimators on two-coefficient logistic regression with prior . Generate 80 examples with seed 41, normal covariates and generating coefficients . Results of this simulation do not replace comparison on another dataset or model. Variational parameters are and , with . In the diagonal family fix .
For reparameterization use and differentiate by hand. Components of contain , where 1 comes from Gaussian entropy; the component of is . Score uses , a per-coordinate baseline calculated from independent pilot samples followed by a second gradient batch. Both estimates use the same model and number of samples per step.
import numpy as np
from scipy.special import expit, logsumexp
def make_logistic_data():
rg=np.random.default_rng(41)
X=rg.normal(size=(80,2))
y=(rg.random(80)<expit([email protected]([1.2,-.8]))).astype(float)
return X,y
def quantities(theta,eps,X,y):
mu=theta[:2]; s=np.exp(theta[2:4]); off=theta[4]
L=np.array([[s[0],0.],[off,s[1]]]); [email protected]
[email protected]
logp=np.sum(y[None,:]*logits-np.logaddexp(0,logits),axis=1)-.5*np.sum(w*w,axis=1)/4-2*np.log(2*np.sqrt(2*np.pi))
logq=-np.log(2*np.pi)-np.log(s).sum()-.5*np.sum(eps*eps,axis=1)
grad_w=(y[None,:]-expit(logits))@X-w/4
return L,logp-logq,grad_w
def score_values(theta,eps,X,y):
L,f,_=quantities(theta,eps,X,y)
mu_score=np.linalg.solve(L.T,eps.T).T
outer=np.einsum('ni,nj->nij',eps,eps)-np.eye(2)[None,:,:]
G=np.linalg.solve(L.T,outer); s=np.exp(theta[2:4])
scores=np.column_stack((mu_score,G[:,0,0]*s[0],G[:,1,1]*s[1],G[:,1,0]))
return f,scores
def path_values(theta,eps,X,y):
L,f,g=quantities(theta,eps,X,y)
grad=np.column_stack((g,g[:,0]*L[0,0]*eps[:,0]+1,g[:,1]*L[1,1]*eps[:,1]+1,g[:,1]*eps[:,0]))
return f,grad
def estimate(theta,method,rg,X,y,S=64,full=True):
eps=rg.normal(size=(S,2))
if method=='path':
_,grad=path_values(theta,eps,X,y)
else:
pilot=rg.normal(size=(S,2)); fp,sp=score_values(theta,pilot,X,y)
baseline=np.mean(fp[:,None]*sp*sp,axis=0)/np.maximum(np.mean(sp*sp,axis=0),1e-12)
f,scores=score_values(theta,eps,X,y); grad=(f[:,None]-baseline)*scores
out=grad.mean(axis=0)
if not full: out[4]=0
return out
def fit_vi(X,y,method,full=True,steps=600,seed=2):
rg=np.random.default_rng(seed); theta=np.array([0.,0.,-.7,-.7,0.]); m=np.zeros(5); v=np.zeros(5)
for t in range(1,steps+1):
g=estimate(theta,method,rg,X,y,64,full)
m=.9*m+.1*g; v=.999*v+.001*g*g
theta+=.025*(m/(1-.9**t))/(np.sqrt(v/(1-.999**t))+1e-8)
return theta
X,y=make_logistic_data()
print('n, dimensión, proporción de clase 1',len(y),X.shape[1],y.mean())The next two cells run 600 steps per combination. Results are stochastic approximations, not convergence proofs. Compare means and off-diagonal term; a serious posterior analysis would use more initializations, diagnostics and out-of-sample predictives.
diagonal_path=fit_vi(X,y,'path',False)
diagonal_score=fit_vi(X,y,'score',False)
print('pathwise, media y log desviaciones',np.round(diagonal_path,4))
print('score con piloto, media y log desviaciones',np.round(diagonal_score,4))full_path=fit_vi(X,y,'path',True)
full_score=fit_vi(X,y,'score',True)
print('pathwise, media, log diagonal y término inferior',np.round(full_path,4))
print('score con piloto, media, log diagonal y término inferior',np.round(full_score,4))Two-dimensional quadrature provides a reference for this independent experiment. Its domain and resolution are finite, so expand them and check stability. The last part measures variance of each gradient component of a Monte Carlo minibatch of size 32 at one variational point; it does not prove universal superiority of an estimator.
grid=np.linspace(-4.,6.,201)
a,b=np.meshgrid(grid,grid,indexing='ij'); W=np.column_stack((a.ravel(),b.ravel()))
[email protected]
logp=np.sum(y[None,:]*logits-np.logaddexp(0,logits),axis=1)-np.sum(W*W,axis=1)/8
weights=np.exp(logp-logsumexp(logp)); posterior_mean=weights@W
diff=W-posterior_mean; posterior_cov=(diff*weights[:,None]).T@diff
print('media de la cuadratura',np.round(posterior_mean,4))
print('covarianza de la cuadratura',np.round(posterior_cov,4))theta=np.array([.8,-.5,-1.,-1.,.1]); rg=np.random.default_rng(7)
scores=[]; paths=[]
for _ in range(400):
scores.append(estimate(theta,'score',rg,X,y,32,True))
paths.append(estimate(theta,'path',rg,X,y,32,True))
print('varianzas score',np.round(np.var(scores,axis=0,ddof=1),3))
print('varianzas pathwise',np.round(np.var(paths,axis=0,ddof=1),3))Comparison with Laplace logistic regression
We reuse the m14-l07 model with the same generator, 40 training data, 2000 test data, seed 2026 and prior precision 1.5. The original module is available to download logreg.py; the first cell reproduces it so this lesson’s session is self-contained. Data are simulated and the test split belongs to the same generating mechanism.
"""MAP logístico con prior gaussiano y aproximación de Laplace."""
import numpy as np
from scipy.special import expit
def negative_log_posterior(w, X, y, alpha):
z = X @ w
p = expit(z)
value = np.logaddexp(0., z).sum() - y @ z + .5 * alpha * (w @ w)
gradient = X.T @ (p-y) + alpha*w
H = X.T @ ((p*(1-p))[:,None]*X) + alpha*np.eye(X.shape[1])
return value, gradient, H
def fit_laplace(X, y, alpha=1., tol=1e-9, max_iter=100):
X=np.asarray(X,dtype=float);y=np.asarray(y,dtype=float)
if X.ndim!=2 or y.shape!=(X.shape[0],) or X.shape[1]==0:
raise ValueError('dimensiones incompatibles')
if not np.all(np.isfinite(X)) or not np.all(np.isfinite(y)) or np.any((y!=0)&(y!=1)) or not np.isfinite(alpha) or alpha<=0 or tol<=0 or max_iter<1:
raise ValueError('datos finitos, etiquetas binarias, alpha y tolerancia positivos y al menos una iteración')
w=np.zeros(X.shape[1]); converged=False
for iteration in range(max_iter):
value,gradient,H=negative_log_posterior(w,X,y,alpha)
if np.linalg.norm(gradient,np.inf)<tol:
converged=True;break
direction=np.linalg.solve(H,gradient)
rate=1.
while rate>1e-12:
candidate=w-rate*direction
if negative_log_posterior(candidate,X,y,alpha)[0]<=value-1e-4*rate*(gradient@direction):
break
rate*=.5
if rate<=1e-12:break
w=candidate
value,gradient,H=negative_log_posterior(w,X,y,alpha)
if np.linalg.norm(gradient,np.inf)<tol:converged=True
cov=np.linalg.solve(H,np.eye(X.shape[1]))
return w,cov,{'converged':converged,'iterations':iteration+1,
'gradient_inf':np.linalg.norm(gradient,np.inf),'objective':value}
def predict_probit(X, mean, covariance):
X=np.asarray(X,dtype=float)
variance=np.einsum('ij,jk,ik->i',X,covariance,X)
return expit((X@mean)/np.sqrt(1+np.pi*np.maximum(variance,0)/8))
def synthetic_data(seed=2026,n_train=40,n_test=2000):
"""Datos sintéticos Bernoulli, partición de test independiente en el mismo generador."""
rng=np.random.default_rng(seed)
true_w=np.array([-.4,1.4,-1.])
def generate(n):
X=np.column_stack((np.ones(n),rng.normal(size=(n,2))))
y=rng.binomial(1,expit(X@true_w))
return X,y
X,y=generate(n_train);X_test,y_test=generate(n_test)
return X,y,X_test,y_test,true_wThe next code extends the manual estimator to three coefficients. For the full family, the Cholesky diagonal is parameterized in logs and lower entries are free. Compare both estimators with the same number of samples per step; score also needs an independent pilot. The predictive distribution integrates the sigmoid by Gauss-Hermite quadrature. Runs are short and do not prove convergence.
import numpy as np
from scipy.special import expit
from numpy.polynomial.hermite import hermgauss
X,y,Xtest,ytest,_=synthetic_data(); alpha=1.5; d=X.shape[1]
lap_mean,lap_cov,info=fit_laplace(X,y,alpha=alpha)
ij=np.tril_indices(d,-1)
def unpack(theta):
L=np.diag(np.exp(theta[d:2*d])); L[ij]=theta[2*d:]
return theta[:d],L
def terms(theta,eps):
mu,L=unpack(theta); [email protected]; [email protected]
logp=np.sum(y*logits-np.logaddexp(0,logits),axis=1)-alpha*np.sum(w*w,axis=1)/2+d/2*np.log(alpha/(2*np.pi))
logq=-d/2*np.log(2*np.pi)-np.log(np.diag(L)).sum()-np.sum(eps*eps,axis=1)/2
grad=(y-expit(logits))@X-alpha*w
return L,logp-logq,grad
def score(theta,eps):
L,f,_=terms(theta,eps); mu_score=np.linalg.solve(L.T,eps.T).T
G=np.linalg.solve(L.T,np.einsum('ni,nj->nij',eps,eps)-np.eye(d)[None,:,:])
return f,np.column_stack((mu_score,G[:,range(d),range(d)]*np.diag(L),G[:,ij[0],ij[1]]))
def path(theta,eps):
L,f,g=terms(theta,eps)
return f,np.column_stack((g,g*np.diag(L)*eps+1,g[:,ij[0]]*eps[:,ij[1]]))
def estimate(theta,method,rg,S=64,full=True):
eps=rg.normal(size=(S,d))
if method=='path': _,g=path(theta,eps)
else:
fp,sp=score(theta,rg.normal(size=(S,d))); base=(fp[:,None]*sp**2).mean(0)/(sp**2).mean(0)
f,s=score(theta,eps);g=(f[:,None]-base)*s
out=g.mean(0)
if not full:out[2*d:]=0
return out
def fit(method,full,steps=800):
rg=np.random.default_rng(14);theta=np.r_[np.zeros(d),np.full(d,-.7),np.zeros(len(ij[0]))];m=np.zeros_like(theta);v=m.copy()
for t in range(1,steps+1):
g=estimate(theta,method,rg,64,full);m=.9*m+.1*g;v=.999*v+.001*g*g
theta+=.025*(m/(1-.9**t))/(np.sqrt(v/(1-.999**t))+1e-8)
return theta
nodes,weights=hermgauss(30);weights/=np.sqrt(np.pi)
def evaluate(mean,cov):
m=Xtest@mean;v=np.einsum('ij,jk,ik->i',Xtest,cov,Xtest)
p=(expit(m[:,None]+np.sqrt(2*v[:,None])*nodes)*weights).sum(1).clip(1e-9,1-1e-9)
return -np.mean(ytest*np.log(p)+(1-ytest)*np.log1p(-p)),np.mean((ytest-p)**2)
print('Laplace convergió',info['converged'],'media',np.round(lap_mean,4),'covarianza',np.round(lap_cov,4))
print('Laplace NLL y Brier',evaluate(lap_mean,lap_cov))for method in ('path','score'):
t=fit(method,False);m,L=unpack(t);[email protected]
print(method,'diagonal: media',np.round(m,4),'covarianza',np.round(c,4),'NLL/Brier',evaluate(m,c))for method in ('path','score'):
t=fit(method,True);m,L=unpack(t);[email protected]
print(method,'completa: media',np.round(m,4),'covarianza',np.round(c,4),'NLL/Brier',evaluate(m,c))For this seed Laplace obtains log loss approximately 0.538; the four short stochastic fits are near 0.544 to 0.545. The Laplace reference is an approximation around the mode, while BBVI optimizes a directed KL and can deviate from that mode. The test sample is synthetic too: these figures do not rank methods on other data.
Automatic guides with Pyro
This local cell repeats m14-l07 logistic regression with AutoNormal and AutoMultivariateNormal, adding an eight-group hierarchical model with positive scale. It uses 200 steps per guide, 20 particles to estimate final ELBO and 200 predictive samples. Evaluate log loss on the previous comparison’s 2000 synthetic test observations. Time includes GPU synchronization and varies by machine. The parameter store is cleared between fits to avoid reusing a prior guide.
The checked short Pyro 1.9.2 run with CUDA produced log losses 0.5475 and 0.5469 and estimated ELBOs -17.655 and -17.715 for diagonal and full guides respectively. In the hierarchical model estimated scale means were 0.561 and 0.523. These check the workflow with Monte Carlo noise, not prove convergence or that either guide always wins. Increase steps, particles and seeds before interpreting differences.
import time
import numpy as np
from scipy.special import expit
def synthetic_data(seed=2026,n_train=40,n_test=2000):
"""Datos sintéticos Bernoulli, partición de test independiente en el mismo generador."""
rng=np.random.default_rng(seed)
true_w=np.array([-.4,1.4,-1.])
def generate(n):
X=np.column_stack((np.ones(n),rng.normal(size=(n,2))))
y=rng.binomial(1,expit(X@true_w))
return X,y
X,y=generate(n_train);X_test,y_test=generate(n_test)
return X,y,X_test,y_test,true_w
import torch,pyro
import pyro.distributions as dist
from pyro.infer import SVI,Trace_ELBO,Predictive
from pyro.infer.autoguide import AutoNormal,AutoMultivariateNormal
from pyro.optim import Adam
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
X,y,Xtest,ytest,_=synthetic_data()
X=torch.tensor(X,dtype=torch.float32,device=device);y=torch.tensor(y,dtype=torch.float32,device=device)
Xtest=torch.tensor(Xtest,dtype=torch.float32,device=device);ytest=torch.tensor(ytest,dtype=torch.float32,device=device)
d=X.shape[1]
def model(X,y=None):
w=pyro.sample('w',dist.Normal(torch.zeros(d,device=device),torch.ones(d,device=device)/1.5**.5).to_event(1))
with pyro.plate('data',X.shape[0]):pyro.sample('obs',dist.Bernoulli(logits=X@w),obs=y)
def run(guide_class):
pyro.clear_param_store();pyro.set_rng_seed(123)
guide=guide_class(model);svi=SVI(model,guide,Adam({'lr':.025}),Trace_ELBO())
if device.type=='cuda':torch.cuda.synchronize()
start=time.perf_counter()
for _ in range(200):svi.step(X,y)
if device.type=='cuda':torch.cuda.synchronize()
elapsed=time.perf_counter()-start
elbo=-Trace_ELBO(num_particles=20).loss(model,guide,X,y)
w=Predictive(model,guide=guide,num_samples=200,return_sites=('w',))(X,y)['w'].reshape(-1,d)
p=torch.sigmoid([email protected]).mean(1).clamp(1e-7,1-1e-7)
nll=-(ytest*p.log()+(1-ytest)*(1-p).log()).mean()
print(guide_class.__name__,'ELBO MC',round(elbo,3),'NLL',round(nll.item(),4),'mean',w.mean(0).cpu().numpy().round(4),'cov',torch.cov(w.T).cpu().numpy().round(4),'seconds',round(elapsed,2))
print('Pyro',pyro.__version__,'device',device)
run(AutoNormal);run(AutoMultivariateNormal)
rg=np.random.default_rng(71); groups=np.repeat(np.arange(8),30)
offset=rg.normal(0,.9,size=8); ygroup=(rg.random(len(groups))<expit(offset[groups])).astype(float)
G=torch.tensor(groups,dtype=torch.long,device=device); yg=torch.tensor(ygroup,dtype=torch.float32,device=device)
def hierarchical(G,y=None):
scale=pyro.sample('scale',dist.HalfNormal(torch.tensor(2.,device=device)))
with pyro.plate('groups',8):
offsets=pyro.sample('offsets',dist.Normal(torch.tensor(0.,device=device),scale))
with pyro.plate('data',G.shape[0]):
pyro.sample('obs',dist.Bernoulli(logits=offsets[G]),obs=y)
def run_h(guide_class):
pyro.clear_param_store();pyro.set_rng_seed(52)
guide=guide_class(hierarchical);svi=SVI(hierarchical,guide,Adam({'lr':.02}),Trace_ELBO())
for i in range(200):svi.step(G,yg)
elbo=-Trace_ELBO(num_particles=20).loss(hierarchical,guide,G,yg)
draws=Predictive(hierarchical,guide=guide,num_samples=200,return_sites=('scale',))(G,yg)['scale']
print('hierarchical',guide_class.__name__,'ELBO MC',round(elbo,3),'scale mean',round(draws.mean().item(),3))
run_h(AutoNormal);run_h(AutoMultivariateNormal)npm run lab and open the connection link.Exercises
Step 1 of 2. What is the expected score?
Step 1 of 2. What derivatives does z have?
controlled_score(log_joint, log_q, score, pilot, samples). The first two functions return a vector of values per sample and score returns a score matrix. Calculate an optimal baseline per coordinate using the pilot and apply the estimator to the independent batch. Return (gradiente, linea_base). Assume positive denominators.def controlled_score(log_joint, log_q, score, pilot, samples):
passSummary
- Score gradients also apply to discrete latents; independent baselines can reduce their variance.
- Reparameterization uses derivatives through a transformation and requires regularity assumptions.
- ADVI includes each transformation Jacobian; a full guide or flow expands the family without guaranteeing a good solution.
- Amortized inference shares work across observations but introduces another source of gap.
Main sources: Hoffman and colleagues, SVI; Ranganath and colleagues, BBVI; Kucukelbir and colleagues, ADVI; Kingma and Welling, reparameterization.