M5.3 8 min read Oct 2026

M5.3 Adjusting a Sample-Producing Machine: Differentiating a Generator

Builds on3 notes

A machine turning noise into products

A differentiable program transforms noise zz into products x=Gθ(z)x=G_\theta(z). We know the noise and program, but may not know the output density pθp_\theta.

We want the whole output distribution to match a target p∗p^*, rather than making every product identical. Which parameter update improves that match?

Fixing the same noise and changing parameters reveals how samples move. Can those movements give the gradient of a distributional discrepancy?

DiscussionQ1

How does the output law depend on parameters, and what makes direct differentiation difficult?

Show the reasoning

The output law is the pushforward of fixed pzp_z through GθG_\theta. Compare it with the target using

L(θ)=KL(pθ ∥ p∗)=Ex∼pθ[log⁡pθ(x)−log⁡p∗(x)].L(\theta)=\mathrm{KL}(p_\theta\,\|\,p^*)=\mathbb E_{x\sim p_\theta}\big[\log p_\theta(x)-\log p^*(x)\big].

This direction, KL(pθ∥p∗)\mathrm{KL}(p_\theta\|p^*), penalizes generated mass placed where the target density is too small. The choice also affects treatment of missing modes.

Both the sampling law and log⁡pθ\log p_\theta depend on parameters. A black-box sampler does not reveal how individual samples move. Reparameterization provides that path, though it is not the only gradient-estimation method.

Write the expectation over fixed noise z∼pzz\sim p_z, then place all sampling dependence in a differentiable GθG_\theta. This is reparameterization.

Fix the random draws and adjust the machine

Imagine pre-drawing z1,…,zNz_1,\ldots,z_N. For fixed parameters each output is now deterministic. The derivative ∂θGθ(zi)\partial_\theta G_\theta(z_i) describes how a parameter change moves sample ii.

At each sample, the spatial slope of log⁡pθ(x)−log⁡p∗(x)\log p_\theta(x)-\log p^*(x) describes the local mismatch. Pulling this slope back through the generator derivative converts a sample-space direction into a parameter gradient. The density itself also depends explicitly on parameters, so we must account for that term too.

The resulting expression averages spatial score differences multiplied by parameter sensitivities. The following derivation explains why an additional term vanishes in expectation.

Score differences pulled back through generator parameter sensitivities.

Fixed noise exposes sample motion; generator derivatives convert spatial scores into parameter updates.

Derive it in one dimension

First use scalar samples and parameters. Assume differentiable GθG_\theta, suitable smooth densities, finite KL, and justified exchanges of derivatives and integrals. The support must be parameter-independent or moving-boundary contributions correctly handled. Then

L(θ)=Ez[log⁡pθ(Gθ(z))−log⁡p∗(Gθ(z))].L(\theta)=\mathbb E_{z}\Big[\log p_\theta\big(G_\theta(z)\big)-\log p^*\big(G_\theta(z)\big)\Big].

Differentiate inside the fixed-noise expectation. Parameters occur both through GθG_\theta and explicitly in the model-density index:

∂θL=Ez ⁣[(∂xlog⁡pθ−∂xlog⁡p∗)(Gθ(z)) ∂θGθ(z)⏟A: spatial slope times sensitivity+(∂θlog⁡pθ)(Gθ(z))⏟B: explicit density dependence].\partial_\theta L=\mathbb E_z\!\left[ \underbrace{(\partial_x\log p_\theta-\partial_x\log p^*)(G_\theta(z))\,\partial_\theta G_\theta(z)}_{A:\ \text{spatial slope times sensitivity}} +\underbrace{(\partial_\theta\log p_\theta)(G_\theta(z))}_{B:\ \text{explicit density dependence}} \right].

Term BB differentiates the density parameter at fixed xx, not along the generated sample path. Under the regularity assumptions its expectation is zero:

Ez[∂θlog⁡pθ(Gθ(z))]=Ex∼pθ[∂θlog⁡pθ(x)]=∫pθ ∂θpθpθ dx=∂θ ⁣∫pθ dx=∂θ1=0.\mathbb E_z\big[\partial_\theta\log p_\theta(G_\theta(z))\big]=\mathbb E_{x\sim p_\theta}\big[\partial_\theta\log p_\theta(x)\big]=\int p_\theta\,\frac{\partial_\theta p_\theta}{p_\theta}\,dx=\partial_\theta\!\int p_\theta\,dx=\partial_\theta1=0.

Changing the variable name from Gθ(z)G_\theta(z) to xx gives the first equality; differentiating normalization gives the final zero. Therefore

  ∂θ KL(pθ∥p∗)=Ez[(∂xlog⁡pθ(x)−∂xlog⁡p∗(x))∣x=Gθ(z)⋅∂θGθ(z)].  \boxed{\;\partial_\theta\,\mathrm{KL}(p_\theta\|p^*)=\mathbb E_{z}\Big[\big(\partial_x\log p_\theta(x)-\partial_x\log p^*(x)\big)\Big|_{x=G_\theta(z)}\cdot\partial_\theta G_\theta(z)\Big].\;}

