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 loginSince 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:
Resizechanges the image size to the one defined inconfig.image_size.RandomHorizontalFlipaugments the dataset by randomly mirroring the images.Normalizeis 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