4.5.4Generative Models

Reparameterization trick

2,435 words11 min readdifficulty · medium2 backlinks

The Core Problem

In a VAE, the encoder outputs parameters of a distribution qϕ(zx)q_\phi(z|x), typically N(μϕ(x),σϕ2(x))\mathcal{N}(\mu_\phi(x), \sigma_\phi^2(x)). We need to:

  1. Sample zqϕ(zx)z \sim q_\phi(z|x)
  2. Compute loss involving zz
  3. Backpropagate to update ϕ\phi (the encoder parameters)

The Reparameterization Trick: Derivation from Scratch

Step-by-Step Construction

Start with the property of Gaussian distributions:

If ϵN(0,1)\epsilon \sim \mathcal{N}(0, 1) (standard normal), then for any μ\mu and σ>0\sigma > 0:

z=μ+σϵN(μ,σ2)z = \mu + \sigma \cdot \epsilon \sim \mathcal{N}(\mu, \sigma^2)

Why this step? This is the location-scale property of the Gaussian. We're shifting (μ\mu) and stretching (σ\sigma) a standard normal.

Proof:

  • E[z]=E[μ+σϵ]=μ+σ0=μ\mathbb{E}[z] = \mathbb{E}[\mu + \sigma\epsilon] = \mu + \sigma \cdot 0 = \mu
  • Var(z)=Var(μ+σϵ)=σ2Var(ϵ)=σ21=σ2\text{Var}(z) = \text{Var}(\mu + \sigma\epsilon) = \sigma^2 \cdot \text{Var}(\epsilon) = \sigma^2 \cdot 1 = \sigma^2

Now the critical rewrite:

Instead of: zqϕ(zx)=N(μϕ(x),σϕ2(x))z \sim q_\phi(z|x) = \mathcal{N}(\mu_\phi(x), \sigma_\phi^2(x))

We write: ϵN(0,1)\epsilon \sim \mathcal{N}(0, 1) z=μϕ(x)+σϕ(x)ϵz = \mu_\phi(x) + \sigma_\phi(x) \cdot \epsilon

Why this step? Now zz is a deterministic function of ϕ\phi (through μϕ\mu_\phi and σϕ\sigma_\phi) and the random noise ϵ\epsilon. The randomness lives only in ϵ\epsilon, which doesn't depend on our parameters.

Gradient Flow

The loss typically looks like: L(ϕ)=Eqϕ(zx)[f(z,x)]\mathcal{L}(\phi) = \mathbb{E}_{q_\phi(z|x)}[f(z, x)]

Old way (doesn't work): ϕL=Eqϕ(zx)[ϕf(z,x)]← STUCK! Can’t compute ϕz\nabla_\phi \mathcal{L} = \mathbb{E}_{q_\phi(z|x)}\left[\nabla_\phi f(z, x)\right] \quad \text{← STUCK! Can't compute } \nabla_\phi z

New way (reparameterized): L(ϕ)=Ep(ϵ)[f(gϕ(ϵ,x),x)]\mathcal{L}(\phi) = \mathbb{E}_{p(\epsilon)}[f(g_\phi(\epsilon, x), x)]

ϕL=Ep(ϵ)[ϕf(gϕ(ϵ,x),x)]\nabla_\phi \mathcal{L} = \mathbb{E}_{p(\epsilon)}\left[\nabla_\phi f(g_\phi(\epsilon, x), x)\right]

Why this step? The expectation is now over p(ϵ)p(\epsilon), which doesn't depend on ϕ\phi. We can swap the gradient and expectation:

=Ep(ϵ)[fzgϕϕ]= \mathbb{E}_{p(\epsilon)}\left[\frac{\partial f}{\partial z} \cdot \frac{\partial g_\phi}{\partial \phi}\right]

The chain rule works! gϕϕ\frac{\partial g_\phi}{\partial \phi} involves simple derivatives:

  • μϕ(μϕ+σϕϵ)=1\frac{\partial}{\partial \mu_\phi}(\mu_\phi + \sigma_\phi \epsilon) = 1
  • σϕ(μϕ+σϕϵ)=ϵ\frac{\partial}{\partial \sigma_\phi}(\mu_\phi + \sigma_\phi \epsilon) = \epsilon
Figure — Reparameterization trick

Why It Works: The Math

Proof sketch: Change of variables. If z=μ+σϵz = \mu + \sigma \epsilon, then dz=σdϵdz = \sigma \, d\epsilon, and: pz(z)dz=pϵ(zμσ)dzσp_z(z) dz = p_\epsilon\left(\frac{z-\mu}{\sigma}\right) \frac{dz}{\sigma}

The distributions match by construction. The expectations are equal.

The gradient trick works because:

  • The expectation over ϵ\epsilon doesn't depend on ϕ\phi
  • Leibniz integral rule: ϕp(ϵ)f(gϕ(ϵ))dϵ=p(ϵ)ϕf(gϕ(ϵ))dϵ\nabla_\phi \int p(\epsilon) f(g_\phi(\epsilon)) d\epsilon = \int p(\epsilon) \nabla_\phi f(g_\phi(\epsilon)) d\epsilon
  • We can push the gradient inside the expectation

Practical Implementation

# PyTorch pseudocode
def reparameterize(mu, log_var):
    """
    mu: [batch, latent_dim] - mean from encoder
    log_var: [batch, latent_dim] - log variance (for numerical stability)
    """
    std = torch.exp(0.5 * log_var)  # sigma = exp(log_var / 2)
    eps = torch.randn_like(std)      # sample epsilon ~ N(0, 1)
    z = mu + std * eps               # reparameterization
    return z

Common Mistakes

Generalizations

The trick extends beyond Gaussians:

