AI Wiki中文/EN

Reparameterization: differentiate the sampling recipe

重参数化技巧

Compare exact gradient moments, test a baseline bias and find why a discrete threshold breaks pathwise differentiation.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Can a computation graph differentiate through sampling?

A teaching program draws z∼N(μ,σ2)z\sim\mathcal N(\mu,\sigma^2) and evaluates the loss (z−a)2(z-a)^2. We want to change the mean and scale to reduce average loss. Treating the drawn zz as a fixed number unrelated to the parameters cuts the path by which changing parameters changes the sampling distribution.

The reparameterization trick moves randomness into noise with a fixed distribution, then transforms that noise through a differentiable function. The same noise value produces a different sample when parameters change, giving the chain rule a path to follow. AEVB Sections 2.3–2.4 construct this estimator; Section 3 of Rezende and colleagues’ v1 also uses coordinate transformations to derive stochastic backpropagation.

The prerequisites are Gaussian distributions, the chain rule and gradient checking. The task is to understand an estimator’s expectation, variance and failure conditions, rather than merely call a random-number interface.

Calculated gradient variances and a discrete counterexample distinguish pathwise derivatives, score estimates and biased baselines.
Calculated gradient variances and a discrete counterexample distinguish pathwise derivatives, score estimates and biased baselines.

Fix the noise distribution and parameterize the transformation

Suppose qϕq_\phi can be sampled by transforming noise whose distribution p(ϵ)p(\epsilon) does not depend on ϕ\phi. If the transformation is sufficiently differentiable, the relevant expectations exist and differentiation can pass through integration, then:

z=gϕ(ϵ),ϵ∼p(ϵ),∇ϕEqϕf(z)=Ep(ϵ)[∇ϕf(gϕ(ϵ))].z=g_\phi(\epsilon),\quad\epsilon\sim p(\epsilon),\qquad\nabla_\phi\mathbb E_{q_\phi}f(z)=\mathbb E_{p(\epsilon)}[\nabla_\phi f(g_\phi(\epsilon))].

Initially assume that ff has no additional explicit dependence on ϕ\phi. If it does, include that direct derivative path too. The transformation must actually generate distribution qϕq_\phi; adding noise somewhere in a computation is not sufficient. The Gaussian location-scale example in AEVB is particularly direct:

z=μ+σϵ,σ=eρ,ϵ∼N(0,1),δ=μ−a,f(z)=(z−a)2.z=\mu+\sigma\epsilon,\quad\sigma=e^\rho,\quad\epsilon\sim\mathcal N(0,1),\quad\delta=\mu-a,\quad f(z)=(z-a)^2.

Here ρ\rho is log standard deviation, unlike the log variance commonly emitted by a VAE encoder. The noise stays standard normal. Writing the offset as δ=μ−a\delta=\mu-a, expand the quadratic and use Eϵ=0\mathbb E\epsilon=0 and Eϵ2=1\mathbb E\epsilon^2=1:

Ef=δ2+σ2,∇(μ,ρ)Ef=(2δ,2σ2).\mathbb E f=\delta^2+\sigma^2,\qquad\nabla_{(\mu,\rho)}\mathbb E f=(2\delta,2\sigma^2).

For a single draw, ∂z/∂μ=1\partial z/\partial\mu=1 and ∂z/∂ρ=σϵ\partial z/\partial\rho=\sigma\epsilon, giving the pathwise gradient:

Gpath=(2(z−a),  2(z−a)σϵ).G_{\rm path}=\left(2(z-a),\;2(z-a)\sigma\epsilon\right).

Each component has the expectation of the corresponding true gradient above. A single draw need not equal that expectation. Unbiasedness concerns an average over repeated sampling, not the accuracy of every individual direction or magnitude.

A score-function route to the same objective

Alternatively, differentiate the density using ∇q=q∇log⁡q\nabla q=q\nabla\log q. Under appropriate regularity, fixed support and no explicit parameter dependence in ff:

∇ϕEqf=Eq[f∇ϕlog⁡q],Gscore=(fϵσ,  f(ϵ2−1)).\nabla_\phi\mathbb E_qf=\mathbb E_q[f\nabla_\phi\log q],\qquad G_{\rm score}=\left(f\frac\epsilon\sigma,\;f(\epsilon^2-1)\right).

