Module contents
Lesson 19 of 27Advanced 110 min

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

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 BB provides an unbiased estimate of that sum when multiplied by N/BN/B. If local factors correspond to the current global state, the natural update has the form

λt+1=(1−ρt)λt+ρtλ^t∗,ρt=(t+τ)−κ.\lambda_{t+1}=(1-\rho_t)\lambda_t+\rho_t\widehat\lambda_t^*,\qquad \rho_t=(t+\tau)^{-\kappa}.

The natural gradient uses the inverse Fisher metric to measure distributional changes; in this family geometry cancels curvature and leaves the difference λ^∗−λ\widehat\lambda^*-\lambda. The estimate is not automatically unbiased if local factors are stale or examples are sampled with unequal probabilities without correction. With τ>0\tau>0, classical Robbins-Monro rate conditions ∑tρt=∞\sum_t\rho_t=\infty and ∑tρt2<∞\sum_t\rho_t^2<\infty hold for 1/2<κ≤11/2<\kappa\le1. Additional assumptions on gradients, noise and stability are needed; these alone do not guarantee finding the global optimum.

InteractiveRate and minibatch in SVI
0.7
Exact posterior mean0.6987
Final q mean0.6880
Observations1 000 000
Change minibatch size and exponent. The curve shows exact gap to optimal ELBO on a log10(1 + gap) scale for a conjugate normal model with one million simulated data points.

The figure generates 10610^6 observations xi=0.7+ϵix_i=0.7+\epsilon_i, ϵi∼N(0,1)\epsilon_i\sim\Normal(0,1) with a fixed seed; it uses prior θ∼N(0,1)\theta\sim\Normal(0,1) and sampling with replacement per minibatch. It evaluates exact gap L(q∗)−L(qt)=KL⁡(qt∥p(θ∣x))\mathcal L(q^*)-\mathcal L(q_t)=\KL(q_t\|p(\theta\mid x)) 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 J(ϕ)=Eqϕ[f(z)]J(\phi)=\E_{q_\phi}[f(z)], with support independent of ϕ\phi and under conditions permitting interchange of derivative and integral,

∇ϕJ=∫f(z)∇ϕqϕ(z) ⁣dz=Eqϕ[f(z)∇ϕlog⁡qϕ(z)].\nabla_\phi J=\int f(z)\nabla_\phi q_\phi(z)\dd z =\E_{q_\phi}[f(z)\nabla_\phi\log q_\phi(z)].

This is the score-function estimator, also called likelihood-ratio trick or REINFORCE. It does not need to differentiate ff with respect to zz and also works for discrete latents. But variance can be high. Since Eq[∇ϕlog⁡q]=0\E_q[\nabla_\phi\log q]=0, a constant bb independent of the sample can be subtracted from ff without changing expectation.

For score coordinate SjS_j, the constant minimizing Var⁡((f−b)Sj)\Var((f-b)S_j) is bj∗=E[fSj2]/E[Sj2]b_j^*=\E[fS_j^2]/\E[S_j^2] if the denominator is positive. It follows by differentiating the second moment with respect to bb. 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 z=gϕ(ϵ)z=g_\phi(\epsilon) with ϵ\epsilon from a distribution independent of ϕ\phi, and differentiation under expectation and the chain rule are justified, the reparameterization gradient (pathwise) is

∇ϕJ=Eϵ[∇zf(gϕ(ϵ)) ∇ϕgϕ(ϵ)].\nabla_\phi J=\E_\epsilon[\nabla_z f(g_\phi(\epsilon))\,\nabla_\phi g_\phi(\epsilon)].

For z=μ+σϵz=\mu+\sigma\epsilon, ϵ∼N(0,1)\epsilon\sim\Normal(0,1), gradients of Ef\E f with respect to μ\mu and σ\sigma are E[f′(z)]\E[f'(z)] and E[f′(z)ϵ]\E[f'(z)\epsilon]. If the integrand also explicitly depends on ϕ\phi, add its direct derivative. For Gaussian ELBO it is convenient to differentiate entropy analytically, as in the lab.

InteractiveEstimator distributions
Empirical densities from 5000 samples with fixed seed; tails outside joint 0.5 and 99.5 percentiles are omitted.
  • Score
  • Score with baseline
  • Reparameterization
Function f
1.0
1.0
Exact gradient2.000
Score variance30.98
Variance with baseline13.84
Pathwise variance4.03
Compare score, score with baseline and reparameterization. The step function has no valid pathwise estimator by ordinary differentiation. The histogram clips extreme tails to show the body; variances use all samples.

The simulation uses 5000 standard normals with a fixed seed and represents gradients with respect to μ\mu of Eq[f(z)]\E_q[f(z)] with q=N(μ,σ2)q=\Normal(\mu,\sigma^2). For the quadratic, the optimal baseline is μ2+3σ2\mu^2+3\sigma^2; for sine it is sin⁡μ(1−σ2)e−σ2/2\sin\mu(1-\sigma^2)e^{-\sigma^2/2}. For step 1[z>0]\ind[z>0], the true gradient is ϕ(μ/σ)/σ\phi(\mu/\sigma)/\sigma: 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 θ=T(u)\theta=T(u) is bijective, change of variables requires

