skip to content

Reparameterization Trick

Drawing the latent as mean plus standard deviation times fixed noise moves the randomness off the gradient path, so backprop reaches the encoder. Interviewers ask what breaks if you sample directly.

on this pageshow

questions

4

How does the reparameterization trick get a gradient through a random latent sample?

level: middleimportance: must knowfreq 72%

answer

  1. the sampler node has no derivative
  2. move the noise off the parameter path
  3. draw the noise first, transform after
  4. location-scale: mean plus scale times noise

basics

~20 s

The reparameterization trick moves randomness off the parameter path: draw fixed noise eps, then set z = mu + sigma * eps. That makes z a differentiable function of mu and sigma, so gradients reach the encoder.

solid answer

~50 s

The objective contains an expectation over a latent drawn from a distribution the encoder produces, so if you implement the draw literally the graph is `mu, sigma -> sampler -> z -> decoder -> loss`. Reverse-mode differentiation carries `dL/dz` back to the sampler and stops there: the emitted value is not a deterministic function of `mu` and `sigma` inside the graph, so there is no `dz/dmu` to chain through and the encoder gets exactly zero gradient. The fix is to draw `eps` from a fixed, parameter-free standard normal and compute `z = mu + sigma * eps` elementwise. The distribution of `z` is unchanged, but now the noise is an input leaf and everything from the parameters to `z` is arithmetic: `dz/dmu = 1` and `dz/dsigma = eps`. This is the pathwise estimator, and a single noise draw per example gives an unbiased gradient of the expectation.

go deeper

for a junior

Be ready to state the rewrite itself: sample standard-normal noise, then form the latent as mean plus scale times that noise, and say in one sentence why a raw sampling step leaves the encoder untrained.

for a middle

Explain the mechanics: which local derivatives appear (one with respect to the mean, the noise value with respect to the scale) and why moving the parameter out of the sampling distribution and into the arithmetic lets you exchange gradient and expectation.

for a senior

Show you have debugged this. Talk about spotting an encoder whose gradients are identically zero, keeping the scale positive, drawing independent noise per example, and never detaching the scale path.

for a principal

Own the boundary question: which parts of a model may hold randomness at all, and what it costs when a component's latent is discrete and no pathwise rewrite exists, so the team must trade bias against gradient variance.

