17 min read

GANs

A GAN learns through a contest between a generator and a discriminator. That simple setup leads to a less simple set of questions: how to keep training stable, how to judge the results, and how to control what gets generated. This article connects those questions to image-to-image translation and practical applications.

Generators and discriminators

Generators and discriminators — illustration
Generators and discriminators — illustration
Generators and discriminators — illustration
Generators and discriminators — illustration
Generators and discriminators — illustration
Generators and discriminators — illustration
Generators and discriminators — illustration

A classifier is a type of model that distinguishes between different classes. For instance, it can determine whether an image is of a cat or a dog.

Initially, the model makes poor predictions, but it learns to improve by adjusting its parameters (weights) to minimize the difference between its predictions Yhat and the true labels (Y).

The difference between Yhat Y is quantified using a cost function. The model updates its parameters to reduce this cost.

In GANs, the discriminator is a classifier that distinguishes between real and fake examples.

The probability output from the discriminator is used to inform and improve the generator's performance over time, helping it to produce more realistic examples.

Binary cost entropy cost function (BCE Loss)

Generators and discriminators — illustration

It's crucial to keep the generator and discriminator at similar skill levels during training.

If the discriminator is too good, it labels all fake examples as obviously fake (100% fake), providing no useful feedback for the generator.

If the generator is too good, it produces examples that the discriminator cannot distinguish from real, making it ineffective in guiding the generator's improvements.

The discriminator's feedback should ideally provide nuanced probabilities (e.g., 0.85 fake) to help the generator refine its outputs effectively.

Normalization and convolutional GANs

GANs take time to train and can be fragile, as generator and discrimnator might not always be perfectly aligned in their learning processes

Normalization can speedup GAN training

Normalization smooths the cost function

Covariate shift: when distribution of data changes between training and testing, potentially altering cost function

Internal Covariate shift: similar to covariate shift happens withing the hidden layers of NN, makes training unstable and slow

Batch normalization

Normalization and convolutional GANs — illustration
Normalization and convolutional GANs — illustration

After training the mean and std are frozen,

Running mean and running std are used from training

Same values are used for testing

Upsampling:

Normalization and convolutional GANs — illustration

Mode collapse and Wasserstein loss

Getting a generator to produce an image is only a starting point. Training also needs to produce varied results instead of settling on a narrow set of outputs.

GAN training Issue

GANs often fall into a pattern where the generator produces identical outputs, such as generating only golden retrievers when trained on various dog breeds.

This happens because the discriminator, as it improves, begins to classify images very strictly as either real (1) or fake (0). It does so based on binary cross-entropy loss, which encourages it to push its output towards these extreme values

During training, if the discriminator identifies a particular type of generated image (like a golden retriever) as somewhat real, the generator focuses on producing that image. When the discriminator subsequently learns that this image is fake, the generator lacks diversity in its outputs to pivot to another realistic image, leading to a halt in learning.

To combat this issue, the introduction of a new loss function is suggested. This loss function allows the discriminator to output any value between negative infinity and infinity.

Mode collapse and Wasserstein loss — illustration
Mode collapse and Wasserstein loss — illustration

In BCE loss function generator wants to maximize this cost value,

Discriminator wants to minimize the cost value

AKA minimax game

Often times discriminator outperforms generator while training,

Discriminator output : single output

Generator output: complex output

Mode collapse and Wasserstein loss — illustration

When discriminator improves too much, the function approximated

by BCE Loss will contain flat regions

Vanishing gradient problems for generator as generator doesn’t knows how to improve

Earth Mover's Distance (Wasserstein metric)

How much Effort needed to make the generated distribution to the real distribution.

Amount of earth moved multiplied by distance its moved

Mode collapse and Wasserstein loss — illustration

We rename the discriminator as critic

Now the critic outputs how real the image is

Mode collapse and Wasserstein loss — illustration
Mode collapse and Wasserstein loss — illustration

Critic needs to be 1-L continuous, the norm of gradient should be at most 1 for every point

Mode collapse and Wasserstein loss — illustration

If critic value is 1-L continuous, this ensures that W-Loss is validly approximating Earth movers distance

How to ensure that critic's loss the 1-Lipschitz continuous?

  1. Weight clipping
    but it limits the learning ability of the critic
  2. Gradient penalty
    add regularization term to loss function
    gradient penalty tends to work better

Since checking the critic’s gradient at each possible point of the feature space is virtually impossible, you can approximate this by using interpolated images(a point in data distribution).

you penalize the critic if its gradient norm deviates from 1 at these interpolated points.

