Search

Search papers and lessons

Reparameterization Trick

Level 3 · 12 min read

Write a random sample as a fixed noise draw passed through a smooth function of the parameters, so gradients can flow through the sampling step.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Linear algebra
  • Generative models
  • Discrete math
  • Sampling
  • Sign in to see your progress

TL;DR

Training a model usually means following gradients, but a random draw is a step gradients cannot pass through: nudging the parameters changes which number comes out, not how the number changes. The reparameterization trick fixes this by writing the draw as fixed noise pushed through a smooth function of the parameters. A sample from N(μ,σ2)\mathcal{N}(\mu, \sigma^2) becomes μ+σ ϵ\mu + \sigma\,\epsilon with ϵ\epsilon drawn from N(0,1)\mathcal{N}(0, 1), so the sample is differentiable in μ\mu and σ\sigma.

Where you'll see it: in the encoder of a Variational Autoencoder, which must sample a latent code and still train by gradient descent, and in the noising step of a Diffusion Model, where the same formula jumps straight to any noise level.

Intuition

A fixed noise source and a machine with knobs

Picture a machine that turns a random input into an output. If the randomness is drawn inside the machine, each run gives a different answer and the knobs only change the odds. You cannot ask "if I turn this knob a little, how does this output move?" because the output jumps around for reasons unrelated to the knob.

Now reverse the order. Draw the randomness first, from a standard source that the knobs cannot touch: a standard Gaussian ball ϵ\epsilon. Then feed it into a fixed machine that stretches it by σ\sigma and shifts it by μ\mu. The knobs now act on a number that is already fixed, so turning them moves the output smoothly. Every run still gives a different sample, because ϵ\epsilon is different each time, but for any one ϵ\epsilon the output is a plain function of the knobs.

That is the whole idea. The randomness does not disappear; it is relocated to a place where the parameters do not reach.

Why the naive way fails

Suppose you have a model that encodes an input into a mean μ\mu and a spread σ\sigma, then samples a latent code z∼N(μ,σ2)z \sim \mathcal{N}(\mu, \sigma^2), and then a decoder scores zz with some loss. Training wants the gradient of the loss with respect to μ\mu and σ\sigma. The loss depends on μ\mu only through the sample zz, and zz is produced by a random number generator that has no derivative with respect to μ\mu. The chain rule has nowhere to go.

There is a workaround that does not need a reparameterization, called the score-function estimator (also known as REINFORCE). It works for almost any distribution, but its gradient estimates are very noisy, so training is slow. The reparameterization trick gives a much lower-variance estimate whenever it applies.

flowchart LR
  A[Parameters mu and sigma] --> B[Draw z from N mu sigma squared]
  B --> C[Loss]
  D[Parameters mu and sigma] --> E[Draw eps from N 0 1]
  E --> F[z equals mu plus sigma times eps]
  F --> G[Loss]

The top path has a random draw in the middle that gradients cannot cross. The bottom path draws ϵ\epsilon from a distribution that does not depend on the parameters, so the only parameter-dependent step is the smooth arithmetic in the middle.

The math

Setup

Definition: Reparameterization

A random variable XX with distribution pθp_\theta admits a reparameterization if there is a fixed distribution qq for a noise variable ϵ\epsilon and a deterministic function gg such that X=g(ϵ,θ)X = g(\epsilon, \theta), with ϵ∼q\epsilon \sim q and ϵ\epsilon not depending on θ\theta. The function gg should be differentiable in θ\theta.

Here θ\theta stands for the parameters, which in the Gaussian case are θ=(μ,σ)\theta = (\mu, \sigma). For a Gaussian, the map is g(ϵ,μ,σ)=μ+σϵg(\epsilon, \mu, \sigma) = \mu + \sigma\epsilon and q=N(0,1)q = \mathcal{N}(0, 1). Check that this is correct: E[μ+σϵ]=μ\mathbb{E}[\mu + \sigma\epsilon] = \mu and Var(μ+σϵ)=σ2Var(ϵ)=σ2\mathrm{Var}(\mu + \sigma\epsilon) = \sigma^2 \mathrm{Var}(\epsilon) = \sigma^2. The sample has the right mean and variance, and it is exactly Gaussian because a scaled and shifted Gaussian is Gaussian (see Gaussian (Normal) Distribution).

The gradient of an expectation

