Backpropagate through the VAE reparameterization and KL term
Why it matters Every VAE encoder, including the latent encoders of image generators, learns mu and logvar through these two gradient paths.
The reparameterization trick moves the randomness into eps so gradients can reach mu and logvar. Writing the backward pass by hand shows both paths: through the sample and through the KL.
Write vae_latent_backward(mu, logvar, eps, dz, beta). All arrays are (n, d). Forward: z = mu + exp(0.5 * logvar) * eps, and kl = beta * mean over the batch of 0.5 * sum over d of (mu^2 + exp(logvar) - 1 - logvar). dz is the gradient of the reconstruction loss with respect to z. Return a dict with "z", "kl" (a float), "dmu" and "dlogvar": the gradients of (reconstruction loss + kl) with respect to mu and logvar.
def vae_latent_backward(mu, logvar, eps, dz, beta)Example
mu = [[1]], logvar = [[0]], eps = [[2]], dz = [[0.5]], beta = 1 gives z [[3]], kl 0.5, dmu [[1.5]] and dlogvar [[0.5]].
Understand the idea
Sampling is random, and you cannot take a gradient through a coin flip. The trick is to draw the randomness eps first, from a fixed N(0, 1), and then build the sample as z = mu + sigma * eps. Now z is an ordinary function of mu and sigma, so gradients flow to them. It is like rolling a die once and then deciding how to stretch and shift the result.
Tiny example: mu = 1, logvar = 0 (sigma = 1), eps = 2: z = 3. KL = 0.5 * (1 + 1 - 1 - 0) = 0.5. With dz = 0.5: dmu = 0.5 + 1 = 1.5. dlogvar = 0.5 * 2 * 0.5 * 1 = 0.5 from the sample, plus 0.5 * (1 - 1) = 0 from the KL.
Rules: dmu = dz + beta mu / n; dlogvar = dz eps 0.5 sigma + beta 0.5 (exp(logvar) - 1) / n.
This is what lets VAEs, and the VAE encoders used by latent diffusion models, train with plain backprop.
Shapes and data flow
mu, logvar, eps, dz (n, d) -> z, dmu, dlogvar (n, d); kl scalar