Mode collapse and Wasserstein loss — illustration
Mode collapse and Wasserstein loss — illustration
Mode collapse and Wasserstein loss — illustration

Conditional generation and latent-space control

Conditional GANs

Conditional generation and latent-space control — illustration

In a Conditional GAN, labeled dataset is required

Input is one-hot vector which has zeros in all positions except for the

Desired class label

Second input is noise vector which allows generator to create diverse examples within the specified class.

Discriminator receives both image and class information

Its job is to determine whether input image is real or fake example of given class

The discriminator is trained to predict that an image is real only if it matches the class label. This forces the generator to produce images that not only look real but also belong to the correct class.

Conditional generation and latent-space control — illustration

Controllable generation

Conditional generation and latent-space control — illustration

We interpolate in Z-space

Modify the noise vector z to control desired features

Conditional generation and latent-space control — illustration
Conditional generation and latent-space control — illustration

We found that by adding vector d into v2 we can get blue hair

Conditional generation and latent-space control — illustration

Thus by adding the same vector d we can get blue hair color on any image

Challenges in controllable generation

  1. Some features are co-related,
    we can't add just the beard without making the face

more masculine asper the z -space

Conditional generation and latent-space control — illustration
  1. Z space entanglement
    when z space doesn’t has enough dimensions, very unusual features gets related to one another
Conditional generation and latent-space control — illustration
Conditional generation and latent-space control — illustration

Disentanglement

A crucial different between 

a disentangled z-space and 

an entangled z-space is that, here, 

with a disentangled z-space, 

when you control one of the features on the output, 

for example, glasses, the other features remain the same. 

The beard and hair will remain the same. 

Or if I change whether someone has a beard, 

the glasses and hair will stay the same. 

What this means is that with a disentangled z-space, 

you're much more likely to be able 

to add a beard to a person that looks 

To encourage the model towards disentanglement

very feminine without changing 

We should completely forget using one-hot vectors and use

her hair or her facial features.

Noise vectors with the class information embedded inside

Another method is to add regularization terms to loss function encourages model to associate specific noise vector indices with distinct features

And then use classifier gradients to ensure model associates each index from the noise vectors, two different features on the output

Evaluating generated images

Evaluation asks two different questions: how convincing are the samples, and how much of the data distribution do they cover?

Evaluating GANs

Evaluating GANs poses unique challenges due to lack of clear 'right or wrong' output. Unlike classifiers, GANs don’t have a set of exact outputs to match. This makes defining a "correct" output difficult.

There is a tradeoff between:

  1. Fidelity
    quality and realism of generated images
    How close generated images are to real ones in terms of visual and structural detail
  2. Diversity
    range and variety of images a GAN can produce

The discriminator also overfits to generator

Comparing images

  1. Pixel distance
    You can subtract pixel value
    Real - Fake = abs Diff
Evaluating generated images — illustration
  1. Feature distance
Evaluating generated images — illustration

Feature extraction

To evaluate GANs, we need to compare using feature distance

Features are extracted from pre-trained classifiers, which captures meaningful aspects of images

Evaluating generated images — illustration

The features extract are sometimes knows as image embeddings/features

Evaluating generated images — illustration
Evaluating generated images — illustration

Fréchet Inception distance(FID)

Two curves are considered: one for the dog's path (blue) and one for the walker's path (orange). The dog and walker can move at their own speeds. Neither can move backwards along their respective paths.

FID is the minimum length of a leash needed to connect the dog and walker.

This leash must allow both to complete their paths from start to finish.

The Fréchet distance is the length of this leash at its most stretched point, assuming the optimal movement strategy is used.

Evaluating generated images — illustration

Formulae:

Evaluating generated images — illustration

For multivariate Normal distributions, use a Covariance matrix

Evaluating generated images — illustration
Evaluating generated images — illustration
Evaluating generated images — illustration
Evaluating generated images — illustration

FID is calculated over a large sample size to reduce noise

FID disadvantages

-ve) FID is biased towards using more data

-ve) uses pretrained inception model, which may not capture all features

-ve) slow to run

-ve) uses only mean and covariance which are thora sa stat of what we couldve used

Inception score

This method was used before FID and was widely used but now replaced

By FID scores. Inception V3 classifier pretrained on ImageNet was used

For feature extraction.

We keep the classifier and don’t use any embeddings, you input

generated image and see what inception v3 classifier says its classified as

If a class label has a high value and very low values on other classes, then

it is high fidelity

Evaluating generated images — illustration
Evaluating generated images — illustration

Inception score (IS)

Evaluating generated images — illustration

-ve) Can be exploited or gamed (generator generates one realistic image of each class)

-ve) Only looks at fake images and no comparison to real images

