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 becomes with drawn from , so the sample is differentiable in and .
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 . Then feed it into a fixed machine that stretches it by and shifts it by . 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 is different each time, but for any one 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 and a spread , then samples a latent code , and then a decoder scores with some loss. Training wants the gradient of the loss with respect to and . The loss depends on only through the sample , and is produced by a random number generator that has no derivative with respect to . 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 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
A random variable with distribution admits a reparameterization if there is a fixed distribution for a noise variable and a deterministic function such that , with and not depending on . The function should be differentiable in .
Here stands for the parameters, which in the Gaussian case are . For a Gaussian, the map is and . Check that this is correct: and . 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 . Using the reparameterization, the expectation is over instead, and the parameters sit inside the function:
Because does not depend on , the gradient can move inside the expectation. The chain rule, from Chain Rule, then gives
For the Gaussian this reads
Both expectations are averages over , so they can be estimated by Monte Carlo: draw values , compute the average of and of , and use those as the gradient estimates. The estimator is unbiased, and its noise shrinks as as with any Monte Carlo average.
Checking the formula on a known answer
Take . Then , so the true gradient is and . The reparameterized formulas give for the first, since . For the second, , because and . Both match. This is the kind of check worth doing whenever you write a new reparameterized loss.
Several dimensions
For a vector with mean and covariance , use a matrix with (a Cholesky factor, which exists for any valid covariance matrix). Then with has the right distribution. When the covariance is diagonal, is just the diagonal of standard deviations, and each coordinate is reparameterized on its own. The diffusion-model form is this same map with the mean set to and the scale set to , where is a number between 0 and 1 from a fixed noise schedule that shrinks as 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 , one can instead write with uniform on . Then plays the role of , but 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
Let , , objective , and a noise draw .
- Build the sample: .
- The objective at this sample is .
- Derivative of at the sample: .
- Gradient with respect to : .
- Gradient with respect to : .
- Interpretation: if a gradient step raises by 0.1 with held fixed, the sample moves by and the objective rises by about , which matches .
Same , , . The exact gradient is and . Estimate both with four draws .
- Samples: gives .
- Estimate for is the average of : . Exact value is 4.
- Estimate for is the average of : . Exact value is 6.
- 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.
A Variational Autoencoder encoder outputs and for one input. It samples , so . The decoder then gives a loss whose derivative with respect to is .
- Gradient with respect to : .
- Gradient with respect to : .
- One gradient descent step with learning rate 0.1: and .
- Interpretation: the encoder moves its mean toward a point that lowers the loss at this sample, and widens its spread, because with this negative a larger pushes lower and the loss falls. Without the reparameterization, the loss would depend on and 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.
| Situation | Problem | Better choice |
|---|---|---|
| Discrete latent variable (a category, a binary switch) | No smooth map from noise to a discrete value | Gumbel-softmax relaxation, or the score-function estimator |
| Distribution with no simple transform of noise | Cannot differentiate the sampler | Score-function estimator with a baseline to reduce variance |
| Very high-dimensional latent with complex dependence | Full covariance is expensive to factor | Diagonal covariance, which is what most VAEs use |
| Gradients needed through a sampled discrete action in reinforcement learning | Sampling blocks the gradient path | Score-function estimator (REINFORCE), often with a learned baseline |
Some practical warnings:
- The noise must not depend on the parameters. If is drawn from a distribution whose shape depends on or , 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 with . The randomness lives entirely in , which does not depend on or . That lets the gradient pass through as a smooth function of the parameters: and .
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 . The derivative of at is . So and . 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 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
- Kingma and Welling, Auto-Encoding Variational Bayes (2013): https://arxiv.org/abs/1312.6114
- Rezende, Mohamed and Wierstra, Stochastic Backpropagation and Approximate Inference in Deep Generative Models (2014): https://arxiv.org/abs/1401.4082
- Ho, Jain and Abbeel, Denoising Diffusion Probabilistic Models (2020): https://arxiv.org/abs/2006.11239
- Normal distribution (Wikipedia): https://en.wikipedia.org/wiki/Normal_distribution