## The problem: a sampler node has no derivative Training a latent-variable model means optimising something that contains an expectation over a latent variable whose distribution the network itself emits — an objective of the form `E over z ~ q(z|x) of f(z)`. The encoder maps an input to distribution parameters (for a Gaussian latent, a mean vector `mu(x)` and a positive scale `sigma(x)`), a value `z` is drawn from that distribution, and the decoder consumes `z`. Write that literally and the forward graph is `mu, sigma -> [sampler] -> z -> decoder -> loss`. Reverse-mode differentiation walks back from the loss, computes `dL/dz`, arrives at the sampler — and halts. The sampler consumed `mu` and `sigma`, but the number it emitted came from an external random source; inside the graph the output is not a deterministic function of the inputs, so there is no local Jacobian `dz/dmu` or `dz/dsigma` to multiply by. The decoder still trains, because it sits downstream of `z`. The encoder receives nothing from the reconstruction term, which is the half of the model whose whole job is to place inputs in latent space. Worth being precise: the gradient of the expectation with respect to the encoder's parameters exists and is perfectly well defined. What is broken is the *sample path* — the naive graph gives you no way to estimate it. ## The rewrite Draw `eps` from a standard normal — a fixed base distribution with no learnable parameters — and set, elementwise, ``` z = mu + sigma * eps ``` A location-scale shift of a standard normal is a normal with that mean and that scale, so the distribution of `z` is exactly what it was before. What changed is where the randomness enters: `eps` is now an input leaf that no parameter touches, and everything between the parameters and `z` is ordinary differentiable arithmetic. The local derivatives are `dz/dmu = 1` and `dz/dsigma = eps`, so backpropagation gives `dL/dmu = dL/dz` and `dL/dsigma = dL/dz * eps`. The encoder is back on the path. Formally, writing `z = g(theta, eps)`, the trick lets you swap the order of differentiation and expectation: ``` grad_theta E_q[f(z)] = grad_theta E_eps[f(g(theta, eps))] = E_eps[ grad_theta f(g(theta, eps)) ] ``` The swap is legitimate because the density of `eps` no longer depends on `theta` — the parameter has moved from the measure into the integrand. A single `eps` per example therefore gives an unbiased estimate of the gradient, which is why one draw per example per step is standard practice: the batch average and the many steps of training do the averaging for you. ## Which distributions admit the rewrite Any location-scale family works directly: Gaussian, Laplace, logistic, and a uniform on a learned interval via `a + (b - a) * u`. More generally, any distribution you can express as a deterministic, differentiable transform of a parameter-free base variable is reparameterizable — that is the same construction normalizing flows are built from. Gamma and Dirichlet latents are awkward but not hopeless; implicit and accept-reject reparameterizations exist for them. Discrete latents are the real wall. Any map from continuous noise to a discrete value is piecewise constant, so its derivative with respect to the parameters is zero almost everywhere and undefined at the jumps — there is no useful pathwise gradient to be had. That is why a categorical or Bernoulli latent forces a different choice: relax the sample into something continuous, quantize against a codebook and copy the gradient past the lookup, or keep the sample exact and switch to a score-function estimator that only needs the *value* of the objective. ## Practical notes and common bugs - The scale must stay positive, so it is emitted through an unconstrained output and mapped to a positive number; forgetting that produces silent NaNs the first time the network pushes it negative. - Reusing one `eps` for a whole batch is a classic mistake. Each example's gradient stays unbiased, but the draws are perfectly correlated, so the batch average stops averaging the noise down and the latent samples all move together. - Detaching the scale from the graph is another: the model then learns a mean but never learns how uncertain it should be, and the scale drifts wherever the rest of the objective pushes it. - Nothing about the objective changes. The trick is purely a change in how the gradient is estimated, not in what is being optimised. - At generation time you sample `eps` as usual; when you want a deterministic embedding or reconstruction you use `mu` alone and drop the noise.

  • Is a single noise draw per example enough for an unbiased gradient?
    Yes. Once the noise density is parameter-free, the gradient of the expectation equals the expectation of the gradient, so one draw is an unbiased single-sample Monte Carlo estimate. More draws only reduce variance, and in practice the batch size plus many optimisation steps already do that averaging, so one draw per example per step is the norm.
  • Which latent distributions resist the rewrite, and what do you do instead?
    Location-scale families and anything expressible as a differentiable transform of parameter-free noise are fine; Gamma and Dirichlet need implicit or accept-reject variants. Discrete latents have no clean rewrite, because any map from continuous noise to a discrete value is piecewise constant with zero derivative. There you relax the sample, quantize against a codebook, or fall back to a score-function estimator.
  • What goes wrong if you reuse one noise draw across the whole batch?
    Each example's gradient is still unbiased, but the draws are perfectly correlated, so averaging over the batch no longer averages the noise away. Effectively you take a batch-sized step along one noise realisation, which raises gradient variance and makes the latent samples move in lockstep. Draw independent noise per example.

Asking a black box for a random number tells you nothing about how turning your dials would have changed it. Holding the random number yourself and passing it through your own dials lets you see exactly how each dial moves the result.

saying these in an interview costs you the question

  • Claims gradients flow through a random draw automatically
  • Says the trick removes randomness from the model
  • Thinks the noise variable is learned or has parameters
  • Believes the rewrite changes the latent's distribution
  • Confuses it with detaching the sample from the graph

context

open as a page

How does a Gumbel-Softmax relaxation make a categorical latent trainable by gradients?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Gumbel-Softmax adds independent Gumbel noise to the logits and replaces the argmax with a temperature-scaled softmax. The noise is parameter-free, so gradients flow to the logits; the price is a soft sample and a biased gradient.

open as a page

Why does the pathwise gradient estimator usually beat the score-function estimator on variance?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Both estimators are unbiased, but the pathwise one differentiates the objective at the sample, so each draw carries directional information. The score-function estimator only multiplies a scalar value by a score vector, which is far noisier and needs a baseline.

open as a page

Gumbel-Softmax or a vector-quantized codebook for a discrete latent: how do you choose?

level: principalimportance: nice to knowfreq 26%

basics

~20 s

Pick a relaxation when the code may be soft during training and the class count is modest; pick a quantized codebook when the forward pass must be discrete and a downstream model consumes the codes. Both are biased.

open as a page