Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/main/diffusers_doc/en/basic_training.ipynb
Views: 2542
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).
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:
Or login in from the terminal:
Since the model checkpoints are quite large, install Git-LFS to version these large files:
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:
๐ก 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 inconfig.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:
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.
๐ก 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.