4.5.3 · D3Generative Models

Worked examples — Variational Autoencoders (VAE) theory

2,297 words10 min readBack to topic

This page is a hands-on companion to the VAE theory note. We will compute the pieces that the parent note only wrote as symbols. Everything here reduces to two numbers you can check by hand: the reconstruction term and the KL term, whose sum (with a minus sign) is the ELBO we maximise.

Before any example, let me re-earn every symbol so a newcomer can read line one.

Why this exact formula and not a general integral? Because both blobs are Gaussians, the messy integral from the parent note collapses to elementary arithmetic on and . That is the reason VAEs use Gaussians — the regulariser becomes a formula you can differentiate and even evaluate by hand.


The scenario matrix

Every VAE computation you will meet lives in one of these cells. The examples below are labelled by cell so you can see we skipped nothing.

Cell Scenario What is stressed
C1 (encoder already matches prior) KL should be exactly (degenerate/ideal case)
C2 (shifted, right width) only the force acts
C3 — both and the force, both signs
C4 Limiting case (blob collapses to a point) KL ; why a deterministic encoder is punished
C5 Multi-dimensional latent, mixed dimensions KL is a sum; Posterior Collapse preview
C6 Reparameterization: turn into a concrete separating randomness from parameters
C7 Full ELBO on a tiny Bernoulli pixel (word problem) reconstruction + KL together, real units (nats)
C8 Exam twist: -VAE / which term dominates reasoning about the trade-off, no arithmetic trap

Worked examples

C1 — The perfect encoder (degenerate baseline)

Forecast: Guess before reading. The encoder's blob is the target. What should the "distance" be?

  1. Write the per-dimension formula. With : Why this step? Both distributions are Gaussian, so we may use the closed form instead of integrating.
  2. Substitute . Why this step? , so every term vanishes.
  3. Evaluate: .

Verify: KL divergence between two identical distributions is always , and otherwise. Our result sits exactly at the floor — consistent. Units: nats (natural-log information units).


C2 — Shifted mean, correct width

Forecast: Only the centre moved. Which of the three forces should switch on?

  1. Formula, : . Why this step? With correct width the -forces cancel exactly, isolating the mean penalty.
  2. Plug : nats. Why this step? ; the penalty grows quadratically with drift — moving twice as far costs four times as much.

Verify: Sign check — KL is positive (the blob no longer matches the prior). Symmetry check: would give the same nats, because the formula uses ; picture two blobs shifted equally left and right of centre — they are equally "wrong". ✓


C3 — Wrong width, both directions

Here we split into the two sub-cases the matrix demands: too wide () and too narrow (). See the figure — it plots the width-penalty .

Figure — Variational Autoencoders (VAE) theory

Look at the green curve: it bottoms out at exactly (dashed white line) with value , and rises on both sides. That is why any deviation of width, wider or narrower, costs KL.

Forecast: Which is punished harder — a blob twice as wide, or one half as wide?

  1. Formula with : . Why this step? Zero mean kills the term, leaving the pure width force.
  2. C3a, : nats. Why this step? ; the linear growth dominates for wide blobs.
  3. C3b, : nats. Why this step? Now is negative, so is a large positive penalty — this is the force that stops the blob shrinking to a point.

Verify: Both positive ✓. The too-wide blob () costs more than this particular too-narrow one (), matching the curve's steeper right arm in the figure. As a limiting sanity check, C4 next shows the narrow arm eventually wins as . ✓


C4 — The collapse limit

Forecast: A standard autoencoder outputs a single point (zero width). Guess whether the VAE's KL rewards or punishes that.

  1. Formula: .
  2. Evaluate the three values:
    • Why this step? Each tenfold shrink adds about nats — the penalty grows without bound.
  3. Limit: as , the term , so . Why this step? of a number approaching zero dives to ; negating it launches the penalty to .

Verify: The increments rise by — approaching the predicted . ✓


C5 — Multi-dimensional latent, mixed dimensions

Forecast: Which single dimension contributes nothing?

  1. KL is a sum over independent dimensions: Why this step? A diagonal Gaussian factorises, so information distances add — no cross terms.
  2. Dimension 1 (): . (This is a "collapsed" dimension — a preview of Posterior Collapse.)
  3. Dimension 2 (): .
  4. Dimension 3 (): reuse C3b .
  5. Add: nats.

Verify: Total is the plain sum of three non-negative per-dim values ✓. Dimension 1 contributes exactly — an inactive latent the decoder ignores, precisely what posterior collapse looks like at the arithmetic level. ✓


C6 — Reparameterization: from to a concrete

Forecast: Which parts of the calculation depend on the trainable parameters, and which is "frozen noise"?

  1. Apply the trick : Why this step? This is the Reparameterization Trick: it moves the randomness out of the network into , so the path is a plain differentiable formula.
  2. Gradient check (by hand): Why this step? Both derivatives exist and are finite — that is the whole point. Sampling directly from would have no usable derivative w.r.t. .

The figure shows it visually: fixed noise on a standard bell curve, stretched by and shifted by into the output blob.

Figure — Variational Autoencoders (VAE) theory

Verify: Statistically, with has mean and variance — exactly the distribution we wanted to sample from. Sanity: means a unit shift of the mean shifts the sample one-for-one. ✓


C7 — Full ELBO on a single Bernoulli pixel (word problem)

Forecast: The ELBO has two parts. Guess which one is a familiar cross-entropy.

  1. Reconstruction term — log-likelihood of a Bernoulli pixel: Why this step? A binary pixel is a coin flip; its log-probability is the Bernoulli log-likelihood (this is exactly negative binary cross-entropy).
  2. Plug : nats. Why this step? Correct-but-uncertain prediction gives a small negative log-likelihood; a perfect would give .
  3. KL term (): nats. (reuses the C2 pattern) Why this step? Regularises the encoder toward the prior; here only the small mean-drift acts.
  4. ELBO nats. Why this step? Definition of the ELBO from the parent note; we maximise it, i.e. minimise its negative.
  5. Training loss nats.

Verify: Units all in nats ✓. Both pieces have the right sign: reconstruction log-likelihood ✓, KL ✓. If the decoder were perfect () and encoder ideal (), loss would drop to — the global optimum. ✓


C8 — Exam twist: which term wins in -VAE?

Forecast: Big favours organisation over fidelity — guess which failure mode it invites.

  1. Balance condition: set , i.e. . Why this step? We want the point where the two competing forces are equal in size.
  2. Solve: . Why this step? Above this, regularisation outweighs reconstruction.
  3. Limit reasoning (): the loss is dominated by , which is minimised at , i.e. — the encoder ignores entirely. That is Posterior Collapse; it also links to why disentanglement is sought by moderate , not extreme. Why this step? No arithmetic trap — the exam tests whether you can reason about the trade-off's endpoints.

Verify: At , ✓. As the reconstruction term becomes negligible relative to the exploding KL weight, forcing onto the prior. ✓


Recall Quick self-test

What is when ? ::: Exactly — the encoder already matches the prior. Why does blow up the KL? ::: The term goes to , forbidding a deterministic encoder. In the reparameterization , what is ? ::: — gradients flow straight through the mean. For a 3-D latent, how do the per-dimension KLs combine? ::: They add (the diagonal Gaussian factorises). As in a -VAE, what failure appears? ::: Posterior collapse (, latent ignored).

See also: Bayesian Inference for the posterior these examples approximate, and Generative Adversarial Networks (GANs) / Normalizing Flows / Conditional VAE for alternative generative objectives.