Automatic Differentiation Variational Inference (ADVI)

Summary

ADVI (Kucukelbir, Tran, Ranganath, Gelman & Blei 2017) turns VI into a generic algorithm for any differentiable probability model: the user writes the model (e.g. in Stan) and nothing else. The recipe has three ingredients: (1) automatically transform constrained latent variables to , adding a log-Jacobian term, so that one variational family serves every model; (2) posit a Gaussian in the unconstrained space, either mean-field or full-rank, which implies a non-Gaussian approximation in the original space; (3) standardize the Gaussian (the reparameterization trick) so the gradient moves inside the expectation, compute it by automatic differentiation with a single Monte Carlo draw, and run stochastic gradient ascent with an adaptive step size. It is fast and automatic; its accuracy is limited by the Gaussian family and, in mean-field form, by ignored posterior correlation.

Overview

Before ADVI, “each step requires expert thought and analysis in the service of a single algorithm for a single model” (Sec. 2.2): choose a family satisfying the support constraint, derive expectations, derive updates, implement, debug. ADVI removes every model-specific step for the class of models that Stan already supports for HMC, those with continuous latent variables and a gradient on the support of the prior. Discrete latents must be marginalized out, exactly as for HMC in Stan. No conjugacy of any kind is assumed; the running example is a Poisson likelihood with a Weibull prior on the rate.

This is the algorithm behind Stan’s variational method and PyMC’s ADVI/FullRankADVI, and therefore the algorithm that SBC Case Studies finds miscalibrated on a simple linear regression.

Main Content

Differentiable probability model ^def-differentiable-model

A joint density with continuous latent variables whose log-joint gradient exists on the support of the prior. Includes GLMs, mixtures and HMMs/topic models with discrete variables marginalized, state-space models, Gaussian processes, deep exponential families (Table 1). Excludes models where marginalization is intractable (Ising, sigmoid belief nets, untruncated Bayesian nonparametrics).

Step 1: transform to real coordinate space

Reverse KL requires (support constraint); ADVI additionally assumes the posterior support equals the prior support. Rather than pick a family per constraint type, define a one-to-one differentiable and set . The transformed joint is

For a positive rate, and the Jacobian factor is ; e.g. (Sec. 2.3). Stan supplies the library of transforms (bounds, simplexes, ordered vectors, covariance and Cholesky factors), the same ones it uses for HMC.

Step 2: a Gaussian family in the unconstrained space

Mean-field and full-rank Gaussian families ^def-advi-families

Mean-field: with , so is unconstrained. Full-rank: with lower-triangular (diagonal not constrained positive), so . The implied density on the original space, , is non-Gaussian and automatically respects the support (Sec. 2.4).

Two remarks from the paper. A Gaussian variational approximation “is not equivalent to the Laplace approximation”: Laplace expands around the MAP (Approximations Based on Joint and Conditional Posterior Modes); ADVI minimizes an average discrepancy. And full-rank is “a form of structured mean-field variational inference” whose off-diagonal terms “capture posterior correlations,” at parameter cost.

Step 3: the objective, standardization and gradients

ELBO in real coordinate space ^thm-advi-elbo

(Eq. 5). The optimization is now unconstrained. The Gaussian entropy is analytic: implemented once, reused for all models.

Automatic differentiation cannot differentiate an expectation whose measure depends on . Elliptical standardization fixes this: (mean-field) or (full-rank), so regardless of . The paper notes this is the same device “also known as… the ‘re-parameterization trick’ (Kingma and Welling, 2014)” (fn. 6); see Reparameterization Trick and Variational Autoencoders. With and :

and for full-rank the same bracket times plus (Eqs. 7-9). Everything inside the expectations is an autodiff call; the expectation is a Monte Carlo average over draws and “in practice a single sample suffices.”

ADVI (Kucukelbir et al., Algorithm 1) ^alg-advi

Input: data , model .

  1. Initialize and (mean-field) or (full-rank): a standard Gaussian in unconstrained space.
  2. Choose the step-size scale by a short search on a data subset.
  3. While the change in ELBO exceeds a threshold:
    • draw , ;
    • estimate and (or ) by Monte Carlo;
    • compute step sizes and update , similarly or .
  4. Return (or ).