We want the gradient of an expected objective J(θ)=Ex∼pθ[f(x)]J(\theta) = \mathbb{E}_{x \sim p_\theta}[f(x)]. Using the reparameterization, the expectation is over ϵ\epsilon instead, and the parameters sit inside the function:

J(θ)=Eϵ∼q[f(g(ϵ,θ))].J(\theta) = \mathbb{E}_{\epsilon \sim q}\big[f(g(\epsilon, \theta))\big].

Because qq does not depend on θ\theta, the gradient can move inside the expectation. The chain rule, from Chain Rule, then gives

∇θJ(θ)=Eϵ∼q[f′(g(ϵ,θ)) ∇θg(ϵ,θ)].\nabla_\theta J(\theta) = \mathbb{E}_{\epsilon \sim q}\Big[f'(g(\epsilon, \theta)) \, \nabla_\theta g(\epsilon, \theta)\Big].

For the Gaussian this reads

∂J∂μ=Eϵ[f′(x)],∂J∂σ=Eϵ[f′(x) ϵ],x=μ+σϵ.\frac{\partial J}{\partial \mu} = \mathbb{E}_{\epsilon}\big[f'(x)\big], \qquad \frac{\partial J}{\partial \sigma} = \mathbb{E}_{\epsilon}\big[f'(x)\,\epsilon\big], \qquad x = \mu + \sigma\epsilon.

Both expectations are averages over ϵ\epsilon, so they can be estimated by Monte Carlo: draw NN values ϵ1,…,ϵN\epsilon_1, \dots, \epsilon_N, compute the average of f′(xi)f'(x_i) and of f′(xi)ϵif'(x_i)\epsilon_i, and use those as the gradient estimates. The estimator is unbiased, and its noise shrinks as 1/N1/\sqrt{N} as with any Monte Carlo average.

Checking the formula on a known answer

Take f(x)=x2f(x) = x^2. Then J(μ,σ)=E[x2]=μ2+σ2J(\mu, \sigma) = \mathbb{E}[x^2] = \mu^2 + \sigma^2, so the true gradient is ∂J/∂μ=2μ\partial J/\partial \mu = 2\mu and ∂J/∂σ=2σ\partial J/\partial \sigma = 2\sigma. The reparameterized formulas give E[2x]=2μ\mathbb{E}[2x] = 2\mu for the first, since E[x]=μ\mathbb{E}[x] = \mu. For the second, E[2xϵ]=E[2(μ+σϵ)ϵ]=2σ E[ϵ2]=2σ\mathbb{E}[2x\epsilon] = \mathbb{E}[2(\mu + \sigma\epsilon)\epsilon] = 2\sigma\,\mathbb{E}[\epsilon^2] = 2\sigma, because E[ϵ]=0\mathbb{E}[\epsilon] = 0 and E[ϵ2]=1\mathbb{E}[\epsilon^2] = 1. Both match. This is the kind of check worth doing whenever you write a new reparameterized loss.

Several dimensions

For a vector x\mathbf{x} with mean μ\boldsymbol{\mu} and covariance Σ\Sigma, use a matrix LL with Σ=LL⊤\Sigma = LL^\top (a Cholesky factor, which exists for any valid covariance matrix). Then x=μ+Lϵ\mathbf{x} = \boldsymbol{\mu} + L\boldsymbol{\epsilon} with ϵ∼N(0,I)\boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, I) has the right distribution. When the covariance is diagonal, LL is just the diagonal of standard deviations, and each coordinate is reparameterized on its own. The diffusion-model form xt=αˉt x0+1−αˉt ϵ\mathbf{x}_t = \sqrt{\bar\alpha_t}\,\mathbf{x}_0 + \sqrt{1-\bar\alpha_t}\,\boldsymbol{\epsilon} is this same map with the mean set to αˉt x0\sqrt{\bar\alpha_t}\,\mathbf{x}_0 and the scale set to 1−αˉt\sqrt{1-\bar\alpha_t}, where αˉt\bar\alpha_t is a number between 0 and 1 from a fixed noise schedule that shrinks as tt grows.

General distributions

Not every distribution has such a map. The Gaussian family is a location-scale family, meaning one standard shape plus a shift and a stretch. For any distribution with a computable inverse cumulative distribution function F−1F^{-1}, one can instead write x=F−1(u)x = F^{-1}(u) with uu uniform on [0,1][0, 1]. Then uu plays the role of ϵ\epsilon, but F−1F^{-1} may be hard to differentiate. For discrete distributions there is no smooth map at all, and a relaxation such as the Gumbel-softmax is used instead.

