Variational Inference in Stan

Variational inference is a scalable technique for approximate Bayesian inference. Stan implements an automatic variational inference algorithm, called Automatic Differentiation Variational Inference (ADVI) which searches over a family of simple densities to find the best approximate posterior density. ADVI produces an estimate of the parameter means together with a sample from the approximate posterior density.

ADVI approximates the variational objective function, the evidence lower bound or ELBO, using stochastic gradient ascent. The algorithm ascends these gradients using an adaptive stepsize sequence that has one parameter eta which is adjusted during warmup. The number of draws used to approximate the ELBO is denoted by elbo_samples. ADVI heuristically determines a rolling window over which it computes the average and the median change of the ELBO. When this change falls below a threshold, denoted by tol_rel_obj, the algorithm is considered to have converged.

Example: variational inference for model bernoulli.stan

In CmdStanPy, the CmdStanModel class method variational invokes CmdStan with method=variational and returns an estimate of the approximate posterior mean of all model parameters as well as a set of draws from this approximate posterior.

import os
from cmdstanpy.model import CmdStanModel
from cmdstanpy.utils import cmdstan_path

bernoulli_dir = os.path.join(cmdstan_path(), 'examples', 'bernoulli')
stan_file = os.path.join(bernoulli_dir, 'bernoulli.stan')
data_file = os.path.join(bernoulli_dir, '')
# instantiate, compile bernoulli model
model = CmdStanModel(stan_file=stan_file)
# run CmdStan's variational inference method, returns object `CmdStanVB`
vi = model.variational(data=data_file)
INFO:cmdstanpy:found newer exe file, not recompiling
INFO:cmdstanpy:compiled model file: /home/docs/checkouts/
INFO:cmdstanpy:start chain 1
INFO:cmdstanpy:finish chain 1

The class `CmdStanVB <>`__ provides the following properties to access information about the parameter names, estimated means, and the sample: + column_names + variational_params_dict + variational_params_np + variational_params_pd + variational_sample

('lp__', 'log_p__', 'log_g__', 'theta')
(1000, 4)

These estimates are only valid if the algorithm has converged to a good approximation. When the algorithm fails to do so, the variational method will throw a RuntimeError.

model_fail = CmdStanModel(stan_file='eta_should_fail.stan')
vi_fail = model_fail.variational()
INFO:cmdstanpy:compiling stan program, exe file: /home/docs/checkouts/
INFO:cmdstanpy:compiler options: stanc_options={}, cpp_options={}
INFO:cmdstanpy:compiled model file: /home/docs/checkouts/
INFO:cmdstanpy:start chain 1
INFO:cmdstanpy:finish chain 1
RuntimeError                              Traceback (most recent call last)
/tmp/ipykernel_27718/ in <module>
      1 model_fail = CmdStanModel(stan_file='eta_should_fail.stan')
----> 2 vi_fail = model_fail.variational()

~/checkouts/ in variational(self, data, seed, inits, output_dir, sig_figs, save_latent_dynamics, save_profile, algorithm, iter, grad_samples, elbo_samples, eta, adapt_engaged, adapt_iter, tol_rel_obj, eval_elbo, output_samples, require_converged, show_console, refresh, time_fmt)
   1248             if require_converged:
   1249                 raise RuntimeError(
-> 1250                     'The algorithm may not have converged.\n'
   1251                     'If you would like to inspect the output, '
   1252                     're-call with require_converged=False'

RuntimeError: The algorithm may not have converged.
If you would like to inspect the output, re-call with require_converged=False

Unless you set require_converged=False:

vi_fail = model_fail.variational(require_converged=False)
INFO:cmdstanpy:start chain 1
INFO:cmdstanpy:finish chain 1
WARNING:cmdstanpy:The algorithm may not have converged.
Proceeding because require_converged is set to False

This lets you inspect the output to try to diagnose the issue with the model

OrderedDict([('lp__', 0.0),
             ('log_p__', 0.0),
             ('log_g__', 0.0),
             ('mu[1]', -0.0274604),
             ('mu[2]', 0.00105762)])

See the api docs, section `CmdStanModel.variational <>`__ for a full description of all arguments.