Understanding models and schedulers
Last updated
Last updated
🧨 Diffusers is designed to be a user-friendly and flexible toolbox for building diffusion systems tailored to your use-case. At the core of the toolbox are models and schedulers. While the DiffusionPipeline bundles these components together for convenience, you can also unbundle the pipeline and use the models and schedulers separately to create new diffusion systems.
In this tutorial, you’ll learn how to use models and schedulers to assemble a diffusion system for inference, starting with a basic pipeline and then progressing to the Stable Diffusion pipeline.
A pipeline is a quick and easy way to run a model for inference, requiring no more than four lines of code to generate an image:
Copied
That was super easy, but how did the pipeline do that? Let’s breakdown the pipeline and take a look at what’s happening under the hood.
In the example above, the pipeline contains a UNet2DModel model and a DDPMScheduler. The pipeline denoises an image by taking random noise the size of the desired output and passing it through the model several times. At each timestep, the model predicts the noise residual and the scheduler uses it to predict a less noisy image. The pipeline repeats this process until it reaches the end of the specified number of inference steps.
To recreate the pipeline with the model and scheduler separately, let’s write our own denoising process.
Load the model and scheduler:
Copied
Set the number of timesteps to run the denoising process for:
Copied
Setting the scheduler timesteps creates a tensor with evenly spaced elements in it, 50 in this example. Each element corresponds to a timestep at which the model denoises an image. When you create the denoising loop later, you’ll iterate over this tensor to denoise an image:
Copied
Create some random noise with the same shape as the desired output:
Copied
Now write a loop to iterate over the timesteps. At each timestep, the model does a UNet2DModel.forward() pass and returns the noisy residual. The scheduler’s step() method takes the noisy residual, timestep, and input and it predicts the image at the previous timestep. This output becomes the next input to the model in the denoising loop, and it’ll repeat until it reaches the end of the timesteps
array.
Copied
This is the entire denoising process, and you can use this same pattern to write any diffusion system.
The last step is to convert the denoised output into an image:
Copied
In the next section, you’ll put your skills to the test and breakdown the more complex Stable Diffusion pipeline. The steps are more or less the same. You’ll initialize the necessary components, and set the number of timesteps to create a timestep
array. The timestep
array is used in the denoising loop, and for each element in this array, the model predicts a less noisy image. The denoising loop iterates over the timestep
’s, and at each timestep, it outputs a noisy residual and the scheduler uses it to predict a less noisy image at the previous timestep. This process is repeated until you reach the end of the timestep
array.
Let’s try it out!
Stable Diffusion is a text-to-image latent diffusion model. It is called a latent diffusion model because it works with a lower-dimensional representation of the image instead of the actual pixel space, which makes it more memory efficient. The encoder compresses the image into a smaller representation, and a decoder to convert the compressed representation back into an image. For text-to-image models, you’ll need a tokenizer and an encoder to generate text embeddings. From the previous example, you already know you need a UNet model and a scheduler.
As you can see, this is already more complex than the DDPM pipeline which only contains a UNet model. The Stable Diffusion model has three separate pretrained models.
💡 Read the How does Stable Diffusion work? blog for more details about how the VAE, UNet, and text encoder models.
Now that you know what you need for the Stable Diffusion pipeline, load all these components with the from_pretrained() method. You can find them in the pretrained runwayml/stable-diffusion-v1-5
checkpoint, and each component is stored in a separate subfolder:
Copied
Instead of the default PNDMScheduler, exchange it for the UniPCMultistepScheduler to see how easy it is to plug a different scheduler in:
Copied
To speed up inference, move the models to a GPU since, unlike the scheduler, they have trainable weights:
Copied
The next step is to tokenize the text to generate embeddings. The text is used to condition the UNet model and steer the diffusion process towards something that resembles the input prompt.
💡 The guidance_scale
parameter determines how much weight should be given to the prompt when generating an image.
Feel free to choose any prompt you like if you want to generate something else!
Copied
Tokenize the text and generate the embeddings from the prompt:
Copied
You’ll also need to generate the unconditional text embeddings which are the embeddings for the padding token. These need to have the same shape (batch_size
and seq_length
) as the conditional text_embeddings
:
Copied
Let’s concatenate the conditional and unconditional embeddings into a batch to avoid doing two forward passes:
Copied
Next, generate some initial random noise as a starting point for the diffusion process. This is the latent representation of the image, and it’ll be gradually denoised. At this point, the latent
image is smaller than the final image size but that’s okay though because the model will transform it into the final 512x512 image dimensions later.
💡 The height and width are divided by 8 because the vae
model has 3 down-sampling layers. You can check by running the following:
Copied
Copied
Start by scaling the input with the initial noise distribution, sigma, the noise scale value, which is required for improved schedulers like UniPCMultistepScheduler:
Copied
The last step is to create the denoising loop that’ll progressively transform the pure noise in latents
to an image described by your prompt. Remember, the denoising loop needs to do three things:
Set the scheduler’s timesteps to use during denoising.
Iterate over the timesteps.
At each timestep, call the UNet model to predict the noise residual and pass it to the scheduler to compute the previous noisy sample.
Copied
The final step is to use the vae
to decode the latent representation into an image and get the decoded output with sample
:
Copied
Lastly, convert the image to a PIL.Image
to see your generated image!
Copied
From basic to complex pipelines, you’ve seen that all you really need to write your own diffusion system is a denoising loop. The loop should set the scheduler’s timesteps, iterate over them, and alternate between calling the UNet model to predict the noise residual and passing it to the scheduler to compute the previous noisy sample.
This is really what 🧨 Diffusers is designed for: to make it intuitive and easy to write your own diffusion system using models and schedulers.
For your next steps, feel free to:
Learn how to build and contribute a pipeline to 🧨 Diffusers. We can’t wait and see what you’ll come up with!
Explore existing pipelines in the library, and see if you can deconstruct and build a pipeline from scratch using the models and schedulers separately.