Variational Autoencoders — Learning Latent Representations
The reparameterisation trick, KL divergence loss, and why VAEs enable controllable generation through structured latent spaces.
A regular autoencoder compresses images to a point. A VAE compresses images to a region — a probability distribution. That one change makes the latent space smooth, structured, and generatable from.
A standard autoencoder has an encoder that maps an image to a fixed latent vector z, and a decoder that maps z back to an image. Trained to minimise reconstruction error, it learns an efficient compression. But the latent space it creates is fragmented — arbitrary points in it decode to garbage because the model was never trained to handle points other than the exact codes it memorised for training images.
A VAE changes the encoder's output from a single point to a probability distribution — specifically a Gaussian defined by mean μ and variance σ². During training, the latent code z is sampled from this distribution rather than fixed. A regularisation term (KL divergence) forces all these distributions to stay close to a standard normal N(0, I). The result: the entire latent space is covered continuously — any point you sample from N(0, I) decodes to a meaningful image.
A regular autoencoder is like a library where each book has a specific assigned shelf location. The shelves between books are empty — if you reach between two books you get nothing. A VAE is like a library organised by topic, with smooth transitions between subjects — books on cricket shade gradually into books on other sports, then into general fitness. Any point on the shelf has something meaningful. You can navigate by sliding from one location to another and find related content throughout.
The KL divergence term is the librarian enforcing this organisation. Without it, the encoder would cram all books into tiny clusters and leave most of the shelf empty — efficient but not navigable.
Encoder, reparameterisation, decoder — every component explained
ELBO — Evidence Lower Bound — reconstruction loss plus KL divergence
The VAE is trained to maximise the ELBO (Evidence Lower Bound) — a lower bound on the log likelihood of the data. Maximising ELBO is equivalent to minimising two terms: the reconstruction loss (how well does the decoder reconstruct the input) and the KL divergence (how close is the encoder's distribution to N(0, I)). These two terms are in tension — the KL term wants to collapse all encodings to N(0, I) which would lose all information, while the reconstruction term wants to preserve all information. The balance between them creates the structured latent space.
Binary CE for image pixels in [0,1]. MSE also common.
Maximise → decoder gets better at reconstruction.
Closed form: −0.5 × Σ(1 + log σ² − μ² − σ²)
Minimise → encoder's distributions stay near standard normal.
Complete training pipeline with KL annealing
A critical practical detail: if you start training with the full KL term, the encoder immediately collapses all posteriors to N(0, I) because that minimises KL loss trivially — the reconstruction loss hasn't had time to build useful representations yet. KL annealing fixes this: start with β=0 (pure reconstruction), gradually increase β to 1 over the first 10–20 epochs. The encoder first learns to reconstruct, then learns to organise the latent space.
Interpolation, generation, and anomaly detection — the three VAE superpowers
β-VAE — disentangled representations where each dimension has meaning
In a standard VAE (β=1), the latent dimensions are not necessarily interpretable — dimension 7 might encode a mixture of colour, texture, and shape simultaneously. β-VAE increases the KL weight (β > 1), forcing the encoder to use each latent dimension more independently. With enough pressure, individual dimensions learn to represent single factors of variation — one dimension for colour, one for shape, one for size. This is called disentanglement.
Every common VAE mistake — explained and fixed
Where VAEs show up in production — as the headline model, and hidden inside bigger ones
VAEs never had a "GANs vs diffusion"-style spotlight moment, which makes it easy to assume they quietly disappeared. In practice they show up constantly in production — sometimes as the model a team explicitly chose, and, more often than people realise, as an uncredited component wired inside a system whose headline architecture is something else entirely.
The Stable Diffusion fact is worth remembering specifically because it resolves the "VAE vs GAN vs diffusion, pick one" framing this module started with: a huge share of people using diffusion models in production are running a VAE on every single image they generate, without necessarily knowing it — it is doing the unglamorous job of making diffusion computationally affordable in the first place.
Five things people get wrong about VAEs
Sampling from a distribution stays a fundamentally stochastic operation — no trick turns randomness itself into something differentiable. What the reparameterisation trick actually does is move the randomness out of the path that needs a gradient: instead of sampling z directly from N(mu, sigma squared), it samples an independent epsilon from N(0, I) and computes z as a deterministic function of mu, sigma, and epsilon. Gradients flow cleanly through that deterministic function with respect to mu and sigma; the random part is sidestepped, not made differentiable.
Blurriness is a predictable mathematical consequence of the objective, not evidence of a weaker architecture. Pixel-wise reconstruction loss (binary cross-entropy or MSE) is minimised by outputting the average of plausible values whenever the decoder is uncertain between them, and an average of several sharp options looks smeared. This is fixable without abandoning the VAE framework — adding a perceptual loss, adding an adversarial loss on top of the ELBO (as in VQ-GAN-style hybrids), or moving to a discrete latent space (VQ-VAE) all address the same root cause directly.
The KL term has nothing to do with reconstruction quality — its entire job is regularising the shape of the encoder's output distribution to stay close to a standard normal, which is what makes the latent space continuous and sample-able in the first place. It actually competes with reconstruction rather than assisting it, which is the whole tension the ELBO is built to balance. Turning the KL weight up, as in beta-VAE, deliberately trades away some reconstruction fidelity in exchange for a more organised, disentangled latent space — proof that the two terms pull in different directions, not the same one.
Posterior collapse is a specific, diagnosable failure — the encoder gives up and outputs close to N(0, I) for every input regardless of content, and the decoder compensates by learning to generate a generic average output that ignores z entirely. The overall loss can look like it is decreasing the whole time, which is exactly what makes it deceptive to spot from the training curve alone. It is a symptom of the latent code being ignored, not the network failing to learn anything, and it is fixed with known techniques — KL annealing, free bits, reducing decoder capacity — rather than being a sign the VAE approach itself is wrong for the data.
As the production examples above show, a VAE is frequently a component living inside a diffusion pipeline rather than a competing headline architecture — latent diffusion models like Stable Diffusion use a VAE as their compression stage. Hybrids combining a VAE encoder with a GAN-style discriminator loss on top of the ELBO exist too. Treating these three as three separate competing tools you must pick exactly one of obscures how often real production systems combine them instead.
VAEs — 5 questions interviewers actually ask
The ELBO is a lower bound on the log likelihood of the data, and maximising it splits into two terms. The reconstruction term, E of log p(x given z), measures how well the decoder reproduces the input from a sampled latent code — maximising it pushes the decoder toward accurate reconstructions. The KL divergence term measures how far the encoder's distribution q(z given x) sits from the prior p(z), a standard normal — minimising it keeps the latent space smooth and centred instead of letting the encoder scatter arbitrary codes anywhere. These two terms are in direct tension, and that tension is what produces a latent space that is both informative and navigable.
Without it, z is sampled directly from a distribution parameterised by mu and sigma, and sampling is not a differentiable operation with respect to those parameters — gradients cannot flow backward through a random draw, so the encoder could never be trained end to end with standard backpropagation. The reparameterisation trick rewrites the sample as a deterministic function of mu, sigma, and an independent noise term epsilon drawn from N(0, I). Since epsilon carries no learnable parameters, gradients flow cleanly through the mu and sigma paths, and the whole network trains with ordinary backprop.
The pixel-wise reconstruction loss is minimised by predicting the average of plausible pixel values whenever the model is uncertain, and an average of several sharp possibilities reads as blur. A GAN sidesteps this because its loss comes from a discriminator judging overall realism rather than penalising each pixel independently, so it has no incentive to average. Diffusion sidesteps it differently — by refining the image gradually over many steps rather than committing to a single-shot reconstruction, it never has to resolve all its uncertainty in one averaged guess.
Posterior collapse is when the encoder stops encoding useful information and outputs close to the prior, N(0, I), for every input, while the decoder learns to reconstruct a generic average output without actually using z. It typically happens when the KL term dominates too early in training — before the reconstruction signal has had a chance to teach the encoder anything worth preserving — or when the decoder is powerful enough to reconstruct reasonably well without relying on the latent code at all. The standard fix is KL annealing: start training with the KL weight at zero and ramp it up over the first several epochs, so the encoder learns to encode meaningful structure before the regularisation pressure kicks in.
A plain autoencoder's latent space is never regularised to be continuous — the model is only ever trained to correctly decode the exact codes it assigned to training examples, so the empty space between two encoded points can decode to something meaningless. A VAE's KL term forces every encoded distribution to overlap with the same standard normal prior, which packs the whole space with meaningfully decodable regions rather than leaving gaps. That is precisely why walking a straight line between two encoded means and decoding along the way produces a smooth, semantically sensible transition instead of noise.
You understand latent variable models. Next: the architecture that generates the sharpest images ever produced by AI.
GANs are sharp but unstable. VAEs are stable but blurry. Diffusion models get the best of both — they are stable to train, produce sharp photorealistic outputs, and avoid mode collapse entirely. Module 63 explains the forward noising process, the reverse denoising network, and how Stable Diffusion uses a VAE latent space to make diffusion fast enough for practical use.
Forward noise, reverse denoising, DDPM, latent diffusion — how Stable Diffusion generates photorealistic images from text.
🎯 Key Takeaways
- ✓A regular autoencoder maps each image to a fixed point in latent space — the space between points is empty and decodes to garbage. A VAE maps each image to a probability distribution (Gaussian with mean μ and variance σ²) and regularises all distributions to stay near N(0, I). Any point sampled from N(0, I) decodes to a meaningful image.
- ✓The reparameterisation trick makes VAE training possible: instead of sampling z ~ N(μ, σ²) directly (which breaks gradients), compute z = μ + σ × ε where ε ~ N(0, I). The random ε is independent of the parameters — gradients flow through μ and σ normally.
- ✓ELBO loss has two terms: reconstruction loss (BCE or MSE — how well does decoder reproduce the input) and KL divergence (−0.5 × Σ(1 + log σ² − μ² − σ²) — how close is the encoder distribution to N(0, I)). These are in tension — the balance creates a structured, navigable latent space.
- ✓KL annealing is essential for stable training: start β=0 (pure reconstruction) and linearly increase to β=1 over 10–20 epochs. Without annealing the KL term causes posterior collapse — the encoder ignores the input and outputs N(0, I) trivially, and the decoder learns to generate average blurry images without using z.
- ✓β-VAE (β > 1) increases KL weight to encourage disentanglement — individual latent dimensions learn to represent independent factors (colour, shape, size). β=1 gives best reconstruction quality. β=4 gives partial disentanglement. β≥10 gives strong disentanglement but noticeably blurry outputs.
- ✓Three production applications: interpolation (smooth transition between two encoded images by linearly blending their latent vectors), anomaly detection (high reconstruction error = unusual item — train only on normal items), and attribute manipulation (compute direction vectors in latent space for specific attributes like colour and add them to new encodings).
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.