18 / 34 · GANs
Autoencoding GANs: adversarial autoencoders and α-GAN
What an encoder adds to a GAN, which distribution a code discriminator matches, and how reconstruction, density ratios and latent geometry interact.
Variational autoencoders · Generative adversarial networks · Wasserstein GANs and Lipschitz constraints
On this page 9
A generator can produce a plausible object without telling us how to encode an observed one. Adding an encoder supplies that route, but creates another distribution to control: the codes obtained from actual inputs may occupy a different region from the noise used for generation. A reconstruction can be accurate while a fresh sample is poor.
Consider a small sensor with readings −2, 1 and 7 occurring with probabilities 1/2, 1/3 and 1/6. We will compress them into three codes. All quantities can be enumerated, so reconstruction quality and code-distribution matching can be examined separately before considering images.
What each family is missing#
Let be the data distribution, the chosen prior, an encoder distribution and a deterministic decoder. A deterministic encoder is the special case ; a noisy encoder can instead use . Averaging over data gives the aggregate posterior:
The word posterior here names the encoder distribution. Training an autoencoder does not automatically make it the exact Bayesian posterior of a specified generative model.
A VAE defines a decoder likelihood and penalizes each conditional encoder distribution relative to the prior. When the KL terms are finite, splitting the density ratio inside the logarithm gives
The first averaged log ratio measures information about the input; the second measures marginal mismatch. A discriminator that sees only a code cannot inspect the first term. Replacing the full conditional KL by marginal matching therefore changes the objective.
Reconstruction loss also depends on its definition. Squared error selects the conditional mean: differentiating the expected squared distance to a proposed reconstruction gives twice its difference from that mean. Absolute error selects a median. Averaging different plausible images can smooth detail, but blur is not a theorem about every VAE. Likewise, an adversarial image objective does not guarantee sharpness, coverage or successful optimization.
Adversarial autoencoders: a discriminator on codes#
An adversarial autoencoder, introduced by Makhzani et al., combines reconstruction with a classifier distinguishing prior samples from encoded data. Call this classifier and give prior samples the positive label. With equal class weights, its minimized binary loss is
At a fixed code, differentiate with respect to its predicted probability. Setting the derivative to zero gives
The differentiation assumes positive p and q. At a zero boundary mass, the same optimum follows by choosing the appropriate endpoint probability. The pointwise formula assumes an unrestricted classifier and positive total mass. A finite trained network only approximates it. The encoder receives a separate adversarial update, often minimizing the non-saturating loss while the classifier’s parameters are frozen. The classifier must remain differentiable with respect to its input so that gradients can reach the encoder.
Reconstruction constrains the pairing between an input and its decoded code. The code game constrains how frequently regions of code space are used. Under the ideal conditions and almost surely for the encoder’s joint distribution, generation is correct: has the same distribution as an encoded code, whose decoded value has distribution . Either condition alone is insufficient.
What the code discriminator matches#
Choose the following stochastic encoder for the sensor readings. Each row sums to one.
| Reading | Probability | Code 0 | Code 1 | Code 2 |
|---|---|---|---|---|
| −2 | 1/2 | 1 | 0 | 0 |
| 1 | 1/3 | 0 | 1/2 | 1/2 |
| 7 | 1/6 | 0 | 0 | 1 |
Multiplying each row by its input probability and summing columns yields aggregate probabilities 1/2, 1/6 and 1/3. Against a uniform prior, the three KL quantities, in nats, are
The first number is the sum of the other two. For code 2, readings 1 and 7 each contribute joint probability 1/6. The least-squares decoder consequently returns their mean, 4; the other two reconstructions are −2 and 1. The total mean squared error is 3.
Alternatively, let every input produce a uniformly random code. The aggregate now exactly matches the prior, but the code contains no input information. Every least-squares reconstruction becomes the overall mean, 1/2, with error 41/4. A perfect code-distribution match has not produced useful reconstruction.
One code distribution, two class weights
α-GAN: a discriminator on images as well#
Rosca et al. add an image discriminator to the encoder, decoder and code discriminator. Their hybrid objective combines reconstruction with discriminator log odds; their practical procedure also presents fresh prior-generated samples to the image discriminator. This adds a distributional test of decoded objects alongside the paired reconstruction test.
Write for a reconstruction, where and , and for a fresh sample, where . Define as the distribution of reconstructions and as that of fresh samples. An explicitly normalized fake mixture is
With equal real/fake class weights, the image-classifier optimum is , using masses or densities where defined. Its log odds compare the real marginal with this fake mixture. They do not evaluate a conditional decoder likelihood for each input.
For a concrete hybrid convention, let and define similarly. Use these finite log-odds expressions on common positive real/fake and prior/code support, with both classifier outputs strictly between zero and one. We can minimize
with positive weights . This states the reduction convention; coefficients and update schedules vary between implementations. A normalized discriminator mixture and two unnormalized generator terms can coexist, but their scale must be documented. Practical approximate classifiers and a code-only marginal ratio do not turn this hybrid loss into an exactly computable ELBO.
Why all three parts are needed#
The sensor example already separates code matching from reconstruction. We can also keep the aggregate code probabilities fixed and change the decoder to return one constant. The code discriminator sees the same inputs, while reconstructions and generated samples collapse. An image discriminator can detect the resulting marginal error; it cannot determine which original reading should correspond to a particular reconstruction.
Class weights affect the meaning of its probabilities. If real examples have effective class probability , with , Bayes’ rule gives
One equally weighted real batch and two equally weighted fake batches correspond to . The log odds then differ from the log density ratio by . This offset does not change a generator gradient when fixed, but it changes reported values and any claim that those values directly equal a KL. Weighting the real loss twice restores equal total class weights.
α-WGAN: two Wasserstein critics#
Kwon, Han and Kim use real-valued Wasserstein critics for images and codes in an autoencoding GAN. A critic output is a score, not a class probability, so it has no discriminator-odds interpretation. With for images and for codes, their two-fake-stream convention leads to the minimized losses
The doubled real term balances the two fake expectations. Dividing that critic objective by two also changes the relative penalty coefficient unless it is rescaled. Adding a constant to a critic leaves its balanced real/fake difference unchanged; it shifts the numerical generator loss by a constant while leaving its parameter gradients unchanged.
For a critic , the gradient penalty introduced by Gulrajani et al. uses interpolation points between the distributions being compared:
The image penalty must specify how its endpoints sample the two fake streams. This is a soft sampled penalty, not proof of a global Lipschitz bound. Training-mode batch normalization also makes a critic’s output depend on other batch items, conflicting with a simple per-example gradient interpretation; the WGAN-GP paper uses alternatives without that coupling.
Worked example: a code critic in one dimension#
For our three code locations 0, 1 and 2, the uniform prior and encoded distribution give optimal equal-class probabilities 2/5, 2/3 and 1/2. If prior examples instead receive effective class probability 1/3, the values become 1/4, 1/2 and 1/3. Multiplying their odds by two restores the same prior-to-aggregate ratios.
A small parametric change makes the gradient explicit. Set
At , differentiate the finite KL sum. Terms from differentiating the normalization cancel, leaving
A step of size 0.1 changes the parameter to about 0.436348583171 and decreases marginal KL from 0.087208023961 to 0.054818030399. This is an enumerated probability-vector update, not backpropagation through a discrete sampling operation. With the classifier held at its current exact optimum, differentiating the expectation of negative log odds gives this same local derivative. Differentiating an arbitrary trained classifier need not do so.
Geometry changes the objective. On these unit-spaced code locations, the one-dimensional transport cost is the sum of absolute cumulative-mass differences. It equals 1/6: the aggregate has excess mass 1/6 at code 0 and a matching deficit at code 1, so that mass moves one unit. For the linear critic , the prior-minus-aggregate expectation is . A hard unit Lipschitz constraint allows at most 1/6. A soft penalty with coefficient 2 instead maximizes
On the positive branch, differentiating gives ; the negative branch gives a smaller value. The maximizing slope exceeds one. Thus a penalized training score need not equal the Wasserstein distance even when every expectation is exact.
Training: four networks, three optimizers#
A possible implementation groups the encoder and decoder in one optimizer and gives each critic its own optimizer. That grouping is an implementation choice, not a defining theorem about α-GAN. Separate losses and gradient paths still need explicit control.
During critic updates, treat encoded codes, reconstructions and prior samples as fixed inputs. Detaching them prevents unintended encoder/decoder updates. During the joint encoder–decoder update, freeze critic parameters but retain differentiation through critic inputs. Detaching the critic output would remove the adversarial signal entirely. The fresh-sample image term updates the decoder; the reconstruction image term can update both networks; the code term updates the encoder.
Clear gradients between phases and recompute forward passes after parameter changes. A previously built graph can refer to stale parameters. Gradient-penalty differentiation also needs the input-gradient computation to remain differentiable with respect to critic parameters. Monitor reconstruction, fresh-sample quality and code mismatch separately: their differently weighted sum can conceal deterioration in one component. Update counts and weights are hyperparameters rather than guarantees of convergence.
Latent interpolation: lerp or slerp?#
Once observed inputs have codes, we can explore a path between them. Linear interpolation is . For independent standard Gaussian endpoints in dimensions, independence and zero means give
At the midpoint the expected squared radius is halved. This describes the distribution of random endpoints; it does not say that every particular midpoint is implausible. High-dimensional radius concentration explains why the effect can matter.
For nonzero equal-length endpoints of radius , with angle , spherical interpolation is
To check its radius, write and in an orthonormal basis. Substitution reduces the path to , whose squared norm is .
Use the newly chosen endpoints and . Both have radius 3 and their angle has cosine −4/9. Their linear midpoint has squared norm 5/2, while the spherical midpoint has norm 3. These are geometric calculations, not measured image-quality results.
Radius depends on the path definition
Unequal endpoint lengths require another decision. For endpoints and , applying the same sine coefficients directly gives midpoint norm about 5.108815909778. An alternative first interpolates unit directions and then linearly interpolates the radius, giving midpoint radius 4.5. Neither construction automatically preserves a Gaussian prior distribution. Equal-radius paths constrain radius; Gaussian radii themselves vary. White motivates spherical paths for generative-model exploration, without supplying a universal guarantee for every learned decoder.
At coincident directions, use the continuous limiting direction. At exactly opposite directions the shortest great-circle path is not unique; choose and document an orthogonal direction. Zero vectors have no direction. Near these cases, a numerical implementation needs explicit tolerances rather than division by a nearly zero sine.
Where it breaks#
A classifier reporting chance performance may be weak, undertrained or evaluated on an inappropriate sample. It does not establish equality of distributions. Evaluate a separate held-out discriminator if using such a test, and remember that its failure to distinguish is still relative to its hypothesis class and statistical power.
A deterministic encoder applied to a finite empirical dataset produces a finite atomic code distribution. It cannot exactly equal an atomless Gaussian prior. More generally, a Lipschitz image of an intrinsically lower-dimensional smooth data manifold has zero higher-dimensional volume, so it cannot acquire a full-dimensional density merely by increasing code width. Such distributions can be singular even when their topological supports intersect. Added encoder noise changes this restriction and the reconstruction problem. Take a compact coordinate subset of dimension on which the smooth chart has bounded derivative. Composing this chart with the Lipschitz encoder is Lipschitz. The coordinate subset needs small boxes. A Lipschitz map sends each into a ball of radius , so their total ambient volume is . A countable covering by such patches preserves the zero-volume conclusion.
Reconstruction pressure can discourage some forms of collapse without proving generalization or protecting rare examples in a weighted average. Marginal matching leaves the meaning and ordering of codes unidentified. A visually smooth interpolation does not certify disentanglement, calibrated likelihood or a semantically correct path. Image and medical-data benchmarks additionally require their own data access, privacy and evaluation procedures; the finite calculations here establish none of those outcomes.
What changed#
Compared with a generator-only GAN, the encoder provides an input-dependent code and a paired reconstruction objective. AAE adds a marginal code constraint; α-GAN additionally evaluates decoded objects adversarially. Wasserstein critics change the comparison and its geometry. These choices introduce distinct tests and optimization problems rather than a single guarantee of sample quality.
What you should remember#
- Code-only discrimination tests the aggregate posterior, not every conditional distribution.
- Reconstruction and marginal matching need separate checks.
- Class weights determine the probability-to-density-ratio correction.
- Wasserstein scores are not classifier probabilities; a soft penalty is not a hard bound.
- Interpolation geometry and prior sampling are different contracts.
Code#
The following independent standard-library calculation checks the code-classifier values and marginal KL. It uses the explicit finite probabilities above and downloads nothing.
from fractions import Fraction as F
from math import log
p = [F(1, 3)] * 3
q = [F(1, 2), F(1, 6), F(1, 3)]
balanced = [a / (a + b) for a, b in zip(p, q)]
skewed = [a / (a + 2*b) for a, b in zip(p, q)]
assert [2*c/(1-c) for c in skewed] == [a/b for a,b in zip(p,q)]
kl = sum(float(b)*log(float(b/a)) for a,b in zip(p,q))
print('equal class weights:', ', '.join(map(str, balanced)))
print('prior class probability 1/3:', ', '.join(map(str, skewed)))
print('marginal KL: %.12f' % kl)
equal class weights: 2/5, 2/3, 1/2
prior class probability 1/3: 1/4, 1/2, 1/3
marginal KL: 0.087208023961
The complete reproducible calculation additionally checks the conditional-KL decomposition, optimal finite decoder, one parameter update, the penalized linear critic and both interpolation figures. Its saved outputs come from executing those explicit inputs; no neural network was trained.
Next#
Reconstruction links an observation to its latent code. CycleGAN instead links two observed domains with a pair of translation maps. Its cycle constraint introduces another question: whether reconstructing an input identifies the intended correspondence between domains.
References#
- Alireza Makhzani, Jonathon Shlens, Navdeep Jaitly, Ian Goodfellow and Brendan Frey. Adversarial Autoencoders, 2016 revision. Sections 2–2.1: aggregate posterior, encoder variants and alternating reconstruction/regularization.
- Mihaela Rosca, Balaji Lakshminarayanan, David Warde-Farley and Shakir Mohamed. Variational Approaches for Auto-Encoding Generative Adversarial Networks, 2017. Sections 2–3: density ratios, hybrid objective and adding prior samples to the image-discriminator stream.
- Gihyun Kwon, Chihye Han and Dae-shik Kim. Generation of 3D Brain MRI Using Auto-Encoding Generative Adversarial Networks, MICCAI, 2019. Section 2, equations 1–3: two fake streams and code/image critics. No MRI data, model or reported image result is reproduced here.
- Ishaan Gulrajani, Faruk Ahmed, Martin Arjovsky, Vincent Dumoulin and Aaron Courville. Improved Training of Wasserstein GANs, NeurIPS, 2017. Section 4: gradient penalty and per-example normalization considerations.
- Tom White. Sampling Generative Networks, 2016. Section 2.1: spherical interpolation as a generative-model exploration method. The finite endpoints, curves and numerical comparisons here are newly specified.