A variational autoencoder's encoder outputs a Gaussian for each input. Training maximises the ELBO, which means minimising reconstruction error plus the KL divergence from the prior .
Implement:
reparameterize(mu, logvar, eps): . This lets gradients flow through the sampling.kl_divergence(mu, logvar): the closed form , summed over latent dimensions and averaged over the batchkl_grads(mu, logvar): gradients of that (batch-averaged) KL with respect to mu and logvarvae_loss(x, x_hat, mu, logvar, beta=1.0): the mean over the batch of (summed squared reconstruction error + β · KL per sample)