What Are Generative Adversarial Networks (GANs)?
Generative adversarial networks (GANs) train two neural networks against each other: a generator that turns random inputs into synthetic samples, and a discriminator that learns to distinguish synthetic samples from real training data. The generator learns through the discriminator's gradients and can generate new samples on its own after training.
A GAN in deep learning is a training framework rather than a fixed architecture. A generator can be a small multilayer perceptron that draws binary patterns, or a convolutional network that synthesises full images. GANs have also been used for video generation and image-to-image translation. The common element is the adversarial objective, regardless of the network blocks or data format.
The generator turns a simple distribution, such as a standard Gaussian, into a more complicated distribution over images. This is an implicit generative model: you can draw a sample by running a forward pass, but a standard GAN does not directly give you a tractable probability density for a particular image. Its discriminator is a classifier, but its predictions concern where training examples came from. The distinction between these roles is easier to see after comparing generative and discriminative models.
How Do the GAN Generator and Discriminator Work?
Write the generator as G(z), where z is a latent vector drawn from a fixed prior. If z has shape [batch_size, 16] and each output is a flattened grayscale image of size 8 by 8, then G(z) has shape [batch_size, 64]. A new draw of z can produce a different image. Reusing the same z with a fixed, deterministic generator produces the same image.

The discriminator maps a real or generated image to a scalar logit s(x). Its sigmoid D(x) = sigmoid(s(x)) is the model's estimate that its input came from the real source in the training mixture. In code, pass the raw logit into a numerically stable binary cross-entropy function. Applying a sigmoid before BCEWithLogitsLoss would apply the sigmoid twice.
- Discriminator update: Take a real batch and generate a fake batch. Give real inputs target 1 and fake inputs target 0. Block gradients into the generator and update the discriminator's parameters.
- Generator update: Draw noise, generate another fake batch and evaluate it with the current discriminator. Give the discriminator's fake-image logits target 1 for this loss. Keep discriminator parameters fixed while differentiating through its operations into the generator.
- Sampling: After training, draw fresh noise and run the generator alone. A separate evaluator can inspect the samples, but the training discriminator is unnecessary for generation.
The target 1 in the generator step is a direction for optimisation. The discriminator still learns from fake images labelled 0 during its own step. Freezing discriminator parameters differs from wrapping its generator-step forward pass in torch.no_grad(): the latter would also remove the gradient with respect to the generated image. This separation between parameter updates and forward execution is an instance of the broader distinction between training and inference.
What Loss Does a GAN Use for Adversarial Training?
The original GAN game asks the discriminator to maximise the value below and the generator to minimise it. The first expectation uses real images x and the second uses latent draws z. In practice, each expectation is estimated with a minibatch mean.
V(D, G) = E_x[log D(x)] + E_z[log(1 - D(G(z)))]
With a fixed generator, maximising this expression is equivalent to minimising the sum of the real and fake binary cross-entropy losses. For the generator, only the fake term depends on its parameters. The original minimax update therefore minimises E_z[log(1 - D(G(z)))]. If the discriminator confidently rejects poor samples early on, this objective has a small derivative with respect to the fake logit. The usual non-saturating generator loss replaces that term with -E_z[log D(G(z))], which supplies a larger logit gradient under those conditions.
There is a useful theoretical result for the original minimax game. Let p_data(x) and p_g(x) be the real and generated densities or probability masses, expressed with respect to a common measure. For a fixed generator and an unrestricted discriminator, maximising a log d + b log(1 - d) at each input gives d = a / (a + b), with endpoint solutions when one mass is zero. Thus D*(x) = p_data(x) / (p_data(x) + p_g(x)) wherever the denominator is positive.
Substituting this optimal discriminator yields -log(4) + 2 JS(p_data || p_g), where JS is Jensen-Shannon divergence. It is zero when the distributions match, so the game's value is then -log(4) and the optimal discriminator outputs one half on their support. This result assumes an optimal discriminator and sufficient model capacity. Alternating a few gradient steps between finite networks does not mean every update reduces this divergence. Likewise, a measured discriminator accuracy around one half may reflect a weak classifier rather than a good generator.
Worked Example: How Do GAN Losses Turn into Gradients?
Consider one real image with discriminator probability 0.75 and one fake image with probability 0.25. These come from logits log(3) and -log(3). Use natural logarithms and sum the two discriminator terms, as in the PyTorch example below.
| Update or quantity | Calculation | Result |
|---|---|---|
| Discriminator loss on real | -log(0.75) | 0.2877 |
| Discriminator loss on fake | -log(1 - 0.25) | 0.2877 |
| Total discriminator loss | 0.2877 + 0.2877 | 0.5754 |
| Non-saturating generator loss | -log(0.25) | 1.3863 |
| Generator loss derivative with respect to fake logit | 0.25 - 1 | -0.75 |
Binary cross-entropy with logits has derivative sigmoid(s) - y with respect to the logit s, where y is the target. In the discriminator step, the derivatives for this pair are -0.25 on the real logit and +0.25 on the fake logit. If those logits were independent parameters, gradient descent would raise the real logit and lower the fake one. In an actual discriminator, both logits depend on shared weights, so the optimiser combines the parameter gradients from both examples.
In the generator step, the fake logit gets derivative -0.75. The chain rule multiplies that scalar by the discriminator's input gradient and then propagates through the generator. Holding the discriminator fixed, this update locally pushes the generator toward images with higher fake-image logits. For comparison, the original minimax generator loss has logit derivative -0.25 here. At a fake probability of 0.001, the two derivatives would be -0.999 and -0.001. A strong logit derivative still cannot help when the discriminator's gradient with respect to the image is nearly zero.
How Do You Train a Simple GAN in PyTorch?
This CPU example learns a synthetic distribution of 16 equally likely 8 by 8 images: eight contain a single bright row and eight contain a single bright column. Run it with PyTorch installed. The generator outputs continuous pixel intensities in [0, 1]; keeping the training path continuous lets gradients flow into the generator. Thresholding is reserved for the diagnostic after training.
import torch
from torch import nn
torch.manual_seed(7)
z_dim, batch_size = 16, 64
# Make one template for each row and each column.
templates = torch.zeros(16, 8, 8)
for i in range(8):
templates[i, i, :] = 1.0
templates[8 + i, :, i] = 1.0
templates = templates.flatten(1)
G = nn.Sequential(
nn.Linear(z_dim, 128), nn.LeakyReLU(0.2),
nn.Linear(128, 128), nn.LeakyReLU(0.2),
nn.Linear(128, 64), nn.Sigmoid(),
)
D = nn.Sequential(
nn.Linear(64, 128), nn.LeakyReLU(0.2),
nn.Linear(128, 64), nn.LeakyReLU(0.2),
nn.Linear(64, 1),
)
bce = nn.BCEWithLogitsLoss()
opt_g = torch.optim.Adam(G.parameters(), lr=0.001, betas=(0.5, 0.999))
opt_d = torch.optim.Adam(D.parameters(), lr=0.001, betas=(0.5, 0.999))
for step in range(1, 3001):
x_real = templates[torch.randint(0, 16, (batch_size,))]
with torch.no_grad():
x_fake = G(torch.randn(batch_size, z_dim))
opt_d.zero_grad(set_to_none=True)
real_logits, fake_logits = D(x_real), D(x_fake)
loss_d = (
bce(real_logits, torch.ones_like(real_logits))
+ bce(fake_logits, torch.zeros_like(fake_logits))
)
loss_d.backward()
opt_d.step()
D.requires_grad_(False)
opt_g.zero_grad(set_to_none=True)
x_fake = G(torch.randn(batch_size, z_dim))
fake_logits = D(x_fake)
loss_g = bce(fake_logits, torch.ones_like(fake_logits))
loss_g.backward()
opt_g.step()
D.requires_grad_(True)
if step % 500 == 0:
print(step, round(loss_d.item(), 3), round(loss_g.item(), 3))
G.eval()
with torch.no_grad():
pixels = G(torch.randn(2048, z_dim))
binary = pixels.ge(0.5)
matches = (binary[:, None, :] == templates.bool()[None, :, :]).all(dim=-1)
valid = matches.any(dim=1)
counts = matches.sum(dim=0)
print("Valid fraction:", valid.float().mean().item())
print("Modes seen out of 16:", counts.count_nonzero().item())
print("Counts per mode:", counts.tolist())
The discriminator returns one raw logit per input. The generator has a final sigmoid because its output represents pixels. These two output conventions serve different purposes. During the discriminator step, generating samples inside torch.no_grad() avoids storing a generator computation graph that the step will never use. During the generator step, the script freezes discriminator parameters, but tracks the path from the fake pixels to the logits.
Read the last three lines together. Valid fraction measures how often thresholded outputs match a legal template. Modes seen measures coverage across those valid outputs. Per-mode counts check whether valid draws are roughly balanced. For example, a generator that always draws the first row scores a valid fraction of 1 and covers only one mode. Conversely, seeing all 16 modes at least once tells you little if most outputs are invalid. Thresholded matching also hides uncertain intensities, so inspect the raw images if you want to check for pixels hovering around 0.5. Try multiple seeds before attributing a change to an optimiser setting.
Why Do GANs Suffer from Mode Collapse and Unstable Training?
Mode collapse occurs when the generator concentrates on a subset of the variations present in the real distribution. Many latent vectors may map to essentially the same output. In an image dataset, a grid of individually plausible samples can hide missing viewpoints, object types or backgrounds. In the bar example, missing modes can be read directly from the histogram.
Training is also a moving-target problem. Updating the discriminator changes the loss surface seen by the generator, and updating the generator changes the negative examples that the discriminator sees. A discriminator can overfit a small real dataset or reject generated samples using shortcuts. A weak discriminator can provide little information about which features are wrong. The loss values alone do not show whether either failure is happening.
- Check data scaling and splits: Use compatible ranges for real and generated inputs. Compare generated samples against held-out examples and inspect nearest training neighbours when memorisation is a concern.
- Track sample quality and diversity separately: Use fixed latent vectors to see whether particular outputs improve across checkpoints, and fresh latent draws for distribution-level comparisons. For real image datasets, the Fréchet Inception Distance (FID) compares feature means and covariances. Keep the feature extractor, preprocessing and sample count fixed across runs, and pair FID with coverage checks.
- Try a targeted stabilisation method: Spectral normalisation constrains layer spectral norms in the discriminator. Wasserstein GAN with gradient penalty uses a real-valued critic and penalises deviations of the input-gradient norm from one on points interpolated between real and generated samples. Its critic objective differs from binary cross-entropy.
If you need a specific output class, a conditional GAN feeds a condition c to both networks, giving G(z, c) and D(x, c). The discriminator can then learn to assess image and condition jointly from real and generated pairs. For the toy dataset, a condition can request a row or a column. Test coverage within each requested orientation: conditioning can fix which orientation appears while leaving several positions missing.
How Do GANs Compare with VAEs, Diffusion and Autoregressive Models?
The main types of generative AI models are easier to compare by asking two questions: what target determines the gradients during training, and what computation produces a sample? A category such as “image model” describes an output modality. A category such as “autoregressive model” describes a factorisation of the probability distribution. Both labels can apply to the same model.

