πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
NEWSLIVESearch All Content
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

GANs vs VAEs: Two Routes to Generation

🟒 Free Lesson

GANs vs VAEs: Two Routes to Generation

Before diffusion models dominated image generation, two families defined the field and both remain essential to understand β€” GANs for their unmatched sample sharpness, VAEs for their principled latent spaces. They solve the same problem with almost opposite strategies. A GAN learns to generate by pitting two networks against each other until the forger cannot be caught. A VAE learns by compressing data into a probabilistic bottleneck and measuring how well it can reconstruct what it threw away.

The difference shows up immediately in results. GAN samples are crisp and detailed but the training is unstable, and the model can silently ignore modes of the data. VAE samples are blurrier β€” optimizing average-case reconstruction naturally washes out detail β€” but training is a stable single loss, and interpolating through the latent space produces meaningful, smooth transitions.

This lesson builds both from scratch in PyTorch, explains why each failure mode emerges from its objective, and gives a decision table for choosing between them (and against modern diffusion models) for a given task.

Two philosophies of generation

A GAN never computes a likelihood. It defines generation implicitly: map noise through a generator network, and judge realism by whether a discriminator can tell the output from real data. The generator's gradient comes from the discriminator's mistakes. There is no notion of reconstruction β€” only of passing a test.

A VAE defines generation explicitly through a latent variable model. Encode each input to a distribution over latent codes, sample from that distribution, decode back, and optimize a tractable lower bound on the log likelihood (the ELBO: reconstruction quality plus a regularizer pushing the latent distribution toward a prior). Generation at test time means sampling the prior and decoding.

PropertyGANVAE
Training signalDiscriminator comparisonReconstruction + KL regularizer
Loss stabilityUnstable, sensitive to balanceStable, single smooth objective
Sample sharpnessHighBlurry (average-case recon)
Latent spaceIrregular, poor for interpolationSmooth, structured, interpolable
Mode coverageRisk of mode collapseUsually covers all modes
Likelihood estimateNoneLower bound available (ELBO)
Typical usesHigh-fidelity images, style transferRepresentation learning, compression, drug design

Neither column is a verdict. If your product needs photorealistic samples and you can invest in training stability, a GAN family model may still fit; if you need a continuous latent space you can traverse, optimize over, or sample from with a known prior, a VAE is the cleaner tool.

The GAN training loop

The generator maps a noise vector to a synthetic sample; the discriminator outputs the probability that an input is real. Each training step advances both: the discriminator learns to spot fakes, the generator learns to fool the discriminator.

python
import torch
import torch.nn as nn

class Generator(nn.Module):
    def __init__(self, z_dim: int = 100, out_dim: int = 784):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(z_dim, 256), nn.LeakyReLU(0.2), nn.BatchNorm1d(256),
            nn.Linear(256, 512), nn.LeakyReLU(0.2), nn.BatchNorm1d(512),
            nn.Linear(512, 1024), nn.LeakyReLU(0.2), nn.BatchNorm1d(1024),
            nn.Linear(1024, out_dim), nn.Tanh(),
        )

    def forward(self, z):
        return self.net(z)

class Discriminator(nn.Module):
    def __init__(self, in_dim: int = 784):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(in_dim, 512), nn.LeakyReLU(0.2), nn.Dropout(0.3),
            nn.Linear(512, 256), nn.LeakyReLU(0.2), nn.Dropout(0.3),
            nn.Linear(256, 1),
        )

    def forward(self, x):
        return self.net(x)