Worked examples

Example
One sample, two gradients

Let μ=2\mu = 2, σ=3\sigma = 3, objective f(x)=x2f(x) = x^2, and a noise draw ϵ=0.5\epsilon = 0.5.

  1. Build the sample: x=μ+σϵ=2+3×0.5=3.5x = \mu + \sigma\epsilon = 2 + 3 \times 0.5 = 3.5.
  2. The objective at this sample is f(3.5)=12.25f(3.5) = 12.25.
  3. Derivative of ff at the sample: f′(x)=2x=7f'(x) = 2x = 7.
  4. Gradient with respect to μ\mu: f′(x)×∂x/∂μ=7×1=7f'(x) \times \partial x/\partial\mu = 7 \times 1 = 7.
  5. Gradient with respect to σ\sigma: f′(x)×∂x/∂σ=7×ϵ=7×0.5=3.5f'(x) \times \partial x/\partial\sigma = 7 \times \epsilon = 7 \times 0.5 = 3.5.
  6. Interpretation: if a gradient step raises σ\sigma by 0.1 with ϵ\epsilon held fixed, the sample moves by 0.1×0.5=0.050.1 \times 0.5 = 0.05 and the objective rises by about 7×0.05=0.357 \times 0.05 = 0.35, which matches 3.5×0.13.5 \times 0.1.
Example
Averaging over noise draws

Same μ=2\mu = 2, σ=3\sigma = 3, f(x)=x2f(x) = x^2. The exact gradient is ∂J/∂μ=2μ=4\partial J/\partial\mu = 2\mu = 4 and ∂J/∂σ=2σ=6\partial J/\partial\sigma = 2\sigma = 6. Estimate both with four draws ϵ∈{−1,0,0.5,1.5}\epsilon \in \{-1, 0, 0.5, 1.5\}.

  1. Samples: x=2+3ϵx = 2 + 3\epsilon gives −1, 2, 3.5, 6.5-1,\ 2,\ 3.5,\ 6.5.
  2. Estimate for μ\mu is the average of 2x2x: (−2+4+7+13)/4=22/4=5.5(-2 + 4 + 7 + 13)/4 = 22/4 = 5.5. Exact value is 4.
  3. Estimate for σ\sigma is the average of 2xϵ2x\epsilon: (2+0+3.5+19.5)/4=25/4=6.25(2 + 0 + 3.5 + 19.5)/4 = 25/4 = 6.25. Exact value is 6.
  4. Interpretation: four draws are noisy, but both estimates are already in the right range. With a few hundred draws in a training batch, the noise becomes small enough to ignore in practice.
Example
Training an encoder with a sampled latent

A Variational Autoencoder encoder outputs μ=0.8\mu = 0.8 and σ=0.5\sigma = 0.5 for one input. It samples ϵ=−0.4\epsilon = -0.4, so z=0.8+0.5×(−0.4)=0.6z = 0.8 + 0.5 \times (-0.4) = 0.6. The decoder then gives a loss whose derivative with respect to zz is ∂L/∂z=1.5\partial L/\partial z = 1.5.

  1. Gradient with respect to μ\mu: ∂L/∂z×1=1.5\partial L/\partial z \times 1 = 1.5.
  2. Gradient with respect to σ\sigma: ∂L/∂z×ϵ=1.5×(−0.4)=−0.6\partial L/\partial z \times \epsilon = 1.5 \times (-0.4) = -0.6.
  3. One gradient descent step with learning rate 0.1: μ←0.8−0.1×1.5=0.65\mu \leftarrow 0.8 - 0.1 \times 1.5 = 0.65 and σ←0.5−0.1×(−0.6)=0.56\sigma \leftarrow 0.5 - 0.1 \times (-0.6) = 0.56.
  4. Interpretation: the encoder moves its mean toward a point that lowers the loss at this sample, and widens its spread, because with this negative ϵ\epsilon a larger σ\sigma pushes zz lower and the loss falls. Without the reparameterization, the loss would depend on μ\mu and σ\sigma only through an unpredictable draw, and there would be no gradient to follow.

Tradeoffs and failure modes

The reparameterization trick is the first choice when it applies, because it gives low-variance gradients. It applies cleanly to location-scale families such as the Gaussian, and to a few others with a simple transform. When it does not apply, the alternatives are noisier or biased.

