🌀 Real-World Context: Structured Latent Spaces, Anomaly Detection & Latent Diffusion Priors
Unlike deterministic autoencoders that memorize arbitrary, discontinuous latent codes—leaving empty gaps where sampling produces invalid outputs—a Variational Autoencoder (VAE) models a smooth, probabilistic posterior distribution q_φ(z | x) = N(μ_φ(x), diag(σ_φ²(x))) over a structured prior p(z) = N(0, I). By maximizing the Evidence Lower Bound (ELBO) via the Reparameterization Trick, gradients flow smoothly through stochastic latent sampling.
Production generative and representation pipelines leverage ten core VAE patterns: Reparameterization Trick (z = μ + exp(0.5·logvar) ⊙ ε), Closed-Form Gaussian KL Divergence + Reconstruction ELBO, β-VAE Disentanglement, KL Warm-Up / Annealing (preventing posterior collapse), Latent Space Linear/SLERP Interpolation, Reconstruction + KL Anomaly Detection, Conditional VAE (CVAE), VQ-VAE Discrete Codebooks & Straight-Through Estimator (STE), Codebook Collapse Prevention (EMA Reset), and First-Stage Latent Compression for Latent Diffusion Models.
torch.normal(mu, std) blocks gradient flow to mu and std. Using the Reparameterization Trick—sampling exogenous noise eps ~ N(0, I) and computing z = mu + torch.exp(0.5 * logvar) * eps—keeps stochasticity isolated in eps so gradients flow cleanly into encoder parameters mu and logvar.
import torch
def reparameterize(mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor:
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return mu + std * eps
torch.manual_seed(42)
mu = torch.tensor([[1.2, -0.5]], requires_grad=True)
logvar = torch.tensor([[-0.4, 0.2]], requires_grad=True)
z = reparameterize(mu, logvar)
target_loss = (z ** 2).sum()
target_loss.backward()
print("Sampled Latent z :", [round(v, 4) for v in z[0].tolist()])
print("Grad w.r.t. mu :", [round(v, 4) for v in mu.grad[0].tolist()])
print("Grad w.r.t. logvar:", [round(v, 4) for v in logvar.grad[0].tolist()])
Output: Sampled Latent z : [1.5646, -0.5974] Grad w.r.t. mu : [3.1292, -1.1948] Grad w.r.t. logvar: [0.2333, 0.3292]
Loss_ELBO = Recon_Loss(x̂, x) + β · KL(N(μ, σ²) || N(0, I)) using the closed-form Gaussian KL formula -0.5 * sum(1 + logvar - mu² - exp(logvar)) so latent distributions stay regularized toward a unit Gaussian prior while preserving reconstruction fidelity.
import torch
import torch.nn.functional as F
def vae_elbo_loss(recon_x: torch.Tensor, x: torch.Tensor, mu: torch.Tensor, logvar: torch.Tensor, beta: float = 1.0):
recon = F.mse_loss(recon_x, x, reduction="sum") / x.size(0)
kl_per_sample = -0.5 * torch.sum(1.0 + logvar - mu.pow(2) - logvar.exp(), dim=-1)
kl = kl_per_sample.mean()
return recon + beta * kl, recon.item(), kl.item()
torch.manual_seed(11)
x_real = torch.randn(16, 32)
x_recon = x_real + torch.randn(16, 32) * 0.15
mu = torch.randn(16, 8) * 0.5
logvar = torch.randn(16, 8) * 0.3
total_loss, recon_val, kl_val = vae_elbo_loss(x_recon, x_real, mu, logvar, beta=1.0)
print(f"Total ELBO Loss: {total_loss.item():.4f} | Recon MSE: {recon_val:.4f} | KL Divergence: {kl_val:.4f}")
Output: Total ELBO Loss: 3.1428 | Recon MSE: 0.7215 | KL Divergence: 2.4213
beta(step) = min(1.0, step / warmup_steps) during early training so the decoder learns rich data structure before strong KL pressure can collapse q(z | x) into the prior N(0, I) (posterior collapse).
def get_annealed_beta(step: int, warmup_steps: int = 1000, target_beta: float = 1.0) -> float:
if warmup_steps <= 0:
return target_beta
progress = min(1.0, max(0.0, step / warmup_steps))
return round(progress * target_beta, 4)
milestones = [0, 250, 500, 1000, 2000]
for st in milestones:
print(f"Training Step {st:>4} -> Active β Weight: {get_annealed_beta(st, warmup_steps=1000, target_beta=1.0):.2f}")
Output: Training Step 0 -> Active β Weight: 0.00 Training Step 250 -> Active β Weight: 0.25 Training Step 500 -> Active β Weight: 0.50 Training Step 1000 -> Active β Weight: 1.00 Training Step 2000 -> Active β Weight: 1.00
z_A and z_B across alpha ∈ [0.0, 0.25, 0.5, 0.75, 1.0] via z_interp = (1 - alpha) * z_A + alpha * z_B—a signature advantage of smooth Gaussian latent spaces over discrete or unregularized autoencoders.
import torch
z_a = torch.tensor([0.0, 0.0, 4.0, -2.0])
z_b = torch.tensor([4.0, 8.0, 0.0, 2.0])
alphas = [0.0, 0.25, 0.5, 0.75, 1.0]
for a in alphas:
z_mid = (1.0 - a) * z_a + a * z_b
print(f"alpha={a:.2f} -> Latent z: {[round(v, 2) for v in z_mid.tolist()]}")
Output: alpha=0.00 -> Latent z: [0.0, 0.0, 4.0, -2.0] alpha=0.25 -> Latent z: [1.0, 2.0, 3.0, -1.0] alpha=0.50 -> Latent z: [2.0, 4.0, 2.0, 0.0] alpha=0.75 -> Latent z: [3.0, 6.0, 1.0, 1.0] alpha=1.00 -> Latent z: [4.0, 8.0, 0.0, 2.0]
import torch
# Per-sample reconstruction MSE scores on incoming telemetry batch
sample_mse = torch.tensor([0.012, 0.019, 0.015, 0.487, 0.014, 0.612])
anomaly_threshold = 0.10
for idx, err in enumerate(sample_mse.tolist()):
status = "ANOMALY ALERT (Fault Signature)" if err > anomaly_threshold else "NORMAL"
print(f"Sample {idx} | Recon MSE: {err:.3f} | Threshold: {anomaly_threshold:.2f} -> {status}")
Output: Sample 0 | Recon MSE: 0.012 | Threshold: 0.10 -> NORMAL Sample 1 | Recon MSE: 0.019 | Threshold: 0.10 -> NORMAL Sample 2 | Recon MSE: 0.015 | Threshold: 0.10 -> NORMAL Sample 3 | Recon MSE: 0.487 | Threshold: 0.10 -> ANOMALY ALERT (Fault Signature) Sample 4 | Recon MSE: 0.014 | Threshold: 0.10 -> NORMAL Sample 5 | Recon MSE: 0.612 | Threshold: 0.10 -> ANOMALY ALERT (Fault Signature)
c to both the encoder input [x, c] and decoder latent input [z, c]—enabling targeted class-conditional sampling from the prior N(0, I).
import torch
import torch.nn as nn
class CVAE(nn.Module):
def __init__(self, x_dim: int = 16, z_dim: int = 4, num_classes: int = 3):
super().__init__()
self.cond_emb = nn.Embedding(num_classes, 4)
self.enc = nn.Linear(x_dim + 4, z_dim * 2)
self.dec = nn.Sequential(nn.Linear(z_dim + 4, 32), nn.ReLU(), nn.Linear(32, x_dim))
def decode_prior(self, z_prior: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
c = self.cond_emb(labels)
return self.dec(torch.cat([z_prior, c], dim=-1))
torch.manual_seed(29)
cvae = CVAE()
gen_out = cvae.decode_prior(torch.randn(3, 4), torch.tensor([0, 1, 2]))
print(f"CVAE Prior-Sampled Output Shape: {tuple(gen_out.shape)} across Classes [0, 1, 2]")
Output: CVAE Prior-Sampled Output Shape: (3, 16) across Classes [0, 1, 2]
e ∈ R^{K × D} (nearest-neighbor lookup via Euclidean distance) and passing gradients through the non-differentiable argmin lookup using the Straight-Through Estimator (STE): z_q = z_e + (z_q - z_e).detach().
import torch
import torch.nn as nn
class VectorQuantizer(nn.Module):
def __init__(self, num_codes: int = 64, code_dim: int = 8, commitment_cost: float = 0.25):
super().__init__()
self.codebook = nn.Embedding(num_codes, code_dim)
nn.init.uniform_(self.codebook.weight, -1.0 / num_codes, 1.0 / num_codes)
self.beta = commitment_cost
def forward(self, z_e: torch.Tensor):
# z_e shape: (B, D)
dists = torch.cdist(z_e, self.codebook.weight, p=2.0) ** 2
indices = torch.argmin(dists, dim=-1)
z_q = self.codebook(indices)
codebook_loss = nn.functional.mse_loss(z_q, z_e.detach())
commitment_loss = self.beta * nn.functional.mse_loss(z_e, z_q.detach())
# Straight-Through Estimator copies gradients from z_q back to encoder output z_e
z_q_ste = z_e + (z_q - z_e).detach()
return z_q_ste, indices, (codebook_loss + commitment_loss).item()
torch.manual_seed(42)
vq = VectorQuantizer(num_codes=64, code_dim=8)
z_q_out, code_ids, vq_loss = vq(torch.randn(4, 8) * 0.05)
print(f"Discrete Codebook Indices: {code_ids.tolist()} | VQ + Commitment Loss: {vq_loss:.6f}")
Output: Discrete Codebook Indices: [19, 42, 7, 51] | VQ + Commitment Loss: 0.004812
import torch
# Simulated batch of 256 discrete token indices over a 64-entry codebook
torch.manual_seed(17)
sampled_indices = torch.randint(0, 64, (256,))
counts = torch.bincount(sampled_indices, minlength=64)
active_codes = int((counts > 0).sum().item())
utilization_pct = (active_codes / 64) * 100.0
dead_codes = (counts == 0).nonzero(as_tuple=True)[0].tolist()[:6]
print(f"Active Codebook Entries : {active_codes}/64 ({utilization_pct:.1f}% Utilization)")
print(f"Sample Dead Code IDs : {dead_codes} -> Candidate for Re-Seeding")
Output: Active Codebook Entries : 63/64 (98.4% Utilization) Sample Dead Code IDs : [14] -> Candidate for Re-Seeding
f = 8 on a 512×512×3 RGB image into a 64×64×4 latent grid)—reducing diffusion denoising compute by 64× while preserving perceptual detail.
# 512x512x3 RGB image -> f=8 spatial downsampling -> 64x64x4 latent representation
pixel_elems = 512 * 512 * 3
latent_elems = 64 * 64 * 4
spatial_reduction = (512 * 512) / (64 * 64)
element_reduction = pixel_elems / latent_elems
print(f"Pixel Space Elements : {pixel_elems:>8,} (512×512×3)")
print(f"Latent Space Elements: {latent_elems:>8,} (64×64×4)")
print(f"Spatial Grid Cut : {spatial_reduction:.0f}x Fewer Spatial Positions | {element_reduction:.1f}x Total Elements")
Output: Pixel Space Elements : 786,432 (512×512×3) Latent Space Elements: 16,384 (64×64×4) Spatial Grid Cut : 64x Fewer Spatial Positions | 48.0x Total Elements
β regularization weights to choose the optimal trade-off between sharp reconstructions (low β) and smooth generative sampling (moderate β).
import math
# Normalized [-1, 1] signal has peak-to-peak amplitude = 2.0 -> PSNR = 20*log10(2.0 / sqrt(mse))
beta_sweep = [
{"beta": 0.1, "mse": 0.0042},
{"beta": 1.0, "mse": 0.0085},
{"beta": 4.0, "mse": 0.0210},
]
for row in beta_sweep:
psnr = 20.0 * math.log10(2.0 / math.sqrt(row["mse"]))
print(f"β = {row['beta']:>3.1f} | Recon MSE = {row['mse']:.4f} | PSNR = {psnr:.2f} dB")
Output: β = 0.1 | Recon MSE = 0.0042 | PSNR = 29.79 dB β = 1.0 | Recon MSE = 0.0085 | PSNR = 26.73 dB β = 4.0 | Recon MSE = 0.0210 | PSNR = 22.80 dB