Sample a VAE latent with the reparameterization trick

A VAE encoder outputs a mean and a log-variance per latent dimension. Sampling directly would block gradients, so the noise is drawn separately and the sample is written as a differentiable function of the encoder outputs.

Write reparameterize(mu, logvar, eps). All three have the same shape. Return z = mu + sigma * eps, where sigma = exp(0.5 * logvar) is the standard deviation.

Signaturedef reparameterize(mu, logvar, eps)

Example

mu = [1], logvar = [log(4)], eps = [0.5] gives sigma = 2 and z = [2.0].

Understand the idea

A VAE encoder predicts a mean and a log-variance for each latent dimension, and we need a random sample from that Gaussian. Drawing it directly would block gradients, so the trick is to draw plain noise eps from N(0, 1) separately and then shift and stretch it. The randomness sits entirely in eps, and the sample becomes simple arithmetic on mu and sigma, which gradients can flow through. Worked example: mu = 1, logvar = 2 * ln 3 = 2.1972, eps = -0.5. sigma = exp(0.5 * 2.1972) = exp(1.0986) = 3, so z = 1 + 3 * (-0.5) = -0.5. Rule: sigma = exp(0.5 * logvar), which is the standard deviation, and z = mu + sigma * eps, elementwise. Using exp(logvar) would scale by the variance (9 here) instead of the standard deviation (3), and is wrong whenever the variance is not 1. The same trick appears in VAEs, diffusion forward noising and many latent variable models.

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

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplereparameterize([1.0], [np.log(4.0)], [0.5])
  • Sample 2: zero noise returns meanreparameterize(_mu, _lv, np.zeros((3, 4)))
  • Test 3: random batchreparameterize(_mu, _lv, _eps)