log⁡pu(x,u)=log⁡pθ(x,T(u))+log⁡∣det⁡JT(u)∣.\log p_u(x,u)=\log p_\theta(x,T(u))+\log|\det J_T(u)|.

Equivalently, the induced density in original space is qθ(θ)=qu(T−1(θ))/∣det⁡JT(T−1(θ))∣q_\theta(\theta)=q_u(T^{-1}(\theta))/|\det J_T(T^{-1}(\theta))|. For θ=eu\theta=e^u, the Jacobian is θ\theta. Omitting it is not a mere change of plot scale: it changes density and the optimized objective.

InteractiveTransforms and Jacobians
  • Selected density
Domain
Density
0.0
0.8
Numerical integral on [0,7]0.993
Select the positive parameter or simplex and compare with and without the Jacobian. The positive numerical integral covers only [0,7]; the simplex one approximates integration over the triangle.

For the simplex of three probabilities use two free coordinates and θ=softmax⁡(u1,u2,0)\theta=\operatorname{softmax}(u_1,u_2,0). In coordinates (θ1,θ2)(\theta_1,\theta_2) the determinant is θ1θ2θ3\theta_1\theta_2\theta_3. Three logits without fixing a reference are not bijective: adding the same constant leaves the simplex unchanged. The figure shows an independent normal in (u1,u2)(u_1,u_2) 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 zK=TK∘⋯∘T1(z0)z_K=T_K\circ\cdots\circ T_1(z_0) with invertible transforms,

log⁡qK(zK)=log⁡q0(z0)−∑k=1Klog⁡∣det⁡JTk(zk−1)∣.\log q_K(z_K)=\log q_0(z_0)-\sum_{k=1}^K\log|\det J_{T_k}(z_{k-1})|.

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 qϕ(z∣x)q_\phi(z\mid x) 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 w∼N(0,4I)\vb w\sim\Normal(\vb0,4\mat I). Generate 80 examples with seed 41, normal covariates and generating coefficients (1.2,−0.8)(1.2,-0.8). Results of this simulation do not replace comparison on another dataset or model. Variational parameters are μ\vb\mu and L=[eρ10ceρ2]\mat L=\begin{bmatrix}e^{\rho_1}&0\\c&e^{\rho_2}\end{bmatrix}, with w=μ+Lϵ\vb w=\vb\mu+\mat L\vb\epsilon. In the diagonal family fix c=0c=0.

For reparameterization use g=∇wlog⁡p(y,w)g=\nabla_w\log p(y,\vb w) and differentiate by hand. Components of ∇ρi\nabla_{\rho_i} contain giLiiϵi+1g_iL_{ii}\epsilon_i+1, where 1 comes from Gaussian entropy; the component of cc is g2ϵ1g_2\epsilon_1. Score uses f=log⁡p−log⁡qf=\log p-\log q, 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.

[ ]Model and manual gradientsBrowser
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(X@np.array([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]]]); w=mu+eps@L.T
    logits=w@X.T
    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 familyBrowser
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 familyBrowser
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.

[ ]Quadrature referenceBrowser
grid=np.linspace(-4.,6.,201)
a,b=np.meshgrid(grid,grid,indexing='ij'); W=np.column_stack((a.ravel(),b.ravel()))
logits=W@X.T
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))
[ ]Gradient variabilityBrowser
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.

[ ]Logistic module from m14-l07Browser
"""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_w

The 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.

[ ]BBVI and predictive metricBrowser
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); w=mu+eps@L.T; logits=w@X.T
    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))
[ ]Diagonal fitBrowser
for method in ('path','score'):
    t=fit(method,False);m,L=unpack(t);c=L@L.T
    print(method,'diagonal: media',np.round(m,4),'covarianza',np.round(c,4),'NLL/Brier',evaluate(m,c))
[ ]Full fitBrowser
for method in ('path','score'):
    t=fit(method,True);m,L=unpack(t);c=L@L.T
    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.

[ ]Pyro: diagonal and full guidesLocal GPU
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(Xtest@w.T).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)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericScore variance
For z=1+ϵz=1+\epsilon, with ϵ∼N(0,1)\epsilon\sim\Normal(0,1), estimate ∂μE[z2]\partial_\mu\E[z^2] using score (1+ϵ)2ϵ(1+\epsilon)^2\epsilon. What is the variance of one sample of that estimator?
QuizGeometry of SVI
Why does the natural update simplify in the conjugate exponential case?
ProofScore identity and baseline
Prove: A constant baseline independent of the sample does not change expected score gradient.
0
Assume fixed support, differentiable density and conditions allowing derivative and integral to be interchanged.

Step 1 of 2. What is the expected score?

ProofGaussian reparameterization
Prove: Derive gradients of EN(μ,σ2)[f(z)]\E_{\Normal(\mu,\sigma^2)}[f(z)] with respect to μ\mu and σ\sigma.
0
Write z=μ+σϵz=\mu+\sigma\epsilon, with ϵ∼N(0,1)\epsilon\sim\Normal(0,1), and assume differentiation under expectation is valid.

Step 1 of 2. What derivatives does z have?

CodePer-coordinate baseline
Implement 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):
  pass
Shift+Enter to run

Summary

Key idea
Stochastic variational inference replaces expensive sums and expectations with noisy estimates; its validity depends on how those estimates are constructed and on the chosen family.
  • 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.