Training¶
A PAVIGuide is a regular Pyro guide, so you can train it with Pyro's ELBOs and any PyTorch optimizer. pavi.inference adds a PyTorch Lightning module and callbacks for large-scale runs.
A plain PyTorch loop¶
elbo = pyro.infer.Trace_ELBO(num_particles=8)
optimizer = torch.optim.Adam(guide.parameters(), lr=1e-2)
for step in range(num_steps):
optimizer.zero_grad()
loss = elbo.differentiable_loss(model, guide, data, idx) # idx=None: full batch
loss.backward()
optimizer.step()
differentiable_lossreturns a tensor you can backpropagate. All guide parameters (transforms, networks, encodings) are inguide.parameters().- More particles reduce the variance of the gradient estimates.
- Decaying the learning rate (e.g.
ExponentialLR) reduces the noise of the final estimates.
Discrete variables: enumeration¶
Discrete latent variables (e.g. the network label of each vertex) cannot be reparameterized. Marginalize them exactly instead:
- mark them for enumeration in the model, e.g.
infer={"enumerate": "parallel"}or@config_enumerate; - hide them from the guide:
hidden_sites=["label", "X"]; - use
pyro.infer.TraceEnum_ELBO(max_plate_nesting=<number of plates>).
The guide automatically skips sites with enumeration support. This is how the brain model handles its per-run labels \(l^{s,n,t}\) (see the brain functional networks example).
Mini-batches with PlateSampler¶
Stochastic VI evaluates the ELBO on subsampled plates: pass idx = {plate: indices} to both the model and the guide, together with the matching slice of the data. The simplest scheme draws random indices at each step:
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"]
guide = PAVIGuide(
model,
{"z_2": [affine(scale_init=1.0)], "z_1": [conditional_affine(hidden_layers=[32, 32])]},
NormalizingFlowScheme,
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(200):
groups = torch.randperm(NUM_GROUPS)[:2]
idx = {"P_1": groups}
optimizer.zero_grad()
loss = elbo.differentiable_loss(model, guide, X[:, groups], idx)
loss.backward()
optimizer.step()
For datasets that do not fit in memory, pavi.data.generic.PlateSampler is a torch.utils.data.Sampler that enumerates chunks of plate indices:
from pavi.data.generic import PlateSampler
sampler = PlateSampler(
plate_indices={"subjects": 4, "vertices": 6}, # plate sizes (or explicit index lists)
subsampling_size={"subjects": 2, "vertices": 3},
batch_plates=["subjects"], # plates whose elements are split across the items of a batch
shuffle=False,
)
print(len(sampler), sampler.batch_size) # 8 2
print(next(iter(sampler))) # {'subjects': [0], 'vertices': [0, 1, 2]} (numpy ints): one dataset item
Each yielded dict indexes one dataset item. Used with DataLoader(dataset, sampler=sampler, batch_size=sampler.batch_size), a batch gathers sampler.batch_size items, i.e. one chunk of each plate. experiments/src/datasets/datasets_fcon.py (ConnectivityProfileDataLoader) is a complete example, which reshapes the collated items into (data, idx) batches for the brain model.
Lightning: InferenceModule¶
pavi.inference.lightning_module.InferenceModule wraps a model and a guide into a LightningModule:
- the loss is
TraceEnum_ELBO.differentiable_loss, so it supports enumeration; - each batch is unpacked as
loss_fn(model, guide, *batch), typicallybatch = (data, idx); AdamWfor dense parameters andSparseAdamfor sparse embeddings (JointEM(sparse=True));- per-variable learning rates:
lr_per_rv={"theta_s": 1e-3, "encodings": 1e-2}matches the keys against the components of parameter names (e.g.guide.theta_s.0_transform.…); lr_schedule: a list of learning-rate multipliers, one per epoch, turned into aLambdaLRper optimizer and stepped at the end of each epoch. After the last entry, the last multiplier is reused. Do not combine it with another callback that steps the schedulers (e.g.LRSchedulerCallbackinexperiments/src/callbacks/callbacks_shared.py).
from pytorch_lightning import Trainer
from torch.utils.data import DataLoader, Dataset
from pavi.inference.callbacks import AnnealingScheduleCallback
from pavi.inference.lightning_module import InferenceModule
class GroupBatches(Dataset):
"""Two mini-batches of groups; each item is a ready-made (data, idx) batch."""
batches = [torch.tensor([0, 1, 2]), torch.tensor([3, 4])]
def __len__(self):
return len(self.batches)
def __getitem__(self, i):
groups = self.batches[i]
return X[:, groups], {"P_1": groups}
pyro.clear_param_store()
guide = PAVIGuide(
model,
{"z_2": [affine(scale_init=1.0)], "z_1": [conditional_affine(hidden_layers=[32, 32])]},
NormalizingFlowScheme,
JointEM(encoding_size={"P_1": 8}),
hidden_sites=["X"],
device="cpu",
data=X,
)
module = InferenceModule(model, guide, num_particles=8, max_plate_nesting=2, lr=1e-2, lr_schedule=[1.0] * 50 + [0.1])
num_epochs = 100
trainer = Trainer(
max_epochs=num_epochs,
accelerator="cpu",
logger=False,
enable_checkpointing=False,
enable_progress_bar=False,
callbacks=[AnnealingScheduleCallback([0.01, 0.1, 0.5, 1.0])], # the last value is reused after epoch 3
)
trainer.fit(module, train_dataloaders=DataLoader(GroupBatches(), batch_size=None, shuffle=True))
Callbacks¶
KL annealing¶
AnnealingScheduleCallback(annealing_schedule) multiplies the log-densities of all latent sites, in the model and in the guide, by annealing_schedule[epoch]. This scales the KL term of the ELBO while leaving the likelihood untouched:
Starting with small \(\beta\) lets the model fit the data before the prior pulls \(q\) back. This was required for the brain model to converge. The current scale is logged as kl_scale.
Per-variable losses¶
RVLossCallback(frequency="batch" | "epoch") logs the contribution of each site to the loss (normalized by event size), plus aggregated reconstruction and KL terms. It is useful to see which level of the hierarchy dominates the ELBO.
Practical tips¶
- Call
pyro.clear_param_store()before building a new guide in the same process (InferenceModuledoes it in its constructor). - Start conditional posteriors wide:
affine(scale_init=1.0)rather than the default 0.01 scale when the prior is broad. - Monitor the loss of individual sites (
RVLossCallback). The likelihood term usually dominates by orders of magnitude.