-ve) Can miss useful features

Sampling and truncation

truncates the normal distribution that you sample your noise vector from based on a hyperparameter that determines how much of the tails to cut off or keep.

If you want higher fidelity, you want to sample around 0 and truncate a larger part of the tails. If you want greater diversity, then you want to sample more from the tails of the distribution and have a lower truncation value.

Evaluating generated images — illustration

Truncation done after training

HYPE and human evaluation

Sampling is the process of selecting a subset of elements from a larger set, or distribution, to make inferences or decisions about the whole set.

Sampling from the center of normal distribution yields higher fidelity but lower diversity

Sampling from tails can increase diversity but at the cost of fidelity

Truncation trick involves modifying normal distribution by cutting off the tail ends of the distribution after training

Using truncation trick results in lower FID though

High fidelity: Truncate more of the tails

High diversity: Retain more of the tails

Human eYe perceptual evaluation of generative models

Human eYe Perceptual Evaluation is a system developed to assess the realism of images using human evaluators.

Evaluating generated images — illustration

Evaluators determine if an image is real or fake within varying time frames. (millisecs)

: Evaluators assess images without time constraints.

Despite the progress in automated metrics, human perception remains the gold standard for evaluating the realism and quality of GAN-generated images.

Precision and recall in generative models

Evaluating generated images — illustration

Precision is to fidelity as recall is to diversity

Models tend to be better at recall

Use truncation trick to improve precision

Bias, fairness, and alternative models

GANs AdvantagesGANs Disadvantages
Amazing empirical resultsLack of intrinsic evaluation metrics (difficult to measure performance based purely on model weights or outputs.)
Fast inferenceUnstable training (GANs can be unstable to train, requiring careful tuning and monitoring. Issues like mode collapse can occur)
No density estimation (While GANs can approximate feature probabilities over many samples, they do not provide explicit density estimates inherently.)
Inverting not straight forward (GANs are not inherently designed to map an image back to its noise vector)

Alternatives to GANS

Bias, fairness, and alternative models — illustration
Bias, fairness, and alternative models — illustration
Bias, fairness, and alternative models — illustration
Bias, fairness, and alternative models — illustration

Machine Bias

COMPAS algorithm is one of two leading commercial tools used by the legal system

Used in pretrial hearings and criminal sentencing to assess risk of re-offense

Unfortunately the COMPAS algorithm predicted recurrence of violent crime correctly only 20% of the time, gives biased risk assessment

A high COMPAS score results in harsher punishments

Bias, fairness, and alternative models — illustration

Defining Fairness

There is no single, universally accepted definition of fairness

Some definitions:

  1. Equalized odds
    The outcome should be independent of sensitive attributes like ethnicity or gender.
  2. Representational fairness
    In a generative model (like a GAN), the frequency of generating images of people from different ethnic groups should match their proportions in the general population.
  3. Equality of odds
    The rates of false positives and false negatives should be equal across different demographic groups.

What is considered fair can vary depending on the context, the application, and societal values.

How bias enters your model

  1. No variation in who or what is represented
  2. Bias in collection method
  3. Diversity of labellers, they may annotate date based on what they think
  4. Images can be biased to reflect 'correctness' in the dominant culture
Bias, fairness, and alternative models — illustration
Bias, fairness, and alternative models — illustration

Images from higher income households, were on average had better resolution than low income households

  1. Model architecture bias
    sometimes code changes can introduce bias
    sometimes a loss function may skew the distribution a little

StyleGAN and architectural improvements

Advancements in GANs

  1. Mode collapse prevention
  2. Wasserstein loss
  3. Spectral normalization
  4. Moving average of weights
  5. Progressive growing: gradually increasing resolution of images during training
  6. Deeper and wider Networks
  7. Enhanced diversity

StyleGAN

Greater fidelity on high-resolution images

Increased diversity of outputs

More control over image features

'Style' refers to any variation in the image from larger, coarser styles to finer more detailed styles

Components:

StyleGAN and architectural improvements — illustration

Adaptive Instance Normalization (AdaIN)

Operation where Injection of W by adding W into various layers

during training. It adjusts the statistics of the generated image at various layers,

influenced by the intermediate noise vector (W).

This allows for the separation of different image styles and

their controlled application during generation.

StyleGAN and architectural improvements — illustration

Progressive Growing

technique used in StyleGAN to generate high-resolution images by gradually increasing the image resolution during training process

Begins with low-res images and progressively increases the resolution allowing the generator to tackle simpler tasks initially and handle more complex tasks

By slowly increasing the resolution, model avoids challenges of generating high-res images from the start

