pavi.core¶
pavi.core.pavi_autoguide
¶
The PAVI guide: plate-amortized variational inference for Pyro models.
A Pyro guide is the parameterized variational family that approximates the
posterior of a model. PAVIGuide approximates the posterior of each
continuous latent site (random variable) with a normalizing flow: a base
distribution, chosen by a transform scheme, mapped by a pipeline of invertible
transforms. For sites inside plates, the transforms are shared by all the
instances of the plate and conditioned on small per-instance encodings, created
by an EncodingManager. With a standard Normal base and diagonal affine
transforms, this is the mean-field approximation.
Reference: Rouillard, Le Bris, Moreau & Wassermann (2023), "PAVI: Plate-Amortized Variational Inference", Transactions on Machine Learning Research.
Implementation notes:
- Discrete random variables with enumerate support are excluded from inference to
avoid contributing to the ELBO unnecessarily.
- Constrained distributions are unconstrained via biject_to transforms before the
user-defined transforms are applied.
- Multi-dimensional event shapes are flattened to 1-D via ReshapeTransform to
simplify downstream transform composition.
- Plate information (size, reduced size, tensor dimension) is captured during
initialization so that context dimensions can be computed per-site.
PAVIGuide
¶
Bases: AutoGuide
Plate-amortized variational guide for Pyro models.
Extends pyro.infer.autoguide.AutoGuide. Each continuous latent site
listed in transform_modules is approximated by a normalizing flow; for
sites inside plates, conditional transforms receive the encodings of the
plate instances produced by the encoding_manager. Latent sites missing
from transform_modules are sampled from their prior. Discrete sites
(those with has_enumerate_support) are excluded, as they are expected
to be enumerated.
Model requirements: the guide calls the model as model(data, idx, ...),
so the model must accept idx (a dict mapping plate names to subsample
indices, or None) and pass it to its plates
(pyro.plate(name, size, subsample=idx.get(name), dim=...)), with explicit
plate dims.
Guide parameters live in Pyro's global parameter store, under names derived
from the sites: call pyro.clear_param_store() before building another
guide in the same process, otherwise the new guide silently reuses the
parameters of the previous one.
Example::
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"],
data=X,
)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Model
|
The Pyro model to guide: a |
required |
transform_modules
|
dict[str, list[TransformFactory]]
|
Mapping from site name to a list of transform
factories, applied in order. Each factory is called as
|
required |
transform_scheme
|
type[NormalizingFlowScheme] | type[CascadingScheme]
|
The scheme class setting the base distribution of
the flows ( |
required |
encoding_manager
|
EncodingManager
|
An |
required |
hidden_sites
|
list[str] | None
|
Site names to hide from the guide: observed sites (if they are not hidden, the likelihood cancels out in the ELBO) and enumerated discrete sites. |
None
|
create_plates
|
Callable | None
|
Optional callable forwarded to the parent |
None
|
device
|
str | device | None
|
Target device for all parameters. Defaults to |
None
|
*args
|
Example positional arguments of the model, used to run it once and discover its latent sites, plates and shapes. |
()
|
|
**kwargs
|
Example keyword arguments of the model (e.g. |
{}
|
Attributes (internal):
all_sites:
Topologically sorted list of continuous, stochastic site names.
plate_size,
plate_reduced_size,
plate_dim:
Plate metadata captured during prototype construction.
sample_plate:
Maps each site to the list of plates that condition it.
batch_shapes,
event_shapes:
Per-site distribution shapes used to compute input dimensions.
transform_modules:
Per-site lists of transforms (support inverse → reshape → user transforms
→ support forward).
transform_scheme:
Messenger that applies the transform chain during forward.
forward(data=None, idx=None, *args, return_all=False, **kwargs)
¶
Draw one sample of every latent site from the approximate posterior.
For every site in transform_modules, conditional transforms are bound to
their encodings (produced by the EncodingManager). Unconditional transforms
are passed through unchanged. The resulting transform chain is applied inside
the transform_scheme messenger while the original model is executed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor | ndarray | None
|
Observed data forwarded to the model, typically a |
None
|
idx
|
dict | None
|
Optional mapping from plate names to subsample indices (a mini-batch
of plate elements). Forwarded to the model, and used by the encoding
manager to select the encodings of the sampled instances. |
None
|
*args
|
Additional positional arguments forwarded to the model. |
()
|
|
return_all
|
bool
|
If |
False
|
**kwargs
|
Additional keyword arguments forwarded to the model. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
A dictionary mapping the name of every latent site ( |
dict[str, Tensor]
|
sampled value. |
pavi.core.encoding_manager
¶
Encoding managers: the per-instance encodings of PAVI.
In PAVI, the posterior of each instance of a site (random variable) inside a
plate is a normalizing flow whose transforms are shared across the plate and
conditioned on a small learnable encoding of the instance. The encoding
encodes the statistics of the instance's posterior, which is much cheaper than
storing these statistics for every instance (as in the mean-field
approximation). Encoding managers create these encodings and give each site its
context vector. They differ in how the encoding of an instance in several
plates (e.g. subject s and vertex n) is built:
JointEM: every instance has its own encodingE^{s,n}, stored in one table per plate combination (size: product of the plate sizes).FactorizedEM: the encoding is built from one encoding per plate, concatenated[E^s, E^n]or summedE^s + E^n(size: sum of the plate sizes).
Both managers share the same options:
share_across_sites: whether sites in the same plates reuse the same encodings (default) or each site gets its own tables.sparseanddevice_params: sparse gradients and storage of the tables on another device (e.g. CPU memory) to save GPU memory.expose: restrict the manager to some sites.
Encodings are torch.nn.Embedding tables stored in guide.encodings, with
stable parameter names: encodings.<plates>.weight for shared tables and
encodings.<site>.<plates>.weight for per-site tables, where <plates> is
the names of the plates of the table joined by |, from the outermost to the
innermost plate (e.g. encodings.subjects|vertices.weight).
PlateKey = str | Iterable[str]
module-attribute
¶
A plate, or a combination of plates: a name, names joined by |, or an iterable of names.
EncodingSizeType = int | Mapping[PlateKey, int]
module-attribute
¶
Encoding size specification: either a single integer applied to every table, or a mapping from plates (or plate combinations) to encoding sizes.
EncodingManager
¶
Bases: ABC
Base class of the encoding managers.
An encoding manager stores encoding tables, i.e. torch.nn.Embedding
modules with one row per instance of a plate (or of a plate combination),
and builds the context vector of each site from them. Subclasses define
which tables a site uses (_site_tables) and how they are combined
(_combine).
The manager is tightly coupled with PAVIGuide: during guide
initialization, init_encodings() creates the tables in
guide.encodings, and get_encodings() returns the encodings of the
plate instances selected by idx, which condition the transforms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoding_size
|
EncodingSizeType
|
The size of the encodings: an |
required |
share_across_sites
|
bool
|
If |
True
|
expose
|
list[str] | None
|
Optional list of the sites this manager handles. |
None
|
sparse
|
bool
|
If |
False
|
device_params
|
str | device | None
|
Device of the tables, e.g. |
None
|
init_scale
|
float
|
Standard deviation of the Normal initialization of the encodings. |
0.1
|
Attributes:
| Name | Type | Description |
|---|---|---|
encoding_size |
int | dict[tuple[str, ...], int]
|
The encoding size specification, with keys converted to tuples of plate names. |
site_tables |
dict[str, list[tuple[tuple[str, ...], tuple[str, ...]]]]
|
Maps each managed site to the list of its tables, as
|
init_encodings(guide, *args, **kwargs)
¶
Create the encoding tables in guide.encodings.
Uses guide.sample_plate, guide.plate_size, guide.plate_dim and
guide.device. Called once by PAVIGuide.__init__.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
guide
|
AutoGuide
|
The guide onto which the tables are registered. |
required |
*args
|
Unused. |
()
|
|
**kwargs
|
Unused. |
{}
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
get_encodings(guide, name_sample, idx=None, device=None, *args, **kwargs)
¶
Return the context of a site for the plate instances selected by idx.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
guide
|
AutoGuide
|
The guide holding the encoding tables. |
required |
name_sample
|
str
|
The name of the site. |
required |
idx
|
dict | None
|
Optional mapping from plate names to subsample indices. Plates
missing from |
None
|
device
|
str | device | None
|
Device of the output. Defaults to |
None
|
*args
|
Unused. |
()
|
|
**kwargs
|
Unused. |
{}
|
Returns:
| Type | Description |
|---|---|
Tensor
|
A tensor of shape |
Tensor
|
the batch shape of the site, or an empty tensor if the site has no |
Tensor
|
encodings. |
get_sample_encodings_size(guide, name_sample)
¶
Return the context size of a site (0 if the site has no encodings).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
guide
|
AutoGuide
|
The guide (unused, kept for API consistency). |
required |
name_sample
|
str
|
The name of the site. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The size of the last dimension of |
JointEM
¶
Bases: EncodingManager
One encoding per instance, for every plate combination.
Every instance of a site gets its own encoding, even for sites in several
plates: the table of a plate combination has as many rows as the product of
the plate sizes (e.g. subjects × vertices). This is the most flexible
manager, and the natural choice for sites in a single plate; for nested
plates, the table can become very large (see FactorizedEM).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoding_size
|
EncodingSizeType
|
An |
required |
share_across_sites
|
bool
|
If |
True
|
**kwargs
|
|
{}
|
Example
JointEM({"subjects": 8, "subjects|vertices": 4})
# sites in `subjects` use `encodings.subjects.weight` (S rows of size 8),
# sites in both plates use `encodings.subjects|vertices.weight` (S × N rows of size 4)
FactorizedEM
¶
Bases: EncodingManager
Encodings built from one encoding per plate.
The encoding of an instance in several plates combines per-plate encodings,
e.g. [E^s, E^n] (agg_type="concat") or E^s + E^n
(agg_type="sum") for subject s and vertex n. Only the sum of the
plate sizes is stored, instead of their product with JointEM. With
share_across_sites=True (default), every site of a plate reuses the same
plate encodings: this is the configuration of the PAVI brain application,
whose subject encodings are refitted for new subjects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoding_size
|
EncodingSizeType
|
An |
required |
agg_type
|
Literal['concat', 'sum']
|
How per-plate encodings are combined: |
'concat'
|
share_across_sites
|
bool
|
If |
True
|
**kwargs
|
|
{}
|
Example
FactorizedEM({"subjects": 120, "vertices": 8})
# tables `encodings.subjects.weight` (S × 120) and `encodings.vertices.weight` (N × 8);
# a site in both plates gets a context of size 128
pavi.core.transform_scheme
¶
Transform schemes: the base distribution of PAVI's normalizing flows.
PAVI approximates the posterior of each latent site with a normalizing flow: a base distribution mapped by a pipeline of invertible transforms. A scheme is a Pyro messenger that, while the guide runs the model, replaces the prior of each targeted site with this transformed distribution. The two schemes differ only in the base distribution:
- :class:
NormalizingFlowSchemeuses a standard Normal base on the site's unconstrained space. With a single diagonal affine transform, this is the mean-field Gaussian approximation. - :class:
CascadingSchemeuses the site's prior given its parents as the base. This is the cascading flows algorithm of Ambrogioni, Silvestri & van Gerven (2021), "Automatic Variational Inference with Cascading Flows" (ICML), which keeps the hierarchical dependencies of the model in the variational family.
The scheme class is passed to :class:~pavi.core.PAVIGuide
(transform_scheme=NormalizingFlowScheme); the guide instantiates it at each
call with the conditioned transforms of every site.
Common behavior of both schemes:
- Subsample sites (plate indices) are skipped.
- The sampled values are recorded in
results, which the guide returns.
Example::
from pavi.core import JointEM, NormalizingFlowScheme, PAVIGuide
guide = PAVIGuide(model, transform_modules, NormalizingFlowScheme, JointEM(8), data=X)
CascadingScheme
¶
Bases: Messenger
Use the prior of each site as the base distribution (cascading flows).
For every site whose name appears in transform_modules, the site's prior
p(z | parents), evaluated at the guide's samples of the parents, becomes
the base distribution of a
:class:~pyro.distributions.TransformedDistribution with the site's
transforms. This is the cascading flows algorithm of Ambrogioni et al.
(2021): unlike :class:NormalizingFlowScheme, the variational family keeps
the hierarchical dependencies of the model, and with identity transforms the
approximate posterior is the prior itself.
Pass the class to :class:~pavi.core.PAVIGuide
(transform_scheme=CascadingScheme) rather than using it directly.
Attributes:
| Name | Type | Description |
|---|---|---|
transform_modules |
Mapping from site name to the sequence of transforms applied to that site. |
|
results |
dict[str, Tensor]
|
Sampled values (after transformation) keyed by site name. |
NormalizingFlowScheme
¶
Bases: Messenger
Use a standard Normal as the base distribution of each site's flow.
Each targeted site (random variable of the generative model) is approximated by a standard Normal base distribution, on the site's unconstrained space, pushed forward through the site's sequence of invertible transforms. This is the classical normalizing-flow construction. With a single diagonal affine transform, it is the mean-field Gaussian approximation used in the PAVI brain application.
Support-transform pruning: When a transform pair consisting of a support constraint mapping and its inverse is detected at the beginning and end of the transform sequence, the messenger automatically prunes both (skipping the first transform). This is necessary because the base Normal must be defined on the unconstrained space — the support transform that maps from unconstrained to constrained space would conflict with this requirement.
Device selection: When no device is specified, the messenger automatically selects the best available device (CUDA → MPS → CPU).
Pass the class to :class:~pavi.core.PAVIGuide
(transform_scheme=NormalizingFlowScheme) rather than using it directly.
Attributes:
| Name | Type | Description |
|---|---|---|
transform_modules |
Mapping from site name to the sequence of transforms applied to that site. |
|
names |
List of targeted site names. |
|
results |
dict[str, Tensor]
|
Final sampled values (after transformation) keyed by site name. |
device |
The device on which the base Normal parameters are allocated. |