Distribution Reparameterization
Gaussian z=μ+σϵz = \mu + \sigma \epsilon, ϵN(0,1)\epsilon \sim \mathcal{N}(0,1)
Exponential z=1λloguz = -\frac{1}{\lambda}\log u, uUniform(0,1)u \sim \text{Uniform}(0,1)
Logistic z=μ+slogu1uz = \mu + s \log\frac{u}{1-u}, uUniform(0,1)u \sim \text{Uniform}(0,1)
Laplace $z = \mu - b \cdot \text{sgn}(u-0.5) \log(1-2

Key requirement: The distribution must have a location-scale form or an invertible CDF (inverse transform sampling).

Recall Explain to a 12-Year-Old

Imagine you're trying to teach a robot to draw. The robot has a "creativity knob" (that's σ\sigma) and a "center point" knob (that's μ\mu). Every time it draws, it picks a random direction and distance to move from the center.

The problem: if the drawing is too wobbly (random), the robot can't learn which knob settings make good art. It's like trying to improve your basketball shot while someone randomly pushes your arm—you can't tell if it was your aim or the push!

The reparameterization trick is like this: instead of the robot randomly picking both direction AND distance (too random to learn from), we give it a standard random step (like always rolling a regular die), and then the robot scales that step with its knobs. Now if the drawing is bad, the robot knows it was the knob settings, not the randomness.

The knobs control a transform of a fixed random step. That transform is smooth and learnable!

Connections

  • 4.5.01-Variational-Autoencoders - the primary application
  • 4.5.02-ELBO-Derivation - where this trick enables gradient-based optimization
  • 4.3.01-KL-Divergence - the KL term in ELBO has a closed form Gaussians
  • 5.2.03-Gumbel-Softmax - the discrete analog
  • 2.4.01-Backpropagation - why gradients need differentiable paths
  • 6.1.02-Policy-Gradients - contrast with REINFORCE (score function method)

Flashcards

#flashcards/ai-ml

What is the core problem that the reparameterization trick solves? :: In VAEs, we need to backpropagate through a stochastic sampling node zqϕ(zx)z \sim q_\phi(z|x), but sampling is non-differentiable w.r.t. the distribution parameters ϕ\phi. Gradients cannot flow through randomness.

What is the reparameterization trick for a Gaussian distribution?
Instead of sampling zN(μ,σ2)z \sim \mathcal{N}(\mu, \sigma^2) directly, sample ϵN(0,1)\epsilon \sim \mathcal{N}(0, 1) from a fixed distribution, then compute z=μ+σϵz = \mu + \sigma \cdot \epsilon. This makes zz a differentiable function of μ\mu and σ\sigma.
Why can we move the gradient inside the expectation after reparameterization?
After reparameterization, the expectation is over p(ϵ)p(\epsilon) which doesn't depend on parameters ϕ\phi: ϕEp(ϵ)[f(gϕ(ϵ)]=Ep(ϵ)[ϕf(gϕ(ϵ))]\nabla_\phi \mathbb{E}_{p(\epsilon)}[f(g_\phi(\epsilon)] = \mathbb{E}_{p(\epsilon)}[\nabla_\phi f(g_\phi(\epsilon))]. The Leibniz integral rule allows swapping gradient and integral when the integration domain is parameter-free.
What is zμ\frac{\partial z}{\partial \mu} when z=μ+σϵz = \mu + \sigma \epsilon?
zμ=1\frac{\partial z}{\partial \mu} = 1 (a constant). This means changes in μ\mu directly shift zz by the same amount.
What is zσ\frac{\partial z}{\partial \sigma} when z=μ+σϵz = \mu + \sigma \epsilon?
zσ=ϵ\frac{\partial z}{\partial \sigma} = \epsilon. The gradient depends on the sampled noise value. When ϵ\epsilon is large, σ\sigma has more influence on zz.
In practice, how many samples SS do VAEs use for the reparameterization gradient estimator?
Often just S=1S=1 (single sample per training step). The mini-batch stochasticity across many training steps provides sufficient gradient signal despite the variance of a single-sample estimator.
Why do we typically parameterize with log-variance instead of variance?
Numerical stability. Variance must be positive, but log-variance can be any real number. Computing σ=exp(0.5log_var)\sigma = \exp(0.5 \cdot \text{log\_var}) ensures σ>0\sigma > 0 and avoids optimization constraints.
What is the correct formula to get σ\sigma from log-variance?
σ=exp(0.5logσ2)=exp(12log_var)\sigma = \exp(0.5 \cdot \log\sigma^2) = \exp(\frac{1}{2} \text{log\_var}), because logσ=12logσ2\log \sigma = \frac{1}{2}\log\sigma^2.
Can the reparameterization trick be applied to discrete distributions like Categorical?
Not directly. Discrete sampling has no gradient (argmax is non-differentiable). Alternatives include Gumbel-Softmax (continuous relaxation) or REINFORCE (score function estimator).
For a multivariate Gaussian with diagonal covariance, how does reparameterization work?
Apply element-wise: ϵN(0,Id)\epsilon \sim \mathcal{N}(0, I_d) and z=μ+σϵz = \mu + \sigma \odot \epsilon where \odot is element-wise multiplication. Each dimension is independent.

Concept Map

requires

blocked by

non-differentiable wrt

breaks

separates

uses

defines

epsilon drawn from

independent of

is deterministic in

restores

enables training of

VAE Training

Backprop through sampling

Random sampling z ~ q

Encoder params phi

Gradient flow stops

Reparameterization Trick

Noise from parameters

Location-scale property

z = mu + sigma * epsilon

Fixed N 0,1 distribution

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, VAE jaise generative models train karte waqt ek bada problem ata hai: humein encoder se nikle hue random sample zz ke through backpropagation karna padta hai

Go deeper — visual, from zero

Test yourself — Generative Models

Connections