6. Choosing an inference algorithm¶
quivers.inference provides eleven guide classes, seven objectives, four gradient estimators, Markov chain Monte Carlo (MCMC) kernels for Hamiltonian Monte Carlo (HMC) (Neal, 2011), the No-U-Turn Sampler (NUTS) (Hoffman and Gelman, 2014), Metropolis–Hastings, and Gibbs updates, and two hybrids of variational inference (VI) and MCMC. The right combination depends on the posterior geometry, the computational budget, and the quantities the analysis needs. Choose VI, MCMC, or a hybrid first. For VI, then choose a guide (which distributions the approximation can represent), an objective (what is optimized), and a gradient estimator (how its gradient is estimated).
Step 1: VI, MCMC, or hybrid?¶
| Posterior shape | First choice |
|---|---|
| Smooth, roughly unimodal, fewer than 1000 latents | VI. |
| Strongly correlated or curved | NUTS, with diagnostics. A reparameterization may still be needed. |
| Well-separated modes | Several initializations, comparing the regions reached. Separate modes may need a mixture guide or a sampler designed to move between modes. |
| Hierarchical with a funnel | NUTS, or VI on the non-centered parameterization. |
| More than 1000 continuous latents | VI, unless the compute budget is large. |
| Mixed discrete and continuous, small discrete support | VI with a marginalize block (chapter 4), or HMC on the continuous remainder. |
| Unknown | AutoNormalGuide with ELBO, which is cheap and whose failures are informative. |
VI turns inference into optimization and can scale to many latent variables (Blei et al., 2017). HMC and NUTS are asymptotically exact under regularity conditions, but a finite run has Monte Carlo error and needs convergence diagnostics. Run times depend on the model and the hardware, so benchmark the alternatives on the model at hand.
Step 2: Which variational guide?¶
flowchart TD
start(["Posterior shape"]) --> id{"Identifiable,<br/>weak correlation?"}
id -- yes --> normal["AutoNormalGuide<br/>default"]
id -- no --> corr{"Strong correlations?"}
corr -- yes --> dim{"Cholesky fits in memory?"}
dim -- yes --> mvn["AutoMultivariateNormalGuide"]
dim -- no --> lr["AutoLowRankMultivariateNormalGuide"]
corr -- no --> multi{"Multimodal?"}
multi -- yes --> mix["AutoMixtureGuide<br/>or AutoNormalizingFlow<br/>or AutoIAFGuide"]
multi -- no --> tails{"Non-Gaussian tails?"}
tails -- yes --> flow["AutoIAFGuide<br/>or AutoNeuralSplineGuide"]
tails -- no --> normal2["back to AutoNormalGuide"]
class start qv-input
class id,corr,dim,multi,tails qv-decision
class normal,mvn,lr,mix,flow,normal2 qv-output
| Guide | Family | When |
|---|---|---|
AutoNormalGuide |
Mean-field Normal | Default: cheap, scales, often adequate. |
AutoDeltaGuide |
A point mass at the maximum a posteriori (MAP) estimate | A MAP estimate with no posterior uncertainty. |
AutoMultivariateNormalGuide |
Full-covariance Normal, parameterized by a Cholesky factor | Strong posterior correlations, with few enough latent dimensions \(D\) for a dense \(D \times D\) factor. Memory and cost per step grow as \(O(D^2)\). |
AutoLowRankMultivariateNormalGuide |
Low-rank plus diagonal covariance | Hierarchical models with local correlations. rank defaults to 5. |
AutoLaplaceApproximation |
The Laplace approximation: a Normal at the MAP with covariance the inverse Hessian of the negative log posterior (Tierney and Kadane, 1986) | A quadratic approximation at the MAP, after AutoDeltaGuide. |
AutoNormalizingFlow |
A normalizing flow: a Normal base pushed through invertible learned maps (Rezende and Mohamed, 2015) | Multimodal or heavy-tailed posteriors. The caller passes the list of transforms. |
AutoIAFGuide |
Inverse autoregressive flow (IAF) (Kingma et al., 2016) | A general non-Gaussian guide. |
AutoNeuralSplineGuide |
Rational-quadratic neural spline flow (Durkan et al., 2019) | Posteriors on bounded support, where it is often more accurate than IAF. |
AutoMixtureGuide |
Mixture of at least two component guides | Multimodal posteriors. The objectives sum over the components exactly. |
AutoGuideList |
Different guides for different latent variables | Mixed families, given as a dict of component guides. |
AutoStructured |
One factor for each site, with chosen dependencies between sites | Keeping specific posterior dependencies. |
The inference benchmarks report how these guides recover known posteriors on a fixed set of problems.
Step 3: Which objective?¶
| Objective | Bound | When |
|---|---|---|
ELBO(num_particles=1) |
Evidence lower bound (ELBO) | Default. |
ELBO(num_particles=K) |
ELBO averaged over \(K\) draws | Lower gradient variance, with the bound itself unchanged. |
IWAEBound(num_particles=K) |
Importance weighted bound (Burda et al., 2016) | Tighter than the ELBO for \(K > 1\). |
RenyiBound(alpha, num_particles=K) |
Variational Rényi bound (Li and Turner, 2016) | Equals the ELBO at \(\alpha = 1\) and the importance weighted bound at \(\alpha = 0\). |
VRIWAEBound(alpha, num_particles=K) |
Variational Rényi importance weighted bound (Daudel et al., 2023) | \(\alpha\) moves the fit between covering the posterior's mass (\(\alpha\) near 0) and seeking one mode (\(\alpha\) near 1). \(K\) tightens it. |
ChiVI(n, num_particles=K) |
\(\chi^n\) upper bound (CUBO) (Dieng et al., 2017) | An upper bound on \(\log p(y)\), which with the ELBO brackets it. The objective minimizes \(\exp(n\,\mathrm{CUBO}_n)\) with an unbiased gradient. Needs \(K \ge 2\), \(n > 1\), and a guide that starts wider than the posterior. |
RWS(num_particles=K) |
Reweighted wake-sleep, wake phase (Bornschein and Bengio, 2015) | Separate model and guide updates from self-normalized importance weights. Takes no estimator. |
DReGsBound(num_particles=K) |
Importance weighted bound with doubly reparameterized gradients (Tucker et al., 2019) | Lower variance guide gradients at large \(K\). |
ELBO() is the usual starting point. An importance weighted bound gives a flow guide a tighter target when the posterior is multimodal. RenyiBound with \(\alpha < 1\) penalizes a guide that misses posterior mass more heavily than the ELBO does.
Step 4: Which gradient estimator?¶
| Estimator | What it does | When |
|---|---|---|
Reparameterized |
Reparameterization (pathwise) gradient (Kingma and Welling, 2014) | Default. |
StickingTheLanding |
Drops the score term of \(\log q\) by detaching the guide parameters in it (Roeder et al., 2017) | Noisy gradients near convergence, when the guide is close to the posterior. Valid for ELBO and other bounds that use one draw. Bounds that use several draws reject it. |
DoublyReparameterized |
Doubly reparameterized gradients (Tucker et al., 2019), extended to the Rényi and VR-IWAE bounds | IWAEBound(K) at large \(K\). ChiVI rejects it, and so does a mixture guide on a bound that uses several draws. |
ScoreFunction |
Score-function (REINFORCE) estimator with the draws held fixed (Ranganath et al., 2014) | Guides whose draws are not differentiable. |
IWAEBound(num_particles=16, estimator=DoublyReparameterized()) combines importance weighting with doubly reparameterized guide gradients. A larger \(K\) gives a tighter bound at a cost in time and memory, so choose it by profiling.
Calling SVI¶
from quivers.inference import (
AutoIAFGuide, IWAEBound, DoublyReparameterized, SVI,
)
guide = AutoIAFGuide(model, observed_names={"y"}, num_flows=4)
objective = IWAEBound(num_particles=16, estimator=DoublyReparameterized())
optimizer = torch.optim.Adam(
list(model.parameters()) + list(guide.parameters()), lr=1e-3,
)
svi = SVI(model, guide, optimizer, objective)
for step in range(5000):
loss = svi.step(x_data, {"y": y_data})
Calling NUTS¶
from quivers.inference import NUTSKernel, MCMC
kernel = NUTSKernel(
target_accept=0.85,
max_tree_depth=10,
mass_matrix="diagonal",
)
mcmc = MCMC(
kernel,
num_warmup=1000,
num_samples=2000,
num_chains=4,
init_strategy="prior",
)
result = mcmc.run(model, x_data, {"y": y_data})
print(result.r_hat) # per-site split-Rhat
print(result.ess) # per-site effective sample size
print("divergences:", result.total_divergences)
Check R-hat, effective sample size, and divergences before using the draws. Chapter 8 gives the thresholds and the usual remedies.
Hybrid samplers¶
WarmupThenHMC(guide, kernel, svi_steps, mcmc_warmup, mcmc_samples)runssvi_stepsof stochastic variational inference (SVI) and then starts MCMC chains from draws of the trained guide, which can shorten HMC's warmup.AutoDAIS(base, model, observations, num_steps=..., init_step_size=...)follows each draw of a base guide withnum_stepsHamiltonian transitions without accept or reject steps along an annealing path, as in differentiable annealed importance sampling (DAIS) (Zhang et al., 2021; Geffner and Domke, 2021). Each draw carries the importance weight of its own trajectory, soELBO()estimates a valid lower bound on the log evidence. It can represent posteriors that a mean-field guide misses, at extra cost. Use the defaultReparameterizedestimator, since the guide has no density at arbitrary points.
from quivers.inference import AutoDAIS, ELBO
base = AutoNormalGuide(model, observed_names={"y"})
guide = AutoDAIS(
base, model, observations={"y": y_data},
num_steps=8, init_step_size=0.05,
)
elbo = ELBO()
svi = SVI(model, guide, optimizer, elbo)
Predictive¶
Predictive takes the result of either kind of inference:
from quivers.inference import Predictive
# `posterior` accepts either a trained Guide or an MCMCResult
pred = Predictive(model, posterior=guide, num_samples=1000)
pred = Predictive(model, posterior=mcmc_result, num_samples=1000)
posterior_predictive = pred(x_test) # dict of (num_samples, ...) tensors
Try this¶
- Fit the eight-schools model of chapter 3 with each guide and compare the posterior of
tauwith a NUTS reference. - Fit the mixture of chapter 4 with an
AutoMixtureGuideof fourAutoNormalGuidecomponents and with oneAutoNormalGuide, and allow for label switching when comparing the modes found. - On a posterior whose high-density region is a ring, compare
AutoDAISwithAutoIAFGuide.
Next¶
Chapter 7 describes the composition rules behind >> and the maps between them.
Cited sources¶
Radford M. Neal. MCMC Using Hamiltonian Dynamics. In Steve Brooks, Andrew Gelman, Galin L. Jones, and Xiao-Li Meng, editors, Handbook of Markov Chain Monte Carlo, chapter 5, pages 113–162. Chapman and Hall/CRC, 2011. URL: https://doi.org/10.1201/b10905-6, doi:10.1201/b10905-6.
Matthew D. Hoffman and Andrew Gelman. The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo. Journal of Machine Learning Research, 15(47):1593–1623, 2014. URL: https://www.jmlr.org/papers/v15/hoffman14a.html.
David M. Blei, Alp Kucukelbir, and Jon D. McAuliffe. Variational Inference: A Review for Statisticians. Journal of the American Statistical Association, 112(518):859–877, 2017. URL: https://doi.org/10.1080/01621459.2017.1285773, doi:10.1080/01621459.2017.1285773.
Luke Tierney and Joseph B. Kadane. Accurate Approximations for Posterior Moments and Marginal Densities. Journal of the American Statistical Association, 81(393):82–86, 1986. URL: https://www.tandfonline.com/doi/abs/10.1080/01621459.1986.10478240, doi:10.1080/01621459.1986.10478240.
Danilo Rezende and Shakir Mohamed. Variational Inference with Normalizing Flows. In Proceedings of the 32nd International Conference on Machine Learning, volume 37 of Proceedings of Machine Learning Research, 1530–1538. 2015. URL: https://proceedings.mlr.press/v37/rezende15.html.
Diederik P. Kingma, Tim Salimans, Rafal Jozefowicz, Xi Chen, Ilya Sutskever, and Max Welling. Improved Variational Inference with Inverse Autoregressive Flow. In Advances in Neural Information Processing Systems, volume 29. 2016. URL: https://proceedings.neurips.cc/paper/2016/hash/ddeebdeefdb7e7e7a697e1c3e3d8ef54-Abstract.html.
Conor Durkan, Artur Bekasov, Iain Murray, and George Papamakarios. Neural Spline Flows. In Advances in Neural Information Processing Systems, volume 32. 2019. URL: https://proceedings.neurips.cc/paper/2019/hash/7ac71d433f282034e088473244df8c02-Abstract.html.
Yuri Burda, Roger Grosse, and Ruslan Salakhutdinov. Importance Weighted Autoencoders. In International Conference on Learning Representations. 2016. URL: https://www.iclr.cc/archive/www/2016.html.
Yingzhen Li and Richard E. Turner. Rényi Divergence Variational Inference. In Advances in Neural Information Processing Systems, volume 29. 2016. URL: https://proceedings.neurips.cc/paper/2016/hash/7750ca3559e5b8e1f44210283368fc16-Abstract.html.
Kamélia Daudel, Joe Benton, Yuyang Shi, and Arnaud Doucet. Alpha-divergence Variational Inference Meets Importance Weighted Auto-Encoders: Methodology and Asymptotics. Journal of Machine Learning Research, 24(243):1–83, 2023. URL: https://jmlr.org/papers/v24/22-1160.html.
Adji Bousso Dieng, Dustin Tran, Rajesh Ranganath, John Paisley, and David Blei. Variational Inference via Chi Upper Bound Minimization. In Advances in Neural Information Processing Systems, volume 30. 2017. URL: https://proceedings.neurips.cc/paper/2017/hash/35464c848f410e55a13bb9d78e7fddd0-Abstract.html.
Jörg Bornschein and Yoshua Bengio. Reweighted Wake-Sleep. In International Conference on Learning Representations. 2015. URL: https://iclr.cc/archive/www/2015.html.
George Tucker, Dieterich Lawson, Shixiang Gu, and Chris J. Maddison. Doubly Reparameterized Gradient Estimators for Monte Carlo Objectives. In International Conference on Learning Representations. 2019. URL: https://openreview.net/forum?id=HkG3e205K7.
Diederik P. Kingma and Max Welling. Auto-Encoding Variational Bayes. In International Conference on Learning Representations. 2014. Accepted conference paper; manuscript available as arXiv:1312.6114. URL: https://arxiv.org/abs/1312.6114, doi:10.48550/arXiv.1312.6114.
Geoffrey Roeder, Yuhuai Wu, and David Duvenaud. Sticking the Landing: Simple, Lower-Variance Gradient Estimators for Variational Inference. In Advances in Neural Information Processing Systems, volume 30. 2017. URL: https://proceedings.neurips.cc/paper/2017/hash/e91068fff3d7fa1594dfdf3b4308433a-Abstract.html.
Rajesh Ranganath, Sean Gerrish, and David Blei. Black Box Variational Inference. In Proceedings of the Seventeenth International Conference on Artificial Intelligence and Statistics, volume 33 of Proceedings of Machine Learning Research, 814–822. 2014. URL: https://proceedings.mlr.press/v33/ranganath14.html.
Guodong Zhang, Kyle Hsu, Jianing Li, Chelsea Finn, and Roger B. Grosse. Differentiable Annealed Importance Sampling and the Perils of Gradient Noise. In Advances in Neural Information Processing Systems, volume 34. 2021. URL: https://proceedings.neurips.cc/paper/2021/hash/a1a609f1ac109d0be28d8ae112db1bbb-Abstract.html.
Tomas Geffner and Justin Domke. MCMC Variational Inference via Uncorrected Hamiltonian Annealing. In Advances in Neural Information Processing Systems, volume 34. 2021. URL: https://arxiv.org/abs/2107.04150, doi:10.48550/arXiv.2107.04150.