Variational autoencoders: learning a decoder and its posterior
变分自编码器
Train a six-parameter Gaussian VAE and compare reconstruction, marginal likelihood and posterior approximation.
variational-autoencodersReconstructing a point and learning a distribution
Consider six scalar observations for teaching: −2, −1, −0.4, 0.4, 1 and 2. An ordinary autoencoder can compress each input into a code and reconstruct it. Reconstruction error alone does not determine whether decoding an arbitrarily drawn code samples the learned data distribution.
A variational autoencoder, or VAE, specifies a generative model: draw a latent variable from a prior, then draw data from a conditional observation distribution. Its encoder reads an observation and approximates which latent variables could have generated it. The encoder therefore outputs distribution parameters, as does the decoder; they are not simply two symmetric deterministic mappings. AEVB Sections 2–3 give this construction; Rezende and colleagues’ early work also jointly learns a recognition model and a latent-variable generative model.
Begin with autoencoders, Gaussian distributions and maximum likelihood. We use a VAE with a tractable posterior to check every quantity before discussing which computations change with neural networks.
Three distributions with different jobs
The prior supplies latents for unconditional generation. The decoder describes observations given a latent. The encoder approximates the current model’s true posterior. The joint and single-observation objective are:
Here denotes generative parameters and encoder parameters. Maximizing the ELBO, or minimizing its negative, places reconstruction and prior KL in one probabilistic objective. The bound is log evidence minus the KL from to the true posterior, rather than an arbitrary combination of two losses. AEVB Equations 1–3 explain this decomposition.
A diagonal Gaussian encoder and its scale
A common choice outputs mean vector and log-variance vector . With latent dimensions, the noise also has dimensions:
Exponentiation is elementwise and denotes elementwise multiplication. Log variance need not be positive, while the resulting variance must be; numerical implementations should also control large exponents. Noise is multiplied by standard deviation , not variance . AEVB Section 3 uses a diagonal Gaussian; lines 60–63 of the pinned PyTorch example likewise exponentiate half of logvar.
For a standard-normal prior, the KL is analytic:
Use and in the expected difference of Gaussian log densities to obtain each dimension’s term. At , the encoder distribution equals the prior and KL is zero. This removes distance to the prior, not necessarily distance to an observation’s true posterior.
Six parameters suffice for a complete training example
Let be scalars and use linear encoder and decoder functions. The six parameters are :
Fix observation-noise variance . Parameters control the generative model; the remaining four make the encoder distribution depend on the input. A shared encoder quickly gives an approximate posterior for different observations. This is amortized inference: it avoids storing a separate set of optimized variational parameters for every observation.
The decoder is linear, so expected reconstruction error expands directly. Averaging over observations gives negative ELBO:
The term is the contribution of latent uncertainty through the decoder. Reconstructing only from the encoder mean and measuring squared error omits it. The Gaussian log-normalization constant is retained too. Removing constants may leave some fixed-variance gradients unchanged, but changes the reported probabilistic objective.
To expose backpropagation, the code still follows the graph . Its default noise nodes are −1 and +1 with equal weights. They match the standard normal’s first two moments, making integration exact for this quadratic reconstruction term. This is deterministic integration, not random SGVB or a general exact method for nonlinear neural decoders.
For one observation, define the scaled residual and apply the chain rule:
The first two derivatives update the decoder. The next two propagate through encoder mean and log variance. Using then gives:
Average each derivative across observations. A neural decoder generally loses the analytic reconstruction expectation, but can estimate it with parameter-independent standard-normal noise while retaining these chain-rule paths. AEVB Section 2.3 and Rezende’s coordinate transformation support this construction.
Compare training against the true model
Completing the square also gives this model’s true marginal and posterior:
They provide an independent check of the objective:
Expected reconstruction, marginal likelihood and posterior approximation gap can be calculated separately. Renaming a variable loss to likelihood would not reveal whether these quantities were confused.
Train every encoder and decoder parameter
Save this as vae.py and run it with Python 3.12 and NumPy 1.26.4. The six synthetic observations are included; no external data is needed. Each iteration uses the whole dataset, updating all six parameters with learning rate 0.01 for 1200 steps. A separate seed-12 calculation uses 32 Gaussian samples per observation to illustrate a Monte Carlo objective.
"""Six-parameter linear Gaussian VAE. Exact quadratic quadrature, optional fixed-noise MC."""
import json
import numpy as np
DATA = np.array([-2., -1., -.4, .4, 1., 2.])
INITIAL = np.array([.5, 0., .2, 0., -.2, 0.]) # a,c,w,b,r,s
TAU2 = .25
def inputs(params, x):
params, x = np.asarray(params, float), np.asarray(x, float)
if (params.shape != (6,) or x.ndim != 1 or not 1 <= x.size <= 128
or not np.isfinite(params).all() or not np.isfinite(x).all()
or np.max(abs(params)) > 10 or np.max(abs(x)) > 4):
raise ValueError('Six bounded parameters and 1..128 scalar observations in [-4,4] required.')
a, c, w, b, r, s = params
mu, lv = w*x+b, r+s*x
if np.max(abs(lv)) > 8:
raise ValueError('Encoder log variance must remain in [-8,8].')
return params, x, mu, lv
def objective(params, x=DATA, eps=None):
params, x, mu, lv = inputs(params, x)
a, c, w, b, r, s = params
if eps is None:
eps = np.broadcast_to([-1., 1.], (x.size, 2))
eps = np.asarray(eps, float)
if (eps.ndim != 2 or eps.shape[0] != x.size or not 1 <= eps.shape[1] <= 256
or not np.isfinite(eps).all() or np.max(abs(eps)) > 20):
raise ValueError('Noise must have shape (observations, 1..256), finite and bounded by 20.')
std = np.exp(.5*lv)
z = mu[:, None] + std[:, None]*eps
residual = a*z+c-x[:, None]
reconstruction = .5 * (np.log(2*np.pi*TAU2) + np.mean(residual**2, axis=1)/TAU2)
kl = .5 * (mu**2 + np.exp(lv) - 1 - lv)
error = residual/TAU2
dmu = a*error.mean(axis=1) + mu
dlv = np.mean(a*error*.5*std[:, None]*eps, axis=1) + .5*(np.exp(lv)-1)
gradient = np.array([np.mean(error*z), np.mean(error), np.mean(dmu*x),
np.mean(dmu), np.mean(dlv), np.mean(dlv*x)])
return float(np.mean(reconstruction+kl)), gradient
def analytic(params, x=DATA):
"""Independent closed-form expectation and true marginal/posterior."""
params, x, mu, lv = inputs(params, x)
a, c = params[:2]; v = np.exp(lv)
reconstruction = .5*(np.log(2*np.pi*TAU2) + ((a*mu+c-x)**2 + a*a*v)/TAU2)
kl = .5*(mu*mu+v-1-lv)
marginal_variance = a*a+TAU2
marginal_nll = .5*(np.log(2*np.pi*marginal_variance)+(x-c)**2/marginal_variance)
post_mu, post_v = a*(x-c)/marginal_variance, TAU2/marginal_variance
gap = .5*(np.log(post_v/v)+(v+(mu-post_mu)**2)/post_v-1)
return dict(negative_elbo=float(np.mean(reconstruction+kl)),
reconstruction_nll=float(reconstruction.mean()), kl_prior=float(kl.mean()),
marginal_nll=float(marginal_nll.mean()), posterior_kl=float(gap.mean()),
posterior_mean=post_mu.tolist(), posterior_variance=float(post_v))
def fit(steps=1200, rate=.01):
if isinstance(steps, bool) or not isinstance(steps, int) or not 0 <= steps <= 5000 or not 0 < rate <= .02:
raise ValueError('Use 0..5000 integer steps and learning rate in (0,.02].')
p = INITIAL.copy(); history = [objective(p)[0]]
for i in range(steps):
_, grad = objective(p)
p -= rate*grad
if (i+1) % 100 == 0 or i+1 == steps:
history.append(objective(p)[0])
return p, history
def demo():
p, history = fit()
noise = np.random.default_rng(12).normal(size=(len(DATA), 32))
return dict(parameters=p.tolist(), exact_quadrature_loss=history,
analytic=analytic(p), fixed_seed_mc_negative_elbo=objective(p, eps=noise)[0],
setting='Six synthetic scalar observations; no held-out accuracy or paper reproduction.')
if __name__ == '__main__':
print(json.dumps(demo(), indent=2, allow_nan=False))
Exact negative ELBO falls from 3.465322 to 1.691041 nats/observation. The final reconstruction NLL is about 0.745127 and prior KL about 0.945914, which sum to that objective. True marginal NLL is about 1.690697, with remaining posterior KL about 0.000343866: close, but not equal.
One fixed-seed sampled negative ELBO is 1.672002, below true marginal NLL. The probability identity has not failed. Exact negative ELBO is an upper bound; a finite-sample estimator need not exceed true NLL on every realization.
Companion checks take finite differences of all six parameters, both with exact nodes and common random noise, and use independent analytic formulas for reconstruction and the posterior gap. The six observations have mean zero and variance 1.72. The model can match marginal variance 1.72 using , but the 1200-step result is not certified as a global optimum.
For scalar observations and nodes or samples each, a step uses time and stored-array space; fixed gives . A neural VAE adds encoder/decoder depth, width and activation storage. This six-parameter cost is not an estimate for image training.
Implementation choices can change the interpretation
Match the observation distribution first. Binary observations can use a Bernoulli likelihood; real observations can use a Gaussian with a specified variance or another density. The pinned PyTorch example uses ToTensor grayscale inputs, summed BCE and summed KL. With fractional targets, BCE can be a soft-label cross-entropy, but should not be called a Bernoulli probability density over continuous grayscale. Comparisons must also align sums and means over pixels, latent dimensions and batches.
For generation, draw from the prior, then sample the decoder’s observation distribution. Returning only yields a conditional mean and omits observation variance ; its distribution differs from that of a full generated . Reconstruction instead begins with . Mixing these procedures obscures the relationship between good reconstruction and good unconditional generation.
A diagonal Gaussian restricts posterior shape, and a shared encoder may not express every observation’s best approximation simultaneously. If equals the prior and the decoder ignores , the prior KL is zero but the latent communicates no input information. Low KL alone is therefore not a success measure. This linear example checks the computation; it neither reproduces high-dimensional image quality nor has a separate real-data test set.
Check four parts of the generative model
- With , what multiplies standard-normal noise, and what is the KL to the standard normal?
Answer: The multiplier is two and the variance is four. KL is . Multiplying noise by four instead produces variance sixteen and a different .
- At , which encoder distribution makes the posterior gap zero?
Answer: matches both true posterior mean and variance. Merely making the reconstruction mean close to one is a different requirement.
- Why do duplicating every observation leave the code’s mean objective and gradient unchanged? What if mean is changed to sum?
Answer: Duplication doubles both the numerator and observation count, preserving their mean. The same averaging applies to gradients. With a sum instead, both objective and gradient double; at the same learning rate, the update magnitude doubles too. Both the logging scale and optimization scale change.
- At , compare the marginal variance when generation returns only decoder mean versus actually sampling .
Answer: Mean-only output has variance one. Full generation adds independent observation noise, giving variance . A cleaner-looking mean output is not a sample from the model’s full observation distribution.
Papers, a runnable reference and teaching simplifications
AEVB was first submitted on 2013-12-20; this article uses the method sections 2–3 of v11 dated 2022-12-10. The read Rezende v1 is dated 2014-01-16 and covers Gaussian derivatives, coordinate transformations and the opening bound discussion; its title differs from the final PMLR paper. Together they explain joint learning of stochastic encoders and generative models without reducing attribution to an unqualified invention claim.
The PyTorch VAE example is pinned to commit acc295d dated 2025-09-01. Reading covered lines 35–89, its README and the complete root BSD3-Clause license; upstream training was not executed and its implementation was not copied. This article’s original six-parameter Gaussian model deliberately uses a tractable posterior, two-node exact integration and a small dataset.
Make a prediction, then check
An encoder outputs log variance ℓ. What multiplies standard-normal noise?
Learning objectives
- Distinguish encoder, decoder and prior roles.
- Derive Gaussian KL and log-variance scaling.
- Train and gradient-check all six model parameters.
- Separate exact integration, sampled bounds and generative likelihood.
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 - PyTorch examples: VAE implementation at acc295d
PyTorch examples contributors · 2025
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked AEVB v11 method sections, Rezende v1 Gaussian transforms and fixed PyTorch VAE code. Nine paired equations and four explained exercises; six-parameter Gaussian VAE with exact quadratic quadrature, full gradients, true marginal/posterior and a sampled-bound counterexample. No image benchmark replication.
- Verified all6 parameter gradients for exact two-node integration and fixed Gaussian noise, independent analytic objective, posterior KL identity,1200 updates, mean scaling and sampled negative ELBO below true NLL.
- 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.
- PyTorch examples: VAE implementation at acc295d · Read lines35–89, VAE README and full root BSD3-Clause license. Commit2025-09-01. Checked ToTensor, logvar scaling and summed BCE/KL; no upstream execution, copied code or MNIST download.
Related topics