Review: Rejection sampling¶
Acceptance-rejection sampling algorithm. For $M \geq \frac{p(x)}{q(x)}$:
- sample $x \sim q(x)$ from the proposal distribution $q(x)$
- sample $u \sim \text{Uniform}(0,1)$ independently of $X$
- while $u > \frac{p(x)}{M q(x)}$, reject $x$ and GOTO 1:
- Accept (output) $x$ as a sample from $p(x)$.
If the output of this algorithm is $X'$, then we can prove (last class) that $X' \sim p(x)$.
Sample Generation via Classifiers¶
Rejection sampling is key idea behind modern generative models: make generative tasks look like classification tasks.
- Train a binary classifier $\hat{y}(x; {\bf W}_y) = \sigma(h(x;{\bf W}_y))$ with the following labeled dataset: $\mathcal{D}^\text{(tr)} = \mathcal{D}_\text{true} \cup \mathcal{D}_\text{noise}$ with $\mathcal{D}_\text{true} = \{(x_i,y_i=1)\}_{i=1}^N$ and $\mathcal{D}_\text{noise} = \{(x_j,y_j=0)\}_{j=1}^{KN} $, $N \gg 1$, where $x_i \sim p(x)$ are samples from the true distribution and $x_j \sim q(x)$ are samples from a noise distribution.
- Assume the support of $p(x)$ is a subset of the support of $q(x)$.
- Hence, $\mathcal{D}^\text{(tr)}$ is sampled from the mixture $\frac{1}{K+1} p(x) + \frac{K}{K+1} q(x)$.
- Note that $p(y= 1 | x) = \frac{p(x)}{p(x) + K \cdot q(x)}$
- Often, it is important that $\forall x$, $K \gg \frac{p(x)}{q(x)}$, such that $p(y= 1 | x) = \frac{p(x)}{p(x) + K \cdot q(x)}\approx \frac{p(x)}{K \cdot q(x)}$, $\forall x$.
- Also assume we can learn $ {\bf W}^\star_y$ such that $p(y= 1 | x) = \hat{y}(x; {\bf W}^\star_y)$ (this is a key assumption).
Use the learned classifier (which distinguishes noise from the data) to generate new data via rejection sampling:
- sample $x \sim q(x)$ from the noise generator (proposal distribution)
- sample $u \sim \text{Uniform}(0,1)$.
- while $u > \hat{y}(x; {\bf W}^\star_y)$, reject $x$ and GOTO 1:
- Accept (output) $x$ as a sample from $p(x)$
Review: Distribution of generated data¶
Note that if $\hat{y}(x; {\bf W}^\star_y)$ is a perfect classifier, $$\hat{y}(x; {\bf W}^\star_y) = \frac{p(x)}{p(x) + K q(x)}$$
Q1: Let $X'$ be the output of the above algorithm. What is the distribution of $X'$?
A1: $$ p(X' = x) = p(X = x | Accept) = \frac{p(Accept| X = x )p(X = x)}{p(Accept)} = \frac{\frac{p(x)}{p(x) + K q(x)} q(x)}{p(Accept)} \approx \frac{\frac{p(x)}{K}}{p(Accept)} \approx p(x), $$ where $$ p(Accept) = \int p(Accept| X = x )p(X = x) dx = \int \frac{p(x)}{p(x) + K q(x)} q(x) dx \approx \frac{1}{K}. $$
Generative Adversarial Networks: A better proposal distribution $q(x)$¶
In the above data generation procedure, the number $K$ of noise examples must be very large if $\frac{p(x)}{q(x)}$ is large.
- Clearly, if $q(x) \approx p(x)$, then $\frac{p(x)}{q(x)} \approx 1$ and almost any $K \geq 0$ works. This is clearly ideal but it means we almost can sample directly from $p(x)$.
- If $q(x)$ is a standard normal, it is unlikely it will generate a beautiful landscape.
- Eventually yes, but it will take a long long time.
from IPython.display import HTML
HTML("""
<center><h2>Nvidia Research</h2> <h3> Example of use of generative adversarial networks: <a href="https://www.youtube.com/watch?v=mlZYRwJ2oJg">link</a></h3></center>
<video alt="Nvidia" controls width=400px>
<source src="Canvas.mp4" type="video/mp4">
</video>
""")
Nvidia Research
Example of use of generative adversarial networks: link
- What if we make $q(x ; {\bf W}_q)$ parametric using a neural network? Can we now learn to generate $X' \sim q(x ; {\bf W}_q)$ that are more likely accepted?
Q1: But, once we update $q(x ; {\bf W}'_q)$, can we still use $\hat{y}(x; {\bf W}^\star_y)$?
- A1: No, since we need $\hat{y}(x; {\bf W}^\star_y) = \frac{p(x)}{p(x) + K q(x ; {\bf W}'_q)}$
This creates a chicken-and-egg problem:¶
- Once we update $q(x ; {\bf W}'_q)$ to sample $X' \sim q(x ; {\bf W}'_q)$ to achieve $\hat{y}(X'; {\bf W}^\star_y) \approx 1$, we need to update $\hat{y}(X'; {{\bf W}'}^\star_y)$.
- The above can be understood as a game:
- We are trying to learn $q(x ; {\bf W}'_q)$ as to generate a sample $X' \sim q(x ; {\bf W}'_q)$ that can fool the classifier $\hat{y}(X'; {\bf W}^\star_y)$ into thinking $X'$ is a sample from $p(x)$.
- But the classifier $\hat{y}$ then must adapt to the new distribution of $q(x ; {\bf W}'_q)$ --- try to avoid being fooled
Generative Adversarial Networks (GANs) (Goodfellow et al, 2014)¶
Generative Adversarial Networks precisely is our Adaptive Proposal Distribution algorithm described above. A more compact representation of the objective function is the following negative log-likelihood (binary cross-entropy) $$ {\bf W}_\text{q}^\star , {\bf W}_\text{y}^\star = \arg\min_{{\bf W}_\text{q}}\max_{{\bf W}_\text{y}} E_{x \sim \text{data}}\Big[\log \hat{y}(x;{\bf W}_\text{y})\Big] + E_{x \sim q(x;{\bf W}_\text{q})}\Big[\log (1 - \hat{y}(x;{\bf W}_\text{y}))\Big] $$
Consider the dataset:
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
import numpy as np
import pylab
X, _ = make_moons(n_samples=10000, random_state=42, noise=0.1)
pylab.scatter(X[:,0], X[:,1])
pylab.show()
# Import the torch functions
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
Proposal distribution through variable transformation¶
We will use variable transformation (the same trick we used in the Variational AutoEncoder) for our proposal distribution. Let ${\bf z} \sim \text{Normal}({\bf 0},I)$, where $I$ is an $n\times n$ identity matrix. Vector ${\bf z}$ is a vector with $n$ independent standard Normal samples.
# Define the z (the random input to the GAN)
def z(n):
return torch.Tensor(np.random.normal(0, 1, (n,2))) # Gaussian. You can also use torch.randn
Now we create a neural network with fully connected layers¶
The general outline of a GAN is depicted here:
Create Generator $q(x;{\bf W}_q)$¶
# Generator
g_input_size = 2 # Dimension of random noise given to generator
g_hidden_size = 50 # Number of hidden units of the generator complexity
g_output_size = 2 # size of generated output vector
class Generator(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(Generator, self).__init__()
self.layer1 = nn.Linear(input_size, hidden_size)
self.layer2 = nn.Linear(hidden_size, hidden_size)
self.layer3 = nn.Linear(hidden_size, output_size)
def forward(self, x):
x = F.elu(self.layer1(x)) # ELU activations are like ReLU activations but without zero gradients for ELU(x), x < 0.
x = F.elu(self.layer2(x))
return self.layer3(x)
Generator learning parameters¶
Creates generator and define learning optimization. We will use the adam optimizer because sampled gradients in GANs have very high variance.
# Generator creation
G = Generator(input_size=g_input_size, hidden_size=g_hidden_size, output_size=g_output_size).to(device)
g_learning_rate = 1e-4
optim_betas = (0.9, 0.999)
g_optimizer = optim.Adam(G.parameters(), lr=g_learning_rate, betas=optim_betas)
Define $\hat{y}(x;{\bf W}_y)$ classifier (discriminator)¶
# Discriminator y (classifier) creation
y_input_size = 2 # Input to the discriminator (will determine 'real' or 'fake')
y_hidden_size = 50 # Number of hidden units of the discriminator
y_output_size = 1 # Output of discriminator for 'real' vs. 'fake' classes
class Discriminator(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(Discriminator, self).__init__()
self.layer1 = nn.Linear(input_size, hidden_size)
self.layer2 = nn.Linear(hidden_size, hidden_size)
self.layer3 = nn.Linear(hidden_size, output_size)
def forward(self, x):
x = F.elu(self.layer1(x))
x = F.elu(self.layer2(x))
return torch.sigmoid(self.layer3(x))
Create $\hat{y}(x;{\bf W}_y)$ optimizer¶
Need to define a loss function: we will use the negative log-likelihood (cross-entropy) loss for binary classes (BCELoss - Binary Cross-Entropy Loss)
y_hat = Discriminator(input_size=y_input_size, hidden_size=y_hidden_size, output_size=y_output_size).to(device)
# Negative log-likelihood loss (aka, cross-entropy loss) for binary classes (fake, real)
loss = nn.BCELoss()
y_learning_rate = 1e-3
optim_betas = (0.9, 0.999) # paramters specific to Adam optimnization (not part of this lecture)
y_optimizer = optim.Adam(y_hat.parameters(), lr=y_learning_rate, betas=optim_betas)
Make several alternating gradient steps between Discriminator and Geneartor¶
We will perform for every global iteration:
- one gradient step to improve the classifier (discriminator)
- one gradient step to improve the generator
We will use $K=1$ (same number of fake and true samples).
num_epochs = 20000
minibatch_size = 100
d_steps = 1 # number of gradient steps of discriminator per minibatch
g_steps = 1 # number of gradient steps of generator per minibatch
print_interval = 1000
batch_no = 0
for epoch in range(num_epochs):
for d_index in range(d_steps):
# 1. Train Discriminator on real+fake
y_hat.zero_grad()
# Train D on real data
y_real_data = torch.FloatTensor(X[(batch_no*minibatch_size):((batch_no+1)*minibatch_size),:]).to(device)
y_real_decision = y_hat(y_real_data)
y_real_error = loss(y_real_decision, torch.Tensor([[1]]*minibatch_size).to(device)) # ones = true data
y_real_error.backward() # store gradients, but don't change params yet
batch_no += 1
if batch_no >= 5000/minibatch_size:
batch_no = 0
y_gen_input = z(minibatch_size).to(device)
y_fake_data = G(y_gen_input).detach() # Generate outputs and detach to avoid training the Generator on these labels
y_fake_decision = y_hat(y_fake_data)
y_fake_error = loss(y_fake_decision, torch.Tensor([[0]]*minibatch_size).to(device)) # zeros = fake data
y_fake_error.backward()
y_optimizer.step() # Only optimizes y_hat based on stored gradients from both backwards
for g_index in range(g_steps):
# 2. Train Generator on Discriminator's response (but WE WILL NOT train Discriminator on these labels)
G.zero_grad()
y_gen_input = z(minibatch_size).to(device)
y_fake_data = G(y_gen_input) # we will be training G on these labels
yg_fake_decision = y_hat(y_fake_data)
g_error = loss(yg_fake_decision, torch.Tensor([[1]]*minibatch_size).to(device)) # we want to fool, so pretend it's all genuine
g_error.backward()
g_optimizer.step() # Only optimizes G's parameters
if epoch % print_interval == 0:
print(f"Epoch {epoch}")
Epoch 0 Epoch 1000 Epoch 2000 Epoch 3000 Epoch 4000 Epoch 5000 Epoch 6000 Epoch 7000 Epoch 8000 Epoch 9000 Epoch 10000 Epoch 11000 Epoch 12000 Epoch 13000 Epoch 14000 Epoch 15000 Epoch 16000 Epoch 17000 Epoch 18000 Epoch 19000
Generates examples from the generator¶
Questions:
- What is the input of the generator?
- What is the output of the generator?
This will generate 5000 examples from the noise and the generator
Let's first see what the input data to the generator looks like¶
noise = z(5000).cpu().numpy()
pylab.scatter(noise[:,0], noise[:,1])
pylab.show()
Let's see how the Generator is distorting the input to generate the data¶
d_gen_input = z(5000).to(device)
d_fake_data = G(d_gen_input).detach().data.cpu().numpy()
pylab.scatter(X[:,0], X[:,1],c="blue")
pylab.scatter(d_fake_data[:,0], d_fake_data[:,1],c="red")
pylab.show()
Some important properties not ensured by GANs:¶
- GANs do not guarantee the support of $p(x)$ is a subset of the support of $q(x)$.
- GANs don't guarantee we will learn $ {\bf W}^\star_y$ such that $p(y= 1 | x) = \hat{y}(x; {\bf W}^\star_y)$.
- GANs don't guarantee that $\forall x$, $K \gg \frac{p(x)}{q(x)}$, such that $p(y= 1 | x) = \frac{p(x)}{p(x) + K \cdot q(x)}\approx \frac{p(x)}{K \cdot q(x)}$, $\forall x$.
GAN Challenges: Mode Collapse¶
Or: Why won't the generated examples cover the support of $p(x)$?¶
Consider a case where the true data is generated by $p(x)$ and has two modes, generating images of cats and dogs.
Consider an initial proposal distribution $q(x; {\bf W}_q)$ that generates new images. This is the "noise" distribution. But $q(x; {\bf W}_q)$ perfectly generates images of dogs and effectively no cats.
- Then, the output $X'$ has mostly dogs. And if it had images of cats, they would be generated in the wrong frequency: dogs would be a lot more abundant in the dataset generated by $q(x; {\bf W}_q)$.
- And the classifier $\hat{y}$ will correctly classify the dogs in $X' \sim q(x; {\bf W}_q)$ as being true data, and then $q(x; {\bf W}_q)$ will not change since we don't make any mistakes and the gradient of the GAN w.r.t. ${\bf W}_q$ is zero.
Distribution Modes: The modes of a distribution are somewhat isolated areas in the domain where $p(x)$ has higher densitiy (probability), surrounded by areas of low probability.
Mode collapse means that $q(x; {\bf W}_q)$ cannot generate all modes.
Consider an example of a bi-modal Normal distribution, with modes in 1 and 6:
# Example of
import numpy as np
import matplotlib.pyplot as plt
n = 1000
z1 = np.random.normal(1, 1, n)
z6= np.random.normal(6, 1, n)
z = np.hstack((z1, z6))
plt.hist(z, bins='auto')
plt.show()
Fighting mode collapse with distribution divergences¶
Rather than relying on rejection sampling and using a classifier $\hat{y}$, we could rely on a distribution divergence metric to make sure $q(x; {\bf W}_q)$ is similar to $p(x)$.
- Distribution divergences, like the Wasserstein distance or Maximum Mean Discrepancy, can be used to also train GANs to generate distribution $q(x; {\bf W}_q)$ more similar to $p(x)$.
- The first of these approaches is the Wasserstein GAN of (Arjovsky et al., 2017)
GANs in the Literature¶
GAN as a Game¶
- (Salimans et al., 2016) discusses the problem of training a GAN as a game between two players where the equilibrium is the Nash equilibrium of a two-player non-cooperative game.
- However, each model updates its cost independently of the strategy of the other player in the game.
- Updating the gradient of both models concurrently does not guarantee convergence.
Understanding GANs in the Literature¶
- DCGANs — Radford et al. (2015)
- A generator architecture with upsampling convolutional layers
- Lots of useful architectural guidelines
- Progressively Growing GANs Karras et al. (2017)
- Takes upsampling to the next level.
- Shows how to build a multi-scale architecture where the GAN builds up from $4^2$, $8^2$, up to $1024^2$ resolution.
- Classifier follows the reverse order (from large to small)
- GAN instability is significantly improved
- Takes upsampling to the next level.
Improved Techniques for Training GANs - Salimans et al. (2016)
- Recommendations for building on the architectural guidelines
- Discusses GAN training instability
Discriminator Rejection Sampling - (Azadi et al., ICLR 2019)
- Does an extra rejection sampling step with the proposals that come out of the GAN
- I.e., $G(z)$ is accepted/rejected by another classifier
- Does an extra rejection sampling step with the proposals that come out of the GAN
Self-Attention Generative Adversarial Networks - (Zhang et al., ICML 2019)
- Traditional convolutional GANs generate high-resolution details as a function of only spatially local points in lower-resolution feature maps
- This approach uses self-attention to better correlate the features in the generated image.
- Conditional GANs (Mirza and Osindero (2014))
- In addition to the noise z, the generator also takes the class label y as input
- BigGAN (Brock et al. (2019))
- Combines many ideas to get good results with ImageNet
- State-of-the-art on ImageNet is, however, a VAE approach (Razavi et al. ICLR 2019)
- CycleGAN (Zhu et al. (2017))
- Discusses image translation in an Encoder - Decoder framework
- Task: Image-to-image translation where we do not have paired training samples
Image from Zhu et al. (2017)
- Tries to enforce consistency between generated images via Translator G $\to$ Translator F losses
Image from Zhu et al. (2017)
- StackGAN (Zhang et al. (2017))
- Generates images from text
- Uses progressively growing GANs
Some Practical Observations of Useful Methods:¶
We will use StyleGAN by Karras, Laine & Aila CVPR 2019 to describe some developments in GANs.
- Changes the geometry of Z from Gaussian (spherical) to a manifold (with forbidden areas)
Image from Karras, Laine & Aila CVPR 2019
- Generator and discriminator models are trained using the progressive growing GAN training (Karras, Aila, Laine & Lehtinen ICLR 2018).
- At each block of the generator model, after the convolutional layers, perform a LayerNorm and add style vector
- Style vector is the output of a neural network whose input is the style of a person (hair color, eye color, skin tone, accessories, etc.).
- Also adds Gaussian noise to GAN layers after activation
Image from Karras, Laine & Aila CVPR 2019
- Impressive results when mixing the style dimensions of the decoder output $Z(\text{input image})$ of different images: