Skip to main content

pavi — plate-amortized variational inference in Pyro

Scalable Bayesian inference for hierarchical models with millions of latent variables.

Documentation Python Pyro License: MIT

Population-level and individual parcellations of the cortex into 17 functional networks, estimated with PAVI on the HCP dataset
Population-level (top) and individual (bottom) parcellations of the cortex into 17 functional networks, inferred with PAVI from HCP resting-state fMRI (Le Bris et al., 2024).

pavi implements PAVI (Rouillard et al., 2023) for Pyro, the probabilistic programming library built on PyTorch. You describe your data with a hierarchical Bayesian model; pavi approximates the posterior distribution of its latent variables, even when there are millions of them. In particular, a main application of the algorithm and this implementation was estimating individualized functional networks over the cortex from fMRI data (see the figure above and Le Bris et al., 2024).

Why PAVI?

Hierarchical models repeat the same variable across plates1, and the number of latent variables quickly explodes. In the brain application, about 1,000 subjects × 60,000 cortical vertices give 60 million latent variables. With a classical mean-field Gaussian approximation over about 20 functional networks, this requires more than 2 billion variational parameters.

PAVI builds the variational family with normalizing flows: a simple base distribution is mapped to a complex one by an invertible, learnable transform $f$. For an instance $n$ of a plate,

$$z^n = f(u^n;\ \phi, E^n), \qquad u^n \sim \text{base distribution}.$$

  • The parameters $\phi$ of the transform are shared by all the instances of the plate. They capture what instances have in common and act as a group-level regularization.
  • Each instance only keeps a small encoding $E^n \in \mathbb{R}^m$, which encodes the statistics of its posterior (hence the name).

The number of parameters still grows with the number of instances $N$, but much more slowly: for large $N$ it is reduced by a factor $O(m/d)$ compared to the mean-field approximation, where $d$ is the size of each variable and $m \ll d$. The mean-field approximation itself is the special case of a standard normal base and a diagonal affine transform. New subjects can be inferred by refitting only their encodings.

(A) Generative model and PAVI variational family: posteriors of z_1 are parameterized by a shared phi_1 and per-instance encodings E_1^n. (B) Each posterior is a base distribution mapped by an invertible transform f.

Learn more in Concepts.

Features

  • Bring your own generative model, implemented with Pyro and PyTorch.
  • An off-the-shelf implementation of PAVI, with training utilities: plate-aware mini-batch sampler, PyTorch Lightning inference module, KL annealing and logging callbacks.
  • Many customization options:
    • a wide choice of parameterized invertible transforms;
    • several strategies to manage the encodings;
    • several strategies for the base distribution, called schemes.

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

See Getting started to install from source.

Quickstart

A three-level hierarchical model: a global mean $z_2$, the means $z_1^i$ of 5 groups (plate P_1), and 50 observations $X^{i,j}$ per group (plate P_0).

1. Write the generative model in Pyro. The model receives the data and, optionally, the indices of a mini-batch (idx).

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)


# Simulate a dataset from the model
pyro.set_rng_seed(0)
X = pyro.poutine.trace(model).get_trace().nodes["X"]["value"]

2. Build the PAVI guide2. Choose a transform for each latent site3, an encoding manager and a scheme.

guide = PAVIGuide(
    model,
    transform_modules={
        "z_2": [affine(scale_init=1.0)],                     # global variable
        "z_1": [conditional_affine(hidden_layers=[32, 32])],  # plate P_1: conditioned on encodings
    },
    transform_scheme=NormalizingFlowScheme,
    encoding_manager=JointEM(encoding_size={"P_1": 8}),
    hidden_sites=["X"],  # observed sites are not inferred
    device="cpu",
    data=X,
)

3. Fit the guide by maximizing the evidence lower bound (ELBO).

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()

4. Sample from the approximate posterior.

with torch.no_grad():
    posterior_sample = guide(X)
print(posterior_sample["z_1"])  # one sample of the 5 group means

The toy-model notebook compares the result with the exact posterior.

How it works

flowchart LR
    M["Pyro model<br/>with plates"] -->|"inspected once"| S["latent sites<br/>and their plates"]
    S --> EM["encoding manager<br/>encodings E"]
    S --> T["transforms<br/>per site"]
    EM -->|"conditions"| T
    T --> SC["scheme<br/>base distribution"]
    SC --> Q["approximate posterior q"]

