VAE ELBO loss
Background
A variational autoencoder (VAE) is trained to maximize the evidence lower bound (ELBO), equivalently to minimize a loss with two terms: a reconstruction term (how well the decoder rebuilds the input) and a KL term that pulls the encoder's latent distribution toward a standard-normal prior. The KL term is what regularizes the latent space so it can be sampled to generate new data.
Problem statement
Implement vae_elbo_loss(x, x_recon, mu, logvar) returning the mean negative-ELBO loss. Use squared-error reconstruction (summed over features) and the closed-form Gaussian KL:
Input
x,x_recon—np.ndarray(N, d), input and its reconstruction.mu,logvar—np.ndarray(N, d), the encoder's latent mean and log-variance.
Output
A scalar float: the mean loss over the batch.
Examples
Example 1
Input: x = [[1, 0]], x_recon = [[1, 0]], mu = [[0, 0]], logvar = [[0, 0]]
Output: 0.0
Explanation: perfect reconstruction makes the SSE term 0; with and the posterior equals the prior, so KL is . The loss is 0.
Constraints
- Convert
logvarto variance withexpinside the KL. - Sum both terms over the feature axis per example, then average over the batch.
- Return reconstruction plus KL (the quantity minimized = negative ELBO).
Notes
- The KL is always and is 0 exactly when — the posterior matches the prior.
- Using
logvar(rather than ) keeps the variance positive and the optimization numerically stable.
This problem ships 5 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.
- •Perfect reconstruction with prior-matching posterior is 0
- •KL term for mu=1, logvar=0 equals 1 (per latent dim)
- •Reconstruction term is summed squared error
- •KL is always non-negative
- •Loss is the batch mean