Reparameterization: differentiate the sampling recipe
重参数化技巧
Compare exact gradient moments, test a baseline bias and find why a discrete threshold breaks pathwise differentiation.
reparameterizationCan a computation graph differentiate through sampling?
A teaching program draws and evaluates the loss . We want to change the mean and scale to reduce average loss. Treating the drawn 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.
Fix the noise distribution and parameterize the transformation
Suppose can be sampled by transforming noise whose distribution does not depend on . If the transformation is sufficiently differentiable, the relevant expectations exist and differentiation can pass through integration, then:
Initially assume that has no additional explicit dependence on . If it does, include that direct derivative path too. The transformation must actually generate distribution ; adding noise somewhere in a computation is not sufficient. The Gaussian location-scale example in AEVB is particularly direct:
Here is log standard deviation, unlike the log variance commonly emitted by a VAE encoder. The noise stays standard normal. Writing the offset as , expand the quadratic and use and :
For a single draw, and , giving the pathwise gradient:
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 . Under appropriate regularity, fixed support and no explicit parameter dependence in :
Here score means the parameter derivative of log density. When differentiating the Gaussian density with respect to , hold the observed fixed. The scores are and . Differentiating 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 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:
For example, the mean score component expands to . Its second moment is ; subtracting gives the expression above. Similarly, for log scale:
At , the true gradient is approximately . 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 from preserves the gradient expectation. Using the same batch’s mean loss instead introduces dependence. If is sample ‘s score, independent identically distributed samples satisfy:
Treat as constant in the first estimator. The second estimator is biased because includes itself. With , 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 , this example’s score variances become and , 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:
For almost every fixed , a small change in leaves unchanged and automatic differentiation returns zero. Yet the derivative of 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 , not its logit. With a logit parameter the true derivative is . 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 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 scalar samples takes time. This implementation stores sample arrays and therefore also uses 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
- If an encoder emits log variance , should standard-normal noise be multiplied by or ?
Answer: Use . The multiplier is standard deviation, whose square is variance . This article uses log standard deviation , so .
- At , what are the true gradient and the two estimators’ variances?
Answer: The true gradient is . Pathwise variances are and raw score variances are . A zero true mean-parameter gradient does not imply a noiseless single-sample estimate.
- For Bernoulli , what are the true derivatives with respect to and its logit? Why is the threshold’s zero pathwise derivative incorrect?
Answer: They are one and . 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.
- 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?
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
- Auto-Encoding Variational Bayes (v11): bound and reparameterization
Diederik P. Kingma; Max Welling · 2022 - 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:
- Auto-Encoding Variational Bayes (v11): bound and reparameterization · Read Sections2.2–2.4 and3, Equations1–10/Algorithm1; inspected PDF pages3 and5. First submitted2013-12-20; v11 dated2022-12-10. No full appendices or benchmark replication.
- Stochastic Back-propagation and Variational Inference in Deep Latent Gaussian Models (v1) · Read Section3 Gaussian derivatives/coordinate transforms and4.1 bound opening; inspected PDF page3. v1 dated2014-01-16, whose title differs from the final PMLR paper. No full appendix or experiment review.
Related topics