Parametric Variational Autoencoder#
variational_autoencoder
#
| CLASS | DESCRIPTION |
|---|---|
VariationalAutoencoder |
Variational Autoencoder (VAE) with Gaussian latent space. |
Classes#
VariationalAutoencoder(*, model: dict[str, ModelType], z_dim: int = 2, loss_fn: Literal['elbo', 'elbo_log_cosh'] = 'elbo', loss_kwargs: dict | None = None, optimizer_fn: type[torch.optim.Optimizer] | str | None = None, optimizer_kwargs: dict | None = None, lr_scheduler_fn: Any | str | None = None, lr_scheduler_kwargs: dict | None = None, device: Literal['cuda', 'cpu'] = 'cuda')
#
Bases: Parametric
Variational Autoencoder (VAE) with Gaussian latent space.
This class implements a Variational Autoencoder that learns to encode input data into a probabilistic latent space and decode it back to the original space. The model uses the reparameterization trick to enable gradient-based optimization of the evidence lower bound (ELBO).
The VAE architecture consists of:
- Encoder network that maps inputs to latent distribution parameters
- Latent space parameterization (mean and log-variance)
- Stochastic sampling using the reparameterization trick
- Decoder network that reconstructs inputs from latent samples
The model optimizes the ELBO, which combines reconstruction loss with KL divergence regularization to encourage the latent space to match a standard Gaussian prior.
The negative ELBO is given by
\(-\mathbb{E}_{q(z|x)}[\log p(x|z)] + D_{KL}(q(z|x) || p(z))\),
where \(q(z|x)\) is the approximate posterior, \(p(x|z)\) is the likelihood, and \(p(z)\) is the prior (standard normal).
Another option is to use a log-cosh reconstruction loss instead of Gaussian likelihood, which can be more robust to outliers.
The log-cosh loss is defined as
\(-\mathbb{E}_{q(z|x)}[\log \cosh(p(x|z))] + D_{KL}(q(z|x) || p(z))\).
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Dictionary containing 'encoder' and 'decoder' model specifications.
Example: Note: Encoder must have an output activation function.
TYPE:
|
z_dim
|
Dimensionality of the latent space.
TYPE:
|
loss_fn
|
Loss function type.
TYPE:
|
loss_kwargs
|
Additional keyword arguments to pass to the loss function constructor. See ELBOGaussianLoss and ELBOLogCoshLoss for available options.
TYPE:
|
optimizer_fn
|
Optimizer specification for training.
TYPE:
|
optimizer_kwargs
|
Keyword arguments for optimizer instantiation
(e.g.,
TYPE:
|
lr_scheduler_fn
|
Learning rate scheduler specification.
TYPE:
|
lr_scheduler_kwargs
|
Keyword arguments for scheduler instantiation.
TYPE:
|
device
|
Computation device. Automatically falls back to "cpu" if CUDA unavailable.
TYPE:
|
Examples:
>>> import torch
>>> from spectre.core import Model
>>> from spectre.parametric import VariationalAutoencoder
>>>
>>> # Create encoder and decoder networks
>>> encoder = Model(in_features=784, out_features=128, has_output_fn=True)
>>> decoder = Model(in_features=2, out_features=784)
>>>
>>> # Initialize VAE with model dictionary
>>> vae = VariationalAutoencoder(
... model={"encoder": encoder, "decoder": decoder},
... z_dim=2,
... loss_fn="elbo",
... )
>>>
>>> # Training data
>>> X = torch.randn(100, 784)
>>> weights = torch.ones(100)
>>> batch = (X, weights)
>>>
>>> # Training step
>>> loss = vae.training_step(batch, 0)
>>>
>>> # Generate samples (after training)
>>> vae.is_trained = True
>>> z_sample = torch.randn(10, 2) # Sample from prior
>>> reconstructions = vae.decoder(z_sample)
Notes
- The encoder model must have an output activation function
- Latent space is regularized to match standard Gaussian prior
- The
score_stepmethod provides VAE-specific scoring (negative ELBO)
See Also
Autoencoder: Standard deterministic autoencoder
| METHOD | DESCRIPTION |
|---|---|
forward_step |
Forward pass through the encoder network. |
loss |
Compute VAE loss (ELBO or log-cosh). |
score_step |
Compute VAE reconstruction score. |
training_step |
Training step for PyTorch Lightning with VAE loss. |
encode |
Encode input data to latent distribution parameters. |
decode |
Decode latent codes back to input space. |
sample |
Generate samples from the prior latent distribution. |
reconstruct |
Reconstruct input data through the VAE. |
Source code in spectre/parametric/variational_autoencoder.py
Functions#
forward_step(X: torch.Tensor) -> torch.Tensor
#
Forward pass through the encoder network.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
torch.Tensor of shape (n_samples, encoder_out_features)
|
Encoded representations for latent parameter computation. |
Source code in spectre/parametric/variational_autoencoder.py
loss(X: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None) -> torch.Tensor
#
Compute VAE loss (ELBO or log-cosh).
Computes the variational autoencoder loss combining reconstruction loss with KL divergence regularization of the latent space.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data to encode and reconstruct.
TYPE:
|
weights
|
Sample weights for weighted loss computation.
TYPE:
|
target
|
Ignored for VAE (unsupervised learning).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Scalar VAE loss (ELBO or log-cosh variant). |
Source code in spectre/parametric/variational_autoencoder.py
score_step(X: torch.Tensor, weights: torch.Tensor | None = None, target: torch.Tensor | None = None) -> torch.Tensor
#
Compute VAE reconstruction score.
For VAE, the natural scoring metric is the negative ELBO, which measures how well the model can reconstruct the input data while maintaining a regularized latent space.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data to score.
TYPE:
|
weights
|
Sample weights for weighted scoring.
TYPE:
|
target
|
Ignored for VAE (unsupervised learning).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
VAE score (negative ELBO - lower is better). |
Source code in spectre/parametric/variational_autoencoder.py
training_step(batch: DataBatch, batch_idx: int) -> torch.Tensor
#
Training step for PyTorch Lightning with VAE loss.
Computes the VAE loss (ELBO or log-cosh) and logs it for monitoring during training and validation.
| PARAMETER | DESCRIPTION |
|---|---|
batch
|
Input batch containing (X, weights) where:
TYPE:
|
batch_idx
|
Batch index.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Scalar training loss (VAE ELBO or log-cosh loss). |
Source code in spectre/parametric/variational_autoencoder.py
encode(X: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]
#
Encode input data to latent distribution parameters.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data to encode.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[Tensor, Tensor]
|
Tuple of (
|
Source code in spectre/parametric/variational_autoencoder.py
decode(Z: torch.Tensor) -> torch.Tensor
#
Decode latent codes back to input space.
| PARAMETER | DESCRIPTION |
|---|---|
Z
|
Latent codes to decode.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
torch.Tensor of shape (n_samples, decoder_out_features)
|
Reconstructed data. |
Source code in spectre/parametric/variational_autoencoder.py
sample(n_samples: int = 1) -> torch.Tensor
#
Generate samples from the prior latent distribution.
| PARAMETER | DESCRIPTION |
|---|---|
n_samples
|
Number of samples to generate.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
torch.Tensor of shape (n_samples, decoder_out_features)
|
Generated samples. |
Source code in spectre/parametric/variational_autoencoder.py
reconstruct(X: torch.Tensor, use_mean: bool = False) -> torch.Tensor
#
Reconstruct input data through the VAE.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Input data to reconstruct.
TYPE:
|
use_mean
|
If True, use the mean of the latent distribution instead of sampling. If False, use stochastic sampling (reparameterization trick).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
torch.Tensor of shape (n_samples, decoder_out_features)
|
Reconstructed data. |