SituationProblemBetter choice
Discrete latent variable (a category, a binary switch)No smooth map from noise to a discrete valueGumbel-softmax relaxation, or the score-function estimator
Distribution with no simple transform of noiseCannot differentiate the samplerScore-function estimator with a baseline to reduce variance
Very high-dimensional latent with complex dependenceFull covariance is expensive to factorDiagonal covariance, which is what most VAEs use
Gradients needed through a sampled discrete action in reinforcement learningSampling blocks the gradient pathScore-function estimator (REINFORCE), often with a learned baseline

Some practical warnings:

  • The noise must not depend on the parameters. If ϵ\epsilon is drawn from a distribution whose shape depends on μ\mu or σ\sigma, the trick is silently wrong. Draw from a fixed standard distribution every time.
  • Do not detach the sample by accident. In frameworks like PyTorch, calling a sampling method that is not built from differentiable operations, or wrapping the sample in no_grad, cuts the path. The gradients then become zero, and training stalls without an error.
  • Low variance is not zero error. The reparameterized estimator is unbiased, but it is still a Monte Carlo average. Large batches or several samples per input reduce the noise.
  • The trick only moves randomness; it does not make the loss smooth. If the decoder itself has a hard threshold, the gradient is still zero or undefined there.

History

The score-function gradient, which the reparameterization trick is an alternative to, was described by Ronald Williams in 1992 under the name REINFORCE, in the context of training stochastic units in neural networks.

The pathwise idea of differentiating through a simulated random path has older roots in computational finance, where it was used to estimate sensitivities of option prices to model parameters by Monte Carlo simulation from the 1990s onward.

The modern name and the broad use came in 2013 and 2014. Diederik Kingma and Max Welling, in Auto-Encoding Variational Bayes, showed that a sampled latent variable could be trained by gradient descent once the sample was written as a deterministic function of the parameters and fixed noise, and they named the device the reparameterization trick. Danilo Rezende, Shakir Mohamed and Daan Wierstra published the same idea independently in 2014 under the name stochastic backpropagation. Variational autoencoders made the trick standard, and diffusion models later used the same closed-form noising step to sample any noise level directly. It caught on because it turned a hard estimation problem into ordinary backpropagation, which the rest of deep learning was already built around (see Backpropagation).

Check yourself

QuestionWrite the reparameterization of a sample from a Gaussian with mean mu and standard deviation sigma. Which part of the expression carries the randomness, and why does that matter for gradients?Show answer

The sample is x=μ+σϵx = \mu + \sigma\epsilon with ϵ∼N(0,1)\epsilon \sim \mathcal{N}(0, 1). The randomness lives entirely in ϵ\epsilon, which does not depend on μ\mu or σ\sigma. That lets the gradient pass through xx as a smooth function of the parameters: ∂x/∂μ=1\partial x/\partial\mu = 1 and ∂x/∂σ=ϵ\partial x/\partial\sigma = \epsilon.

QuestionTake mu = -1, sigma = 2, and a noise draw epsilon = 1.5. For the objective f(x) = x squared, what are the sample and the gradient of f with respect to mu and sigma at this draw?Show answer

The sample is x=−1+2×1.5=2x = -1 + 2 \times 1.5 = 2. The derivative of ff at xx is 2x=42x = 4. So ∂f/∂μ=4×1=4\partial f/\partial\mu = 4 \times 1 = 4 and ∂f/∂σ=4×1.5=6\partial f/\partial\sigma = 4 \times 1.5 = 6. Both values come from the chain rule applied to the reparameterized sample.

QuestionWhy can you not simply sample from the distribution and backpropagate through the sampling operation as if it were a normal function?Show answer

A random number generator produces a value that is not a smooth function of the distribution's parameters. Changing μ\mu does not change the draw in a differentiable way; it changes the odds of which draw you see, and a single draw gives no slope. The reparameterization moves the randomness into a fixed draw that the parameters cannot alter, so the parameter-dependent part is an ordinary differentiable expression.

QuestionA model picks one of ten discrete codebook entries for each input and must train by gradient descent. Can the reparameterization trick be used directly, and what would you do instead?Show answer

No. A choice among discrete values has no smooth map from continuous noise to the chosen value, so the standard trick does not apply. Options are a continuous relaxation such as the Gumbel-softmax, which approximates the choice with a smooth softmax over noisy logits, or the score-function estimator, which is unbiased but noisier and often benefits from a baseline.

Sources