For dd-dimensional samples and mm parameters, JθG∈Rd×mJ_\theta G\in\mathbb R^{d\times m} gives ∇θL=Ez[(JθG)⊤(sθ−s∗)]\nabla_\theta L=\mathbb E_z[(J_\theta G)^\top(s_\theta-s^*)], where s=∇xlog⁡ps=\nabla_x\log p. The result has parameter dimension mm.

A spatial score ∇xlog⁡p\nabla_x\log p points toward increasing log density. An xx-independent normalizer disappears under this derivative, but is not thereby calculated. The generator supplies the Jacobian; model and target distributions supply the scores.

DetailsZero-mean terms and estimator variance

Another identity is the parameter-score estimator ∂θEpθ[f]=Epθ[f∂θlog⁡pθ]\partial_\theta\mathbb E_{p_\theta}[f]=\mathbb E_{p_\theta}[f\partial_\theta\log p_\theta] for parameter-independent f under appropriate assumptions. Its parameter derivative differs from the spatial score above and can handle discrete outcomes. There is no universal variance ordering against pathwise estimators [3].

Removing zero-mean BB preserves unbiasedness. It does not universally reduce variance, since

Var⁡(A+B)=Var⁡(A)+Var⁡(B)+2Cov⁡(A,B).\begin{aligned} \operatorname{Var}(A+B) &=\operatorname{Var}(A)+\operatorname{Var}(B)\\ &\quad+2\operatorname{Cov}(A,B). \end{aligned}

At exact model-target equality, AA vanishes samplewise, so removing BB eliminates this noise source [4].

What information does the formula need?

At each generated sample, obtain three quantities:

  1. Generator Jacobian: available through differentiation of the program.
  2. Target spatial score: analytic if the target density is known; target samples alone do not directly supply it. Score estimation is another learning problem [5].
  3. Model spatial score: knowing a generator does not generally expose its density or score. An invertible generator may permit change of variables; a general generator may require estimation or may not even induce an ambient-space density.

Two scores do not necessarily require two additional neural networks: analytic expressions and other estimators may exist. Bypassing normalizers in spatial derivatives does not evaluate likelihoods or KL values.

Check differentiable sample paths, score accuracy at generated locations, and the KL direction. Discrete outputs need other estimators or relaxations. Reverse KL can tolerate missing target modes, so a mode-coverage goal may call for a different discrepancy.

A Gaussian calculation with and without the extra term

Let Gθ(z)=θ+zG_\theta(z)=\theta+z, z∼N(0,1)z\sim\mathcal N(0,1), and p∗=N(5,1)p^*=\mathcal N(5,1). KL is (θ−5)2/2(\theta-5)^2/2. Spatial scores are −(x−θ)-(x-\theta) and −(x−5)-(x-5), whose difference is exactly θ−5\theta-5 for every sample. Generator sensitivity is one, so AA has no sampling variation here.

import numpy as np
rng = np.random.default_rng(0)
theta, target, lr = 0., 5., .1
for step in range(60):
    z = rng.standard_normal(256)
    x = theta+z
    score_model = -(x-theta)
    score_target = -(x-target)
    grad_A = np.mean(score_model-score_target)
    grad_B = np.mean(x-theta)  # Parameter derivative at fixed x; mean zero.
    theta -= lr*grad_A
    if step%15==0:
        print(step,theta,grad_A,grad_B)
print(theta)

The update approaches five. Each batch’s AA equals the exact gradient, while BB fluctuates with mean zero. Including BB would add noise in this example; that observation does not establish a universal variance comparison.

Estimated scores can be inaccurate in sparse tails. Nonlinearity alone does not imply no analytic density: θ+∣z∣\theta+|z| has a shifted half-normal law, but its moving support invalidates the simple zero-mean proof without boundary treatment. A low-dimensional latent mapped into higher dimensions can induce a singular law, making the displayed density-based KL undefined or infinite.

Switch generators and target information to inspect how score differences move parameters.

Check your understanding

Check your understanding

A generator outputs discrete product IDs using an argmax. Can the displayed pathwise formula be applied directly?

Check your understanding

What happens if term BB remains in the estimator?

Check your understanding

Only two hundred target samples are available. The fitted generator matches the center but misses the tails. What should be investigated?

References

  1. Kingma, D. P., Welling, M. Auto-Encoding Variational Bayes. ICLR 2014.
  2. Rezende, D. J., Mohamed, S., Wierstra, D. Stochastic Backpropagation and Approximate Inference in Deep Generative Models. ICML 2014.
  3. Mohamed, S., Rosca, M., Figurnov, M., Mnih, A. Monte Carlo Gradient Estimation in Machine Learning. JMLR 21, 2020.
  4. Roeder, G., Wu, Y., Duvenaud, D. Sticking the Landing: Simple, Lower-Variance Gradient Estimators for Variational Inference. NeurIPS 2017.
  5. Hyvärinen, A. Estimation of Non-Normalized Statistical Models by Score Matching. JMLR 6, 2005.