Instead of abrupt increase in resolution, smooth transition is made

Involves upsampling current res to next res

StyleGAN and architectural improvements — illustration
StyleGAN and architectural improvements — illustration
StyleGAN and architectural improvements — illustration
StyleGAN and architectural improvements — illustration

Noise Mapping Network

This network is used in initial layers of StyleGAN, that transforms initial noise vector Z into intermediate noise vector W

This network helps achieve more disentangled representation, allowing finer control over image features

Composed of 8-fully connected layers with activation functions between them

Z-space is often entangled but W-space provides more disentangled representation

W is injected into generator at multiple layers, influencing image generation at various stages

Effect of W varies depending on where its introduced, earlier layers impact coarse features, later layers influence finer details

Adaptive instance normalization (AdaIN)

Adain block

StyleGAN and architectural improvements — illustration
StyleGAN and architectural improvements — illustration

Step1: We only look at one channel in convolution outputs of one example only, and normalize it using Instance normalization

StyleGAN and architectural improvements — illustration
StyleGAN and architectural improvements — illustration
StyleGAN and architectural improvements — illustration

Step3:

StyleGAN and architectural improvements — illustration

Style Mixing and stochastic noise

StyleGAN and architectural improvements — illustration

If you generate images from row 1 and row 3 you can generate images from row 2 too then

StyleGAN and architectural improvements — illustration
StyleGAN and architectural improvements — illustration

W1 is inserted into initial layers

W2 is inserted into later layers

StyleGAN and architectural improvements — illustration

Stochastic noise is added to introduce variations in generated images

Random noise sampled from normal distribution is added to feature maps before they pass AdaIN layers, impact of noise is learned by scaling features λ1​and λ2​

Stochastic noise introduces small random variations in image, enhancing realism

StyleGAN and architectural improvements — illustration

Applications and tradeoffs

Applications and tradeoffs — illustration

GANS could be used for

+ve) Anonymity, can alter face image for those who don’t want to reveal face

+ve) Can provide safe environment for groups such as stigmatized groups, assault, victims, witnesses, activists

-ve) Deepfakes identifity thefts

Paired image translation with Pix2Pix

Image-image translation involves transforming input image into different style while preserving its content

Types of image-to-image translation tasks

  1. Paired image-to-image translation
    every input image has target output image in training dataset
  2. Unpaired image-to-image translation
    there is no one-to-one mapping between input and output images in training data, algorithms like CycleGAN learns to translate images between different domains without paired examples
  3. Multi-model Image-to-image translation
    input includes multiple types of data to generate images

Image-to-image translation frameworks extend to other domains, such as text-to-image generation and video generation

While GANs excel in realistic image generation, challenges include ensuring generated images do not compromise privacy or mimic real data too closely.

Pix2Pix

Paired image translation with Pix2Pix — illustration

Pix2Pix is a type of conditional GAN designed for paired image translation tasks.

It was named to reflect its focus on image-to-image translation where each input image has a corresponding target output image.

In a conditional GAN, a class vector is input

Pix2Pix extends this concept by taking an entire image

The generator in Pix2Pix receives a real input image (e.g., segmentation map) and transforms it into a realistic output image (e.g., photo of a building)

Pix2Pix found that adding noise vectors didn't significantly impact output quality, so they instead introduced stochasticity through dropout during training to add variability.

discriminator in Pix2Pix assesses whether the generated output (e.g., a building photo from a segmentation map) matches the real target output.

It takes in both the real input (condition) and either the real or generated output to determine realism, using a patch-based approach to evaluate different parts of the image.

Pix2Pix has evolved with advancements like U-Net architecture for the generator, which includes an encoder-decoder structure with skip connections, ideal for segmentation tasks.

Paired image translation with Pix2Pix — illustration

The discriminator has been upgraded to a PatchGAN, providing detailed feedback on realism across different patches of the image rather than just the entire image.

PatchGAN

Paired image translation with Pix2Pix — illustration
Paired image translation with Pix2Pix — illustration

PatchGAN is a discriminator architecture used in Pix2Pix for image-to-image translation tasks.

Unlike traditional GAN discriminators that output a single value (real or fake) for the entire image, PatchGAN outputs a matrix of values.

Each value in the matrix ranges between 0 and 1, where 0 signifies a fake patch and 1 signifies a real patch.

PatchGAN is trained using Binary Cross Entropy (BCE) loss.

PatchGAN enhances the discriminative capability by evaluating patches individually rather than the entire image.

Pix2Pix upgraded Generator (U-Net )

Input: Takes an image 𝑥 of size 256x256 with RGB channels.

