Skip to content
BIASED
Back to topic

Optional

Reparameterization — derivation and CPU demo

Detailed derivation of z=μ+σ⊙ε, a NumPy distribution/gradient demo, and links to the code exercises. Self-check in the notebook.

Version
v1
Seed
42
Minutes
~30
Evidence
Self-check in the notebook

Data: synthetic mu/logvar/eps; links to existing platform exercises

Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.

Download .ipynb

Download the notebook and run it locally. Its environment requirements are listed inside.

Notebook contents

Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.

GM · Репараметризация: вывод и CPU-демо / Reparameterization derivation + CPU demo

Activity version: 1 · Seed: 42 · Данные: синтетические μ, log σ², ε; внешних датасетов нет.

Связывает тему Репараметризация с упражнениями implement-reparameterization и implement-kl-term. Здесь — подробный вывод и численный CPU-пример распределения/градиента на NumPy.

Ожидаемые числа (seed 42)
Quantity Value Tolerance
std [1.0, 2.0] exact
eps ≈ [0.30471708, -1.03998411] abs ≤ 1e-8
z = μ + σ ⊙ ε ≈ [0.80471708, -3.07996821] abs ≤ 1e-8
∂L/∂μ for L=12∥z∥2L=\tfrac12\|z\|^2 = z abs ≤ 1e-8
∂L/∂logvar ≈ [0.12260552, 3.20311799] abs ≤ 1e-8
Самопроверка в ноутбуке

Сверьте числа; затем откройте упражнения на сайте. Активность не входит в процент освоения.

Вывод / Derivation

Энкодер задаёт qφ(z∣x)=N(μ,σ2)q_\varphi(z\mid x)=\mathcal N(\mu,\sigma^2). Реконструкция — ожидание по qφq_\varphi; сэмпл z∼qφz\sim q_\varphi без трюка обрывает градиент к μ,σ\mu,\sigma.

Трюк: перенести случайность во вход

z=μ+σ⊙ε,ε∼N(0,I).z=\mu+\sigma\odot\varepsilon,\qquad\varepsilon\sim\mathcal N(0,I).

Распределение zz то же, но ∂zj/∂μj=1\partial z_j/\partial\mu_j=1, ∂zj/∂σj=εj\partial z_j/\partial\sigma_j=\varepsilon_j. Энкодер обычно предсказывает log⁡σ2\log\sigma^2, тогда σ=exp⁡(12log⁡σ2)>0\sigma=\exp(\tfrac12\log\sigma^2)>0.

Для L=12∑jzj2L=\tfrac12\sum_j z_j^2:

∂L∂μ=z,∂L∂log⁡σ2=z⊙ε⊙12σ.\frac{\partial L}{\partial\mu}=z,\quad \frac{\partial L}{\partial\log\sigma^2}=z\odot\varepsilon\odot\tfrac12\sigma.
import numpy as np
 
SEED = 42
rng = np.random.default_rng(SEED)
 
mu = np.array([0.5, -1.0])
logvar = np.array([0.0, np.log(4.0)])  # sigma = [1, 2]
std = np.exp(0.5 * logvar)
eps = rng.standard_normal(mu.shape)
z = mu + std * eps
 
print("std", std)
print("eps", eps)
print("z", z)
 
L = 0.5 * np.sum(z ** 2)
grad_mu = z
grad_logvar = z * eps * 0.5 * std
print("L", L)
print("grad_mu", grad_mu)
print("grad_logvar", grad_logvar)
 
assert np.allclose(std, [1.0, 2.0])
assert np.allclose(eps, [0.30471708, -1.03998411], atol=1e-8)
assert np.allclose(z, [0.80471708, -3.07996821], atol=1e-8)
assert np.allclose(grad_logvar, [0.12260552, 3.20311799], atol=1e-8)
print("OK: reparameterization CPU demo")
 

Дисперсия оценки градиента (из темы)

Для ∇μE[z2]\nabla_\mu\mathbb E[z^2] при μ=σ=1\mu=\sigma=1: репараметризация даёт 2(1+ε)2(1+\varepsilon) с дисперсией 4; score-function — дисперсию 30. Ниже — эмпирическая проверка на NumPy.

rng = np.random.default_rng(0)
n = 200_000
eps = rng.standard_normal(n)
# reparameterized estimator of d/dmu E[z^2] at mu=sigma=1: 2(mu + sigma eps) = 2(1+eps)
g_re = 2 * (1 + eps)
# score-function: z^2 * (z - mu) / sigma^2 with z ~ N(1,1)
z = 1 + eps
g_sf = (z ** 2) * (z - 1)
print("var reparam ≈", float(g_re.var()), "expected 4")
print("var score   ≈", float(g_sf.var()), "expected 30")
assert abs(g_re.var() - 4) < 0.05
assert abs(g_sf.var() - 30) < 0.5
print("OK: estimator variance check")
 

Дальше на платформе

  1. Упражнение Репараметризация в коде (implement-reparameterization) — допишите z = μ + σ ⊙ ε в шаблоне PyTorch.
  2. Упражнение KL-слагаемое (implement-kl-term) — поэлементный KL к N(0,1)\mathcal N(0,1).
Самопроверка в ноутбуке
  • std, eps, z, градиенты совпали с таблицей
  • дисперсии ≈ 4 и ≈ 30
  • связь с упражнениями понятна (открыть по желанию)