Equations · Kingma and Welling, “Auto-Encoding Variational Bayes” (2014)

The reparameterization trick (z = μ + σ ⊙ ε), explained

A VAE's encoder outputs a Gaussian over latent codes, and the loss needs a sample from it. Sampling directly would block backpropagation, since you cannot differentiate through a random draw. The trick draws standard noise separately, then builds the sample as a differentiable function of the encoder's outputs.

z=μ+σ⊙ϵ,ϵ∼N(0,I)\mathbf{z} = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\epsilon}, \quad \boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I})

Open in the decoder →

Term by term

  1. μ, σ\boldsymbol{\mu}, \ \boldsymbol{\sigma}

    The mean and standard deviation of the encoder's Gaussian qϕ(z∣x)q_\phi(\mathbf{z} \mid \mathbf{x}), one entry per latent dimension. Encoders usually output log⁡σ2\log \boldsymbol{\sigma}^2 and exponentiate, to keep σ\boldsymbol{\sigma} positive.

  2. ϵ∼N(0,I)\boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I})

    Standard normal noise, independent of the parameters. All the randomness lives here. ϵ\boldsymbol{\epsilon} is a random vector, not a small constant.

  3. σ⊙ϵ\boldsymbol{\sigma} \odot \boldsymbol{\epsilon}

    Elementwise product: each noise entry scaled by its dimension's standard deviation.

  4. z\mathbf{z}

    The latent sample, distributed as N(μ,diag⁡(σ2))\mathcal{N}(\boldsymbol{\mu}, \operatorname{diag}(\boldsymbol{\sigma}^2)), exactly as if drawn directly. Now ∂z/∂μ=1\partial \mathbf{z}/\partial \boldsymbol{\mu} = 1 and ∂z/∂σ=ϵ\partial \mathbf{z}/\partial \boldsymbol{\sigma} = \boldsymbol{\epsilon}, so gradients reach the encoder.

A small worked example

One latent dimension: μ=1\mu = 1, σ=0.5\sigma = 0.5, drawn ϵ=−0.6\epsilon = -0.6. Then z=1+0.5×(−0.6)=0.7z = 1 + 0.5 \times (-0.6) = 0.7. If the loss has gradient gg with respect to zz, the encoder receives gg for μ\mu and −0.6 g-0.6\,g for σ\sigma.

In code

import torch

def reparameterize(mu, logvar):
    std = torch.exp(0.5 * logvar)     # sigma from log sigma^2
    eps = torch.randn_like(std)       # the randomness, outside the graph
    return mu + std * eps

Every symbol in it

μ\muMuσ(z)\sigma(z)Sigma (lowercase)x∈Rd\mathbf{x} \in \mathbb{R}^{d}Bold lowercase (vector)ϵ\epsilonEpsilonx∼pdatax \sim p_{\text{data}}Distributed as (tilde)N(μ,σ2)\mathcal{N}(\mu, \sigma^2)Normal distributionIn\mathbf{I}_nIdentity matrixa⊙b\mathbf{a} \odot \mathbf{b}Hadamard (elementwise) product

Other equations