Denoising Diffusion Probabilistic Model

Shan-Hung Wu & DataLab
Fall 2023

In this lab, we introduce the Denoising Diffusion Probabilistic Models (DDPMs), which is one of the implementations to demonstrate the usage of the diffusion model generating images, and as an example, dataset Oxford Flowers 102 are used for training the model to generate the images of flower.

Introduction to the diffusion model

Generative modeling experienced tremendous growth in the last five years. Models like VAEs, GANs, and flow-based models proved to be a great success in generating high-quality content, especially images. Diffusion models are a new type of generative model that has proven to be better than previous approaches.

Diffusion models are inspired by non-equilibrium thermodynamics, and they learn to generate by denoising. Learning by denoising consists of two processes, each of which is a Markov Chain. These are:

  1. The forward process: In the forward process, we slowly add random noise to the data in a series of time steps (t1, t2, ..., tn ). Samples at the current time step are drawn from a Gaussian distribution where the mean of the distribution is conditioned on the sample at the previous time step, and the variance of the distribution follows a fixed schedule. At the end of the forward process, the samples end up with a pure noise distribution.

  2. The reverse process: During the reverse process, we try to undo the added noise at every time step. We start with the pure noise distribution (the last step of the forward process) and try to denoise the samples in the backward direction (tn, tn-1, ..., t1).

We implement the Denoising Diffusion Probabilistic Models paper or DDPMs for short in this code example. It was the first paper demonstrating the use of diffusion models for generating high-quality images. The authors proved that a certain parameterization of diffusion models reveals an equivalence with denoising score matching over multiple noise levels during training and with annealed Langevin dynamics during sampling that generates the best quality results.

This paper replicates both the Markov chains (forward process and reverse process) involved in the diffusion process but for images. The forward process is fixed and gradually adds Gaussian noise to the images according to a fixed variance schedule denoted by beta in the paper. This is what the diffusion process looks like in case of images: (image -> noise::noise -> image)

diffusion process gif

The paper describes two algorithms, one for training the model, and the other for sampling from the trained model. Training is performed by optimizing the usual variational bound on negative log-likelihood. The objective function is further simplified, and the network is treated as a noise prediction network. Once optimized, we can sample from the network to generate new images from noise samples. Here is an overview of both algorithms as presented in the paper:

ddpms

Note: DDPM is just one way of implementing a diffusion model. Also, the sampling algorithm in the DDPM replicates the complete Markov chain. Hence, it's slow in generating new samples compared to other generative models like GANs. Lots of research efforts have been made to address this issue. One such example is Denoising Diffusion Implicit Models, or DDIM for short, where the authors replaced the Markov chain with a non-Markovian process to sample faster. You can find the code example for DDIM here

Implementing a DDPM model is simple. We define a model that takes two inputs: Images and the randomly sampled time steps. At each training step, we perform the following operations to train our model:

  1. Sample random noise to be added to the inputs.
  2. Apply the forward process to diffuse the inputs with the sampled noise.
  3. Your model takes these noisy samples as inputs and outputs the noise prediction for each time step.
  4. Given true noise and predicted noise, we calculate the loss values
  5. We then calculate the gradients and update the model weights.

Given that our model knows how to denoise a noisy sample at a given time step, we can leverage this idea to generate new samples, starting from a pure noise distribution.

Setup

🍊 Please check on the TensorFlow Addons (TFA) Installation for compatibility with your version before installing the tensorflow_addons.

Hyperparameters

Dataset

We use the Oxford Flowers 102 dataset for generating images of flowers. In terms of preprocessing, we use center cropping for resizing the images to the desired image size, and we rescale the pixel values in the range [-1.0, 1.0]. This is in line with the range of the pixel values that was applied by the authors of the DDPMs paper. For augmenting training data, we randomly flip the images left/right.

Gaussian diffusion utilities

We define the forward process and the reverse process as a separate utility. Most of the code in this utility has been borrowed from the original implementation with some slight modifications.

Network architecture

U-Net, originally developed for semantic segmentation, is an architecture that is widely used for implementing diffusion models but with some slight modifications:

  1. The network accepts two inputs: Image and time step
  2. Self-attention between the convolution blocks once we reach a specific resolution (16x16 in the paper)
  3. Group Normalization instead of weight normalization

We implement most of the things as used in the original paper. We use the swish activation function throughout the network. We use the variance scaling kernel initializer.

The only difference here is the number of groups used for the GroupNormalization layer. For the flowers dataset, we found that a value of groups=8 produces better results compared to the default value of groups=32. Dropout is optional and should be used where chances of over fitting is high. In the paper, the authors used dropout only when training on CIFAR10.

Training

We follow the same setup for training the diffusion model as described in the paper. We use Adam optimizer with a learning rate of 2e-4. We use EMA on model parameters with a decay factor of 0.999. We treat our model as noise prediction network i.e. at every training step, we input a batch of images and corresponding time steps to our UNet, and the network outputs the noise as predictions.

The only difference is that we aren't using the Kernel Inception Distance (KID) or Frechet Inception Distance (FID) for evaluating the quality of generated samples during training. This is because both these metrics are compute heavy and are skipped for the brevity of implementation.

Note: We are using mean squared error as the loss function which is aligned with the paper, and theoretically makes sense. In practice, though, it is also common to use mean absolute error or Huber loss as the loss function.

Results

We trained this model for 800 epochs on a V100 GPU, and each epoch took almost 8 seconds to finish. We load those weights here, and we generate a few samples starting from pure noise.

References

You can find the original introduction by A_K_Nain here.

  1. Denoising Diffusion Probabilistic Models
  2. Author's implementation
  3. A deep dive into DDPMs
  4. Denoising Diffusion Implicit Models
  5. Annotated Diffusion Model
  6. AIAIART

Assignment

In this assignment, you have to implement the DDPMs with the CelebA dataset.

Description of Dataset

  1. The raw data is from Large-scale CelebFaces Attributes (CelebA) Dataset, please download it
    • TensorFlow Datasets has also provide CelebA, but we suggust you to download it and use it locally
  2. CelebA has 202,599 number of face images

The sample images are shown below:

sample images

Requirements

sample results