Here score means the parameter derivative of log density. When differentiating the Gaussian density with respect to μ,ρ\mu,\rho, hold the observed zz fixed. The scores are ϵ/σ\epsilon/\sigma and ϵ2−1\epsilon^2-1. Differentiating z=μ+σϵz=\mu+\sigma\epsilon again within that calculation would mix two different estimators. AEVB Section 2.2 discusses this estimator; Rezende Section 3 compares constructions for Gaussian derivatives.

The pathwise method uses how ff changes with the sample. The score method uses how the distribution weights a sample. Both are unbiased here, but their noise differs.

Compare variances exactly

Standard-normal fourth, sixth and eighth moments are 3, 15 and 105. Expand the squared gradient and subtract its squared mean. For the mean parameter:

Var⁡(Gpath,μ)=4σ2,Var⁡(Gscore,μ)=δ4σ2+14δ2+15σ2.\operatorname{Var}(G_{{\rm path},\mu})=4\sigma^2,\quad\operatorname{Var}(G_{{\rm score},\mu})=\frac{\delta^4}{\sigma^2}+14\delta^2+15\sigma^2.

For example, the mean score component expands to (δ2/σ)ϵ+2δϵ2+σϵ3(\delta^2/\sigma)\epsilon+2\delta\epsilon^2+\sigma\epsilon^3. Its second moment is δ4/σ2+18δ2+15σ2\delta^4/\sigma^2+18\delta^2+15\sigma^2; subtracting (2δ)2(2\delta)^2 gives the expression above. Similarly, for log scale:

Var⁡(Gpath,ρ)=4δ2σ2+8σ4,Var⁡(Gscore,ρ)=2δ4+60δ2σ2+74σ4.\operatorname{Var}(G_{{\rm path},\rho})=4\delta^2\sigma^2+8\sigma^4,\quad\operatorname{Var}(G_{{\rm score},\rho})=2\delta^4+60\delta^2\sigma^2+74\sigma^4.

At μ=0.7,ρ=−0.3,a=−0.2\mu=0.7,\rho=-0.3,a=-0.2, the true gradient is approximately (1.8,1.097623)(1.8,1.097623). Pathwise component variances are about 2.195247 and 4.187703; raw score variances are 20.767667 and 50.272817. These are exact moments for this Gaussian quadratic, not a theorem that pathwise gradients have lower variance in every problem.

A baseline can reduce variance or introduce bias

The score of a regular normalized density has zero expectation, so subtracting a fixed constant BB from ff preserves the gradient expectation. Using the same batch’s mean loss fˉ\bar f instead introduces dependence. If sis_i is sample ii‘s score, independent identically distributed samples satisfy:

E[(f−B)∇ϕlog⁡q]=∇ϕEf,E ⁣[1N∑i(fi−fˉ)si]=(1−1N)E[fs].\mathbb E[(f-B)\nabla_\phi\log q]=\nabla_\phi\mathbb E f,\qquad\mathbb E\!\left[\frac1N\sum_i(f_i-\bar f)s_i\right]=\left(1-\frac1N\right)\mathbb E[f s].

Treat BB as constant in the first estimator. The second estimator is biased because fˉ\bar f includes fif_i itself. With N=2N=2, it shrinks the true gradient by half. A baseline estimated independently of the current sample, or a leave-one-out baseline, avoids this particular dependence, though its implementation still needs checking.

For fixed B=δ2+σ2B=\delta^2+\sigma^2, this example’s score variances become 8δ2+10σ28\delta^2+10\sigma^2 and 40δ2σ2+56σ440\delta^2\sigma^2+56\sigma^4, about 11.968116 and 34.648373. The mean-loss baseline is not necessarily variance-optimal for every gradient component. An improvement is not an optimality proof.

A discrete threshold is a counterexample

A Bernoulli sample can be obtained by thresholding uniform noise:

b=1[u<p],  u∼U(0,1),dbdp=0  a.e.,dE[b]dp=1.b=\mathbf1[u<p],\;u\sim U(0,1),\quad\frac{db}{dp}=0\;\text{a.e.},\qquad\frac{d\mathbb E[b]}{dp}=1.

For almost every fixed uu, a small change in pp leaves bb unchanged and automatic differentiation returns zero. Yet the derivative of Eb=p\mathbb E b=p is one. The moving threshold’s contribution is absent from the ordinary pathwise derivative; interchanging differentiation and expectation fails here.

This differentiates with respect to pp, not its logit. With a logit parameter the true derivative is p(1−p)p(1-p). Discrete variables may admit valid score estimators; continuous relaxations are another route, but change the computational object and require a fresh account of bias and the objective.