When it is created, the guide runs the model once to list its latent sites and their plates. The encoding manager then creates the encodings, and each site gets its chain of transforms, conditioned on the encodings when the site lives in a plate. The scheme chooses the base distribution that the transforms are applied to. See The PAVI guide.

Application: individual brain functional networks

PAVI makes it possible to map the functional networks of each individual brain at the resolution of the cortical mesh, from resting-state fMRI (Le Bris et al., 2024). A hierarchical model explains the functional connectivity of each vertex as a mixture of 17 networks, whose spatial organization varies across individuals around a population-level atlas.

Instead of a discrete atlas, the model yields a continuous, probabilistic map of each network, at the population level (below) and for each individual:

Population-level probabilistic maps of functional networks VIN-1 to CON-2 Population-level probabilistic maps of functional networks CON-3 to DMN-4

These individual maps are reliable, reflect individual-specific organization, predict behavior, and transfer to small datasets through the population-level priors. See the brain application example.

Documentation

Page Content
Getting started installation and a first model
Concepts hierarchical models, variational inference, normalizing flows, plate amortization
The PAVI guide the arguments of PAVIGuide
Encodings · Transforms · Schemes the building blocks and their options
Training ELBOs, enumeration, mini-batches, Lightning, KL annealing
Examples toy model, brain functional networks

The documentation is published at https://dubris.github.io/pavi-pyro/. To browse it locally, run uv run --group docs mkdocs serve.

Citation

If you use pavi, please cite:

@article{rouillard2023pavi,
  title   = {{PAVI}: Plate-Amortized Variational Inference},
  author  = {Rouillard, Louis and Le Bris, Alexandre and Moreau, Thomas and Wassermann, Demian},
  journal = {Transactions on Machine Learning Research},
  year    = {2023}
}

For the brain functional network application:

@unpublished{lebris2024transfer,
  title  = {Improving Individual-Specific Functional Parcellation through Transfer Learning},
  author = {Le Bris, Alexandre and Rouillard, Louis and Wassermann, Demian},
  year   = {2024},
  url    = {https://hal.science/hal-04506561}
}

License

MIT

  1. Plate: a set of random variables that are conditionally independent given their parents, e.g. one variable per subject or per brain vertex. Declared with pyro.plate. ↩

  2. Guide: in Pyro, the parameterized family of distributions $q$ (the variational family) that is fitted to approximate the posterior. pavi provides the guide; you provide the model. ↩

  3. Site: a random variable of a Pyro model, declared with pyro.sample("name", distribution). Latent sites are inferred; observed sites hold the data. ↩

Metadata

Release files for pavi-pyro 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pavi-pyro 0.1.0
File Size Uploaded Provenance Actions
pavi_pyro-0.1.0.tar.gz 40.4 kB Without provenance Details for pavi_pyro-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pavi-pyro 0.1.0
File Interpreter ABI Platform Actions
pavi_pyro-0.1.0-py3-none-any.whl Python 3 none any Details for pavi_pyro-0.1.0-py3-none-any.whl

Total release size: 89.7 kB

Release files / pavi_pyro-0.1.0.tar.gz

Download URL pavi_pyro-0.1.0.tar.gz
Size 40.4 kB
Tags Source
SHA-256 checksum
How to use checksums
f953caff3d45f7323552aef85f427cbfb2ffd5745ee297ec948f69ec4d6fc2c1
BLAKE2b-256 checksum
How to use checksums
5b219649ede2eec5d0099d671bdb53bbff7caee10bde9c7c0a4ca4d3ae0a02f3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.3 {"installer":{"name":"uv","version":"0.12.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / pavi_pyro-0.1.0-py3-none-any.whl

Download URL pavi_pyro-0.1.0-py3-none-any.whl
Size 49.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
858179b1442fc693a336ac72b71bc5d838c75b37468f0639d237c0539f5bc5c3
BLAKE2b-256 checksum
How to use checksums
6e29813e862889e496c21454f385350647f9ce79cee7af36f188b32759404b41
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.3 {"installer":{"name":"uv","version":"0.12.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for pavi-pyro 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page