Skip to content

Variational Inference: Guides, Objectives, and SVI

Variational inference approximates the posterior by the closest member of a tractable family of distributions (Blei et al., 2017). In quivers the family is a guide, the closeness is measured by an objective whose gradient an estimator computes, and SVI optimizes the guide by stochastic gradient steps. Every guide reads the trace, conditioning, and latent registry of Inference Foundations, and MCMC and Hybrid Samplers covers sampling instead.

Guides: variational families

A guide \(q_\phi(z \mid x, y)\) is a distribution over the latent sites with adjustable parameters \(\phi\), fitted to approximate the posterior, as in Pyro (Pyro Developers, n.d.-g). If z is an unknown mean, a simple guide learns a center and a spread for z. The model still gives the prior and the likelihood, the guide gives candidate latent values and their density, and observed sites stay fixed to the data throughout fitting.

A diagonal, or mean-field, normal guide treats the latent coordinates as independent in their unconstrained representation. A full-covariance normal represents linear correlations at the cost of more parameters, a flow can bend the density, and a mixture can put mass near several separated modes. Comparing families means fitting each from several initializations and comparing their ELBOs and posterior predictive draws.

The Auto* guides are built from a model and a set of observed site names (Variational Guides). The guides of a single family are below. AutoGuideList and AutoStructured combine guides for different sites into one family, and AmortizedGuide computes each datum's approximation with an encoder.

Guide Posterior structure When to use
AutoNormalGuide Diagonal Normal (mean-field) Default; an identifiable posterior with weak correlation
AutoMultivariateNormalGuide Full-rank Normal (Cholesky) Strong posterior correlations; \(D \lesssim 1000\)
AutoLowRankMultivariateNormalGuide Low-rank + diagonal Hierarchical models with localized correlations
AutoLaplaceApproximation Gaussian centered at the maximum a posteriori (MAP) point with covariance \(-H^{-1}\), the negative inverse Hessian of the log joint density Laplace approximation at a mode (Tierney and Kadane, 1986)
AutoNormalizingFlow Composed bijectors over a normal base (Rezende and Mohamed, 2015) Skewed or curved posterior densities
AutoIAFGuide Inverse autoregressive flow (Kingma et al., 2016) Autoregressive transformed approximation
AutoNeuralSplineGuide Rational-quadratic spline coupling (Durkan et al., 2019) Flexible spline transformations
AutoMixtureGuide K-component mixture of guides Multimodal posteriors
AutoDeltaGuide Dirac at MAP Quick MAP; no uncertainty

Every guide maps each site through the bijector biject_to(support) of its prior's support (Inference Foundations), so its samples lie inside that support, and its log_prob includes the log absolute determinant of the Jacobian.

An input of B rows is B independent runs of the program, and a guide's law is a law over the latents of one run. log_prob(x, sites) returns B log densities, and entry b is the density of run b's values alone: it equals what log_prob gives for a one-row input holding run b's values, whatever the other runs hold. A site's value has a leading run axis, shape (B, *constrained_shape), or has the site's constrained_shape and is one value every run shares, which then enters every run's density in full. Any other shape is refused, so a run axis of size one does not stand for B runs. Every guide reads site values per run through LatentRegistry.unconstrain_runs, which also keeps each run's Jacobian term apart. The draws rsample gives the runs each follow the guide's law but need not be independent: a guide with one joint draw, such as AutoMultivariateNormalGuide, a flow, AutoStructured, or AutoLaplaceApproximation, gives every run the same draw.

Guides and named initialization use the same LatentSite geometry. Unconstrained coordinates are flat within each site; constrained values retain their declared event axes, including rectangular matrices and singleton matrix dimensions. The shared transform reduces Jacobians over the support's event axes while retaining run and plate axes. Thus a matrix event does not acquire extra independent observations when a guide evaluates its density, and subsampling still selects the declared plate rows.

AutoNormalGuide

A diagonal Gaussian approximation with one bijector per site, which maps unconstrained normal draws into the prior's support:

\[q_\phi(z_i \mid x, y) = T_i\bigl(\,\mathcal{N}(\mu_i, \sigma_i)\,\bigr)\]

where \(T_i = \mathsf{biject\_to}(\mathrm{support}(p_i))\) is the bijector for site \(i\)'s prior support: the identity on the real line for Normal, \(\exp\) for HalfNormal / Gamma / Exponential / LogNormal, sigmoid for Beta / Uniform(0, 1) / LogitNormal, a shifted and scaled sigmoid for arbitrary Uniform(low, high) / TruncatedNormal, and StickBreakingTransform for Dirichlet. The learnable parameters \((\mu_i, \sigma_i)\) live in the unconstrained space, and the constrained draw \(v_i = T_i(z_i)\) is always inside the prior's support, so prior.log_prob(v_i) never raises a support error.

from quivers.inference import AutoNormalGuide

model = ...  # MonadicProgram
conditioned = condition(model, observations)

guide = AutoNormalGuide(conditioned.model, observed_names=set(observations))

# Sample latents from guide (each lives in its prior's support)
latents = guide.rsample(x)  # {name: (batch, *constrained_shape)}; plates: constrained_shape

# Log probability under guide (with Jacobian correction)
log_q = guide.log_prob(x, latents)

Named initial centers

AutoNormalGuide(initial_values={...}) accepts natural-scale values keyed by latent site name. A given value \(v_i\) sets the unconstrained Normal location to \(T_i^{-1}(v_i)\); the transformed guide's expectation can differ from \(v_i\). Unspecified locations remain zero, and init_scale sets the unconstrained standard deviations, with default 0.1.

import torch

from quivers.dsl import loads
from quivers.inference import AutoNormalGuide, ELBO, SVI

model = loads("""
object Obs : FinSet 3
program model : Obs -> Obs
    let mu <- sample Normal(loc=0.0, scale=1.0)
    let sigma <- sample HalfNormal(scale=1.0)
    observe y : Obs <- Normal(loc=mu, scale=sigma)
    return mu
export model
""").morphism

observations = {"y": torch.tensor([0.1, 0.4, 0.8])}
guide = AutoNormalGuide(
    model,
    observed_names={"y"},
    initial_values={"mu": 0.4, "sigma": 0.5},
)
optimizer = torch.optim.Adam(guide.parameters(), lr=0.01)
svi = SVI(model, guide, optimizer, ELBO())
loss = svi.step(torch.zeros(1, 1), observations)
assert torch.isfinite(torch.tensor(loss))

The same support and shape rules as MCMC apply: scalars broadcast, tensors match the site's complete declared shape, and values lie strictly inside its support. The guide detaches and copies the values into trainable parameters; it retains no gradient connection to the caller's tensors. This constructor option belongs to AutoNormalGuide; other guide families have their own initialization interfaces.

AutoDeltaGuide

A delta guide puts all its mass on one fitted value, a Dirac measure, so repeated draws return that value, and fitting it gives a MAP estimate. The point lives in the unconstrained space and passes through biject_to(support) when it is evaluated, so it lies inside the prior's support:

\[q_\phi(z_i \mid x, y) = \delta_{T_i(\zeta_i)}(z_i)\]

where \(\zeta_i\) is the learnable unconstrained point and \(T_i\) the same bijector as for AutoNormalGuide. A point mass has no density with respect to Lebesgue measure, so the identity between the ELBO and the KL divergence in ELBO does not apply to it.

from quivers.inference import AutoDeltaGuide

guide = AutoDeltaGuide(conditioned.model, observed_names=set(observations))

# Point estimate (deterministic, inside the prior's support)
z_map = guide.rsample(x)

# Delta log probability (zero; the delta term cancels in the ELBO)
log_q = guide.log_prob(x, z_map)

AutoMixtureGuide

A mixture guide combines \(K\) component guides with learnable weights \(\pi = \mathrm{softmax}(\texttt{mixture\_logits})\):

\[q_\phi(z) = \sum_{k=1}^{K} \pi_k\, q_k(z).\]