Check estimators against exact moments

Save this as reparameterization.py and run it with Python 3.12 and NumPy 1.26.4. The estimates function returns each noise sample’s function value and both gradients. The quadrature function uses 16-point Gauss-Hermite integration. Its integrands here are finite-degree polynomials, so the rule gives exact moments within floating-point tolerance; it is not a random experiment.

"""Compare gradient estimators for a scalar Gaussian quadratic, plus a discrete failure."""
import itertools
import json
import numpy as np


def estimates(eps, mu=.7, rho=-.3, target=-.2, baseline=0.):
    eps = np.asarray(eps, float)
    if (eps.ndim != 1 or not 1 <= eps.size <= 100000 or not np.isfinite(eps).all()
            or np.max(np.abs(eps)) > 20 or not np.isfinite([mu, rho, target, baseline]).all()
            or max(abs(mu), abs(target), abs(baseline)) > 100 or abs(rho) > 5):
        raise ValueError('Expected bounded finite parameters and 1..100000 bounded noise values.')
    sigma = np.exp(rho)
    residual = mu + sigma * eps - target
    f = residual**2
    path = np.column_stack((2 * residual, 2 * residual * sigma * eps))
    score = np.column_stack(((f - baseline) * eps / sigma, (f - baseline) * (eps**2 - 1)))
    return f, path, score


def exact(mu=.7, rho=-.3, target=-.2):
    estimates([0], mu, rho, target)  # same domain
    d, s = mu - target, np.exp(rho)
    return dict(objective=float(d*d + s*s), gradient=[2*d, 2*s*s],
                path_variance=[4*s*s, 4*d*d*s*s + 8*s**4],
                score_variance=[d**4/s**2 + 14*d*d + 15*s*s,
                                2*d**4 + 60*d*d*s*s + 74*s**4],
                mean_baseline_score_variance=[8*d*d + 10*s*s, 40*d*d*s*s + 56*s**4])


def quadrature(mu=.7, rho=-.3, target=-.2, baseline=0.):
    """16-point Gauss-Hermite: exact polynomial moments here, not random draws."""
    nodes, weights = np.polynomial.hermite.hermgauss(16)
    weights = weights / np.sqrt(np.pi)
    f, path, score = estimates(np.sqrt(2) * nodes, mu, rho, target, baseline)
    result = dict(objective=float(weights @ f))
    for name, values in [('path', path), ('score', score)]:
        mean = weights @ values
        result[name+'_mean'] = mean.tolist()
        result[name+'_variance'] = (weights @ (values - mean)**2).tolist()
    return result


def bernoulli(p=.3):
    """Derivative is with respect to p, not the logit. f(b)=b."""
    if not np.isfinite(p) or not 1e-6 <= p <= 1-1e-6:
        raise ValueError('p must be strictly interior, at least 1e-6 from either endpoint.')
    b = np.array([0., 1.]); weights = np.array([1-p, p])
    score = b/p - (1-b)/(1-p)
    same_batch = 0.
    for pair in itertools.product([0, 1], repeat=2):
        v = b[list(pair)]
        same_batch += float(np.prod(weights[list(pair)]) * np.mean((v - v.mean()) * score[list(pair)]))
    return dict(true_derivative_p=1., naive_path_derivative_almost_everywhere=0.,
                score_expectation=float(weights @ (b*score)),
                fixed_baseline_expectation=float(weights @ ((b-p)*score)),
                same_batch_mean_baseline_expectation=same_batch)


def demo():
    truth = exact()
    return dict(exact=truth, quadrature=quadrature(),
                fixed_mean_baseline=quadrature(baseline=truth['objective']), discrete=bernoulli())


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2, allow_nan=False))

The bernoulli function enumerates all four outcomes of two independent draws. It obtains expectation one for raw and fixed-baseline scores, and 0.5 for the same-batch mean baseline. Continuous checks compare hand-derived variances against integration over a parameter grid.

Finite differences must reuse the same ϵ\epsilon for positive and negative parameter perturbations. Otherwise, the loss difference includes variation from two separate draws; dividing it by a small step can make a correct gradient appear wrong. A common-noise check verifies the sampled objective’s derivative, not equality between a sample average and the population expectation.