class GAN:
    def __init__(self, z_dim: int = 100, img_dim: int = 784):
        self.G = Generator(z_dim, img_dim)
        self.D = Discriminator(img_dim)
        opt_g = torch.optim.Adam(self.G.parameters(), lr=2e-4, betas=(0.5, 0.999))
        opt_d = torch.optim.Adam(self.D.parameters(), lr=2e-4, betas=(0.5, 0.999))
        self.opt_g, self.opt_d = opt_g, opt_d
        self.bce = nn.BCEWithLogitsLoss()

    def train_step(self, real: torch.Tensor):
        b = real.shape[0]
        ones = torch.ones(b, 1)
        zeros = torch.zeros(b, 1)

        real_logits = self.D(real)
        z = torch.randn(b, 100)
        fake = self.G(z)
        fake_logits = self.D(fake.detach())
        d_loss = self.bce(real_logits, ones) + self.bce(fake_logits, zeros)
        self.opt_d.zero_grad()
        d_loss.backward()
        self.opt_d.step()

        z = torch.randn(b, 100)
        g_logits = self.D(self.G(z))
        g_loss = self.bce(g_logits, ones)
        self.opt_g.zero_grad()
        g_loss.backward()
        self.opt_g.step()
        return d_loss.item(), g_loss.item()

gan = GAN()
for epoch in range(100):
    for batch in loader:
        d_loss, g_loss = gan.train_step(batch)

Three implementation choices in that loop are load-bearing. fake.detach() stops gradients flowing from the discriminator's loss into the generator β€” without it the generator receives a contradictory gradient. The betas=(0.5, 0.999) Adam setting reduces momentum, which empirically stabilizes adversarial training. And the discriminator must be strong enough to give useful gradients but not so strong that the generator gets vanishing signal β€” the balance point that makes GAN training notoriously finicky.

Why GANs collapse, and the fixes

Mode collapse is the defining GAN failure: the generator discovers a small set of outputs the discriminator currently accepts and produces only those. From the generator's perspective this is rational β€” if one trick works, repeat it. The discriminator's loss does not necessarily flag the problem, because individual fakes still look plausible; only diversity metrics reveal it.

The standard countermeasures all aim to give the discriminator (or an auxiliary critic) a reason to reward diversity. Minibatch discrimination lets the discriminator see whether a batch of fakes is suspiciously similar to itself. Feature-matching feeds the discriminator's intermediate activations β€” not its final verdict β€” to the generator, which is harder to game. Spectral normalization constrains the discriminator's Lipschitz constant, a requirement made theoretical by Wasserstein GAN (WGAN) and now standard in practice. R1 gradient penalties on real samples stabilize the balance further.

Detection matters as much as prevention: track the number of distinct outputs, sample diversity scores, and coverage of known data subgroups each epoch. Loss curves alone will not tell you the model has collapsed.

Inside the VAE objective

The VAE encoder does not output a code; it outputs parameters of a distribution β€” a mean and a log-variance for each latent dimension. Sampling from that distribution injects noise, and the decoder must learn to reconstruct from noisy codes, which is what produces a smooth, hole-free latent space.

python
import torch
import torch.nn as nn

class VAE(nn.Module):
    def __init__(self, in_dim: int = 784, hidden: int = 400, z_dim: int = 20):
        super().__init__()
        self.encoder = nn.Sequential(
            nn.Linear(in_dim, hidden), nn.ReLU(),
            nn.Linear(hidden, hidden), nn.ReLU(),
        )
        self.mu = nn.Linear(hidden, z_dim)
        self.logvar = nn.Linear(hidden, z_dim)
        self.decoder = nn.Sequential(
            nn.Linear(z_dim, hidden), nn.ReLU(),
            nn.Linear(hidden, hidden), nn.ReLU(),
            nn.Linear(hidden, in_dim), nn.Sigmoid(),
        )

    def encode(self, x):
        h = self.encoder(x)
        return self.mu(h), self.logvar(h)

    def reparameterize(self, mu, logvar):
        std = torch.exp(0.5 * logvar)
        return mu + torch.randn_like(std) * std

    def decode(self, z):
        return self.decoder(z)

    def forward(self, x):
        mu, logvar = self.encode(x)
        z = self.reparameterize(mu, logvar)
        return self.decode(z), mu, logvar

    def elbo(self, recon, x, mu, logvar):
        recon_loss = nn.functional.binary_cross_entropy(
            recon, x, reduction="sum"
        )
        kl = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
        return recon_loss + kl

