In a VAE with prior p(z)=N(0,I) and diagonal Gaussian encoder qϕ(z∣x)=N(μ,diag⁡(σ12,…,σd2)), how do you derive the closed-form KL divergence DKL(qϕ(z∣x) ∥ p(z)), and what does each term encourage?

Deep learning, Variational autoencoders
Level L3 Intermediate. Length Long. Nature Mat Mathematical.

What's being asked

Whether you can integrate the KL between two diagonal Gaussians from first principles and interpret the resulting regulariser.

Key idea

Because both qϕ(z∣x) and p(z) factorise across the d coordinates, the KL splits into a sum of d 1-D integrals, giving DKL(qϕ(z∣x) ∥ p(z))=−12∑j=1d(1+log⁡σj2−μj2−σj2).

Steps

  1. Factorise across dimensions: since covariance is diagonal, DKL(q∥p)=∑j=1dDKL(N(μj,σj2) ∥ N(0,1)), so it suffices to compute one 1-D integral.
  2. Write log⁡q(zj)p(zj): using log⁡q(zj)=−12log⁡(2πσj2)−(zj−μj)22σj2 and log⁡p(zj)=−12log⁡(2π)−zj22, the log⁡(2π) constants cancel: log⁡q(zj)p(zj)=−12log⁡σj2−(zj−μj)22σj2+zj22.
  3. Take the expectation under zj∼q(zj)=N(μj,σj2): use Eq[(zj−μj)2]=σj2 and Eq[zj2]=Var⁡q(zj)+(Eq[zj])2=σj2+μj2.
  4. Substitute and simplify: DKL(qj∥pj)=−12log⁡σj2−12+σj2+μj22=−12(1+log⁡σj2−μj2−σj2). Sum over j=1,…,d.
  5. Sanity check and interpretation: at μj=0,σj=1, the term is −12(1+0−0−1)=0; at μj=1,σj=2, it is −12(1+ln⁡4−1−4)=2−ln⁡2≈1.307>0. Minimising this pulls μj→0 (centring codes near the origin) and σj2→1 (preventing the encoder from collapsing posteriors to zero-variance points).

Common mistakes

How long your answer should be

About one page; 5–7 minutes.

Last checked on 4 December 2026.

Read this

Previous in Deep learning: How does a DenseNet block differ from a ResNet block in how earlier features are combined, what is the channel count entering layer l (with initial channels k0 and growth rate k), and what is the trade-off between parameter efficiency and GPU memory?
Next in Deep learning: For the minimax GAN objective min⁡Gmax⁡DV(D,G)=Ex∼pdata[log⁡D(x)]+Ez∼pz[log⁡(1−D(G(z)))], how do you derive the optimal discriminator DG∗(x) for a fixed generator G, and show that substituting DG∗ reduces the generator objective to 2DJS(pdata∥pg)−log⁡4?