pavi.inference¶
pavi.inference.lightning_module
¶
InferenceModule
¶
Bases: LightningModule
A PyTorch Lightning module for Bayesian inference with Pyro.
Wraps a Pyro model and guide into a Lightning-compatible module, providing training, validation, and testing loops with support for per-random-variable learning rates, sparse embeddings, learning rate schedules, and gradient norm tracking.
Attributes:
| Name | Type | Description |
|---|---|---|
cfg |
Any
|
Arbitrary configuration object attached to checkpoints. |
model |
The PyroModule defining the probabilistic model. |
|
guide |
The AutoGuide defining the variational approximation. |
|
loss_fn |
The differentiable loss function from TraceEnum_ELBO. |
|
_get_trace |
Internal trace builder, exposed for callback use. |
configure_optimizers()
¶
Configure optimizers and an optional learning rate scheduler.
Constructs optimizer instances with per-parameter learning rates derived from lr_per_rv, separating sparse and dense parameters into distinct optimizer groups (AdamW for dense, SparseAdam for sparse embeddings). If a learning rate schedule is provided, attaches a LambdaLR scheduler to each optimizer.
Returns:
| Type | Description |
|---|---|
|
list[Optimizer] | tuple[list[Optimizer], list[LambdaLR]]: A single optimizer, a list of optimizers, or a tuple of (optimizers, schedulers) if an LR schedule is configured. |
on_train_epoch_end()
¶
Step the learning rate schedulers, if any, once per epoch.
With manual optimization, Lightning does not step the schedulers
returned by configure_optimizers.
on_before_optimizer_step(optimizer)
¶
Compute and log gradient norms before each optimizer step.
Hook called by PyTorch Lightning before the optimizer step. When track_grad_norm is enabled, computes the global L2 norm across all parameters and logs it for monitoring gradient explosion or vanishing.
Note
If using mixed precision, gradients are already unscaled at this point, so norms reflect their true magnitude.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
The optimizer about to take a step. |
required |
on_save_checkpoint(checkpoint)
¶
Persist the custom configuration object in the checkpoint.
PyTorch Lightning hook called before saving a checkpoint. If the module has an attached cfg attribute, it is stored in the checkpoint dictionary for later restoration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
checkpoint
|
The checkpoint dictionary to augment with cfg. |
required |
pavi.inference.callbacks
¶
PyTorch Lightning callbacks for Bayesian inference with Pyro.
This module provides callbacks for monitoring per-random-variable losses and managing KL annealing schedules during variational inference training.
RVLossCallback
¶
Bases: Callback
A Lightning callback that logs per-random-variable losses during training.
Computes and logs individual loss contributions for each stochastic node and observation in the model, along with aggregate reconstruction and KL regularization terms. Uses the model and guide traces to normalize losses by event size and separate KL from reconstruction.
Attributes:
| Name | Type | Description |
|---|---|---|
frequency |
Logging frequency, either 'batch' or 'epoch'. |
|
prog_bar |
Whether to display losses in the progress bar. |
|
logger |
Whether to send losses to the logger (e.g., TensorBoard). |
on_train_batch_end(trainer, pl_module, outputs, batch, batch_idx)
¶
Log per-RV losses at the end of each training batch.
Only fires when frequency is set to 'batch' and the current
batch is not None. Logs aggregate terms (reconstruction, KL)
to both the progress bar and logger, while per-RV losses go
to the logger only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trainer
|
The PyTorch Lightning Trainer instance. |
required | |
pl_module
|
The LightningModule being trained. |
required | |
outputs
|
The outputs from the training step (unused). |
required | |
batch
|
The current data batch, unpacked for loss computation. |
required | |
batch_idx
|
The index of this batch within the epoch (unused). |
required |
on_train_epoch_end(trainer, pl_module)
¶
Log per-RV losses at the end of each training epoch.
Only fires when frequency is set to 'epoch'. Computes losses
over the entire training dataset by iterating over the training
dataloader, then logs aggregate terms to both the progress bar
and logger, and per-RV losses to the logger only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trainer
|
The PyTorch Lightning Trainer instance. |
required | |
pl_module
|
The LightningModule being trained. |
required |
AnnealingScheduleCallback
¶
Bases: Callback
A Lightning callback that applies KL annealing across training epochs.
Manages a schedule of scale factors that modulate the KL divergence
term of the ELBO: E_q[log p(X | Z)] - beta(epoch) * KL(q || p). Early
in training, the KL term can dominate and keep the approximate posterior
at the prior; increasing beta from 0 toward 1 lets the model fit the
data first, then gradually take the prior into account.
Uses a context manager (ScaleLogprobMessenger) to temporarily
modify log probability scaling during each epoch, ensuring that
the annealing is applied consistently across all guide sites.
Attributes:
| Name | Type | Description |
|---|---|---|
annealing_schedule |
A list of float scale factors, one per epoch. |
on_train_epoch_start(trainer, pl_module)
¶
Activate the KL annealing context for the current epoch.
Determines the scale factor for the current epoch (clamped to
the schedule length), creates a ScaleLogprobMessenger context
that applies this scale uniformly to all guide sites, logs the
current scale, and enters the context so that subsequent forward
passes use the annealed KL weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trainer
|
The PyTorch Lightning Trainer instance. |
required | |
pl_module
|
The LightningModule being trained. |
required |
on_train_epoch_end(trainer, pl_module)
¶
Exit the KL annealing context after the current epoch.
Ensures that the ScaleLogprobMessenger context is properly
closed, restoring the original log probability scaling for
any operations outside the epoch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trainer
|
The PyTorch Lightning Trainer instance. |
required | |
pl_module
|
The LightningModule being trained. |
required |
state_dict()
¶
Serialize the callback's state for checkpointing.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
A dictionary containing the 'annealing_schedule' list. |
load_state_dict(state_dict)
¶
Restore the callback's state from a checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dict
|
dict
|
A dictionary produced by |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
pavi.core.utils
¶
ScaleLogprobMessenger
¶
Bases: Messenger
Scale the log-density of selected sample sites (used for KL annealing).
Multiplies the scale of every sample site whose name is in scales,
in the model and in the guide alike. Applied to all latent sites, this
scales the KL term of the ELBO while leaving the likelihood untouched. Used
by pavi.inference.callbacks.AnnealingScheduleCallback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scales
|
dict | None
|
Mapping from site name to scale factor. |
None
|