vae = VAE()
opt = torch.optim.Adam(vae.parameters(), lr=1e-3)
for batch in loader:
    recon, mu, logvar = vae(batch)
    loss = vae.elbo(recon, batch, mu, logvar)
    opt.zero_grad()
    loss.backward()
    opt.step()

The reparameterization trick is what makes the whole thing differentiable: instead of sampling (a non-differentiable operation), we sample a fixed noise tensor and apply a differentiable transformation. The KL term pulls the aggregated posterior toward the standard normal prior; the reconstruction term pushes back. Their tug-of-war sets how much information each latent dimension carries.

Blur emerges from exactly this setup. When the decoder must reconstruct from a noisy sample of the code, it minimizes expected error across plausible codes β€” and averaging over plausible alternatives blurs detail. Ways out include reducing the KL weight (beta-VAE trade-offs), dequantization for discrete data, and VQ-VAE, which replaces continuous codes with a learned discrete codebook and reconstructs sharply β€” the approach behind several production text-to-image systems.

Measuring whether either model learned

Both families need evaluation beyond their training loss, because the losses answer different questions and neither one equals sample quality. The standard suite for image generators combines an distributional metric with a reference metric. FrΓ©chet Inception Distance (FID) embeds real and generated images with a pretrained network and compares the mean and covariance of those embeddings β€” lower is closer. Inception Score rewards images that a classifier finds both confident and diverse. Precision and recall for generative models separate two failure modes directly: precision measures whether generated samples lie on the real data manifold, recall measures how much of the manifold the generator covers, and mode collapse shows up almost entirely as a recall deficit.

For VAEs, the evidence lower bound itself is comparable across runs, which gives you a likelihood-adjacent number that GANs simply do not offer. The practical habit worth building is to evaluate every candidate checkpoint with the same fixed metric suite on the same fixed noise seeds β€” otherwise sampling variance between runs masquerades as progress, and architecture comparisons turn into noise comparisons.

Choosing between them

For high-fidelity sample generation where training instability is acceptable, GANs (particularly StyleGAN-family and relativistic variants) remain strong. For representation learning, anomaly detection, molecule generation, or any task that needs a well-behaved latent space, VAEs are the better fit. For most new image-generation projects today, diffusion models have taken the headline role by combining stable training with sharp samples β€” but their sampling cost reopens the door for GAN distillation and consistency-style generators when latency matters.

The deciding questions are concrete: do you need likelihoods or a prior you can sample from? Do you need one-step generation? Is your team prepared to babysit an adversarial training run? Answer those and the choice usually makes itself.

Common Mistakes

Letting the discriminator overpower the generator early

Fix: Track both losses separately β€” a discriminator loss near zero for long stretches means the generator gets no gradient.

Updating the generator on the discriminator's loss without detaching fakes in the D step

Fix: Detach fake samples in the discriminator update so gradients flow only where intended.

Declaring GAN success from loss curves

Fix: Measure sample diversity explicitly; mode collapse often happens while both losses look healthy.

Expecting crisp VAE reconstructions from a heavy KL penalty

Fix: Reduce the KL weight, use free-bits, or move to VQ-VAE if sharpness matters more than a smooth prior.

Sampling from a VAE prior without checking aggregate posterior match

Fix: If KL training is weak, prior samples will be out-of-distribution for the decoder β€” validate them, do not assume.

Key Takeaways

  • GANs learn realism adversarially with no likelihood; VAEs maximize a tractable lower bound on likelihood.
  • Mode collapse is a rational generator strategy β€” detect it with diversity metrics, not losses.
  • The reparameterization trick is what makes VAE training differentiable through the sampling step.
  • VAE blur comes from reconstructing under code noise; VQ-VAE's discrete codebook is the standard fix.
  • Choose by need: sharp one-step samples (GAN), smooth latent space and stable training (VAE), or trade compute for both (diffusion).
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

β€”
β˜†β˜†β˜†β˜†β˜†
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement