Skip to content

← Generative Models step 4 of 11

Medium Primitives

VAE ELBO Loss

A variational autoencoder (VAE) encodes each input as a distribution over latent vectors, then decodes a sampled vector to reconstruct the input. This exercise combines two training terms:

  • Reconstruction error measures how far the decoder output is from the input.
  • KL divergence penalizes a difference between the encoder's distribution and a standard normal prior (zero mean and unit variance).

The encoder distribution is a diagonal Gaussian. mu gives its means, and log_var gives the natural logarithms of its variances. Coordinates are independent under this distribution; their variances are exp(log_var).

Your task

Implement vae_elbo_loss(reconstructed, original, mu, log_var):

  • reconstructed and original have shape (N, d).
  • mu and log_var have shape (N, d_z).
  • All inputs are floating-point tensors. N, d, and d_z are positive; the input dimension d need not equal the latent dimension d_z.

For each example, sum (reconstructed - original) ** 2 over its d input features. Average those sums over the batch to obtain the reconstruction loss.

For each example, compute

KL = 0.5 * sum(mu ** 2 + exp(log_var) - 1 - log_var)

over its d_z latent coordinates. Average those KL values over the batch. Return the reconstruction loss plus the KL loss as a Python float. Do not average over features or latent coordinates, and do not add a separate weight to either term.

For one example with original = [1, 2], reconstructed = [2, 2], mu = [1, 0], and log_var = [0, 0], reconstruction contributes 1 and KL contributes 0.5. The total is 1.5. A perfect reconstruction with zero means and zero log variances gives zero loss.

How this relates to the ELBO

The evidence lower bound (ELBO) is an objective that VAEs maximize. Its negative combines expected negative log likelihood with KL divergence. The sum of squared errors used here corresponds to a Gaussian decoder with fixed variance 0.5 per input coordinate, after dropping an additive constant. A reconstruction from a sampled latent vector supplies an estimate of the expectation. Other likelihoods or variances give different reconstruction losses or scales; squared error is not a universal VAE rule.

You receive the reconstructed values here, so no sampling is required. Use inputs for which the exponentials and total are representable. This exercise requests a float for comparison; a training loop should keep the loss as a tensor for differentiation.

Reference: Auto-Encoding Variational Bayes.