Getting started¶
Installation¶
pavi requires Python ≥ 3.14. It is published on PyPI as pavi-pyro and imported as pavi:
pip install pavi-pyro # or: uv add pavi-pyro
It installs PyTorch, Pyro and PyTorch Lightning (used by the training tools of pavi.inference).
To install from source, from the repository root:
uv sync # library only; or: pip install -e .
uv sync --all-groups # also the development, documentation and experiment dependencies
A first model¶
We fit a three-level hierarchical Gaussian model (HGM): a global mean \(z_2\), group means \(z_1^i\) in plate P_1, and observations \(X^{i,j}\) in plate P_0.
import pyro
import pyro.distributions as dist
import torch
from pavi.core import JointEM, NormalizingFlowScheme, PAVIGuide
from pavi.distributions import affine, conditional_affine
NUM_GROUPS, NUM_OBS, DIM = 5, 50, 2
def model(data=None, idx=None):
idx = idx or {}
z_2 = pyro.sample("z_2", dist.Normal(torch.zeros(DIM), 1.0).to_event(1))
with pyro.plate("P_1", NUM_GROUPS, subsample=idx.get("P_1"), dim=-1):
z_1 = pyro.sample("z_1", dist.Normal(z_2, 5.0).to_event(1))
with pyro.plate("P_0", NUM_OBS, subsample=idx.get("P_0"), dim=-2):
pyro.sample("X", dist.Normal(z_1, 1.0).to_event(1), obs=data)
pyro.set_rng_seed(0)
X = pyro.poutine.trace(model).get_trace().nodes["X"]["value"] # (NUM_OBS, NUM_GROUPS, DIM)
guide = PAVIGuide(
model,
transform_modules={
"z_2": [affine(scale_init=1.0)],
"z_1": [conditional_affine(hidden_layers=[32, 32])],
},
transform_scheme=NormalizingFlowScheme,
encoding_manager=JointEM(encoding_size={"P_1": 8}),
hidden_sites=["X"],
device="cpu",
data=X,
)
elbo = pyro.infer.Trace_ELBO(num_particles=8)
optimizer = torch.optim.Adam(guide.parameters(), lr=1e-2)
for step in range(2000):
optimizer.zero_grad()
loss = elbo.differentiable_loss(model, guide, X)
loss.backward()
optimizer.step()
Calling the guide draws one posterior sample. It returns a dict with the value of every sample site it visited, which includes the plate index sites:
with torch.no_grad():
sample = guide(X)
print({name: tuple(value.shape) for name, value in sample.items()})
# {'z_2': (2,), 'P_1': (5,), 'z_1': (5, 2), 'P_0': (50,)}
The full example, with a comparison to the exact posterior, is in the toy-model notebook.
Precisions about PAVI guide instantiation¶
A few rules to follow when writing the model and building the guide:
- The model accepts
idx. The guide calls the model asmodel(data, idx), whereidxoptionally selects a mini-batch of plate elements. Pass it to the plates withsubsample=idx.get("plate name"). - Plates have an explicit
dim(dim=-1,dim=-2, …). - Observed sites are listed in
hidden_sites, together with discrete sites that are summed out (enumeration). - Example arguments of the model (here
data=X) are passed toPAVIGuide, which runs the model once to discover its structure. - One guide at a time: call
pyro.clear_param_store()before building a new guide in the same Python session.
Warning
If an observed site is not listed in hidden_sites, the likelihood cancels out in the ELBO: the loss stays near zero and the posterior never leaves the prior.
Each argument of PAVIGuide is described in The PAVI guide, and mini-batch training in Training.
Next steps¶
- Concepts: the ideas behind PAVI.
- Encodings, transforms and schemes: the options available for each building block.