Step size (Eqs. 10-11): with , using , , . The decaying factor satisfies Robbins-Monro; the last factor is RMSProp-like finite-memory curvature adaptation. Cost: per iteration, or with minibatches of size and the likelihood scaled by .

Properties (Sec. 3)

Accuracy: what mean-field loses ^ex-advi-accuracy

  • Correlated 2-D Gaussian (1000 data points, analytic posterior): both variants recover the mean. Marginal variances: analytic , full-rank , mean-field (Fig. 4). “ADVI minimizes the KL divergence from the approximation to the exact posterior; this leads to a systemic underestimation of marginal variances.”
  • Logistic regression (10 coefficients, 1000 points): posterior means agree with NUTS; mean-field “underestimates marginal posterior variances on most of the coefficients,” full-rank matches (Fig. 5).
  • Stochastic volatility (500 time steps, AR(1) log-volatility): here mean-field gets even the mean wrong, “particularly when the log volatility drifts far away from ,” because neighbouring are strongly correlated; full-rank matches sampling, and its covariance matrix shows the banded structure that mean-field cannot (Figs. 6-7).

Recommendation: “Scientists interested in posterior variances and covariances should use the full-rank approximation… Scientists interested in prediction should initially rely on the mean-field approximation,” because “accurate posterior mean estimates dominate predictive accuracy; underestimating marginal variances matters less.”

The stochastic volatility case is the warning for time-series work: latent states in a media mix model with time-varying baselines or coefficients have exactly this local correlation structure.

Sensitivity to the transformation and the optimal

The choice of changes the implied family on the original space. For Gamma posteriors on , beats : is vs for , and vs for (Table 2), because is nearly linear for large and both Gamma and Gaussian are light-tailed. The optimal transformation is

posterior CDF followed by the standard-normal quantile function, under which a Gaussian is exact. But estimating “is just as hard as the original goal” (Sec. 3.3). Learning an approximation to is what normalizing flows do.

Gradient variance. The ADVI (pathwise) gradient has lower variance than the BBVI score-function gradient, with or without control variates, on both a univariate and a 100-dimensional model (Fig. 8); see Stochastic and Black-Box Variational Inference.

Speed (Sec. 4). Measured by held-out predictive likelihood against time: parity with NUTS on ARD linear regression (250 regressors, 10,000 points) and hierarchical logistic regression (145 regressors); “an order of magnitude” faster on non-negative matrix factorization of the Frey faces; on a 30-component Gaussian mixture over 250,000 images, minibatch ADVI converges in about two hours where “NUTS cannot handle such large datasets,” with minibatches below giving worse optima; clustering 1.7 million taxi trajectories after ADVI-fitted PPCA with an ARD prior selected an 11-dimensional subspace. All of these comparisons are predictive, the regime in which the paper itself says variance errors matter least.

Examples

Running and checking ADVI ^ex-advi-usage

# PyMC (sketch): mean-field, then full-rank, then draw for diagnostics
with model:
    mf = pm.fit(n=50_000, method="advi")            # mean-field Gaussian
    fr = pm.fit(n=50_000, method="fullrank_advi")   # full-rank Gaussian
    idata_vi = fr.sample(2_000)
# CmdStanR (sketch)
fit <- mod$variational(data = d, algorithm = "fullrank",
                       tol_rel_obj = 1e-4, output_samples = 2000)

Three habits follow directly from the papers:

  1. Center and scale predictors, and non-center hierarchies. Mean-field can only be right if the posterior is nearly factorized in the unconstrained coordinates. The linear-regression calculation in the mean-field note shows an uncentered predictor alone can halve the slope’s posterior sd; hierarchical funnels need the non-centered form (see Computational Troubleshooting).
  2. Tighten the tolerance. Yao et al. (2018) show the default relative-ELBO tolerance of can stop far too early ( vs at on a 100-regressor linear model).
  3. Compute from the draws before using any interval: Diagnosing Variational Inference (PSIS k-hat and VSBC).

Open issues named by the authors (Sec. 5): sensitivity to ; first-order optimization only; initialization at a standard Gaussian and the finite search for are heuristics; no discrete latents without falling back on the high-variance score-function estimator.

Connections

See Also