Skip to content

Commit b848d47

Browse files
authored
[docs] Memory optims (#11385)
* reformat * initial * fin * review * inference * feedback * feedback * feedback
1 parent d0c0239 commit b848d47

File tree

4 files changed

+433
-401
lines changed

4 files changed

+433
-401
lines changed

docs/source/en/_toctree.yml

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,6 @@
2121
title: Load LoRAs for inference
2222
- local: tutorials/fast_diffusion
2323
title: Accelerate inference of text-to-image diffusion models
24-
- local: tutorials/inference_with_big_models
25-
title: Working with big models
2624
title: Tutorials
2725
- sections:
2826
- local: using-diffusers/loading
@@ -180,7 +178,7 @@
180178
title: Quantization Methods
181179
- sections:
182180
- local: optimization/fp16
183-
title: Speed up inference
181+
title: Accelerate inference
184182
- local: optimization/memory
185183
title: Reduce memory usage
186184
- local: optimization/torch2.0

docs/source/en/optimization/fp16.md

Lines changed: 165 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -10,120 +10,211 @@ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express o
1010
specific language governing permissions and limitations under the License.
1111
-->
1212

13-
# Speed up inference
13+
# Accelerate inference
1414

15-
There are several ways to optimize Diffusers for inference speed, such as reducing the computational burden by lowering the data precision or using a lightweight distilled model. There are also memory-efficient attention implementations, [xFormers](xformers) and [scaled dot product attention](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) in PyTorch 2.0, that reduce memory usage which also indirectly speeds up inference. Different speed optimizations can be stacked together to get the fastest inference times.
15+
Diffusion models are slow at inference because generation is an iterative process where noise is gradually refined into an image or video over a certain number of "steps". To speedup this process, you can try experimenting with different [schedulers](../api/schedulers/overview), reduce the precision of the model weights for faster computations, use more memory-efficient attention mechanisms, and more.
1616

17-
> [!TIP]
18-
> Optimizing for inference speed or reduced memory usage can lead to improved performance in the other category, so you should try to optimize for both whenever you can. This guide focuses on inference speed, but you can learn more about lowering memory usage in the [Reduce memory usage](memory) guide.
17+
Combine and use these techniques together to make inference faster than using any single technique on its own.
18+
19+
This guide will go over how to accelerate inference.
1920

20-
The inference times below are obtained from generating a single 512x512 image from the prompt "a photo of an astronaut riding a horse on mars" with 50 DDIM steps on a NVIDIA A100.
21+
## Model data type
2122

22-
| setup | latency | speed-up |
23-
|----------|---------|----------|
24-
| baseline | 5.27s | x1 |
25-
| tf32 | 4.14s | x1.27 |
26-
| fp16 | 3.51s | x1.50 |
27-
| combined | 3.41s | x1.54 |
23+
The precision and data type of the model weights affect inference speed because a higher precision requires more memory to load and more time to perform the computations. PyTorch loads model weights in float32 or full precision by default, so changing the data type is a simple way to quickly get faster inference.
2824

29-
## TensorFloat-32
25+
<hfoptions id="dtypes">
26+
<hfoption id="bfloat16">
3027

31-
On Ampere and later CUDA devices, matrix multiplications and convolutions can use the [TensorFloat-32 (tf32)](https://blogs.nvidia.com/blog/2020/05/14/tensorfloat-32-precision-format/) mode for faster, but slightly less accurate computations. By default, PyTorch enables tf32 mode for convolutions but not matrix multiplications. Unless your network requires full float32 precision, we recommend enabling tf32 for matrix multiplications. It can significantly speed up computations with typically negligible loss in numerical accuracy.
28+
bfloat16 is similar to float16 but it is more robust to numerical errors. Hardware support for bfloat16 varies, but most modern GPUs are capable of supporting bfloat16.
3229

33-
```python
30+
```py
3431
import torch
32+
from diffusers import StableDiffusionXLPipeline
3533

36-
torch.backends.cuda.matmul.allow_tf32 = True
34+
pipeline = StableDiffusionXLPipeline.from_pretrained(
35+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.bfloat16
36+
).to("cuda")
37+
38+
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
39+
pipeline(prompt, num_inference_steps=30).images[0]
40+
```
41+
42+
</hfoption>
43+
<hfoption id="float16">
44+
45+
float16 is similar to bfloat16 but may be more prone to numerical errors.
46+
47+
```py
48+
import torch
49+
from diffusers import StableDiffusionXLPipeline
50+
51+
pipeline = StableDiffusionXLPipeline.from_pretrained(
52+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
53+
).to("cuda")
54+
55+
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
56+
pipeline(prompt, num_inference_steps=30).images[0]
3757
```
3858

39-
Learn more about tf32 in the [Mixed precision training](https://huggingface.co/docs/transformers/en/perf_train_gpu_one#tf32) guide.
59+
</hfoption>
60+
<hfoption id="TensorFloat-32">
4061

41-
## Half-precision weights
62+
[TensorFloat-32 (tf32)](https://blogs.nvidia.com/blog/2020/05/14/tensorfloat-32-precision-format/) mode is supported on NVIDIA Ampere GPUs and it computes the convolution and matrix multiplication operations in tf32. Storage and other operations are kept in float32. This enables significantly faster computations when combined with bfloat16 or float16.
4263

43-
To save GPU memory and get more speed, set `torch_dtype=torch.float16` to load and run the model weights directly with half-precision weights.
64+
PyTorch only enables tf32 mode for convolutions by default and you'll need to explicitly enable it for matrix multiplications.
4465

45-
```Python
66+
```py
4667
import torch
47-
from diffusers import DiffusionPipeline
68+
from diffusers import StableDiffusionXLPipeline
4869

49-
pipe = DiffusionPipeline.from_pretrained(
50-
"stable-diffusion-v1-5/stable-diffusion-v1-5",
51-
torch_dtype=torch.float16,
52-
use_safetensors=True,
53-
)
54-
pipe = pipe.to("cuda")
70+
torch.backends.cuda.matmul.allow_tf32 = True
71+
72+
pipeline = StableDiffusionXLPipeline.from_pretrained(
73+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.bfloat16
74+
).to("cuda")
75+
76+
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
77+
pipeline(prompt, num_inference_steps=30).images[0]
5578
```
5679

57-
> [!WARNING]
58-
> Don't use [torch.autocast](https://pytorch.org/docs/stable/amp.html#torch.autocast) in any of the pipelines as it can lead to black images and is always slower than pure float16 precision.
80+
Refer to the [mixed precision training](https://huggingface.co/docs/transformers/en/perf_train_gpu_one#mixed-precision) docs for more details.
5981

60-
## Distilled model
82+
</hfoption>
83+
</hfoptions>
6184

62-
You could also use a distilled Stable Diffusion model and autoencoder to speed up inference. During distillation, many of the UNet's residual and attention blocks are shed to reduce the model size by 51% and improve latency on CPU/GPU by 43%. The distilled model is faster and uses less memory while generating images of comparable quality to the full Stable Diffusion model.
85+
## Scaled dot product attention
6386

6487
> [!TIP]
65-
> Read the [Open-sourcing Knowledge Distillation Code and Weights of SD-Small and SD-Tiny](https://huggingface.co/blog/sd_distillation) blog post to learn more about how knowledge distillation training works to produce a faster, smaller, and cheaper generative model.
88+
> Memory-efficient attention optimizes for inference speed *and* [memory usage](./memory#memory-efficient-attention)!
6689
67-
The inference times below are obtained from generating 4 images from the prompt "a photo of an astronaut riding a horse on mars" with 25 PNDM steps on a NVIDIA A100. Each generation is repeated 3 times with the distilled Stable Diffusion v1.4 model by [Nota AI](https://hf.co/nota-ai).
90+
[Scaled dot product attention (SDPA)](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) implements several attention backends, [FlashAttention](https://github.com/Dao-AILab/flash-attention), [xFormers](https://github.com/facebookresearch/xformers), and a native C++ implementation. It automatically selects the most optimal backend for your hardware.
6891

69-
| setup | latency | speed-up |
70-
|------------------------------|---------|----------|
71-
| baseline | 6.37s | x1 |
72-
| distilled | 4.18s | x1.52 |
73-
| distilled + tiny autoencoder | 3.83s | x1.66 |
74-
75-
Let's load the distilled Stable Diffusion model and compare it against the original Stable Diffusion model.
92+
SDPA is enabled by default if you're using PyTorch >= 2.0 and no additional changes are required to your code. You could try experimenting with other attention backends though if you'd like to choose your own. The example below uses the [torch.nn.attention.sdpa_kernel](https://pytorch.org/docs/stable/generated/torch.nn.attention.sdpa_kernel.html) context manager to enable efficient attention.
7693

7794
```py
78-
from diffusers import StableDiffusionPipeline
95+
from torch.nn.attention import SDPBackend, sdpa_kernel
7996
import torch
97+
from diffusers import StableDiffusionXLPipeline
8098

81-
distilled = StableDiffusionPipeline.from_pretrained(
82-
"nota-ai/bk-sdm-small", torch_dtype=torch.float16, use_safetensors=True,
99+
pipeline = StableDiffusionXLPipeline.from_pretrained(
100+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.bfloat16
83101
).to("cuda")
84-
prompt = "a golden vase with different flowers"
85-
generator = torch.manual_seed(2023)
86-
image = distilled("a golden vase with different flowers", num_inference_steps=25, generator=generator).images[0]
87-
image
102+
103+
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
104+
105+
with sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION):
106+
image = pipeline(prompt, num_inference_steps=30).images[0]
88107
```
89108

90-
<div class="flex gap-4">
91-
<div>
92-
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/original_sd.png"/>
93-
<figcaption class="mt-2 text-center text-sm text-gray-500">original Stable Diffusion</figcaption>
94-
</div>
95-
<div>
96-
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/distilled_sd.png"/>
97-
<figcaption class="mt-2 text-center text-sm text-gray-500">distilled Stable Diffusion</figcaption>
98-
</div>
99-
</div>
109+
## torch.compile
100110

101-
### Tiny AutoEncoder
111+
[torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) accelerates inference by compiling PyTorch code and operations into optimized kernels. Diffusers typically compiles the more compute-intensive models like the UNet, transformer, or VAE.
102112

103-
To speed inference up even more, replace the autoencoder with a [distilled version](https://huggingface.co/sayakpaul/taesdxl-diffusers) of it.
113+
Enable the following compiler settings for maximum speed (refer to the [full list](https://github.com/pytorch/pytorch/blob/main/torch/_inductor/config.py) for more options).
104114

105115
```py
106116
import torch
107-
from diffusers import AutoencoderTiny, StableDiffusionPipeline
117+
from diffusers import StableDiffusionXLPipeline
118+
119+
torch._inductor.config.conv_1x1_as_mm = True
120+
torch._inductor.config.coordinate_descent_tuning = True
121+
torch._inductor.config.epilogue_fusion = False
122+
torch._inductor.config.coordinate_descent_check_all_directions = True
123+
```
124+
125+
Load and compile the UNet and VAE. There are several different modes you can choose from, but `"max-autotune"` optimizes for the fastest speed by compiling to a CUDA graph. CUDA graphs effectively reduces the overhead by launching multiple GPU operations through a single CPU operation.
108126

109-
distilled = StableDiffusionPipeline.from_pretrained(
110-
"nota-ai/bk-sdm-small", torch_dtype=torch.float16, use_safetensors=True,
127+
> [!TIP]
128+
> With 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.
129+
130+
Changing the memory layout to [channels_last](./memory#torchchannels_last) also optimizes memory and inference speed.
131+
132+
```py
133+
pipeline = StableDiffusionXLPipeline.from_pretrained(
134+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
111135
).to("cuda")
112-
distilled.vae = AutoencoderTiny.from_pretrained(
113-
"sayakpaul/taesd-diffusers", torch_dtype=torch.float16, use_safetensors=True,
136+
pipeline.unet.to(memory_format=torch.channels_last)
137+
pipeline.vae.to(memory_format=torch.channels_last)
138+
pipeline.unet = torch.compile(
139+
pipeline.unet, mode="max-autotune", fullgraph=True
140+
)
141+
pipeline.vae.decode = torch.compile(
142+
pipeline.vae.decode,
143+
mode="max-autotune",
144+
fullgraph=True
145+
)
146+
147+
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
148+
pipeline(prompt, num_inference_steps=30).images[0]
149+
```
150+
151+
Compilation is slow the first time, but once compiled, it is significantly faster. Try to only use the compiled pipeline on the same type of inference operations. Calling the compiled pipeline on a different image size retriggers compilation which is slow and inefficient.
152+
153+
### Graph breaks
154+
155+
It is important to specify `fullgraph=True` in torch.compile to ensure there are no graph breaks in the underlying model. This allows you to take advantage of torch.compile without any performance degradation. For the UNet and VAE, this changes how you access the return variables.
156+
157+
```diff
158+
- latents = unet(
159+
- latents, timestep=timestep, encoder_hidden_states=prompt_embeds
160+
-).sample
161+
162+
+ latents = unet(
163+
+ latents, timestep=timestep, encoder_hidden_states=prompt_embeds, return_dict=False
164+
+)[0]
165+
```
166+
167+
### GPU sync
168+
169+
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 makes a prediction, and the `sigmas` variable is [indexed](https://github.com/huggingface/diffusers/blob/1d686bac8146037e97f3fd8c56e4063230f71751/src/diffusers/schedulers/scheduling_euler_discrete.py#L476). When placed on the GPU, it introduces latency because of the communication sync between the CPU and GPU. It becomes more evident when the denoiser has already been compiled.
170+
171+
In general, the `sigmas` should [stay on the CPU](https://github.com/huggingface/diffusers/blob/35a969d297cba69110d175ee79c59312b9f49e1e/src/diffusers/schedulers/scheduling_euler_discrete.py#L240) to avoid the communication sync and latency.
172+
173+
## Dynamic quantization
174+
175+
[Dynamic quantization](https://pytorch.org/tutorials/recipes/recipes/dynamic_quantization.html) improves inference speed by reducing precision to enable faster math operations. This particular type of quantization determines how to scale the activations based on the data at runtime rather than using a fixed scaling factor. As a result, the scaling factor is more accurately aligned with the data.
176+
177+
The example below applies [dynamic int8 quantization](https://pytorch.org/tutorials/recipes/recipes/dynamic_quantization.html) to the UNet and VAE with the [torchao](../quantization/torchao) library.
178+
179+
> [!TIP]
180+
> Refer to our [torchao](../quantization/torchao) docs to learn more about how to use the Diffusers torchao integration.
181+
182+
Configure the compiler tags for maximum speed.
183+
184+
```py
185+
import torch
186+
from torchao import apply_dynamic_quant
187+
from diffusers import StableDiffusionXLPipeline
188+
189+
torch._inductor.config.conv_1x1_as_mm = True
190+
torch._inductor.config.coordinate_descent_tuning = True
191+
torch._inductor.config.epilogue_fusion = False
192+
torch._inductor.config.coordinate_descent_check_all_directions = True
193+
torch._inductor.config.force_fuse_int_mm_with_mul = True
194+
torch._inductor.config.use_mixed_mm = True
195+
```
196+
197+
Filter out some linear layers in the UNet and VAE which don't benefit from dynamic quantization with the [dynamic_quant_filter_fn](https://github.com/huggingface/diffusion-fast/blob/0f169640b1db106fe6a479f78c1ed3bfaeba3386/utils/pipeline_utils.py#L16).
198+
199+
```py
200+
pipeline = StableDiffusionXLPipeline.from_pretrained(
201+
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.bfloat16
114202
).to("cuda")
115203

116-
prompt = "a golden vase with different flowers"
117-
generator = torch.manual_seed(2023)
118-
image = distilled("a golden vase with different flowers", num_inference_steps=25, generator=generator).images[0]
119-
image
204+
apply_dynamic_quant(pipeline.unet, dynamic_quant_filter_fn)
205+
apply_dynamic_quant(pipeline.vae, dynamic_quant_filter_fn)
206+
207+
prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k"
208+
pipeline(prompt, num_inference_steps=30).images[0]
120209
```
121210

122-
<div class="flex justify-center">
123-
<div>
124-
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/distilled_sd_vae.png" />
125-
<figcaption class="mt-2 text-center text-sm text-gray-500">distilled Stable Diffusion + Tiny AutoEncoder</figcaption>
126-
</div>
127-
</div>
211+
## Fused projection matrices
128212

129-
More tiny autoencoder models for other Stable Diffusion models, like Stable Diffusion 3, are available from [madebyollin](https://huggingface.co/madebyollin).
213+
> [!WARNING]
214+
> The [fuse_qkv_projections](https://github.com/huggingface/diffusers/blob/58431f102cf39c3c8a569f32d71b2ea8caa461e1/src/diffusers/pipelines/pipeline_utils.py#L2034) method is experimental and support is limited to mostly Stable Diffusion pipelines. Take a look at this [PR](https://github.com/huggingface/diffusers/pull/6179) to learn more about how to enable it for other pipelines
215+
216+
An input is projected into three subspaces, represented by the projection matrices Q, K, and V, in an attention block. These projections are typically calculated separately, but you can horizontally combine these into a single matrix and perform the projection in a single step. It increases the size of the matrix multiplications of the input projections and also improves the impact of quantization.
217+
218+
```py
219+
pipeline.fuse_qkv_projections()
220+
```

0 commit comments

Comments
 (0)