Compute the VAE loss: reconstruction BCE plus KL to a standard normal

A VAE is trained by minimising the negative ELBO: how badly the decoder rebuilds the input, plus how far the encoder's Gaussian drifts from the N(0, 1) prior. Getting the sums and constants right matters, because the balance between the two terms sets how blurry or how disorganised the model becomes.

Write vae_loss(x, x_prob, mu, logvar, beta=1.0). x is (B, D) with values in [0, 1]; x_prob is the decoder's Bernoulli probabilities (B, D); mu and logvar are (B, k).
- Clip x_prob to [1e-7, 1 - 1e-7].
- recon per example = sum over D of -(x log p + (1 - x) log(1 - p)).
- kl per example = -0.5 * sum over k of (1 + logvar - mu**2 - exp(logvar)).
Return a dict {"recon": ..., "kl": ..., "loss": ...} where recon and kl are batch means and loss = recon + beta * kl (all floats).

Signaturedef vae_loss(x, x_prob, mu, logvar, beta=1.0)

Example

x = [[1]], x_prob = [[0.5]], mu = [[0]], logvar = [[0]] gives recon = 0.69315, kl = 0, loss = 0.69315.

Understand the idea

The VAE loss has two parts. Reconstruction asks how well the decoder rebuilds the input; with pixels in [0, 1] this is binary cross-entropy summed over pixels. The KL term asks how far the encoder's Gaussian is from a standard normal, and has a closed form. Beta sets the balance between the two. Worked example: x = [[1, 0]], decoder probabilities [[0.8, 0.4]]. recon = -ln 0.8 - ln(1 - 0.4) = 0.2231 + 0.5108 = 0.7340. For one latent with mu = 1 and logvar = 0: kl = -0.5 * (1 + 0 - 1 - 1) = 0.5. With beta = 1, loss = 1.2340. Rules: clip probabilities to [1e-7, 1 - 1e-7]; recon per example = sum over D of -(x log p + (1 - x) log(1 - p)); kl per example = -0.5 * sum over k of (1 + logvar - mu^2 - exp(logvar)); report batch means of each and loss = recon + beta * kl. Dropping the 0.5 doubles the prior term. This is the training objective for VAEs, including the image autoencoders inside latent diffusion.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplevae_loss([[1.0]], [[0.5]], [[0.0]], [[0.0]])
  • Sample 2: random batchvae_loss(_x, _p, _mu, _lv)