Inference Foundations¶
Inference asks which unobserved values are plausible after seeing data. With \(z\) the latent values, \(y\) the observations, and \(x\) the known inputs, a model gives the prior and the likelihood, so the posterior is \(p(z \mid x, y) \propto p(y, z \mid x)\). Evaluating the joint density at a candidate \(z\) is cheap, and inference uses such evaluations to approximate the posterior. Variational inference fits an adjustable approximation to it, and MCMC builds a sequence of draws from it.
For QVR models, checked model fitting packages the common binding, guide, optimizer, and training-loop setup. It derives external input types and observation roles from the program. This guide opens those components to explain their behavior and customization.
Architecture¶
For a first model, list its named sample sites, decide which are observed, and choose
an inference driver. The quivers.inference subpackage has six layers. Each can be
used on its own, and all are exported from
quivers.inference:
flowchart TB
L6["Drivers<br/><small>SVI · MCMC · Predictive</small>"]
L5["Hybrid algorithms<br/><small>AutoDAIS · WarmupThenHMC</small>"]
L4["Posterior approximations<br/><small>Auto*Guide · HMC · NUTS</small>"]
L3["Objectives × estimators<br/><small>ELBO · IWAE · Rényi × Reparam · StL · DReG · Score</small>"]
L2["Transforms<br/><small>affine coupling · MAF · IAF · NSF · BN · LU</small>"]
L1["LatentRegistry<br/><small>support · dimensions · plates · parents</small>"]
L6 -->|"orchestrate"| L5 -->|"combine"| L4 -->|"optimize with"| L3 -->|"parameterize through"| L2 -->|"read structure from"| L1
class L6,L5 qv-output
class L4,L3 qv-checked
class L2,L1 qv-foundation
The objectives are the evidence lower bound (ELBO), the importance weighted
autoencoder bound (IWAE) (Burda et al., 2016), and the variational Rényi bound
(Li and Turner, 2016), with reparameterized, score-function, sticking-the-landing (StL)
(Roeder et al., 2017), and doubly reparameterized (DReG) (Tucker et al., 2019) gradient
estimators. The transforms, which build
normalizing flows, are
affine coupling layers (Dinh et al., 2017), masked and inverse autoregressive flows (MAF,
IAF) (Papamakarios et al., 2017; Kingma et al., 2016), neural spline flows (NSF)
(Durkan et al., 2019), batch normalization (BN) (Dinh et al., 2017), and invertible
linear layers in LU form (Kingma and Dhariwal, 2018). AutoDAIS is differentiable annealed
importance sampling (Geffner and Domke, 2021; Zhang et al., 2021).
Every guide and MCMC kernel reads one LatentRegistry, the list of a model's latent
sites with their supports, sizes, plates, and parents. It is built from a run of the
model, LatentRegistry.from_trace(model, trace(model, x, observations)), as MCMC always
does and a guide does when constructed with x=, or from the program's steps with
LatentRegistry.from_model(model, observed_names). It converts between a dict of site
values and one unconstrained vector, and maps each site with the
bijector that
torch.distributions.constraint_registry.biject_to
gives for its support.
The variational pipeline¶
A positive scale and a real-valued mean have different supports, but an optimizer or a Hamiltonian sampler works on one unconstrained real vector. A bijector is an invertible differentiable map between an unconstrained space and a constrained support, and the registry applies one to each site. Densities in the unconstrained coordinates include the Jacobian correction, the log absolute determinant of the map's Jacobian, so that corresponding regions in the two coordinate systems get the same probability (Stan Development Team, n.d.-f). Flows and constrained guides use the same correction.
flowchart TB
M["Model<br/><small>MonadicProgram</small>"] -->|"execute once"| T["Trace<br/><small>record sample sites</small>"]
T -->|"clamp observed sites"| C["Conditioned model"]
C -->|"inspect latent sites"| LR["LatentRegistry"]
LR -->|"choose family"| G["Guide<br/><small>Auto*Guide subclass</small>"]
G -->|"estimate bound"| O["Objective + estimator<br/><small>ELBO · IWAE · Rényi · VR-IWAE</small>"]
O -->|"differentiate"| S["SVI<br/><small>stochastic optimization</small>"]
S -->|"fitted posterior"| P["Predictive draws"]
class M qv-input
class T,C,LR,G,O qv-checked
class S,P qv-output
Trace and sample sites¶
A trace is the record of one run
of a program, and a sample site is a named point where the run draws or scores a
value (Wingate et al., 2011). For a model with a latent mu and an observed y, a
trace records a value of mu, the given y, and the log density of each, and the log
joint density is the sum of the sites' log densities, as in Pyro's effect handlers
(Pyro Developers, n.d.-d). A deterministic let is recorded with log density zero, since it makes
no random choice. Each site is a
SampleSite:
from quivers.inference import trace, Trace, SampleSite
model = ... # MonadicProgram
# Execute model with tracing
tr = trace(model, x)
# Access sites
sites = tr.sites # dict[site_name -> SampleSite]
for name, site in sites.items():
print(f"{name}: {site.log_prob}")
A SampleSite records:
name: the site's name;morphism: the distribution it was drawn from, orNonefor aletor a score;value: the drawn, observed, or computed value;log_prob: the density the site adds to the run's score, shape(batch,), zero for aletand for a site fixed by an intervention;is_observed: whether the site was fixed to an observed value;is_deterministic: whether the site is alet, a score, or a site fixed by an intervention;units: for a score that factors over units, such as amarginalizeblock, itsSiteUnitsin each run, and empty for any other site.
Input rows are independent runs¶
An input of B rows along its leading axis, the batch axis, is B independent runs of the
whole program. Each run draws its
own value of every site and observes the program's data through its own plates. The
rows a program observes come from its data and its plates, never from the input's rows,
so a program whose observations live in a plate takes an input with one row, such as
torch.zeros(1, 1).
MonadicProgram.log_joint
returns one joint per run, shape (B,), and the joint of all the runs is its sum. A
trace records each site's density per run, shape (B,), and its log_joint agrees. A
value given to log_joint, to a trace, or to a handler is either one value per run,
along a leading axis of length B, or one value that every run shares. Each let and
score step reads one run's values, so a factor, a collection, a reduction, or an
index reads the binding's own axes and never the batch axis. A
grouped marginalize
scores one run at a time: its observations may carry a batch axis of length one, and
data for several runs raise ValueError.
The drivers that target one run's latents refuse an input of more than one row and say
to pass one. They are MCMC, the
Laplace approximation
(Tierney and Kadane, 1986), annealed importance sampling, and lift_to_bayesian_program,
which places a prior on every parameter of a deterministic model (MacKay, 1992),
applied to a program with a plate. The variational objectives sum their terms over
runs. Each run draws its own latents from the guide, so the loss for B runs is a
B-sample estimate of B copies of the objective of one run, and its optimum is the
posterior of one run.
The latents of a program are the sites a run reaches.
LatentRegistry.from_trace
reads them from a trace at the caller's input and data, including every position of a
scanned program cell. MCMC builds its registry that way, and a guide does when it is
constructed with x= (and observations=). LatentRegistry.from_model reads a
program's own steps and refuses a program that scans or that calls a program that
draws.
Latent site shapes¶
A draw is one value of a latent site on its constrained support, with shape
LatentSite.constrained_shape:
() for a scalar site, (d,) for a d-dimensional site, (d, d) for a Cholesky
factor of a correlation matrix, and (|A|, ...) for a site plated over A. Within one
run, a site outside any plate leads with a batch axis of length one,
(1, *constrained_shape), and a plated site holds its plate's rows,
constrained_shape. Across B > 1 runs, a value given or recorded per run leads with
the batch axis, (B, *constrained_shape), for both kinds of site.
| Surface | Site outside any plate | Plated site |
|---|---|---|
One draw (constrained_shape) |
(), (d,) |
(n,), (n, d) for a plate of size n |
MCMCResult.samples |
(chains, draws, *constrained_shape) |
(chains, draws, *constrained_shape) |
MCMCResult.r_hat, MCMCResult.ess |
constrained_shape |
constrained_shape |
Trace value, Guide.rsample, one run |
(1, *constrained_shape) |
constrained_shape |
Trace value, B > 1 runs |
(B, *constrained_shape) |
(B, *constrained_shape) |
Guide.rsample, B > 1 runs |
(B, *constrained_shape) |
constrained_shape, shared by every run |
PotentialFn input to log_joint |
(1, *constrained_shape) |
constrained_shape |
Predictive output |
(num_samples, B, *constrained_shape) |
(num_samples, *constrained_shape) for one run, else (num_samples, B, *constrained_shape) |
LatentRegistry.trace_values
turns one draw into the values of B runs that share it, by expanding each site
outside any plate across the batch axis. MCMC uses it with one run when it scores a
position, so a custom density reached through log_joint sees a leading axis of size
one on every such site.
LatentRegistry.trace_row
reads one run back as a draw per site, which is how a guide sample starts an MCMC
chain.
Conditioning on observations¶
To clamp a site is to use a given value whenever a run reaches it, which makes the
site's likelihood available to inference. Clamping does not replace the prior draws at
other sites with posterior draws, which is the inference algorithm's job. A latent site
is also different from an nn.Parameter, which is optimized as a model or guide
parameter unless the model places a prior on it.
condition()
clamps sites to given values:
from quivers.inference import condition, Conditioned
model = ... # MonadicProgram
# Observed values (e.g., from an experiment)
observations = {
"y_1": torch.tensor(1.5),
"y_2": torch.tensor(-0.3),
}
# Create conditioned model
conditioned = condition(model, observations)
# Trace the conditioned model: observed sites are clamped to the data
tr = conditioned.trace(x)
The result is a
Conditioned
model that wraps the original and fixes the observed sites.
Data inputs: covariates and index arrays¶
A data input is a name that a program reads but no step binds, such as a covariate
or an index array, whose value is given at run time, as with a variable of a Stan
data block (Carpenter et al., 2017). In the condition dict, or the observations dict of an
inference call, a key that matches no sample or observe site is a data input, visible
to let expressions:
import torch
from quivers.dsl import loads
from quivers.inference import condition
model = loads('''
object Subj : FinSet 4
object Resp : FinSet 12
program p : Resp -> Resp
let by_subj : Subj <- sample Normal(loc=0.0, scale=1.0)
let mu = by_subj[subj_idx]
observe r : Resp <- Normal(loc=mu, scale=1.0)
return r
export p
''').morphism
subj_idx = torch.tensor([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3])
r_obs = torch.zeros(12)
cond = condition(model, {"subj_idx": subj_idx, "r": r_obs})
tr = cond.trace(torch.zeros(1, 1)) # one run; its 12 rows come from Resp
r matches the observed site r and is clamped as usual. subj_idx matches no site,
so it is a data input, and let mu = by_subj[subj_idx] reads the subject effect of
each response row. A data input that is missing raises a CompileError that names it.
Debugging¶
Tracing a run shows each site's log density:
from quivers.inference import trace
tr = trace(model, x)
for name, site in tr.sites.items():
print(f"{name}: log_prob={site.log_prob.item():.4f}")
The ELBO during training shows divergence or a poor guide fit (SVI).
Where to next¶
- Variational Inference: SVI: guides, objectives, gradient estimators, the training loop, and predictive sampling.
- MCMC and Hybrid Samplers: Hamiltonian Monte Carlo (HMC), the No-U-Turn Sampler (NUTS), hybrid samplers, and predictive sampling from chains.
- Analysis: Fitting and Diagnostics: fitting, model comparison, and posterior predictive checks built on these pieces.
Cited sources¶
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.
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.
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.
Laurent Dinh, Jascha Sohl-Dickstein, and Samy Bengio. Density estimation using Real NVP. In International Conference on Learning Representations. 2017. URL: https://openreview.net/forum?id=HkpbnH9lx.
George Papamakarios, Theo Pavlakou, and Iain Murray. Masked Autoregressive Flow for Density Estimation. In Advances in Neural Information Processing Systems, volume 30. 2017. URL: https://proceedings.neurips.cc/paper/2017/hash/6c1da886822c67822bcf3679d04369fa-Abstract.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.
Diederik P. Kingma and Prafulla Dhariwal. Glow: Generative Flow with Invertible 1x1 Convolutions. In Advances in Neural Information Processing Systems, volume 31. 2018. URL: https://proceedings.neurips.cc/paper/2018/hash/d139db6a236200b21cc7f752979132d0-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.
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.
Stan Development Team. Reparameterization and change of variables. Stan User's Guide, version 2.40, n.d.-f. URL: https://mc-stan.org/docs/stan-users-guide/reparameterization.html (visited on 2026-11-06).
David Wingate, Andreas Stuhlmueller, and Noah Goodman. Lightweight Implementations of Probabilistic Programming Languages Via Transformational Compilation. In Proceedings of the Fourteenth International Conference on Artificial Intelligence and Statistics, volume 15 of Proceedings of Machine Learning Research, 770–778. PMLR, 2011. URL: https://proceedings.mlr.press/v15/wingate11a.html.
Pyro Developers. Poutine: a guide to programming with effect handlers in Pyro. Pyro Tutorials, version 1.9.1, n.d.-d. URL: https://pyro.ai/examples/effect_handlers.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.
David J. C. MacKay. A Practical Bayesian Framework for Backpropagation Networks. Neural Computation, 4(3):448–472, 1992. URL: https://doi.org/10.1162/neco.1992.4.3.448, doi:10.1162/neco.1992.4.3.448.
Bob Carpenter, Andrew Gelman, Matthew D. Hoffman, Daniel Lee, Ben Goodrich, Michael Betancourt, Marcus Brubaker, Jiqiang Guo, Peter Li, and Allen Riddell. Stan: A Probabilistic Programming Language. Journal of Statistical Software, 2017. URL: https://www.jstatsoft.org/article/view/v076i01, doi:10.18637/jss.v076.i01.