Each component may be any guide, so a mixture of AutoNormalGuide instances can place one component on each of several separated modes. log_prob evaluates the mixture density with a log-sum-exp over the components. rsample draws from that density: it picks a component index \(k \sim \mathrm{Categorical}(\pi)\) and returns component \(k\)'s draw, so predictive sampling from a fitted mixture guide reproduces the distribution that log_prob scores. Its draws carry gradient to the chosen component's parameters but not to the mixture logits, since the component choice is discrete.

Training does not go through rsample. Every objective calls Guide.rsample_strata, which a mixture implements by enumerating its components: one reparameterized draw \(z_k \sim q_k\) per component, weighted by \(\pi_k\). The ELBO is thus estimated as the stratified ELBO (Morningstar et al., 2021)

\[\mathcal{L}(\phi) = \sum_{k=1}^{K} \pi_k\, \mathbb{E}_{q_k}\bigl[\log p(y, z \mid x) - \log q_\phi(z)\bigr],\]

which equals the ELBO of the mixture density exactly. Gradients reach the component parameters through each reparameterized draw and reach the mixture logits through the finite sum. The importance-weighted objectives use the same weights: IWAEBound becomes the stratified IWAE bound \(\log \frac{1}{K'}\sum_{j}\sum_{k} \pi_k\, p(y, z_{jk})/q_\phi(z_{jk})\) over \(K'\) particles, and RenyiBound, VRIWAEBound, ChiVI, and RWS weight each draw the same way. A mixture nested inside another mixture or inside an AutoGuideList part is enumerated as well (an AutoGuideList takes the product of its parts' strata), so each step costs \(K\) model evaluations per particle.

The DoublyReparameterized estimator rewrites the score of the density each particle was drawn from, and stratified draws come from the components rather than from \(q_\phi\). It thus raises an error with a mixture guide. IWAEBound(num_particles=K, estimator=Reparameterized()) and StickingTheLanding() work with one.

from quivers.inference import ELBO, SVI, AutoMixtureGuide, AutoNormalGuide

components = [
    AutoNormalGuide(conditioned.model, observed_names=set(observations))
    for _ in range(3)
]
guide = AutoMixtureGuide(components)
svi = SVI(conditioned.model, guide, optimizer, ELBO(num_particles=4))

# After fitting: draws from the mixture density q
z = guide.rsample(x)
weights = guide.mixture_weights()

AmortizedGuide

In amortized inference the variational posterior of a latent is a kernel applied to the data, \(q_\phi(z \mid y) = e_\phi(y)\), as in the encoder of a variational autoencoder (Kingma and Welling, 2014). One set of encoder weights then serves every datum, new ones included. AmortizedGuide runs such kernels: each binding names a latent site, an encoder (any ContinuousMorphism with an exact density, such as a declared morphism or deterministic layers followed by one stochastic kernel), and the datum it reads.

The encoder is applied to every row of its datum. A site drawn once per run reads a datum with a leading batch axis, so an input of B rows (B independent runs) gives each run its own posterior. A local latent in a plate reads one datum row per plate row. When the encoder's support is the site's support its draw is the site's value. When the encoder is real-valued and the site is not, the draw passes through the site's bijector \(T\) and the density carries the Jacobian, \(\log q(v) = \log e(T^{-1}(v) \mid y) + \log |\det J_{T^{-1}}(v)|\). The guide checks each binding against the registry and refuses an unknown site, an encoder whose support or event size does not fit, a datum that is missing or whose rows do not line up with the site, and a composition with a stochastic hidden layer, whose log_prob scores a reference path rather than a density.

The data reach the guide through Guide.observe, which every objective calls with the step's observations. Calling it directly samples the posterior of held-out data. Sites without an encoder go to another guide in an AutoGuideList, and uncovered_sites lists them. Every objective and estimator applies, since the guide has a reparameterized sampler and a density at any point.

import torch

from quivers.dsl import loads
from quivers.inference import ELBO, SVI, AmortizedGuide

source = """
object UnitSpace : Real 1
object Latent : Real 2
object ObsSpace : Real 4

morphism prior : UnitSpace -> Latent ~ Normal
morphism decoder : Latent -> ObsSpace [param_source=mlp(32)] ~ Normal

program vae : UnitSpace -> ObsSpace
    let z <- sample prior
    observe y <- decoder(z)
    return y

export vae
"""
encoder_source = """
object ObsSpace : Real 4
object Latent : Real 2
morphism encoder : ObsSpace -> Latent [param_source=mlp(32)] ~ Normal
export encoder
"""
model = loads(source).morphism
encoder = loads(encoder_source).morphism

y = torch.randn(256, 4)                 # one datum per run
x = torch.zeros(256, 1)                 # 256 independent runs
guide = AmortizedGuide(model, {"y"}, {"z": (encoder, "y")}, x=x, observations={"y": y})
params = list(model.parameters()) + list(guide.parameters())
svi = SVI(model, guide, torch.optim.Adam(params, lr=1e-2), ELBO(num_particles=4))
losses = [svi.step(x, {"y": y}) for _ in range(200)]

y_new = torch.randn(10, 4)
guide.observe({"y": y_new})             # the posterior of new data
z_new = guide.rsample(torch.zeros(10, 1))["z"]
print(losses[0], losses[-1])   # the negative ELBO falls
print(z_new.shape)             # (10, 2)

Objectives and gradient estimators

The objective is the quantity the fit optimizes, and the gradient estimator is how its derivatives are estimated from random draws. They are separate choices: two estimators can target one objective with different variance and applicability. A particle is one set of latent draws in a Monte Carlo estimate, and more particles reduce sampling noise at more cost. The reparameterization (pathwise) estimator differentiates through a draw written as mu + sigma * epsilon (Kingma and Welling, 2014), and the score-function estimator uses the derivative of the sampling log density, which also works when the draw is not differentiable (Ranganath et al., 2014). The ELBO with its default estimator is the usual starting point.

SVI accepts any Objective subclass. The objectives are:

Objective Bound Use case
ELBO(num_particles=K) \(\mathbb{E}_q[\log p - \log q]\) Default
IWAEBound(K, estimator=...) \(\mathbb{E}[\log \tfrac{1}{K}\sum_k (p/q)_k]\) Tighter than ELBO for \(K > 1\) (Burda et al., 2016)
RenyiBound(alpha, K) \(\alpha\)-divergence bound (Li and Turner, 2016) \(\alpha = 0\) recovers IWAE; \(\alpha \to 1\) recovers the ELBO in the limit (the constructor rejects alpha == 1.0 as numerically singular, and ELBO computes that case)
VRIWAEBound(alpha, K) Variational Rényi-IWAE (Daudel et al., 2023) Controls the tradeoff between computation and approximation
ChiVI(n, K) \(\chi^n\) upper bound \(\mathrm{CUBO}_n = \tfrac{1}{n}\log \mathbb{E}_q[(p/q)^n]\) (Dieng et al., 2017) Over-covering approximation; minimizes \(\exp(n\,\mathrm{CUBO}_n)\) with an unbiased gradient and reports the \(K\)-sample CUBO estimate for the sandwich \(\mathrm{ELBO} \le \log p(y) \le \mathrm{CUBO}_n\)
RWS(K) Reweighted wake-sleep, wake phase (Bornschein and Bengio, 2015) Importance-weighted wake updates with the draws held fixed; not a bound, takes no estimator
DReGsBound(K) IWAE bound with a doubly reparameterized gradient (Tucker et al., 2019) Switch the IWAE bound and DReG estimator together

ELBO, IWAEBound, RenyiBound, VRIWAEBound, and DReGsBound are Monte Carlo estimates of the variational Rényi bound family (Li and Turner, 2016), computed as a power mean of the log importance ratios \(\ell_k = \log p(z_k, y) - \log q_\phi(z_k)\) of the draws:

\[B_a = \frac{1}{a}\log \frac{1}{K}\sum_{k=1}^{K} e^{a \ell_k},\]

with exponent \(a = 0\) (the ELBO, read as the mean of \(\ell_k\)), \(a = 1\) (IWAE), or \(a = 1 - \alpha\) (Rényi and VR-IWAE). Each accepts an estimator= strategy, which estimates the gradient of \(\mathbb{E}[B_a]\) for both the guide and the model parameters. DReGsBound fixes the strategy to DoublyReparameterized, and RWS takes none.

ChiVI is an upper bound, and the log of a Monte Carlo average is biased downward by Jensen's inequality, so minimizing the \(K\)-sample estimate \(\tfrac{1}{n}\log \tfrac{1}{K}\sum_k w_k^n\) would neither keep the bounding property nor give an unbiased gradient. Following Dieng et al. (Dieng et al., 2017), ChiVI minimizes the exponentiated bound \(L_n = \exp(n\,\mathrm{CUBO}_n) = \mathbb{E}_q[w^n]\), which has the same minimizers and the unbiased estimate \(\tfrac{1}{K}\sum_k w_k^n\). To avoid overflow, particle \(k\)'s term is divided by \(e^{m_{-k}}\), where \(m_{-k}\) is the largest \(n \log w_j\) among the other particles. That scale is independent of particle \(k\)'s draws, so the expected update is a positive multiple of \(\nabla L_n\) and the stationary points are unchanged. ChiVI thus needs num_particles >= 2 and an order \(n > 1\). The value it returns is the \(K\)-sample CUBO estimate, directly comparable with the negated ELBO loss. It is biased downward at finite \(K\), so for small \(K\) it can fall below \(\log p(y)\), and the bias vanishes as \(K\) grows. Start ChiVI from a guide wider than the posterior: the gradient's variance is finite only when \(\mathbb{E}_q[w^{2n}]\) is.

Estimator What it does
Reparameterized Pathwise gradient of \(B_a\) (default except for IWAEBound)
StickingTheLanding Detaches the variational parameters in log_q (Roeder et al., 2017), whose variance goes to 0 as \(q \to p^*\)
DoublyReparameterized DReG (Tucker et al., 2019; Daudel et al., 2023): rewrites the score term with the reparameterization identity, weighting draw \(k\) by \((1-a)\bar w_k + a \bar w_k^2\) with \(\bar w = \mathrm{softmax}(a\ell)\); default for IWAEBound
ScoreFunction REINFORCE (Ranganath et al., 2014): the objective draws from the guide and holds the draws fixed, so the guide's rsample need not be differentiable

Not every pair has an unbiased estimator. Dropping the score term, as sticking the landing does, is unbiased only when that term has mean zero: for the ELBO, or for a single draw. The objectives check the pair at construction and on every call, and raise ValueError naming a valid estimator instead of silently using another one:

Objective Reparameterized StickingTheLanding DoublyReparameterized ScoreFunction
ELBO yes yes yes (equals sticking the landing) yes
IWAEBound, RenyiBound, VRIWAEBound yes only with num_particles=1 yes yes
ChiVI yes (Dieng et al., Eq. 3) no no yes (their Algorithm 1)
any of the above with an AutoMixtureGuide yes ELBO only ELBO only yes (independent draws)
from quivers.inference import IWAEBound, DoublyReparameterized

iwae = IWAEBound(num_particles=16, estimator=DoublyReparameterized())
loss = iwae(model, guide, x, observations)

Objectives with several particles run a Python for loop over num_particles, calling guide.rsample_strata once per particle and model.log_joint once per stratum, and stack the log-densities into a leading (K * S, batch) axis with a log weight for each draw. An ordinary guide returns a single stratum (\(S = 1\), equal weights \(1/K\)), and an AutoMixtureGuide returns one stratum per component, weighted by the mixture weights. torch.distributions and the model runtime are not vectorized over a Monte Carlo dimension, so the cost scales linearly in the number of draws.

ELBO: evidence lower bound

The evidence lower bound is

\[\mathcal{L}(\phi) = \mathbb{E}_{q_\phi(z \mid x, y)} [\log p(y, z \mid x) - \log q_\phi(z \mid x, y)].\]

Its first term rewards latent values that the prior and the data support, and the second, the guide's entropy, rewards spreading mass over them (Pyro Developers, n.d.-g). For a guide with a density and the required finite expectations,

\[ \log p(y\mid x)-\mathcal L(\phi) =\mathrm{KL}\bigl(q_\phi(z\mid x,y)\,\|\,p(z\mid x,y)\bigr)\ge 0, \]

so \(\mathcal L\) is a lower bound on the log marginal likelihood, equal to it when \(q_\phi\) is the posterior, and maximizing it minimizes the KL divergence to the posterior. The optimizer minimizes the negative ELBO. A diagonal guide can reach its best ELBO while missing a correlation between two latent variables, which a full-covariance guide would show, and replicated observations compared with the data show predictive fit. The observed values reach the objective in the observations dict, passed to ELBO.forward and SVI.step with the input.

The ELBO class computes:

from quivers.inference import ELBO

model = ...  # MonadicProgram (joint p)
guide = ...  # variational q

elbo = ELBO(num_particles=10)

# Compute loss
x = torch.zeros(1, 1)
observations = {"y": y_obs}
loss = elbo(model, guide, x, observations)  # negative ELBO (for minimization)

loss.backward()  # backprop through both model and guide

Internally, the ELBO:

  1. Draws latent variables with guide.rsample_strata(): one draw \(z \sim q_\phi(\cdot \mid x, y)\) with weight \(\omega = 1\) for an ordinary guide, or one draw per component with weight \(\pi_k\) for an AutoMixtureGuide.
  2. Computes \(\log p(y, z \mid x)\) via model.log_joint().
  3. Computes \(\log q_\phi(z \mid x, y)\) via guide.log_prob().
  4. Returns \(\frac{1}{n}\sum_i \sum_s \omega_{s} [\log q - \log p]\) over the \(n\) particles and their strata \(s\).

SVI: stochastic variational inference

Stochastic variational inference optimizes the objective with gradients estimated from draws (Hoffman et al., 2013). The SVI loop updates the model's and the guide's parameters together:

from quivers.inference import ELBO, SVI
import torch.optim as optim

model = ...   # MonadicProgram
guide = ...   # Guide
elbo  = ELBO(num_particles=5)

optimizer = optim.Adam(
    list(model.parameters()) + list(guide.parameters()),
    lr=1e-3,
)

svi = SVI(model, guide, optimizer, elbo)

# Training loop
for step in range(100):
    loss = svi.step(x, observations)
    print(f"Step {step}: loss={loss:.4f}")

step computes the loss, backpropagates, and steps the optimizer. Each input row is an independent run with its own guide draws, so a minibatch of input rows is a minibatch of runs, and a program whose observations live in a plate takes an input with one row.

SVI.run(x, observations, num_steps=n) repeats step and returns the losses. A non-finite objective raises an error naming the step. At the first step the objective is drawn again instead, up to 100 times and without a parameter update, because a draw of the untrained guide may fall outside the support of the model. The MCMC driver redraws a non-finite initial position in the same way.

Minibatches: subsampled plates

A program whose records live in a plate scores every record on every step. Stochastic variational inference (Hoffman et al., 2013) scores a random subset of the records instead and multiplies their contribution by the number of records over the subset's size. The minibatch estimate of the ELBO is then unbiased for the ELBO of the full data, and so is its gradient, so SVI converges to the same posterior while each step reads only the subset's observations.

subsample does this for one plate. Inside its block, every site whose plate axes include the plate, a plate latent or an observation, is scored at the index's rows, times the plate's size N over the index's size B. The global sites, the latents outside the plate, are scored in full and unscaled, so the prior and the guide's global entropy count once per step rather than once per record. Several blocks compose: a site in two subsampled plates takes the product of the two factors, and a site in one of two sibling plates takes its own plate's factor alone. A trace records each scaled site's factor as metadata["subsample_scale"].

object Item : FinSet 40

program mean_model : Item -> Item
    let mu <- sample Normal(loc=0.0, scale=1.0)
    observe y : Item <- Normal(loc=mu, scale=1.0)
    return mu

export mean_model
import torch
from quivers.dsl import load
from quivers.effects import subsample
from quivers.inference import ELBO, SVI, AutoNormalGuide

model = load("mean_model.qvr").morphism   # the program above
y = torch.randn(40) + 1.0                 # one observation per Item

guide = AutoNormalGuide(model, {"y"})
svi = SVI(model, guide, torch.optim.Adam(guide.parameters(), lr=0.02), ELBO())
x = torch.zeros(1, 1)
for step in range(1500):
    index = torch.randperm(40)[:8].sort().values
    with subsample("Item", index):
        svi.step(x, {"y": y[index]})

The index lists distinct rows in increasing order. An observation may be given at the subset's size, as above, its rows read in the order of the index, or at the plate's full extent. Within a run the plate keeps its declared extent: its latents are drawn at every row and the program's lets compute every row, so a row outside the subset keeps a well-defined value and only its score is left out. The saving is thus in the scored terms and in the data a step reads, not in the lets of the program.

A local latent inside the subsampled plate, one variable per record, is handled by AutoNormalGuide, whose density factors over the plate's rows: it scores the latent at the subset's rows with the same factor, and a row outside the subset receives no gradient from the step. AmortizedGuide factors over the rows in the same way and scores the subset's rows with the same factor. Its encoder reads every row of its datum, since the latent is drawn at every row of the plate, so the observation the encoder reads is passed at the plate's full extent. AutoDeltaGuide, whose density is constant, also admits it. A guide whose density couples the rows, such as AutoMultivariateNormalGuide, refuses a local latent in a subsampled plate rather than score a biased objective. It remains usable when the plate holds only observations.

Only an objective linear in the log joint stays unbiased under subsampling: the ELBO, with any number of particles and any gradient estimator. The importance-weighted and Rényi bounds, ChiVI, and RWS exponentiate or self-normalize the log weights and refuse a subsampled plate, and so do the consumers of the exact posterior, MCMC and PotentialFn, the Laplace approximation, AutoDAIS, and lift_to_bayesian_program. A plate whose extent the program leaves to its data is refused.

A marginalize block is subsampled by its units. Subsampling the plate a block is grouped over keeps some groups, each scored with all its rows, and scales their sum. Subsampling the plate of the rows does the same when the rows of each group are kept together, and a subset that splits a group is refused, since rows that share a class have no scores of their own.

Predictive sampling

The posterior predictive distribution has two sources of variation, uncertainty about z and response noise given z, and drawing from both gives replicated or future observations:

\[p(y_\text{new} \mid x_\text{new}, \text{observations}) = \int p(y_\text{new} \mid z, x_\text{new}) \, p(z \mid x, y_\text{obs}) \, dz\]

With a guide, the fitted \(q\) replaces the exact posterior in this integral, and the result inherits the guide's limitations.

from quivers.inference import Predictive

predictive = Predictive(
    model=conditioned.model,
    posterior=guide,
    num_samples=1000,
)

# Sample from posterior predictive
x_new = torch.zeros(1, 1)
samples = predictive(x_new)              # dict[str, torch.Tensor]
y_new_samples = samples["y"]             # shape (num_samples, batch, ...)

# Posterior mean and credible intervals
y_mean = y_new_samples.mean(dim=0)
y_low = y_new_samples.quantile(0.025, dim=0)
y_high = y_new_samples.quantile(0.975, dim=0)

The Predictive driver:

  1. Samples latents from the guide: \(z \sim q_\phi(\cdot \mid x, y_\text{obs})\).
  2. Samples outcomes: \(y_\text{new} \sim p(\cdot \mid z, x_\text{new})\).
  3. Returns the ensemble.

Full example: Bayesian linear regression

The slope \(w\) is one random variable shared by all responses, and each response has its own known predictor: \(y_n \sim \mathcal N(w x_n, 0.1^2)\). The binding let mu = w * predictor computes every response's mean before the observation is scored, and the input is one row, since the 100 responses come from the plate Row.

import torch
from quivers.dsl import loads
from quivers.inference import AutoNormalGuide, ELBO, SVI

program = loads("""
object Row : FinSet 100
object Value : Real 1
program regression : Row -> Value
    let w <- sample Normal(loc=0.0, scale=1.0)
    let mu = w * predictor
    observe y : Row <- Normal(loc=mu, scale=0.1)
    return y
export regression
""").morphism

x_obs = torch.linspace(-1.0, 1.0, 100)
y_obs = 2.0 * x_obs + 0.1 * torch.randn(100)
observations = {"predictor": x_obs, "y": y_obs}
domain_input = torch.zeros(1, 1)   # one run; its 100 rows come from Row
guide = AutoNormalGuide(program, observed_names={"y"})
optimizer = torch.optim.Adam(
    list(program.parameters()) + list(guide.parameters()), lr=1e-2
)
svi = SVI(program, guide, optimizer, ELBO(num_particles=5))
for _ in range(500):
    loss = svi.step(domain_input, observations)

# Summarize the slope site itself, not the returned response.
w_draws = torch.stack([guide.rsample(domain_input)["w"] for _ in range(500)])
print(w_draws.mean(), w_draws.quantile(0.025), w_draws.quantile(0.975))

predictor is a data input and y the observed responses, so w is the only latent site. The intervals summarize the fitted guide, so inspect fit quality before interpreting them as posterior uncertainty.

Custom guides

A custom guide subclasses Guide and gives latent_names, rsample, which returns one draw per input row of every latent site it covers, and log_prob, which returns one log density per row, the density of that row's values alone. A normal guide for the slope of the regression above:

import torch
from torch.distributions import Normal
from quivers.inference.guides import Guide

class SlopeGuide(Guide):
    def __init__(self, site: str):
        super().__init__()
        self._site = site
        self.loc = torch.nn.Parameter(torch.zeros(1))
        self.log_scale = torch.nn.Parameter(torch.zeros(1))

    @property
    def latent_names(self) -> list[str]:
        return [self._site]

    def rsample(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
        q = Normal(self.loc, self.log_scale.exp())
        return {self._site: q.rsample((x.shape[0],))}   # (batch, 1)

    def log_prob(self, x: torch.Tensor, sites: dict[str, torch.Tensor]) -> torch.Tensor:
        q = Normal(self.loc, self.log_scale.exp())
        return q.log_prob(sites[self._site]).sum(-1)     # (batch,)

guide = SlopeGuide("w")
svi = SVI(program, guide, torch.optim.Adam(guide.parameters(), lr=2e-2), ELBO(num_particles=5))
for _ in range(800):
    svi.step(domain_input, observations)

The objectives draw through Guide.rsample_strata, which returns GuideDraw records: the sites, the guide log-density the objective pairs with them, and a log weight for each stratum. Its default returns one draw from rsample, scored by log_prob, with weight one. A guide whose sampler makes a discrete choice that rsample cannot reparameterize overrides it to return weighted strata whose weighted average estimates expectations under the guide, as AutoMixtureGuide does. A guide whose density exists only along the path that produced a draw returns that density with the draw, as AutoDAIS does.

Cited sources

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.

Pyro Developers. SVI part I: an introduction to stochastic variational inference in Pyro. Pyro Tutorials, version 1.9.1, n.d.-g. URL: https://pyro.ai/examples/svi_part_i.html (visited on 2026-11-06).

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.

Warren R. Morningstar, Sharad M. Vikram, Cusuh Ham, Andrew Gallagher, and Joshua V. Dillon. Automatic Differentiation Variational Inference with Mixtures. In Proceedings of The 24th International Conference on Artificial Intelligence and Statistics, volume 130 of Proceedings of Machine Learning Research, 3250–3258. 2021. URL: https://proceedings.mlr.press/v130/morningstar21b.html.

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.

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.

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.

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.

Matthew D. Hoffman, David M. Blei, Chong Wang, and John Paisley. Stochastic Variational Inference. Journal of Machine Learning Research, 14(40):1303–1347, 2013. URL: https://www.jmlr.org/papers/v14/hoffman13a.html.