The objective of this tutorial is to discover GANs, understand how they are implemented and then explore one specific architecture of GANs that allows us to perform image to image translation (which corresponds to the picture that you can see above this text ! ).
The notebook contains code cells with the **"# TO DO"** comments. Your goal is to complete these cells and run the proposed experiments. Also, there are several questions that you have to anwer.
As the computation is heavy, particularly during training, we encourage you to use a GPU. If your laptob is not equiped, you may use one of these remote jupyter servers, where you can select the execution on GPU :
This server is accessible within the campus network. If outside, you need to use a VPN. Before executing the notebook, select the kernel "Python PyTorch" to run it on GPU and have access to PyTorch module.
Before executing the notebook, select the execution on GPU : "Exécution" Menu -> "Modifier le type d'exécution" and select "T4 GPU".
%% Cell type:markdown id: tags:
# Part1: DC-GAN
%% Cell type:markdown id: tags:
In this part, we aim to learn and understand the basic concepts of **Generative Adversarial Networks** through a DCGAN and generate new celebrities from the learned network after showing it real celebrities. For this purpose, please study the tutorial here: https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html
%% Cell type:markdown id: tags:
Now we want to generate handwritten digits using the MNIST dataset. It is available within torvision package (https://pytorch.org/vision/stable/generated/torchvision.datasets.MNIST.html#torchvision.datasets.MNIST)
%% Cell type:code id: tags:
``` python
# TO DO: your code here to adapt the code from the tutorial to experiment on MNIST dataset
```
%% Cell type:markdown id: tags:
Please re-train the DCGAN and display some automatically generated handwritten digits.
%% Cell type:markdown id: tags:
# Part2: Conditional GAN (cGAN)
%% Cell type:markdown id: tags:
Let's take the example of the set described in the next picture.

We have a picture of a map (from Google Maps) and we want to create an image of what the satellite view may look like.
As we are not only trying to generate a random picture but a mapping between a picture to another one, we can't use the standard GAN architecture. We will then use a cGAN introduced in this [paper](https://arxiv.org/pdf/1611.07004.pdf).
A cGAN is a supervised GAN aiming at mapping a label picture to a real one or a real picture to a label one. As you can see in the diagram below, the discriminator will take as input a pair of images and try to predict if the pair was generated or not. The generator will not only generate an image from noise but will also use an image (label or real) to generate another one (real or label).

%% Cell type:markdown id: tags:
### Generator
In the cGAN architecture, the generator chosen is a U-Net.
A U-Net takes as input an image, and outputs another image.
It can be divided into 2 subparts : an encoder and a decoder.
* The encoder takes the input image and reduces its dimension to encode the main features into a vector.
* The decoder takes this vector and map the features stored into an image.
A U-Net architecture is different from a classic encoder-decoder in that every layer of the decoder takes as input the previous decoded output as well as the output vector from the encoder layers of the same level. It allows the decoder to map low frequencies information encoded during the descent as well as high frequencies from the original picture.
The encoder will take as input a colored picture (3 channels: RGB), it will pass through a series of convolution layers to encode the features of the picture. It will then be decoded by the decoder using transposed convolutional layers. These layers will take as input the previous decoded vector AND the encoded features of the same level.
%% Cell type:markdown id: tags:
Now, let's create or cGAN to generate facades from a template image. For this purpose, we will use the "Facade" dataset that consists of 506 Building Facades & corresponding Segmentations with split into train and test subsets.
%% Cell type:markdown id: tags:
Let's first create a few classes describing the layers we will use in the U-Net.
%% Cell type:code id: tags:
``` python
# Importing all the libraries needed
importmatplotlib.pyplotasplt
importglob
importrandom
importos
importnumpyasnp
importmath
importitertools
importtime
importdatetime
frompathlibimportPath
fromPILimportImage
fromtorch.utils.dataimportDataset,DataLoader
importtorchvision.transformsastransforms
fromtorchvision.utilsimportsave_image,make_grid
fromtorchvisionimportdatasets
fromtorch.autogradimportVariable
importtorch.nnasnn
importtorch.nn.functionalasF
importtorch
```
%% Cell type:code id: tags:
``` python
# code adapted from https://github.com/milesial/Pytorch-UNet/blob/master/unet/unet_parts.py
# At this stage x8 is our encoded vector, we will now decode it
x=self.up7(x8,x7)
x=self.up6(x,x6)
x=self.up5(x,x5)
x=self.up4(x,x4)
x=self.up3(x,x3)
x=self.up2(x,x2)
x=self.up1(x,x1)
x=self.outc(x)
returnx
```
%% Cell type:code id: tags:
``` python
# We take images that have 3 channels (RGB) as input and output an image that also have 3 channels (RGB)
generator=U_Net(3,3)
# Check that the architecture is as expected
generator
```
%% Cell type:markdown id: tags:
You should now have a working U-Net.
%% Cell type:markdown id: tags:
<fontcolor='red'>**Question 1**</font>
Knowing the input and output images will be 256x256, what will be the dimension of the encoded vector x8 ?
Your answer :
%% Cell type:markdown id: tags:
<fontcolor='red'>**Question 2**</font>
As you can see, U-net has an encoder-decoder architecture with skip connections. Explain why it works better than a traditional encoder-decoder.
Your anwer :
%% Cell type:markdown id: tags:
### Discriminator
In the cGAN architecture, the chosen discriminator is a Patch GAN. It is a convolutional discriminator which enables to produce a map of the input pictures where each pixel represents a patch of size NxN of the input.
The size N is given by the depth of the net. According to this table :
| Number of layers | N |
| ---- | ---- |
| 1 | 16 |
| 2 | 34 |
| 3 | 70 |
| 4 | 142 |
| 5 | 286 |
| 6 | 574 |
The number of layers actually means the number of layers with `kernel=(4,4)`, `padding=(1,1)` and `stride=(2,2)`. These layers are followed by 2 layers with `kernel=(4,4)`, `padding=(1,1)` and `stride=(1,1)`.
In our case we are going to create a 70x70 PatchGAN.
As we want a 70x70 Patch GAN, the architecture will be as follows :
```
1. C64 - K4, P1, S2
2. C128 - K4, P1, S2
3. C256 - K4, P1, S2
4. C512 - K4, P1, S1
5. C1 - K4, P1, S1 (output)
```
Where Ck denotes a convolution block with k filters, Kk a kernel of size k, Pk is the padding size and Sk the stride applied.
*Note :* For the first layer, we do not use batchnorm.
%% Cell type:markdown id: tags:
<fontcolor='red'>**Question 3**</font>
Knowing input images will be 256x256 with 3 channels each, how many parameters are there to learn ?
Your answer :
%% Cell type:code id: tags:
``` python
classPatchGAN(nn.Module):
def__init__(self,n_channels,n_classes):
super(PatchGAN,self).__init__()
# TODO :
# create the 4 first layers named conv1 to conv4
self.conv1=
self.conv2=
self.conv3=
self.conv4=
# output layer
self.out=out_block(512,n_classes)
defforward(self,x1,x2):
x=torch.cat([x2,x1],dim=1)
x=self.conv1(x)
x=self.conv2(x)
x=self.conv3(x)
x=self.conv4(x)
x=self.out(x)
returnx
```
%% Cell type:code id: tags:
``` python
# We have 6 input channels as we concatenate 2 images (with 3 channels each)
discriminator=PatchGAN(6,1)
discriminator
```
%% Cell type:markdown id: tags:
You should now have a working discriminator.
%% Cell type:markdown id: tags:
### Loss functions
As we have seen in the choice of the various architectures for this GAN, the issue is to map both low and high frequencies.
To tackle this problem, this GAN rely on the architecture to map the high frequencies (U-Net + PatchGAN) and the loss function to learn low frequencies features. The global loss function will indeed be made of 2 parts :
* the first part to map hight frequencies, will try to optimize the mean squared error of the GAN.
* the second part to map low frequencies, will minimize the $\mathcal{L}_1$ norm of the generated picture.
So the loss can be defined as $$ G^* = arg\ \underset{G}{min}\ \underset{D}{max}\ \mathcal{L}_{cGAN}(G,D) + \lambda \mathcal{L}_1(G)$$
%% Cell type:code id: tags:
``` python
# Loss functions
criterion_GAN=torch.nn.MSELoss()
criterion_pixelwise=torch.nn.L1Loss()
# Loss weight of L1 pixel-wise loss between translated image and real image
lambda_pixel=100
```
%% Cell type:markdown id: tags:
### Training and evaluating models
%% Cell type:code id: tags:
``` python
# parameters
epoch=0# epoch to start training from
n_epoch=200# number of epochs of training
batch_size=10# size of the batches
lr=0.0002# adam: learning rate
b1=0.5# adam: decay of first order momentum of gradient
b2=0.999# adam: decay of first order momentum of gradient
decay_epoch=100# epoch from which to start lr decay
img_height=256# size of image height
img_width=256# size of image width
channels=3# number of image channels
sample_interval=500# interval between sampling of images from generators
checkpoint_interval=-1# interval between model checkpoints
cuda=Trueiftorch.cuda.is_available()elseFalse# do you have cuda ?
The objective of this tutorial is to discover GANs, understand how they are implemented and then explore one specific architecture of GANs that allows us to perform image to image translation (which corresponds to the picture that you can see above this text ! ).
The notebook contains code cells with the **"# TO DO"** comments. Your goal is to complete these cells and run the proposed experiments. Also, there are several questions that you have to anwer.
As the computation is heavy, particularly during training, we encourage you to use a GPU. If your laptob is not equiped, you may use one of these remote jupyter servers, where you can select the execution on GPU :
This server is accessible within the campus network. If outside, you need to use a VPN. Before executing the notebook, select the kernel "Python PyTorch" to run it on GPU and have access to PyTorch module.
Before executing the notebook, select the execution on GPU : "Exécution" Menu -> "Modifier le type d'exécution" and select "T4 GPU".
%% Cell type:markdown id: tags:
# Part1: DC-GAN
%% Cell type:markdown id: tags:
In this part, we aim to learn and understand the basic concepts of **Generative Adversarial Networks** through a DCGAN and generate new celebrities from the learned network after showing it real celebrities. For this purpose, please study the tutorial here: https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html
%% Cell type:markdown id: tags:
Now we want to generate handwritten digits using the MNIST dataset. It is available within torvision package (https://pytorch.org/vision/stable/generated/torchvision.datasets.MNIST.html#torchvision.datasets.MNIST)
%% Cell type:code id: tags:
``` python
# TO DO: your code here to adapt the code from the tutorial to experiment on MNIST dataset
```
%% Cell type:markdown id: tags:
Please re-train the DCGAN and display some automatically generated handwritten digits.
%% Cell type:markdown id: tags:
# Part2: Conditional GAN (cGAN)
%% Cell type:markdown id: tags:
Let's take the example of the set described in the next picture.

We have a picture of a map (from Google Maps) and we want to create an image of what the satellite view may look like.
As we are not only trying to generate a random picture but a mapping between a picture to another one, we can't use the standard GAN architecture. We will then use a cGAN introduced in this [paper](https://arxiv.org/pdf/1611.07004.pdf).
A cGAN is a supervised GAN aiming at mapping a label picture to a real one or a real picture to a label one. As you can see in the diagram below, the discriminator will take as input a pair of images and try to predict if the pair was generated or not. The generator will not only generate an image from noise but will also use an image (label or real) to generate another one (real or label).

%% Cell type:markdown id: tags:
### Generator
In the cGAN architecture, the generator chosen is a U-Net.
A U-Net takes as input an image, and outputs another image.
It can be divided into 2 subparts : an encoder and a decoder.
* The encoder takes the input image and reduces its dimension to encode the main features into a vector.
* The decoder takes this vector and map the features stored into an image.
A U-Net architecture is different from a classic encoder-decoder in that every layer of the decoder takes as input the previous decoded output as well as the output vector from the encoder layers of the same level. It allows the decoder to map low frequencies information encoded during the descent as well as high frequencies from the original picture.
The encoder will take as input a colored picture (3 channels: RGB), it will pass through a series of convolution layers to encode the features of the picture. It will then be decoded by the decoder using transposed convolutional layers. These layers will take as input the previous decoded vector AND the encoded features of the same level.
%% Cell type:markdown id: tags:
Now, let's create or cGAN to generate facades from a template image. For this purpose, we will use the "Facade" dataset that consists of 506 Building Facades & corresponding Segmentations with split into train and test subsets.
%% Cell type:markdown id: tags:
Let's first create a few classes describing the layers we will use in the U-Net.
%% Cell type:code id: tags:
``` python
# Importing all the libraries needed
importmatplotlib.pyplotasplt
importglob
importrandom
importos
importnumpyasnp
importmath
importitertools
importtime
importdatetime
frompathlibimportPath
fromPILimportImage
fromtorch.utils.dataimportDataset,DataLoader
importtorchvision.transformsastransforms
fromtorchvision.utilsimportsave_image,make_grid
fromtorchvisionimportdatasets
fromtorch.autogradimportVariable
importtorch.nnasnn
importtorch.nn.functionalasF
importtorch
```
%% Cell type:code id: tags:
``` python
# code adapted from https://github.com/milesial/Pytorch-UNet/blob/master/unet/unet_parts.py
# At this stage x8 is our encoded vector, we will now decode it
x=self.up7(x8,x7)
x=self.up6(x,x6)
x=self.up5(x,x5)
x=self.up4(x,x4)
x=self.up3(x,x3)
x=self.up2(x,x2)
x=self.up1(x,x1)
x=self.outc(x)
returnx
```
%% Cell type:code id: tags:
``` python
# We take images that have 3 channels (RGB) as input and output an image that also have 3 channels (RGB)
generator=U_Net(3,3)
# Check that the architecture is as expected
generator
```
%% Cell type:markdown id: tags:
You should now have a working U-Net.
%% Cell type:markdown id: tags:
<fontcolor='red'>**Question 1**</font>
Knowing the input and output images will be 256x256, what will be the dimension of the encoded vector x8 ?
Your answer :
%% Cell type:markdown id: tags:
<fontcolor='red'>**Question 2**</font>
As you can see, U-net has an encoder-decoder architecture with skip connections. Explain why it works better than a traditional encoder-decoder.
Your anwer :
%% Cell type:markdown id: tags:
### Discriminator
In the cGAN architecture, the chosen discriminator is a Patch GAN. It is a convolutional discriminator which enables to produce a map of the input pictures where each pixel represents a patch of size NxN of the input.
The size N is given by the depth of the net. According to this table :
| Number of layers | N |
| ---- | ---- |
| 1 | 16 |
| 2 | 34 |
| 3 | 70 |
| 4 | 142 |
| 5 | 286 |
| 6 | 574 |
The number of layers actually means the number of layers with `kernel=(4,4)`, `padding=(1,1)` and `stride=(2,2)`. These layers are followed by 2 layers with `kernel=(4,4)`, `padding=(1,1)` and `stride=(1,1)`.
In our case we are going to create a 70x70 PatchGAN.
As we want a 70x70 Patch GAN, the architecture will be as follows :
```
1. C64 - K4, P1, S2
2. C128 - K4, P1, S2
3. C256 - K4, P1, S2
4. C512 - K4, P1, S1
5. C1 - K4, P1, S1 (output)
```
Where Ck denotes a convolution block with k filters, Kk a kernel of size k, Pk is the padding size and Sk the stride applied.
*Note :* For the first layer, we do not use batchnorm.
%% Cell type:markdown id: tags:
<fontcolor='red'>**Question 3**</font>
Knowing input images will be 256x256 with 3 channels each, how many parameters are there to learn ?
Your answer :
%% Cell type:code id: tags:
``` python
classPatchGAN(nn.Module):
def__init__(self,n_channels,n_classes):
super(PatchGAN,self).__init__()
# TODO :
# create the 4 first layers named conv1 to conv4
self.conv1=
self.conv2=
self.conv3=
self.conv4=
# output layer
self.out=out_block(512,n_classes)
defforward(self,x1,x2):
x=torch.cat([x2,x1],dim=1)
x=self.conv1(x)
x=self.conv2(x)
x=self.conv3(x)
x=self.conv4(x)
x=self.out(x)
returnx
```
%% Cell type:code id: tags:
``` python
# We have 6 input channels as we concatenate 2 images (with 3 channels each)
discriminator=PatchGAN(6,1)
discriminator
```
%% Cell type:markdown id: tags:
You should now have a working discriminator.
%% Cell type:markdown id: tags:
### Loss functions
As we have seen in the choice of the various architectures for this GAN, the issue is to map both low and high frequencies.
To tackle this problem, this GAN rely on the architecture to map the high frequencies (U-Net + PatchGAN) and the loss function to learn low frequencies features. The global loss function will indeed be made of 2 parts :
* the first part to map hight frequencies, will try to optimize the mean squared error of the GAN.
* the second part to map low frequencies, will minimize the $\mathcal{L}_1$ norm of the generated picture.
So the loss can be defined as $$ G^* = arg\ \underset{G}{min}\ \underset{D}{max}\ \mathcal{L}_{cGAN}(G,D) + \lambda \mathcal{L}_1(G)$$
%% Cell type:code id: tags:
``` python
# Loss functions
criterion_GAN=torch.nn.MSELoss()
criterion_pixelwise=torch.nn.L1Loss()
# Loss weight of L1 pixel-wise loss between translated image and real image
lambda_pixel=100
```
%% Cell type:markdown id: tags:
### Training and evaluating models
%% Cell type:code id: tags:
``` python
# parameters
epoch=0# epoch to start training from
n_epoch=200# number of epochs of training
batch_size=10# size of the batches
lr=0.0002# adam: learning rate
b1=0.5# adam: decay of first order momentum of gradient
b2=0.999# adam: decay of first order momentum of gradient
decay_epoch=100# epoch from which to start lr decay
img_height=256# size of image height
img_width=256# size of image width
channels=3# number of image channels
sample_interval=500# interval between sampling of images from generators
checkpoint_interval=-1# interval between model checkpoints
cuda=Trueiftorch.cuda.is_available()elseFalse# do you have cuda ?
The objective of this tutorial is to discover Diffusion Models that are probabilistic generative models which learn to generate data by iteratively refining random noise through a reverse diffusion process. Given a sample of data, noise is progressively added in small steps until it becomes pure noise. Then, a neural network is trained to reverse this process and generate realistic data from noise.
Diffusion models have gained popularity due to their ability to generate high-quality, diverse, and detailed content, surpassing GANs in the quality of the generated images.
In this assignment we will focus on DDPMs, which were introduced in this [paper](https://arxiv.org/abs/2006.11239) and laid the foundation for generative diffusion models.
The notebook contains code cells with the **"# TO DO"** comments. Your goal is to complete these cells and run the proposed experiments.
As the computation is heavy, particularly during training, we encourage you to use a GPU. If your laptob is not equiped, you may use one of these remote jupyter servers, where you can select the execution on GPU :
This server is accessible within the campus network. If outside, you need to use a VPN. Before executing the notebook, select the kernel "Python PyTorch" to run it on GPU and have access to PyTorch module.
As in the previous session, we will use the MNIST dataset.
%% Cell type:code id: tags:
``` python
# TO DO: your code here to load the MNIST dataset. The size of the images should be set to 64x64.
mnist_dataset=
mnist_dataloader=
```
%% Cell type:markdown id: tags:
Auxiliary functions for plotting images
%% Cell type:code id: tags:
``` python
defreverse_transform(image):
image=image.numpy().transpose((1,2,0))
image=np.clip(image,0,1)
image=(image*255).astype(np.uint8)
returnimage
defplot1xNArray(images,labels):
f,axarr=plt.subplots(1,len(images))
forimage,ax,labelinzip(images,axarr,labels):
ax.imshow(image,cmap='gray')
ax.axis('off')
ax.set_title(label)
```
%% Cell type:markdown id: tags:
In order to train the model with the diffusion process, we will use a noise scheduler, which will be in charge of the forward diffusion process. The scheduler takes an image, a sample of random noise and a timestep, and return a noisy image for the corresponding timestep. Noise is progressively added to the image at each timestep, therefore a noisy image at timestep 0 will have barely any noise while a noisy image at the maximum timestep will be basically just noise.
Let's create a noise scheduler with 1000 max timesteps and visualize some noise images.
We will use the diffusers library from Hugging Face, which provides several tools for training and using diffusion models.
%% Cell type:code id: tags:
``` python
fromdiffusersimportDDPMScheduler
# TO DO: Create the scheduler
noise_scheduler=
image,_=mnist_dataset[0]
# TO DO: Create a noise tensor sampled from a normal distribution with the same shape as the image
For the reverse diffusion process we will use a neural network. Given a noisy image and the corresponding timestep, the goal of the neural network is to predict the noise, which allows for the denoising.
For the model, we will have a similar architecture as we used for the cGAN generator, a 2D UNet with a few modifications. The main difference will be that we have to indicate to the model which timestep is currently being denoised. For that purpose, a timestep embedding is added, therefore the model has 2 inputs, the noisy image and the corresponding timestep.
In this exercise, we will use an UNet implementation from the diffusers library, which already has the timestep embedding included.
If the training takes too long, you can download an already trained model from [this link](https://partage.liris.cnrs.fr/index.php/s/AP2t6b3w8SM4Bp5) and use it for inference.
%% Cell type:code id: tags:
``` python
# TO DO: Add the path to the model checkpoint for loading the model
diffusion_backbone.load_state_dict(torch.load())
diffusion_backbone.eval()
```
%% Cell type:markdown id: tags:
### Time to generate some images.
During training, for each data sample, we take a random timestep and the corresponding noisy image to give it as input to our model. With sufficient training, the model should learn how to predict the noise in a noisy image for all possible timesteps.
During inference, to generate an image, we will start from pure noise and step by step predict the noise to go from one noisy image to the next, progressively denoising the image until we reach the timestep 0, in which we should have an image without any noise.
%% Cell type:code id: tags:
``` python
fromtqdmimporttqdm
# Start the image as random noise
image=torch.randn((10,1,64,64)).to(device)
# Create a list of images and labels for visualization
The diffusers library also provides *Pipeline* classes, which are wrappers around the model that abstracts the inference loop implemented above.
We can create a pipeline, giving it the trained model and the noise scheduler, and use it to generate images. In this case, we will only have access to the final image, generated on the last timestep, but not the intermediary images from the denoising process.
In this exercise we achieved decent results for very simple datasets. But we are quite far from those beautiful AI generated images we can find online. That is for 2 main reasons:
- Model size: due to the computation and time constrains, we can't really train very large models
- Dataset size: due to the same constrains, we can't use very complex and large datasets, which requires larger models and longer training times.
Fortunately, even though we can't train those large models with the available hardware and time, we can at least use them for inference !
The goal of this part is to learn how to retrieve and use a pre-trained diffusion models and also to get creative to come up with some nice prompts to generate outstanding images.
We are going to use Stable Diffusion 3.5, which is a state of the art open-source text conditioned model. It takes a prompt in natural language and use it to guide the diffusion process. This type of models are trained with image-text pairs, but can generalize beyond the pairs seen during training, being able to mix several different concepts into a single image.
In order to save memory, we will use quantization, which consists into converting the model weights types from float16 into float4. That simply means that each model weight will be stored using only 4 bits instead of 16 bits. That allows us to run the model in GPUs with less VRAM and have faster inference, with a small drop in the quality of the results.
%% Cell type:markdown id: tags:
For this part of the assignment restart the notebook kernel to be sure your GPU memory is empty. The memory usage can be verified using the command `nvidia-smi` in a terminal. If your GPU has 2GB of VRAM or less, the model will probably not fit into memory even with quantization. In that case, use Google Colab for this part or use the smaller model indicated below. If you are not happy with the results and have plenty of VRAM available, feel free to increase the quantization to 8 bits or even load the model without quantization.
# TO DO: test different prompts and visualize the generated images
# Once you are happy with the results, you can save 3 different images as png file with the correspondent prompts in a text file
prompt=
image=pipeline(
prompt=prompt,
num_inference_steps=40,
guidance_scale=4.5,
max_sequence_length=512
).images[0]
image.save("generated_image.png")
```
%% Cell type:markdown id: tags:
If even with the quantization you still run out of GPU memory and you can't use Google Colab, you can use the following code instead, which uses a much smaller model (the results won't be as near as impressive, but it should be able to run even on a CPU, if you have a little patience)
The objective of this tutorial is to discover Diffusion Models that are probabilistic generative models which learn to generate data by iteratively refining random noise through a reverse diffusion process. Given a sample of data, noise is progressively added in small steps until it becomes pure noise. Then, a neural network is trained to reverse this process and generate realistic data from noise.
Diffusion models have gained popularity due to their ability to generate high-quality, diverse, and detailed content, surpassing GANs in the quality of the generated images.
In this assignment we will focus on DDPMs, which were introduced in this [paper](https://arxiv.org/abs/2006.11239) and laid the foundation for generative diffusion models.
The notebook contains code cells with the **"# TO DO"** comments. Your goal is to complete these cells and run the proposed experiments.
As the computation is heavy, particularly during training, we encourage you to use a GPU. If your laptob is not equiped, you may use one of these remote jupyter servers, where you can select the execution on GPU :
This server is accessible within the campus network. If outside, you need to use a VPN. Before executing the notebook, select the kernel "Python PyTorch" to run it on GPU and have access to PyTorch module.
As in the previous session, we will use the MNIST dataset.
%% Cell type:code id: tags:
``` python
# TO DO: your code here to load the MNIST dataset. The size of the images should be set to 64x64.
mnist_dataset=
mnist_dataloader=
```
%% Cell type:markdown id: tags:
Auxiliary functions for plotting images
%% Cell type:code id: tags:
``` python
defreverse_transform(image):
image=image.numpy().transpose((1,2,0))
image=np.clip(image,0,1)
image=(image*255).astype(np.uint8)
returnimage
defplot1xNArray(images,labels):
f,axarr=plt.subplots(1,len(images))
forimage,ax,labelinzip(images,axarr,labels):
ax.imshow(image,cmap='gray')
ax.axis('off')
ax.set_title(label)
```
%% Cell type:markdown id: tags:
In order to train the model with the diffusion process, we will use a noise scheduler, which will be in charge of the forward diffusion process. The scheduler takes an image, a sample of random noise and a timestep, and return a noisy image for the corresponding timestep. Noise is progressively added to the image at each timestep, therefore a noisy image at timestep 0 will have barely any noise while a noisy image at the maximum timestep will be basically just noise.
Let's create a noise scheduler with 1000 max timesteps and visualize some noise images.
We will use the diffusers library from Hugging Face, which provides several tools for training and using diffusion models.
%% Cell type:code id: tags:
``` python
fromdiffusersimportDDPMScheduler
# TO DO: Create the scheduler
noise_scheduler=
image,_=mnist_dataset[0]
# TO DO: Create a noise tensor sampled from a normal distribution with the same shape as the image
For the reverse diffusion process we will use a neural network. Given a noisy image and the corresponding timestep, the goal of the neural network is to predict the noise, which allows for the denoising.
For the model, we will have a similar architecture as we used for the cGAN generator, a 2D UNet with a few modifications. The main difference will be that we have to indicate to the model which timestep is currently being denoised. For that purpose, a timestep embedding is added, therefore the model has 2 inputs, the noisy image and the corresponding timestep.
In this exercise, we will use an UNet implementation from the diffusers library, which already has the timestep embedding included.
If the training takes too long, you can download an already trained model from [this link](https://partage.liris.cnrs.fr/index.php/s/AP2t6b3w8SM4Bp5) and use it for inference.
%% Cell type:code id: tags:
``` python
# TO DO: Add the path to the model checkpoint for loading the model
diffusion_backbone.load_state_dict(torch.load())
diffusion_backbone.eval()
```
%% Cell type:markdown id: tags:
### Time to generate some images.
During training, for each data sample, we take a random timestep and the corresponding noisy image to give it as input to our model. With sufficient training, the model should learn how to predict the noise in a noisy image for all possible timesteps.
During inference, to generate an image, we will start from pure noise and step by step predict the noise to go from one noisy image to the next, progressively denoising the image until we reach the timestep 0, in which we should have an image without any noise.
%% Cell type:code id: tags:
``` python
fromtqdmimporttqdm
# Start the image as random noise
image=torch.randn((10,1,64,64)).to(device)
# Create a list of images and labels for visualization
The diffusers library also provides *Pipeline* classes, which are wrappers around the model that abstracts the inference loop implemented above.
We can create a pipeline, giving it the trained model and the noise scheduler, and use it to generate images. In this case, we will only have access to the final image, generated on the last timestep, but not the intermediary images from the denoising process.
In this exercise we achieved decent results for very simple datasets. But we are quite far from those beautiful AI generated images we can find online. That is for 2 main reasons:
- Model size: due to the computation and time constrains, we can't really train very large models
- Dataset size: due to the same constrains, we can't use very complex and large datasets, which requires larger models and longer training times.
Fortunately, even though we can't train those large models with the available hardware and time, we can at least use them for inference !
The goal of this part is to learn how to retrieve and use a pre-trained diffusion models and also to get creative to come up with some nice prompts to generate outstanding images.
We are going to use Stable Diffusion 3.5, which is a state of the art open-source text conditioned model. It takes a prompt in natural language and use it to guide the diffusion process. This type of models are trained with image-text pairs, but can generalize beyond the pairs seen during training, being able to mix several different concepts into a single image.
In order to save memory, we will use quantization, which consists into converting the model weights types from float16 into float4. That simply means that each model weight will be stored using only 4 bits instead of 16 bits. That allows us to run the model in GPUs with less VRAM and have faster inference, with a small drop in the quality of the results.
%% Cell type:markdown id: tags:
For this part of the assignment restart the notebook kernel to be sure your GPU memory is empty. The memory usage can be verified using the command `nvidia-smi` in a terminal. If your GPU has 2GB of VRAM or less, the model will probably not fit into memory even with quantization. In that case, use Google Colab for this part or use the smaller model indicated below. If you are not happy with the results and have plenty of VRAM available, feel free to increase the quantization to 8 bits or even load the model without quantization.
# TO DO: test different prompts and visualize the generated images
# Once you are happy with the results, you can save 3 different images as png file with the correspondent prompts in a text file
prompt=
image=pipeline(
prompt=prompt,
num_inference_steps=40,
guidance_scale=4.5,
max_sequence_length=512
).images[0]
image.save("generated_image.png")
```
%% Cell type:markdown id: tags:
If even with the quantization you still run out of GPU memory and you can't use Google Colab, you can use the following code instead, which uses a much smaller model (the results won't be as near as impressive, but it should be able to run even on a CPU, if you have a little patience)