Blocks: Consists of 8 encoder blocks, each reducing spatial dimensions via convolutional layers with a stride of 2 and Mirrors the encoder with 8 decoder blocks, each using transposed convolution (to upsample), BatchNorm, and ReLU activation.

Compresses the input image into a smaller feature representation (1x1 spatial size by the end) with 512 channels.

Output: Generates y, which is the output image of size 256x256 with 3 RGB channels.

Dropout: Applied to the first three decoder blocks during training to introduce stochasticity and prevent overfitting by randomly disabling neurons.

Paired image translation with Pix2Pix — illustration
Paired image translation with Pix2Pix — illustration

Pixel distance Loss term

Paired image translation with Pix2Pix — illustration
Paired image translation with Pix2Pix — illustration
Paired image translation with Pix2Pix — illustration

Unpaired image translation with CycleGAN

Unpaired image-to-image translation

Unpaired image-to-image translation is difficult than paired image translation.

While mapping between two piles,

content = common elements

Style = unique elements

unpaired image to image translation uses piles of different styled images instead of paired images. The model learns that mapping between those two piles by keeping the contents that are present in both, while changing the style which is different or unique to each of those piles.

Unpaired image translation with CycleGAN — illustration

Cycle Consistency:

ensuring that translating an image to another domain and back retains the original image's content.

Cycle Consistency Loss:

Ensures that an image translated from one domain to another and then back to the original domain remains consistent.

This loss preserves the content while only altering the style.

Unpaired image translation with CycleGAN — illustration

Discriminator: two PatchGANs

Generator: U-Net + DCGANs generator

One GAN translates from domain X (e.g., zebras) to domain Y (e.g., horses).

The other GAN translates from domain Y back to domain X.

Skip Connections are used within the bottleneck section to help the model learn identity mappings.

Unpaired image translation with CycleGAN — illustration
Unpaired image translation with CycleGAN — illustration
Unpaired image translation with CycleGAN — illustration

Cycle consistency

Is a loss term to the loss function that is added to CycleGAN and puts a cycle in CycleGAN

This loss term ensures that if you convert an image from one domain to another and then back again, you should recover the original image.

Unpaired image translation with CycleGAN — illustration

Ablation study is a research technique used to evaluate the impact of individual components of a model or system by systematically removing or altering them and observing the resulting changes in performance.

In CycleGAN, ablation studies help determine the importance of the cycle consistency loss and the adversarial loss.

Key findings:

Cycle consistency aloneWithout adversarial loss, the images generated using only cycle consistency loss tend to be unrealistic and can suffer from mode collapse (where the model produces limited, repetitive outputs).
Adversarial loss AloneWithout cycle consistency loss, the model generates more realistic images but still suffers from mode collapse, leading to less diverse outputs.
Partial Cycle ConsistencyUsing only one direction of cycle consistency (e.g., zebra to horse and back to zebra) does not suffice to prevent mode collapse or ensure diverse and high-quality translations.
Combined Loss (Adversarial + Cycle Consistency)The combination of both adversarial loss and cycle consistency loss yields the best results, producing realistic and diverse images while preserving content across translations.

new Least squares loss

Least Squares is a statistical method that minimizes the sum of squared residuals (differences) between data points and a fitted line.

Unpaired image translation with CycleGAN — illustration

Least Squares Loss is used in GANs to improve training stability and reduce issues like vanishing gradients and mode collapse.

It replaces traditional loss functions like Binary Cross-Entropy (BCE) loss used in earlier GANs.

BCE Loss Issues: BCE can lead to vanishing gradients, making training difficult.

Least Squares Advantages: By using the squared distance, Least Squares Loss avoids flat gradients except when predictions are perfect, thus maintaining a stronger gradient and more stable training.

Least Squares Loss helps CycleGAN avoid issues with flat gradients and improves training stability, leading to better quality image translations.

Identity Loss CycleGAN

Identity Loss is an optional additional loss term in CycleGAN aimed primarily at preserving color and overall appearance in the outputs.

It ensures that when an image already in the target style is processed by the generator, it remains unchanged, maintaining its original characteristics.

For instance, if a CycleGAN generator transforms a horse image (already in the target "horse" style) using the zebra-to-horse generator, the output should ideally be identical to the input because no style change is needed.

The identity loss term is added to the generator's loss function alongside adversarial loss and cycle consistency loss.

Without Identity Loss, generators might introduce unwanted changes, such as color distortions or shifts in tone, especially in tasks like seasonal style transfer.

Unpaired image translation with CycleGAN — illustration

XD

Unpaired image translation with CycleGAN — illustration

Papers and implementations

The following references accompany the techniques discussed above.