Basic Training

hf-notebooksdiffusers_docenpytorch

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 ๐Ÿฆ‹.

[!TIP] ๐Ÿ’ก 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).

[ ]

We encourage you to share your model with the community, and in order to do that, you'll need to login to your Hugging Face account (create one here if you don't already have one!). You can login from a notebook and enter your token when prompted. Make sure your token has the write role.

[ ]

Or login in from the terminal:

hf auth login

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

!sudo apt -qq install git-lfs
!git config --global credential.helper store

Training configuration

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

[ ]

Load the dataset

You can easily load the Smithsonian Butterflies dataset with the ๐Ÿค— Datasets library:

[ ]

[!TIP] ๐Ÿ’ก 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:

[ ]

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.
[ ]

Use ๐Ÿค— Datasets' set_transform method to apply the preprocess function on the fly during training:

[ ]

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!

[ ]

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:

[ ]

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

[ ]
Input shape: torch.Size([1, 3, 128, 128])
[ ]
Output shape: torch.Size([1, 3, 128, 128])

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:

[ ]

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

[ ]

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:

[ ]

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:

[ ]

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.

[!TIP] ๐Ÿ’ก 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. ๐Ÿค—

[ ]

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:

[ ]

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

[ ]

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.