Train a diffusion model

Train a diffusion model

Unconditional image generation is a popular application of diffusion models that generates images that look like those in the dataset used for training. Typically, the best results are obtained from finetuning a pretrained model on a specific dataset. You can find many of these checkpoints on the Hub, but if you can’t find one you like, you can always train your own!

This tutorial will teach you how to train a UNet2DModel from scratch on a subset of the Smithsonian Butterflies dataset to generate your own πŸ¦‹ butterflies πŸ¦‹.

πŸ’‘ This training tutorial is based on the Training with 🧨 Diffusers notebook. For additional details and context about diffusion models like how they work, check out the notebook!

Before you begin, make sure you have 🌍 Datasets installed to load and preprocess image datasets, and 🌍 Accelerate, to simplify training on any number of GPUs. The following command will also install TensorBoard to visualize training metrics (you can also use Weights & Biases to track your training).

Copied

# uncomment to install the necessary libraries in Colab
#!pip install diffusers[training]

We encourage you to share your model with the community, and in order to do that, you’ll need to login to your BOINC AI account (create one here if you don’t already have one!). You can login from a notebook and enter your token when prompted:

Copied

>>> from boincai import notebook_login

>>> notebook_login()

Or login in from the terminal:

Copied

boincai-cli login

Since the model checkpoints are quite large, install Git-LFS to version these large files:

Copied

Training configuration

For convenience, create a TrainingConfig class containing the training hyperparameters (feel free to adjust them):

Copied

Load the dataset

You can easily load the Smithsonian Butterflies dataset with the 🌍 Datasets library:

Copied

πŸ’‘ You can find additional datasets from the HugGan Community Event or you can use your own dataset by creating a local ImageFolder. Set config.dataset_name to the repository id of the dataset if it is from the HugGan Community Event, or imagefolder if you’re using your own images.

🌍 Datasets uses the Image feature to automatically decode the image data and load it as a PIL.Image which we can visualize:

Copied

The images are all different sizes though, so you’ll need to preprocess them first:

  • Resize changes the image size to the one defined in config.image_size.

  • RandomHorizontalFlip augments the dataset by randomly mirroring the images.

  • Normalize is important to rescale the pixel values into a [-1, 1] range, which is what the model expects.

Copied

Use 🌍 Datasets’ set_transform method to apply the preprocess function on the fly during training:

Copied

Feel free to visualize the images again to confirm that they’ve been resized. Now you’re ready to wrap the dataset in a DataLoader for training!

Copied

Create a UNet2DModel

Pretrained models in 🧨 Diffusers are easily created from their model class with the parameters you want. For example, to create a UNet2DModel:

Copied

It is often a good idea to quickly check the sample image shape matches the model output shape:

Copied

Great! Next, you’ll need a scheduler to add some noise to the image.

Create a scheduler

The scheduler behaves differently depending on whether you’re using the model for training or inference. During inference, the scheduler generates image from the noise. During training, the scheduler takes a model output - or a sample - from a specific point in the diffusion process and applies noise to the image according to a noise schedule and an update rule.

Let’s take a look at the DDPMScheduler and use the add_noise method to add some random noise to the sample_image from before:

Copied

The training objective of the model is to predict the noise added to the image. The loss at this step can be calculated by:

Copied

Train the model

By now, you have most of the pieces to start training the model and all that’s left is putting everything together.

First, you’ll need an optimizer and a learning rate scheduler:

Copied

Then, you’ll need a way to evaluate the model. For evaluation, you can use the DDPMPipeline to generate a batch of sample images and save it as a grid:

Copied

Now you can wrap all these components together in a training loop with 🌍 Accelerate for easy TensorBoard logging, gradient accumulation, and mixed precision training. To upload the model to the Hub, write a function to get your repository name and information and then push it to the Hub.

πŸ’‘ The training loop below may look intimidating and long, but it’ll be worth it later when you launch your training in just one line of code! If you can’t wait and want to start generating images, feel free to copy and run the code below. You can always come back and examine the training loop more closely later, like when you’re waiting for your model to finish training. 🌍

Copied

Phew, that was quite a bit of code! But you’re finally ready to launch the training with 🌍 Accelerate’s notebook_launcher function. Pass the function the training loop, all the training arguments, and the number of processes (you can change this value to the number of GPUs available to you) to use for training:

Copied

Once training is complete, take a look at the final πŸ¦‹ images πŸ¦‹ generated by your diffusion model!

Copied

Next steps

Unconditional image generation is one example of a task that can be trained. You can explore other tasks and training techniques by visiting the 🧨 Diffusers Training Examples page. Here are some examples of what you can learn:

  • Textual Inversion, an algorithm that teaches a model a specific visual concept and integrates it into the generated image.

  • DreamBooth, a technique for generating personalized images of a subject given several input images of the subject.

  • Guide to finetuning a Stable Diffusion model on your own dataset.

  • Guide to using LoRA, a memory-efficient technique for finetuning really large models faster.

Last updated