Estimating SS scalar samples takes O(S)O(S) time. This implementation stores sample arrays and therefore also uses O(S)O(S) space; accumulating only means can stream the calculation. General neural models add the cost of each forward/backward pass. Explicit limits on parameters, noise magnitudes and sample counts keep the teaching computation bounded.

A sampling transformation is not an interchange proof

The Gaussian example is smooth with finite moments, making its conditions easy to check. Heavy tails, parameter-dependent support boundaries, nondifferentiable losses and discrete operations need separate analysis. Expressing sampling as a function does not by itself prove unbiasedness.

Multivariate Gaussians can transform noise through a matrix factor, but covariance validity and matrix-derivative conventions must be consistent. The scalar example keeps these issues from hiding inside an automatic-differentiation library. A practical VAE often evaluates the prior KL analytically and samples only the reconstruction expectation; an analytically available term need not be replaced by a noisy estimate.

Predict before checking

  1. If an encoder emits log variance ℓ\ell, should standard-normal noise be multiplied by eℓe^\ell or eℓ/2e^{\ell/2}?

Answer: Use eℓ/2e^{\ell/2}. The multiplier is standard deviation, whose square is variance eℓe^\ell. This article uses log standard deviation ρ\rho, so ρ=ℓ/2\rho=\ell/2.

  1. At μ=a=0,σ=1\mu=a=0,\sigma=1, what are the true gradient and the two estimators’ variances?

Answer: The true gradient is (0,2)(0,2). Pathwise variances are (4,8)(4,8) and raw score variances are (15,74)(15,74). A zero true mean-parameter gradient does not imply a noiseless single-sample estimate.

  1. For Bernoulli p=0.3p=0.3, what are the true derivatives with respect to pp and its logit? Why is the threshold’s zero pathwise derivative incorrect?

Answer: They are one and 0.3×0.7=0.210.3\times0.7=0.21. The almost-everywhere zero derivative misses the moving discontinuity’s contribution and cannot be interchanged with expectation here. Neither parameterization recovers its true gradient from that zero.

  1. Does subtracting the mean loss of the same two samples preserve an unbiased score estimator? How could it be changed?

Answer: No. In this independent identically distributed setting its expectation is half the original true gradient. Use a predetermined baseline or one independent of the current sample; with two draws, each can use only the other draw’s loss. Treat the baseline as constant in this score calculation and check its expectation again.

Two contemporaneous research threads

Kingma and Welling’s AEVB was first submitted on 2013-12-20; the read v11 is dated 2022-12-10. This article uses estimator and location-scale constructions in Sections 2.2–2.4. Rezende, Mohamed and Wierstra’s early manuscript was submitted on 2014-01-16 and derives Gaussian stochastic backpropagation in Section 3. The cited v1 has “Deep Latent Gaussian Models” in its title and is not treated as the complete final conference version.

Those scoped method readings and the original moment calculations support this teaching comparison. They do not establish unreplicated image metrics, universal variance superiority or applicability to all discrete variables.

Make a prediction, then check

Why hold noise fixed during a finite-difference gradient check?

Choose one answer

Learning objectives

  • Express a parameterized sample using fixed-distribution noise.
  • Derive and compare pathwise and score gradients.
  • Check gradients using common random numbers.
  • Diagnose biased baselines and discrete failures.

Prerequisites & connections

Explore related knowledge →

References

  1. Auto-Encoding Variational Bayes (v11): bound and reparameterization
    Diederik P. Kingma; Max Welling · 2022
  2. Stochastic Back-propagation and Variational Inference in Deep Latent Gaussian Models (v1)
    Danilo Jimenez Rezende; Shakir Mohamed; Daan Wierstra · 2014

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-13 · Single AI author checked AEVB v11 location-scale construction and Rezende v1 coordinate transforms. Nine paired equations and four explained exercises; exact Gaussian gradient means/variances, constant and same-batch baselines, common-noise differences and Bernoulli threshold failure. No universal variance advantage claimed.

  • Verified Gaussian polynomial moments against16-point quadrature, path/score/constant-baseline means and variances, common-noise differences, and exhaustive Bernoulli same-batch baseline bias of one half.
  • Four computed SVGs per topic bind the exact bilingual MDX. The four-topic group passed15 numeric/geometry checks and24 isolated language/width cases with four fallback fonts; eight representative screenshots were actually inspected. VAE heading changed from draw to estimate; original figures preserved, data unchanged. Literal-prose AST checked before freezing. Full article-page acceptance is separate; no independent human review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.