Transforms¶
Normalizing flows in pavi¶
PAVI approximates the posterior of each latent site with a normalizing flow (see concepts):
- a sample \(u\) is drawn from a base distribution: a standard normal distribution, or the prior of the site given its parents, depending on the chosen scheme;
- it goes through a pipeline of invertible transforms \(f = f_k \circ \dots \circ f_1\), whose parameters are learned. For a site in a plate, the transforms can be conditioned on the instance's encoding;
- the result \(z = f(u)\) is a sample of the approximate posterior. Its density is known exactly, thanks to the invertibility of \(f\).
With a standard normal base and a single diagonal affine transform, this is the classical mean-field Gaussian approximation. Adding transforms makes the variational family more expressive.
Choosing the transforms of each site¶
Each latent site gets a list of transform factories in transform_modules. The guide builds the site's pipeline from them: the first factory is applied first.
transform_modules = {
"z_2": [affine(scale_init=1.0)], # unconditional
"z_1": [conditional_affine(hidden_layers=[32, 32])], # conditioned on the encodings
}
The guide takes care of constrained variables: if a site lives on a constrained space (e.g. positive values), the pipeline works on an unconstrained version of it and the result is mapped back, e.g. with exp.
Note
A latent site that is not in transform_modules is sampled from its prior inside the guide: it is not inferred.
The factory protocol¶
A factory is any callable that the guide calls as
factory(event_dim=<flattened unconstrained event size>, context_dim=<size of the site's encodings>)
and that returns either a torch.distributions.Transform (unconditional, possibly an nn.Module with learnable parameters) or a pyro.distributions.ConditionalTransform. The guide calls .condition(encodings) on conditional transforms at each step. context_dim is 0 for sites outside any plate. Unconditional transforms can ignore it.
pavi.distributions provides factories that already follow this protocol. Modules (classes) also qualify when they accept these two keyword arguments, possibly through functools.partial.
Affine transforms¶
The workhorse of PAVI: with a standard normal base, an affine transform gives a Gaussian posterior. After a support bijection, it gives e.g. a log-normal.
affine(scale_type="diag", batch_shape=None, loc_init=None, scale_init=None, scale_eps=1e-5) builds an AffineModule with learnable location and scale: \(z = \mathrm{loc} + \mathrm{scale} \odot u\). The scale is initialized at 0.01 by default (a sharp initial posterior). Use scale_init=1.0 to start from the base distribution.
conditional_affine(hidden_layers, activation_fn="LeakyReLU", scale_type="diag", scale_eps=1e-5, compile_module=False) builds a ConditionalAffineModule, PAVI's amortized transform. Two MLPs (pyro.nn.DenseNN) map the encoding \(E^n\) to \(\beta(E^n)\) and \(\log \alpha(E^n)\):
compile_module=True wraps the networks in torch.compile.
scale_type="tril" replaces the diagonal scale by a lower-triangular Cholesky factor, which gives a full-covariance Gaussian. It works with both affine and conditional_affine, at a cost of \(d(d+1)/2\) parameters per instance instead of \(d\). Householder reflections are a cheaper way to add correlations.
Householder reflections¶
HouseholderModule(event_dim, count_transforms=1) and ConditionalHouseholderModule(context_dim, event_dim, hidden_layers, count_transforms=1) compose orthogonal reflections, i.e. learnable rotations. Placed after a diagonal affine transform, they turn a mean-field Gaussian into a correlated one. Placed before, they have no effect, because a rotated standard normal is still standard normal.
For example, to approximate a correlated 2D Gaussian (a diagonal affine transform alone cannot represent the correlation):
from functools import partial
import pyro
import pyro.distributions as dist
import torch
from pavi.core import JointEM, NormalizingFlowScheme, PAVIGuide
from pavi.distributions import HouseholderModule, affine
def model(data=None, idx=None):
cov = torch.tensor([[1.0, 0.8], [0.8, 1.0]])
pyro.sample("z", dist.MultivariateNormal(torch.tensor([1.0, -1.0]), cov))
pyro.clear_param_store()
guide = PAVIGuide(
model,
{"z": [affine(scale_init=1.0), partial(HouseholderModule, count_transforms=2)]},
NormalizingFlowScheme,
JointEM(1),
device="cpu",
)
Pyro's normalizing flows¶
Pyro's transform factories (spline, affine_autoregressive, conditional_spline, householder, …) take input_dim (and context_dim for conditional ones). pavi.distributions re-exports every such factory, wrapped to the factory protocol: pass the other arguments, and the guide supplies event_dim (as input_dim) and context_dim. Unconditional factories ignore context_dim, so they can also follow a conditional transform for a site in a plate.
import pavi.distributions as pd
transform_modules = {
"z": [pd.spline(count_bins=8)], # site outside plates
"z_1": [pd.conditional_affine_autoregressive(hidden_dims=[32]), pd.spline()], # site in a plate
}
Alternatively, wrap any factory in a lambda that maps the protocol's arguments:
import pyro.distributions.transforms as T
transform_modules = {
"z": [lambda event_dim, context_dim: T.spline(event_dim, count_bins=8)],
}
# for a site in a plate, conditioned on its encodings:
conditional_flow = lambda event_dim, context_dim: T.conditional_affine_autoregressive( # noqa: E731
event_dim, context_dim, hidden_dims=[32]
)
Writing a transform¶
- Unconditional: subclass
pyro.distributions.TransformModule(atorch.distributions.Transformthat is also annn.Module) and implement_call,_inverseandlog_abs_det_jacobian. Acceptevent_dim(and ignorecontext_dim). - Conditional: subclass
pyro.distributions.ConditionalTransformandPyroModule, and implementcondition(context) -> Transform. The context has the site's batch shape followed bycontext_dim. Return a transform whose parameters broadcast to it.ConditionalAffineModuleinpavi/distributions/affine_modules.pyis a complete example.
Reference¶
| Factory / module | Conditional | Parameters |
|---|---|---|
affine / AffineModule |
no | loc, diagonal or Cholesky scale |
conditional_affine / ConditionalAffineModule |
yes | MLPs: encoding → loc, scale |
HouseholderModule |
no | reflection vectors |
ConditionalHouseholderModule |
yes | MLP: encoding → reflection vectors |
Pyro flows (pavi.distributions.<name> or a lambda) |
both | see the Pyro documentation |