| Model family | Typical training signal | Typical sampling path |
|---|---|---|
| GAN | Discriminator or critic scores on real and generated data | Draw latent noise and run the generator |
| Variational autoencoder (VAE) | Optimise an evidence lower bound using a reconstruction term and latent regularisation | Draw a latent vector from the prior and decode it |
| Diffusion model | Learn a denoising-related target at multiple noise levels | Start from noise and use repeated denoising or solver steps |
| Autoregressive model | Predict the next element conditioned on preceding elements | Sample sequentially so earlier outputs condition later ones |
For example, GPT-style large language models are autoregressive because they generate text one token at a time. The same factorisation can describe audio tokens or image tokens. Diffusion methods can generate images, audio or video. A VAE learns an encoder for its latent space, whereas a standard GAN has no built-in mapping from an observed image back to a latent vector. Systems can combine methods: a latent diffusion image generator can denoise in a compressed space and then use an autoencoder's decoder to produce pixels.
A GAN is a reasonable option when a single generator pass suits the latency budget and you can test coverage for a narrow image domain. For example, if a component inspection dataset contains several rare defect shapes, test whether each shape appears before using the synthetic images to augment training. If the model repeatedly omits a rare defect, good-looking samples and low sampling latency do not resolve that data gap.
Key Takeaways
- A GAN trains a generator to produce samples and a discriminator to separate real from generated examples.
- The discriminator step blocks generator gradients. The generator step differentiates through a frozen discriminator.
- The non-saturating generator loss gives a stronger logit gradient than the original minimax loss when fake inputs are confidently rejected.
- A standard GAN samples from an implicit distribution and does not directly expose a tractable image likelihood.
- Track sample validity, diversity and mode balance separately. Discriminator accuracy alone does not establish generator quality.
- Compare GANs, VAEs, diffusion and autoregressive models by their objectives and sampling procedures rather than their output formats.
Frequently Asked Questions
Is a GAN supervised or unsupervised?
An unconditional GAN can learn from a dataset without human-provided class labels. Its training loop creates binary targets from the origin of each input: real examples get one target and generated examples get the other. A conditional GAN may additionally use supervised labels, text descriptions or paired inputs, depending on how the condition is defined.
Why does the generator use a real target for fake images?
During the generator update, target one makes binary cross-entropy decrease as the discriminator assigns a higher real probability to the generated image. The generator changes its weights to move in that direction. The discriminator weights stay fixed in this step and are trained separately with fake examples assigned target zero.
Can a GAN reconstruct a specific input image?
A standard GAN maps noise to images and has no encoder to recover the latent code for a specific input. You can attempt inversion by optimising a latent vector to minimise a reconstruction loss while keeping the generator fixed. This may yield an approximation, since the target image may lie outside the range of the learned generator.
Does discriminator accuracy around chance mean training is complete?
No. With equal proportions of real and fake inputs, an optimal discriminator is at chance when their distributions match. A poorly trained discriminator can also be at chance when poor outputs are easy for another classifier to detect. Examine generated samples and evaluate diversity and distributional similarity independently of the training discriminator.
Are GANs faster than diffusion models at inference?
A typical GAN generates a sample in one generator pass, whereas a conventional diffusion sampler calls a denoising network multiple times. This often favours GANs for low-latency image generation. Actual latency depends on model size, resolution, hardware and the sampler. Distilled diffusion models may use far fewer steps, so compare the specific systems you plan to deploy.