source
stringclasses 273
values | url
stringlengths 47
172
| file_type
stringclasses 1
value | chunk
stringlengths 1
512
| chunk_id
stringlengths 5
9
|
---|---|---|---|---|
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/api/schedulers/score_sde_ve.md | https://huggingface.co./docs/diffusers/en/api/schedulers/score_sde_ve/#scoresdevescheduler | .md | sigma_max (`float`, defaults to 1348.0):
The maximum value used for the range of continuous timesteps passed into the model.
sampling_eps (`float`, defaults to 1e-5):
The end value of sampling where timesteps decrease progressively from 1 to epsilon.
correct_steps (`int`, defaults to 1):
The number of correction steps performed on a produced sample. | 266_2_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/api/schedulers/score_sde_ve.md | https://huggingface.co./docs/diffusers/en/api/schedulers/score_sde_ve/#sdeveoutput | .md | SdeVeOutput
Output class for the scheduler's `step` function output.
Args:
prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
denoising loop.
prev_sample_mean (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
Mean averaged `prev_sample` over previous timesteps. | 266_3_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/ | .md | <!--Copyright 2024 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | 267_0_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/ | .md | an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
-->
[[open-in-colab]] | 267_0_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-a-diffusion-model | .md | 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](https://huggingface.co./search/full-text?q=unconditional-image-generation&type=model), but if you can't find one you like, you can always train your own! | 267_1_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-a-diffusion-model | .md | This tutorial will teach you how to train a [`UNet2DModel`] from scratch on a subset of the [Smithsonian Butterflies](https://huggingface.co./datasets/huggan/smithsonian_butterflies_subset) dataset to generate your own 🦋 butterflies 🦋.
<Tip> | 267_1_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-a-diffusion-model | .md | <Tip>
💡 This training tutorial is based on the [Training with 🧨 Diffusers](https://colab.research.google.com/github/huggingface/notebooks/blob/main/diffusers/training_example.ipynb) notebook. For additional details and context about diffusion models like how they work, check out the notebook!
</Tip> | 267_1_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-a-diffusion-model | .md | </Tip>
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](https://www.tensorflow.org/tensorboard) to visualize training metrics (you can also use [Weights & Biases](https://docs.wandb.ai/) to track your training).
```py
# uncomment to install the necessary libraries in Colab
#!pip install diffusers[training]
``` | 267_1_3 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-a-diffusion-model | .md | ```py
# 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 Hugging Face account (create one [here](https://hf.co/join) 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.
```py
>>> from huggingface_hub import notebook_login | 267_1_4 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-a-diffusion-model | .md | >>> notebook_login()
```
Or login in from the terminal:
```bash
huggingface-cli login
```
Since the model checkpoints are quite large, install [Git-LFS](https://git-lfs.com/) to version these large files:
```bash
!sudo apt -qq install git-lfs
!git config --global credential.helper store
``` | 267_1_5 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#training-configuration | .md | For convenience, create a `TrainingConfig` class containing the training hyperparameters (feel free to adjust them):
```py
>>> from dataclasses import dataclass | 267_2_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#training-configuration | .md | >>> @dataclass
... class TrainingConfig:
... image_size = 128 # the generated image resolution
... train_batch_size = 16
... eval_batch_size = 16 # how many images to sample during evaluation
... num_epochs = 50
... gradient_accumulation_steps = 1
... learning_rate = 1e-4
... lr_warmup_steps = 500
... save_image_epochs = 10
... save_model_epochs = 30
... mixed_precision = "fp16" # `no` for float32, `fp16` for automatic mixed precision | 267_2_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#training-configuration | .md | ... save_model_epochs = 30
... mixed_precision = "fp16" # `no` for float32, `fp16` for automatic mixed precision
... output_dir = "ddpm-butterflies-128" # the model name locally and on the HF Hub | 267_2_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#training-configuration | .md | ... push_to_hub = True # whether to upload the saved model to the HF Hub
... hub_model_id = "<your-username>/<my-awesome-model>" # the name of the repository to create on the HF Hub
... hub_private_repo = None
... overwrite_output_dir = True # overwrite the old model when re-running the notebook
... seed = 0
>>> config = TrainingConfig()
``` | 267_2_3 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#load-the-dataset | .md | You can easily load the [Smithsonian Butterflies](https://huggingface.co./datasets/huggan/smithsonian_butterflies_subset) dataset with the 🤗 Datasets library:
```py
>>> from datasets import load_dataset | 267_3_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#load-the-dataset | .md | >>> config.dataset_name = "huggan/smithsonian_butterflies_subset"
>>> dataset = load_dataset(config.dataset_name, split="train")
```
<Tip> | 267_3_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#load-the-dataset | .md | >>> dataset = load_dataset(config.dataset_name, split="train")
```
<Tip>
💡 You can find additional datasets from the [HugGan Community Event](https://huggingface.co./huggan) or you can use your own dataset by creating a local [`ImageFolder`](https://huggingface.co./docs/datasets/image_dataset#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.
</Tip> | 267_3_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#load-the-dataset | .md | </Tip>
🤗 Datasets uses the [`~datasets.Image`] feature to automatically decode the image data and load it as a [`PIL.Image`](https://pillow.readthedocs.io/en/stable/reference/Image.html) which we can visualize:
```py
>>> import matplotlib.pyplot as plt | 267_3_3 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#load-the-dataset | .md | >>> fig, axs = plt.subplots(1, 4, figsize=(16, 4))
>>> for i, image in enumerate(dataset[:4]["image"]):
... axs[i].imshow(image)
... axs[i].set_axis_off()
>>> fig.show()
```
<div class="flex justify-center">
<img src="https://huggingface.co./datasets/huggingface/documentation-images/resolve/main/diffusers/butterflies_ds.png"/>
</div>
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`. | 267_3_4 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#load-the-dataset | .md | * `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.
```py
>>> from torchvision import transforms | 267_3_5 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#load-the-dataset | .md | >>> preprocess = transforms.Compose(
... [
... transforms.Resize((config.image_size, config.image_size)),
... transforms.RandomHorizontalFlip(),
... transforms.ToTensor(),
... transforms.Normalize([0.5], [0.5]),
... ]
... )
```
Use 🤗 Datasets' [`~datasets.Dataset.set_transform`] method to apply the `preprocess` function on the fly during training:
```py
>>> def transform(examples): | 267_3_6 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#load-the-dataset | .md | ```py
>>> def transform(examples):
... images = [preprocess(image.convert("RGB")) for image in examples["image"]]
... return {"images": images} | 267_3_7 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#load-the-dataset | .md | >>> dataset.set_transform(transform)
```
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](https://pytorch.org/docs/stable/data#torch.utils.data.DataLoader) for training!
```py
>>> import torch
>>> train_dataloader = torch.utils.data.DataLoader(dataset, batch_size=config.train_batch_size, shuffle=True)
``` | 267_3_8 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#create-a-unet2dmodel | .md | Pretrained models in 🧨 Diffusers are easily created from their model class with the parameters you want. For example, to create a [`UNet2DModel`]:
```py
>>> from diffusers import UNet2DModel | 267_4_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#create-a-unet2dmodel | .md | >>> model = UNet2DModel(
... sample_size=config.image_size, # the target image resolution
... in_channels=3, # the number of input channels, 3 for RGB images
... out_channels=3, # the number of output channels
... layers_per_block=2, # how many ResNet layers to use per UNet block
... block_out_channels=(128, 128, 256, 256, 512, 512), # the number of output channels for each UNet block
... down_block_types=(
... "DownBlock2D", # a regular ResNet downsampling block | 267_4_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#create-a-unet2dmodel | .md | ... down_block_types=(
... "DownBlock2D", # a regular ResNet downsampling block
... "DownBlock2D",
... "DownBlock2D",
... "DownBlock2D",
... "AttnDownBlock2D", # a ResNet downsampling block with spatial self-attention
... "DownBlock2D",
... ),
... up_block_types=(
... "UpBlock2D", # a regular ResNet upsampling block
... "AttnUpBlock2D", # a ResNet upsampling block with spatial self-attention
... "UpBlock2D", | 267_4_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#create-a-unet2dmodel | .md | ... "AttnUpBlock2D", # a ResNet upsampling block with spatial self-attention
... "UpBlock2D",
... "UpBlock2D",
... "UpBlock2D",
... "UpBlock2D",
... ),
... )
```
It is often a good idea to quickly check the sample image shape matches the model output shape:
```py
>>> sample_image = dataset[0]["images"].unsqueeze(0)
>>> print("Input shape:", sample_image.shape)
Input shape: torch.Size([1, 3, 128, 128]) | 267_4_3 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#create-a-unet2dmodel | .md | >>> print("Output shape:", model(sample_image, timestep=0).sample.shape)
Output shape: torch.Size([1, 3, 128, 128])
```
Great! Next, you'll need a scheduler to add some noise to the image. | 267_4_4 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#create-a-scheduler | .md | 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:
```py | 267_5_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#create-a-scheduler | .md | ```py
>>> import torch
>>> from PIL import Image
>>> from diffusers import DDPMScheduler | 267_5_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#create-a-scheduler | .md | >>> noise_scheduler = DDPMScheduler(num_train_timesteps=1000)
>>> noise = torch.randn(sample_image.shape)
>>> timesteps = torch.LongTensor([50])
>>> noisy_image = noise_scheduler.add_noise(sample_image, noise, timesteps) | 267_5_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#create-a-scheduler | .md | >>> Image.fromarray(((noisy_image.permute(0, 2, 3, 1) + 1.0) * 127.5).type(torch.uint8).numpy()[0])
```
<div class="flex justify-center">
<img src="https://huggingface.co./datasets/huggingface/documentation-images/resolve/main/diffusers/noisy_butterfly.png"/>
</div>
The training objective of the model is to predict the noise added to the image. The loss at this step can be calculated by:
```py
>>> import torch.nn.functional as F | 267_5_3 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#create-a-scheduler | .md | >>> noise_pred = model(noisy_image, timesteps).sample
>>> loss = F.mse_loss(noise_pred, noise)
``` | 267_5_4 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | 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:
```py
>>> from diffusers.optimization import get_cosine_schedule_with_warmup | 267_6_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | >>> optimizer = torch.optim.AdamW(model.parameters(), lr=config.learning_rate)
>>> lr_scheduler = get_cosine_schedule_with_warmup(
... optimizer=optimizer,
... num_warmup_steps=config.lr_warmup_steps,
... num_training_steps=(len(train_dataloader) * config.num_epochs),
... )
```
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:
```py
>>> from diffusers import DDPMPipeline | 267_6_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | ```py
>>> from diffusers import DDPMPipeline
>>> from diffusers.utils import make_image_grid
>>> import os | 267_6_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | >>> def evaluate(config, epoch, pipeline):
... # Sample some images from random noise (this is the backward diffusion process).
... # The default pipeline output type is `List[PIL.Image]`
... images = pipeline(
... batch_size=config.eval_batch_size,
... generator=torch.Generator(device='cpu').manual_seed(config.seed), # Use a separate torch generator to avoid rewinding the random state of the main training loop
... ).images | 267_6_3 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | ... # Make a grid out of the images
... image_grid = make_image_grid(images, rows=4, cols=4) | 267_6_4 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | ... # Save the images
... test_dir = os.path.join(config.output_dir, "samples")
... os.makedirs(test_dir, exist_ok=True)
... image_grid.save(f"{test_dir}/{epoch:04d}.png")
```
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> | 267_6_5 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | <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. 🤗
</Tip>
```py
>>> from accelerate import Accelerator
>>> from huggingface_hub import create_repo, upload_folder | 267_6_6 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | </Tip>
```py
>>> from accelerate import Accelerator
>>> from huggingface_hub import create_repo, upload_folder
>>> from tqdm.auto import tqdm
>>> from pathlib import Path
>>> import os | 267_6_7 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | >>> def train_loop(config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler):
... # Initialize accelerator and tensorboard logging
... accelerator = Accelerator(
... mixed_precision=config.mixed_precision,
... gradient_accumulation_steps=config.gradient_accumulation_steps,
... log_with="tensorboard",
... project_dir=os.path.join(config.output_dir, "logs"),
... )
... if accelerator.is_main_process: | 267_6_8 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | ... project_dir=os.path.join(config.output_dir, "logs"),
... )
... if accelerator.is_main_process:
... if config.output_dir is not None:
... os.makedirs(config.output_dir, exist_ok=True)
... if config.push_to_hub:
... repo_id = create_repo(
... repo_id=config.hub_model_id or Path(config.output_dir).name, exist_ok=True
... ).repo_id
... accelerator.init_trackers("train_example") | 267_6_9 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | ... # Prepare everything
... # There is no specific order to remember, you just need to unpack the
... # objects in the same order you gave them to the prepare method.
... model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
... model, optimizer, train_dataloader, lr_scheduler
... )
... global_step = 0 | 267_6_10 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | ... global_step = 0
... # Now you train the model
... for epoch in range(config.num_epochs):
... progress_bar = tqdm(total=len(train_dataloader), disable=not accelerator.is_local_main_process)
... progress_bar.set_description(f"Epoch {epoch}") | 267_6_11 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | ... for step, batch in enumerate(train_dataloader):
... clean_images = batch["images"]
... # Sample noise to add to the images
... noise = torch.randn(clean_images.shape, device=clean_images.device)
... bs = clean_images.shape[0] | 267_6_12 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | ... # Sample a random timestep for each image
... timesteps = torch.randint(
... 0, noise_scheduler.config.num_train_timesteps, (bs,), device=clean_images.device,
... dtype=torch.int64
... )
... # Add noise to the clean images according to the noise magnitude at each timestep
... # (this is the forward diffusion process)
... noisy_images = noise_scheduler.add_noise(clean_images, noise, timesteps) | 267_6_13 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | ... with accelerator.accumulate(model):
... # Predict the noise residual
... noise_pred = model(noisy_images, timesteps, return_dict=False)[0]
... loss = F.mse_loss(noise_pred, noise)
... accelerator.backward(loss) | 267_6_14 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | ... if accelerator.sync_gradients:
... accelerator.clip_grad_norm_(model.parameters(), 1.0)
... optimizer.step()
... lr_scheduler.step()
... optimizer.zero_grad() | 267_6_15 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | ... progress_bar.update(1)
... logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step}
... progress_bar.set_postfix(**logs)
... accelerator.log(logs, step=global_step)
... global_step += 1 | 267_6_16 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | ... # After each epoch you optionally sample some demo images with evaluate() and save the model
... if accelerator.is_main_process:
... pipeline = DDPMPipeline(unet=accelerator.unwrap_model(model), scheduler=noise_scheduler)
... if (epoch + 1) % config.save_image_epochs == 0 or epoch == config.num_epochs - 1:
... evaluate(config, epoch, pipeline) | 267_6_17 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | ... if (epoch + 1) % config.save_model_epochs == 0 or epoch == config.num_epochs - 1:
... if config.push_to_hub:
... upload_folder(
... repo_id=repo_id,
... folder_path=config.output_dir,
... commit_message=f"Epoch {epoch}",
... ignore_patterns=["step_*", "epoch_*"],
... )
... else: | 267_6_18 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | ... ignore_patterns=["step_*", "epoch_*"],
... )
... else:
... pipeline.save_pretrained(config.output_dir)
``` | 267_6_19 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | ... )
... else:
... pipeline.save_pretrained(config.output_dir)
```
Phew, that was quite a bit of code! But you're finally ready to launch the training with 🤗 Accelerate's [`~accelerate.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:
```py
>>> from accelerate import notebook_launcher | 267_6_20 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | >>> args = (config, model, noise_scheduler, optimizer, train_dataloader, lr_scheduler)
>>> notebook_launcher(train_loop, args, num_processes=1)
```
Once training is complete, take a look at the final 🦋 images 🦋 generated by your diffusion model!
```py
>>> import glob | 267_6_21 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#train-the-model | .md | >>> sample_images = sorted(glob.glob(f"{config.output_dir}/samples/*.png"))
>>> Image.open(sample_images[-1])
```
<div class="flex justify-center">
<img src="https://huggingface.co./datasets/huggingface/documentation-images/resolve/main/diffusers/butterflies_final.png"/>
</div> | 267_6_22 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#next-steps | .md | 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](../training/overview) page. Here are some examples of what you can learn:
* [Textual Inversion](../training/text_inversion), an algorithm that teaches a model a specific visual concept and integrates it into the generated image. | 267_7_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/basic_training.md | https://huggingface.co./docs/diffusers/en/tutorials/basic_training/#next-steps | .md | * [DreamBooth](../training/dreambooth), a technique for generating personalized images of a subject given several input images of the subject.
* [Guide](../training/text2image) to finetuning a Stable Diffusion model on your own dataset.
* [Guide](../training/lora) to using LoRA, a memory-efficient technique for finetuning really large models faster. | 267_7_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/tutorial_overview.md | https://huggingface.co./docs/diffusers/en/tutorials/tutorial_overview/ | .md | <!--Copyright 2024 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | 268_0_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/tutorial_overview.md | https://huggingface.co./docs/diffusers/en/tutorials/tutorial_overview/ | .md | an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
--> | 268_0_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/tutorial_overview.md | https://huggingface.co./docs/diffusers/en/tutorials/tutorial_overview/#overview | .md | Welcome to 🧨 Diffusers! If you're new to diffusion models and generative AI, and want to learn more, then you've come to the right place. These beginner-friendly tutorials are designed to provide a gentle introduction to diffusion models and help you understand the library fundamentals - the core components and how 🧨 Diffusers is meant to be used. | 268_1_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/tutorial_overview.md | https://huggingface.co./docs/diffusers/en/tutorials/tutorial_overview/#overview | .md | You'll learn how to use a pipeline for inference to rapidly generate things, and then deconstruct that pipeline to really understand how to use the library as a modular toolbox for building your own diffusion systems. In the next lesson, you'll learn how to train your own diffusion model to generate what you want.
After completing the tutorials, you'll have gained the necessary skills to start exploring the library on your own and see how to use it for your own projects and applications. | 268_1_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/tutorial_overview.md | https://huggingface.co./docs/diffusers/en/tutorials/tutorial_overview/#overview | .md | Feel free to join our community on [Discord](https://discord.com/invite/JfAtkvEtRb) or the [forums](https://discuss.huggingface.co/c/discussion-related-to-httpsgithubcomhuggingfacediffusers/63) to connect and collaborate with other users and developers!
Let's start diffusing! 🧨 | 268_1_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/ | .md | <!--Copyright 2024 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | 269_0_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/ | .md | an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
--> | 269_0_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#accelerate-inference-of-text-to-image-diffusion-models | .md | Diffusion models are slower than their GAN counterparts because of the iterative and sequential reverse diffusion process. There are several techniques that can address this limitation such as progressive timestep distillation ([LCM LoRA](../using-diffusers/inference_with_lcm_lora)), model compression ([SSD-1B](https://huggingface.co./segmind/SSD-1B)), and reusing adjacent features of the denoiser ([DeepCache](../optimization/deepcache)). | 269_1_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#accelerate-inference-of-text-to-image-diffusion-models | .md | However, you don't necessarily need to use these techniques to speed up inference. With PyTorch 2 alone, you can accelerate the inference latency of text-to-image diffusion pipelines by up to 3x. This tutorial will show you how to progressively apply the optimizations found in PyTorch 2 to reduce inference latency. You'll use the [Stable Diffusion XL (SDXL)](../using-diffusers/sdxl) pipeline in this tutorial, but these techniques are applicable to other text-to-image diffusion pipelines too. | 269_1_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#accelerate-inference-of-text-to-image-diffusion-models | .md | Make sure you're using the latest version of Diffusers:
```bash
pip install -U diffusers
```
Then upgrade the other required libraries too:
```bash
pip install -U transformers accelerate peft
```
Install [PyTorch nightly](https://pytorch.org/) to benefit from the latest and fastest kernels:
```bash
pip3 install --pre torch --index-url https://download.pytorch.org/whl/nightly/cu121
```
> [!TIP]
> The results reported below are from a 80GB 400W A100 with its clock rate set to the maximum. | 269_1_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#accelerate-inference-of-text-to-image-diffusion-models | .md | ```
> [!TIP]
> The results reported below are from a 80GB 400W A100 with its clock rate set to the maximum.
> If you're interested in the full benchmarking code, take a look at [huggingface/diffusion-fast](https://github.com/huggingface/diffusion-fast). | 269_1_3 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#baseline | .md | Let's start with a baseline. Disable reduced precision and the [`scaled_dot_product_attention` (SDPA)](../optimization/torch2.0#scaled-dot-product-attention) function which is automatically used by Diffusers:
```python
from diffusers import StableDiffusionXLPipeline
# Load the pipeline in full-precision and place its model components on CUDA.
pipe = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0"
).to("cuda") | 269_2_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#baseline | .md | # Run the attention ops without SDPA.
pipe.unet.set_default_attn_processor()
pipe.vae.set_default_attn_processor()
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
image = pipe(prompt, num_inference_steps=30).images[0]
```
This default setup takes 7.36 seconds.
<div class="flex justify-center">
<img src="https://huggingface.co./datasets/sayakpaul/sample-datasets/resolve/main/progressive-acceleration-sdxl/SDXL%2C_Batch_Size%3A_1%2C_Steps%3A_30_0.png" width=500>
</div> | 269_2_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#bfloat16 | .md | Enable the first optimization, reduced precision or more specifically bfloat16. There are several benefits of using reduced precision:
* Using a reduced numerical precision (such as float16 or bfloat16) for inference doesn’t affect the generation quality but significantly improves latency.
* The benefits of using bfloat16 compared to float16 are hardware dependent, but modern GPUs tend to favor bfloat16. | 269_3_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#bfloat16 | .md | * The benefits of using bfloat16 compared to float16 are hardware dependent, but modern GPUs tend to favor bfloat16.
* bfloat16 is much more resilient when used with quantization compared to float16, but more recent versions of the quantization library ([torchao](https://github.com/pytorch-labs/ao)) we used don't have numerical issues with float16.
```python
from diffusers import StableDiffusionXLPipeline
import torch | 269_3_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#bfloat16 | .md | pipe = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.bfloat16
).to("cuda")
# Run the attention ops without SDPA.
pipe.unet.set_default_attn_processor()
pipe.vae.set_default_attn_processor() | 269_3_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#bfloat16 | .md | prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
image = pipe(prompt, num_inference_steps=30).images[0]
```
bfloat16 reduces the latency from 7.36 seconds to 4.63 seconds.
<div class="flex justify-center">
<img src="https://huggingface.co./datasets/sayakpaul/sample-datasets/resolve/main/progressive-acceleration-sdxl/SDXL%2C_Batch_Size%3A_1%2C_Steps%3A_30_1.png" width=500>
</div>
<Tip> | 269_3_3 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#bfloat16 | .md | </div>
<Tip>
In our later experiments with float16, recent versions of torchao do not incur numerical problems from float16.
</Tip>
Take a look at the [Speed up inference](../optimization/fp16) guide to learn more about running inference with reduced precision. | 269_3_4 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#sdpa | .md | Attention blocks are intensive to run. But with PyTorch's [`scaled_dot_product_attention`](../optimization/torch2.0#scaled-dot-product-attention) function, it is a lot more efficient. This function is used by default in Diffusers so you don't need to make any changes to the code.
```python
from diffusers import StableDiffusionXLPipeline
import torch
pipe = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.bfloat16
).to("cuda") | 269_4_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#sdpa | .md | prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
image = pipe(prompt, num_inference_steps=30).images[0]
```
Scaled dot product attention improves the latency from 4.63 seconds to 3.31 seconds.
<div class="flex justify-center">
<img src="https://huggingface.co./datasets/sayakpaul/sample-datasets/resolve/main/progressive-acceleration-sdxl/SDXL%2C_Batch_Size%3A_1%2C_Steps%3A_30_2.png" width=500>
</div> | 269_4_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#torchcompile | .md | PyTorch 2 includes `torch.compile` which uses fast and optimized kernels. In Diffusers, the UNet and VAE are usually compiled because these are the most compute-intensive modules. First, configure a few compiler flags (refer to the [full list](https://github.com/pytorch/pytorch/blob/main/torch/_inductor/config.py) for more options):
```python
from diffusers import StableDiffusionXLPipeline
import torch | 269_5_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#torchcompile | .md | torch._inductor.config.conv_1x1_as_mm = True
torch._inductor.config.coordinate_descent_tuning = True
torch._inductor.config.epilogue_fusion = False
torch._inductor.config.coordinate_descent_check_all_directions = True
```
It is also important to change the UNet and VAE's memory layout to "channels_last" when compiling them to ensure maximum speed.
```python
pipe.unet.to(memory_format=torch.channels_last)
pipe.vae.to(memory_format=torch.channels_last)
```
Now compile and perform inference: | 269_5_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#torchcompile | .md | pipe.vae.to(memory_format=torch.channels_last)
```
Now compile and perform inference:
```python
# Compile the UNet and VAE.
pipe.unet = torch.compile(pipe.unet, mode="max-autotune", fullgraph=True)
pipe.vae.decode = torch.compile(pipe.vae.decode, mode="max-autotune", fullgraph=True) | 269_5_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#torchcompile | .md | prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" | 269_5_3 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#torchcompile | .md | # First call to `pipe` is slow, subsequent ones are faster.
image = pipe(prompt, num_inference_steps=30).images[0]
```
`torch.compile` offers different backends and modes. For maximum inference speed, use "max-autotune" for the inductor backend. “max-autotune” uses CUDA graphs and optimizes the compilation graph specifically for latency. CUDA graphs greatly reduces the overhead of launching GPU operations by using a mechanism to launch multiple GPU operations through a single CPU operation. | 269_5_4 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#torchcompile | .md | Using SDPA attention and compiling both the UNet and VAE cuts the latency from 3.31 seconds to 2.54 seconds.
<div class="flex justify-center">
<img src="https://huggingface.co./datasets/sayakpaul/sample-datasets/resolve/main/progressive-acceleration-sdxl/SDXL%2C_Batch_Size%3A_1%2C_Steps%3A_30_3.png" width=500>
</div>
> [!TIP] | 269_5_5 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#torchcompile | .md | </div>
> [!TIP]
> From PyTorch 2.3.1, you can control the caching behavior of `torch.compile()`. This is particularly beneficial for compilation modes like `"max-autotune"` which performs a grid-search over several compilation flags to find the optimal configuration. Learn more in the [Compile Time Caching in torch.compile](https://pytorch.org/tutorials/recipes/torch_compile_caching_tutorial.html) tutorial. | 269_5_6 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#prevent-graph-breaks | .md | Specifying `fullgraph=True` ensures there are no graph breaks in the underlying model to take full advantage of `torch.compile` without any performance degradation. For the UNet and VAE, this means changing how you access the return variables.
```diff
- latents = unet(
- latents, timestep=timestep, encoder_hidden_states=prompt_embeds
-).sample
+ latents = unet(
+ latents, timestep=timestep, encoder_hidden_states=prompt_embeds, return_dict=False
+)[0]
``` | 269_6_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#remove-gpu-sync-after-compilation | .md | During the iterative reverse diffusion process, the `step()` function is [called](https://github.com/huggingface/diffusers/blob/1d686bac8146037e97f3fd8c56e4063230f71751/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py#L1228) on the scheduler each time after the denoiser predicts the less noisy latent embeddings. Inside `step()`, the `sigmas` variable is | 269_7_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#remove-gpu-sync-after-compilation | .md | the scheduler each time after the denoiser predicts the less noisy latent embeddings. Inside `step()`, the `sigmas` variable is [indexed](https://github.com/huggingface/diffusers/blob/1d686bac8146037e97f3fd8c56e4063230f71751/src/diffusers/schedulers/scheduling_euler_discrete.py#L476) which when placed on the GPU, causes a communication sync between the CPU and GPU. This introduces latency and it becomes more evident when the denoiser has already been compiled. | 269_7_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#remove-gpu-sync-after-compilation | .md | But if the `sigmas` array always [stays on the CPU](https://github.com/huggingface/diffusers/blob/35a969d297cba69110d175ee79c59312b9f49e1e/src/diffusers/schedulers/scheduling_euler_discrete.py#L240), the CPU and GPU sync doesn’t occur and you don't get any latency. In general, any CPU and GPU communication sync should be none or be kept to a bare minimum because it can impact inference latency. | 269_7_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#combine-the-attention-blocks-projection-matrices | .md | The UNet and VAE in SDXL use Transformer-like blocks which consists of attention blocks and feed-forward blocks. | 269_8_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#combine-the-attention-blocks-projection-matrices | .md | In an attention block, the input is projected into three sub-spaces using three different projection matrices – Q, K, and V. These projections are performed separately on the input. But we can horizontally combine the projection matrices into a single matrix and perform the projection in one step. This increases the size of the matrix multiplications of the input projections and improves the impact of quantization.
You can combine the projection matrices with just a single line of code:
```python | 269_8_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#combine-the-attention-blocks-projection-matrices | .md | You can combine the projection matrices with just a single line of code:
```python
pipe.fuse_qkv_projections()
```
This provides a minor improvement from 2.54 seconds to 2.52 seconds.
<div class="flex justify-center">
<img src="https://huggingface.co./datasets/sayakpaul/sample-datasets/resolve/main/progressive-acceleration-sdxl/SDXL%2C_Batch_Size%3A_1%2C_Steps%3A_30_4.png" width=500>
</div>
<Tip warning={true}> | 269_8_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#combine-the-attention-blocks-projection-matrices | .md | </div>
<Tip warning={true}>
Support for [`~StableDiffusionXLPipeline.fuse_qkv_projections`] is limited and experimental. It's not available for many non-Stable Diffusion pipelines such as [Kandinsky](../using-diffusers/kandinsky). You can refer to this [PR](https://github.com/huggingface/diffusers/pull/6179) to get an idea about how to enable this for the other pipelines.
</Tip> | 269_8_3 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#dynamic-quantization | .md | You can also use the ultra-lightweight PyTorch quantization library, [torchao](https://github.com/pytorch-labs/ao) (commit SHA `54bcd5a10d0abbe7b0c045052029257099f83fd9`), to apply [dynamic int8 quantization](https://pytorch.org/tutorials/recipes/recipes/dynamic_quantization.html) to the UNet and VAE. Quantization adds additional conversion overhead to the model that is hopefully made up for by faster matmuls (dynamic quantization). If the matmuls are too small, these techniques may degrade performance. | 269_9_0 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#dynamic-quantization | .md | First, configure all the compiler tags:
```python
from diffusers import StableDiffusionXLPipeline
import torch | 269_9_1 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#dynamic-quantization | .md | # Notice the two new flags at the end.
torch._inductor.config.conv_1x1_as_mm = True
torch._inductor.config.coordinate_descent_tuning = True
torch._inductor.config.epilogue_fusion = False
torch._inductor.config.coordinate_descent_check_all_directions = True
torch._inductor.config.force_fuse_int_mm_with_mul = True
torch._inductor.config.use_mixed_mm = True
``` | 269_9_2 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#dynamic-quantization | .md | torch._inductor.config.force_fuse_int_mm_with_mul = True
torch._inductor.config.use_mixed_mm = True
```
Certain linear layers in the UNet and VAE don’t benefit from dynamic int8 quantization. You can filter out those layers with the [`dynamic_quant_filter_fn`](https://github.com/huggingface/diffusion-fast/blob/0f169640b1db106fe6a479f78c1ed3bfaeba3386/utils/pipeline_utils.py#L16) shown below.
```python
def dynamic_quant_filter_fn(mod, *args):
return (
isinstance(mod, torch.nn.Linear) | 269_9_3 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#dynamic-quantization | .md | ```python
def dynamic_quant_filter_fn(mod, *args):
return (
isinstance(mod, torch.nn.Linear)
and mod.in_features > 16
and (mod.in_features, mod.out_features)
not in [
(1280, 640),
(1920, 1280),
(1920, 640),
(2048, 1280),
(2048, 2560),
(2560, 1280),
(256, 128),
(2816, 1280),
(320, 640),
(512, 1536),
(512, 256),
(512, 512),
(640, 1280),
(640, 1920),
(640, 320),
(640, 5120),
(640, 640),
(960, 320),
(960, 640),
]
) | 269_9_4 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#dynamic-quantization | .md | def conv_filter_fn(mod, *args):
return (
isinstance(mod, torch.nn.Conv2d) and mod.kernel_size == (1, 1) and 128 in [mod.in_channels, mod.out_channels]
)
```
Finally, apply all the optimizations discussed so far:
```python
# SDPA + bfloat16.
pipe = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.bfloat16
).to("cuda")
# Combine attention projection matrices.
pipe.fuse_qkv_projections() | 269_9_5 |
/Users/nielsrogge/Documents/python_projecten/diffusers/docs/source/en/tutorials/fast_diffusion.md | https://huggingface.co./docs/diffusers/en/tutorials/fast_diffusion/#dynamic-quantization | .md | # Combine attention projection matrices.
pipe.fuse_qkv_projections()
# Change the memory layout.
pipe.unet.to(memory_format=torch.channels_last)
pipe.vae.to(memory_format=torch.channels_last)
```
Since dynamic quantization is only limited to the linear layers, convert the appropriate pointwise convolution layers into linear layers to maximize its benefit.
```python
from torchao import swap_conv2d_1x1_to_linear | 269_9_6 |