Skip to content

Commit 0445d27

Browse files
authored
Merge branch 'main' into fix-vae-scaling-in-training
2 parents 82f6a69 + 3c8b67b commit 0445d27

File tree

16 files changed

+198
-116
lines changed

16 files changed

+198
-116
lines changed

docs/source/en/optimization/fp16.md

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -174,39 +174,36 @@ Feel free to open an issue if dynamic compilation doesn't work as expected for a
174174

175175
### Regional compilation
176176

177+
[Regional compilation](https://docs.pytorch.org/tutorials/recipes/regional_compilation.html) trims cold-start latency by only compiling the *small and frequently-repeated block(s)* of a model - typically a transformer layer - and enables reusing compiled artifacts for every subsequent occurrence.
178+
For many diffusion architectures, this delivers the same runtime speedups as full-graph compilation and reduces compile time by 8–10x.
177179

178-
[Regional compilation](https://docs.pytorch.org/tutorials/recipes/regional_compilation.html) trims cold-start latency by compiling **only the small, frequently-repeated block(s)** of a model, typically a Transformer layer, enabling reuse of compiled artifacts for every subsequent occurrence.
179-
For many diffusion architectures this delivers the *same* runtime speed-ups as full-graph compilation yet cuts compile time by **8–10 ×**.
180-
181-
To make this effortless, [`ModelMixin`] exposes [`ModelMixin.compile_repeated_blocks`] API, a helper that wraps `torch.compile` around any sub-modules you designate as repeatable:
180+
Use the [`~ModelMixin.compile_repeated_blocks`] method, a helper that wraps `torch.compile`, on any component such as the transformer model as shown below.
182181

183182
```py
184183
# pip install -U diffusers
185184
import torch
186185
from diffusers import StableDiffusionXLPipeline
187186

188-
pipe = StableDiffusionXLPipeline.from_pretrained(
187+
pipeline = StableDiffusionXLPipeline.from_pretrained(
189188
"stabilityai/stable-diffusion-xl-base-1.0",
190189
torch_dtype=torch.float16,
191190
).to("cuda")
192191

193-
# Compile only the repeated Transformer layers inside the UNet
194-
pipe.unet.compile_repeated_blocks(fullgraph=True)
192+
# compile only the repeated transformer layers inside the UNet
193+
pipeline.unet.compile_repeated_blocks(fullgraph=True)
195194
```
196195

197-
To enable a new model with regional compilation, add a `_repeated_blocks` attribute to your model class containing the class names (as strings) of the blocks you want compiled:
198-
196+
To enable regional compilation for a new model, add a `_repeated_blocks` attribute to a model class containing the class names (as strings) of the blocks you want to compile.
199197

200198
```py
201199
class MyUNet(ModelMixin):
202200
_repeated_blocks = ("Transformer2DModel",) # ← compiled by default
203201
```
204202

205-
For more examples, see the reference [PR](https://github.com/huggingface/diffusers/pull/11705).
206-
207-
**Relation to Accelerate compile_regions** There is also a separate API in [accelerate](https://huggingface.co/docs/accelerate/index) - [compile_regions](https://github.com/huggingface/accelerate/blob/273799c85d849a1954a4f2e65767216eb37fa089/src/accelerate/utils/other.py#L78). It takes a fully automatic approach: it walks the module, picks candidate blocks, then compiles the remaining graph separately. That hands-off experience is handy for quick experiments, but it also leaves fewer knobs when you want to fine-tune which blocks are compiled or adjust compilation flags.
208-
203+
> [!TIP]
204+
> For more regional compilation examples, see the reference [PR](https://github.com/huggingface/diffusers/pull/11705).
209205
206+
There is also a [compile_regions](https://github.com/huggingface/accelerate/blob/273799c85d849a1954a4f2e65767216eb37fa089/src/accelerate/utils/other.py#L78) method in [Accelerate](https://huggingface.co/docs/accelerate/index) that automatically selects candidate blocks in a model to compile. The remaining graph is compiled separately. This is useful for quick experiments because there aren't as many options for you to set which blocks to compile or adjust compilation flags.
210207

211208
```py
212209
# pip install -U accelerate
@@ -219,8 +216,8 @@ pipeline = StableDiffusionXLPipeline.from_pretrained(
219216
).to("cuda")
220217
pipeline.unet = compile_regions(pipeline.unet, mode="reduce-overhead", fullgraph=True)
221218
```
222-
`compile_repeated_blocks`, by contrast, is intentionally explicit. You list the repeated blocks once (via `_repeated_blocks`) and the helper compiles exactly those, nothing more. In practice this small dose of control hits a sweet spot for diffusion models: predictable behavior, easy reasoning about cache reuse, and still a one-liner for users.
223219

220+
[`~ModelMixin.compile_repeated_blocks`] is intentionally explicit. List the blocks to repeat in `_repeated_blocks` and the helper only compiles those blocks. It offers predictable behavior and easy reasoning about cache reuse in one line of code.
224221

225222
### Graph breaks
226223

@@ -296,3 +293,9 @@ An input is projected into three subspaces, represented by the projection matric
296293
```py
297294
pipeline.fuse_qkv_projections()
298295
```
296+
297+
## Resources
298+
299+
- Read the [Presenting Flux Fast: Making Flux go brrr on H100s](https://pytorch.org/blog/presenting-flux-fast-making-flux-go-brrr-on-h100s/) blog post to learn more about how you can combine all of these optimizations with [TorchInductor](https://docs.pytorch.org/docs/stable/torch.compiler.html) and [AOTInductor](https://docs.pytorch.org/docs/stable/torch.compiler_aot_inductor.html) for a ~2.5x speedup using recipes from [flux-fast](https://github.com/huggingface/flux-fast).
300+
301+
These recipes support AMD hardware and [Flux.1 Kontext Dev](https://huggingface.co/black-forest-labs/FLUX.1-Kontext-dev).

docs/source/en/optimization/speed-memory-optims.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ specific language governing permissions and limitations under the License.
1414

1515
Optimizing models often involves trade-offs between [inference speed](./fp16) and [memory-usage](./memory). For instance, while [caching](./cache) can boost inference speed, it also increases memory consumption since it needs to store the outputs of intermediate attention layers. A more balanced optimization strategy combines quantizing a model, [torch.compile](./fp16#torchcompile) and various [offloading methods](./memory#offloading).
1616

17+
> [!TIP]
18+
> Check the [torch.compile](./fp16#torchcompile) guide to learn more about compilation and how they can be applied here. For example, regional compilation can significantly reduce compilation time without giving up any speedups.
19+
1720
For image generation, combining quantization and [model offloading](./memory#model-offloading) can often give the best trade-off between quality, speed, and memory. Group offloading is not as effective for image generation because it is usually not possible to *fully* overlap data transfer if the compute kernel finishes faster. This results in some communication overhead between the CPU and GPU.
1821

1922
For video generation, combining quantization and [group-offloading](./memory#group-offloading) tends to be better because video models are more compute-bound.
@@ -25,7 +28,7 @@ The table below provides a comparison of optimization strategy combinations and
2528
| quantization | 32.602 | 14.9453 |
2629
| quantization, torch.compile | 25.847 | 14.9448 |
2730
| quantization, torch.compile, model CPU offloading | 32.312 | 12.2369 |
28-
<small>These results are benchmarked on Flux with a RTX 4090. The transformer and text_encoder components are quantized. Refer to the <a href="https://gist.github.com/sayakpaul/0db9d8eeeb3d2a0e5ed7cf0d9ca19b7d" benchmarking script</a> if you're interested in evaluating your own model.</small>
31+
<small>These results are benchmarked on Flux with a RTX 4090. The transformer and text_encoder components are quantized. Refer to the [benchmarking script](https://gist.github.com/sayakpaul/0db9d8eeeb3d2a0e5ed7cf0d9ca19b7d) if you're interested in evaluating your own model.</small>
2932

3033
This guide will show you how to compile and offload a quantized model with [bitsandbytes](../quantization/bitsandbytes#torchcompile). Make sure you are using [PyTorch nightly](https://pytorch.org/get-started/locally/) and the latest version of bitsandbytes.
3134

src/diffusers/loaders/single_file_model.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from .. import __version__
2525
from ..quantizers import DiffusersAutoQuantizer
2626
from ..utils import deprecate, is_accelerate_available, logging
27+
from ..utils.torch_utils import device_synchronize, empty_device_cache
2728
from .single_file_utils import (
2829
SingleFileComponentError,
2930
convert_animatediff_checkpoint_to_diffusers,
@@ -430,6 +431,10 @@ def from_single_file(cls, pretrained_model_link_or_path_or_dict: Optional[str] =
430431
keep_in_fp32_modules=keep_in_fp32_modules,
431432
unexpected_keys=unexpected_keys,
432433
)
434+
# Ensure tensors are correctly placed on device by synchronizing before returning control to user. This is
435+
# required because we move tensors with non_blocking=True, which is slightly faster for model loading.
436+
empty_device_cache()
437+
device_synchronize()
433438
else:
434439
_, unexpected_keys = model.load_state_dict(diffusers_format_checkpoint, strict=False)
435440

src/diffusers/loaders/single_file_utils.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
)
4747
from ..utils.constants import DIFFUSERS_REQUEST_TIMEOUT
4848
from ..utils.hub_utils import _get_model_file
49+
from ..utils.torch_utils import device_synchronize, empty_device_cache
4950

5051

5152
if is_transformers_available():
@@ -1689,6 +1690,10 @@ def create_diffusers_clip_model_from_ldm(
16891690

16901691
if is_accelerate_available():
16911692
load_model_dict_into_meta(model, diffusers_format_checkpoint, dtype=torch_dtype)
1693+
# Ensure tensors are correctly placed on device by synchronizing before returning control to user. This is
1694+
# required because we move tensors with non_blocking=True, which is slightly faster for model loading.
1695+
empty_device_cache()
1696+
device_synchronize()
16921697
else:
16931698
model.load_state_dict(diffusers_format_checkpoint, strict=False)
16941699

@@ -2148,6 +2153,10 @@ def create_diffusers_t5_model_from_checkpoint(
21482153

21492154
if is_accelerate_available():
21502155
load_model_dict_into_meta(model, diffusers_format_checkpoint, dtype=torch_dtype)
2156+
# Ensure tensors are correctly placed on device by synchronizing before returning control to user. This is
2157+
# required because we move tensors with non_blocking=True, which is slightly faster for model loading.
2158+
empty_device_cache()
2159+
device_synchronize()
21512160
else:
21522161
model.load_state_dict(diffusers_format_checkpoint)
21532162

src/diffusers/loaders/transformer_flux.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,8 @@
1818
MultiIPAdapterImageProjection,
1919
)
2020
from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT, load_model_dict_into_meta
21-
from ..utils import (
22-
is_accelerate_available,
23-
is_torch_version,
24-
logging,
25-
)
21+
from ..utils import is_accelerate_available, is_torch_version, logging
22+
from ..utils.torch_utils import device_synchronize, empty_device_cache
2623

2724

2825
if is_accelerate_available():
@@ -84,6 +81,8 @@ def _convert_ip_adapter_image_proj_to_diffusers(self, state_dict, low_cpu_mem_us
8481
else:
8582
device_map = {"": self.device}
8683
load_model_dict_into_meta(image_projection, updated_state_dict, device_map=device_map, dtype=self.dtype)
84+
empty_device_cache()
85+
device_synchronize()
8786

8887
return image_projection
8988

@@ -158,6 +157,9 @@ def _convert_ip_adapter_attn_to_diffusers(self, state_dicts, low_cpu_mem_usage=_
158157

159158
key_id += 1
160159

160+
empty_device_cache()
161+
device_synchronize()
162+
161163
return attn_procs
162164

163165
def _load_ip_adapter_weights(self, state_dicts, low_cpu_mem_usage=_LOW_CPU_MEM_USAGE_DEFAULT):

src/diffusers/loaders/transformer_sd3.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from ..models.embeddings import IPAdapterTimeImageProjection
1919
from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT, load_model_dict_into_meta
2020
from ..utils import is_accelerate_available, is_torch_version, logging
21+
from ..utils.torch_utils import device_synchronize, empty_device_cache
2122

2223

2324
logger = logging.get_logger(__name__)
@@ -80,6 +81,9 @@ def _convert_ip_adapter_attn_to_diffusers(
8081
attn_procs[name], layer_state_dict[idx], device_map=device_map, dtype=self.dtype
8182
)
8283

84+
empty_device_cache()
85+
device_synchronize()
86+
8387
return attn_procs
8488

8589
def _convert_ip_adapter_image_proj_to_diffusers(
@@ -147,6 +151,8 @@ def _convert_ip_adapter_image_proj_to_diffusers(
147151
else:
148152
device_map = {"": self.device}
149153
load_model_dict_into_meta(image_proj, updated_state_dict, device_map=device_map, dtype=self.dtype)
154+
empty_device_cache()
155+
device_synchronize()
150156

151157
return image_proj
152158

src/diffusers/loaders/unet.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
is_torch_version,
4444
logging,
4545
)
46+
from ..utils.torch_utils import device_synchronize, empty_device_cache
4647
from .lora_base import _func_optionally_disable_offloading
4748
from .lora_pipeline import LORA_WEIGHT_NAME, LORA_WEIGHT_NAME_SAFE, TEXT_ENCODER_NAME, UNET_NAME
4849
from .utils import AttnProcsLayers
@@ -753,6 +754,8 @@ def _convert_ip_adapter_image_proj_to_diffusers(self, state_dict, low_cpu_mem_us
753754
else:
754755
device_map = {"": self.device}
755756
load_model_dict_into_meta(image_projection, updated_state_dict, device_map=device_map, dtype=self.dtype)
757+
empty_device_cache()
758+
device_synchronize()
756759

757760
return image_projection
758761

@@ -850,6 +853,9 @@ def _convert_ip_adapter_attn_to_diffusers(self, state_dicts, low_cpu_mem_usage=_
850853

851854
key_id += 2
852855

856+
empty_device_cache()
857+
device_synchronize()
858+
853859
return attn_procs
854860

855861
def _load_ip_adapter_weights(self, state_dicts, low_cpu_mem_usage=_LOW_CPU_MEM_USAGE_DEFAULT):

src/diffusers/models/model_loading_utils.py

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,10 @@
1616

1717
import importlib
1818
import inspect
19+
import math
1920
import os
2021
from array import array
21-
from collections import OrderedDict
22+
from collections import OrderedDict, defaultdict
2223
from pathlib import Path
2324
from typing import Dict, List, Optional, Union
2425
from zipfile import is_zipfile
@@ -38,6 +39,7 @@
3839
_get_model_file,
3940
deprecate,
4041
is_accelerate_available,
42+
is_accelerate_version,
4143
is_gguf_available,
4244
is_torch_available,
4345
is_torch_version,
@@ -252,6 +254,10 @@ def load_model_dict_into_meta(
252254
param = param.to(dtype)
253255
set_module_kwargs["dtype"] = dtype
254256

257+
if is_accelerate_version(">", "1.8.1"):
258+
set_module_kwargs["non_blocking"] = True
259+
set_module_kwargs["clear_cache"] = False
260+
255261
# For compatibility with PyTorch load_state_dict which converts state dict dtype to existing dtype in model, and which
256262
# uses `param.copy_(input_param)` that preserves the contiguity of the parameter in the model.
257263
# Reference: https://github.com/pytorch/pytorch/blob/db79ceb110f6646523019a59bbd7b838f43d4a86/torch/nn/modules/module.py#L2040C29-L2040C29
@@ -520,3 +526,60 @@ def load_gguf_checkpoint(gguf_checkpoint_path, return_tensors=False):
520526
parsed_parameters[name] = GGUFParameter(weights, quant_type=quant_type) if is_gguf_quant else weights
521527

522528
return parsed_parameters
529+
530+
531+
def _find_mismatched_keys(state_dict, model_state_dict, loaded_keys, ignore_mismatched_sizes):
532+
mismatched_keys = []
533+
if not ignore_mismatched_sizes:
534+
return mismatched_keys
535+
for checkpoint_key in loaded_keys:
536+
model_key = checkpoint_key
537+
# If the checkpoint is sharded, we may not have the key here.
538+
if checkpoint_key not in state_dict:
539+
continue
540+
541+
if model_key in model_state_dict and state_dict[checkpoint_key].shape != model_state_dict[model_key].shape:
542+
mismatched_keys.append(
543+
(checkpoint_key, state_dict[checkpoint_key].shape, model_state_dict[model_key].shape)
544+
)
545+
del state_dict[checkpoint_key]
546+
return mismatched_keys
547+
548+
549+
def _expand_device_map(device_map, param_names):
550+
"""
551+
Expand a device map to return the correspondence parameter name to device.
552+
"""
553+
new_device_map = {}
554+
for module, device in device_map.items():
555+
new_device_map.update(
556+
{p: device for p in param_names if p == module or p.startswith(f"{module}.") or module == ""}
557+
)
558+
return new_device_map
559+
560+
561+
# Adapted from: https://github.com/huggingface/transformers/blob/0687d481e2c71544501ef9cb3eef795a6e79b1de/src/transformers/modeling_utils.py#L5859
562+
def _caching_allocator_warmup(model, expanded_device_map: Dict[str, torch.device], dtype: torch.dtype) -> None:
563+
"""
564+
This function warm-ups the caching allocator based on the size of the model tensors that will reside on each
565+
device. It allows to have one large call to Malloc, instead of recursively calling it later when loading the model,
566+
which is actually the loading speed bottleneck. Calling this function allows to cut the model loading time by a
567+
very large margin.
568+
"""
569+
# Remove disk and cpu devices, and cast to proper torch.device
570+
accelerator_device_map = {
571+
param: torch.device(device)
572+
for param, device in expanded_device_map.items()
573+
if str(device) not in ["cpu", "disk"]
574+
}
575+
parameter_count = defaultdict(lambda: 0)
576+
for param_name, device in accelerator_device_map.items():
577+
try:
578+
param = model.get_parameter(param_name)
579+
except AttributeError:
580+
param = model.get_buffer(param_name)
581+
parameter_count[device] += math.prod(param.shape)
582+
583+
# This will kick off the caching allocator to avoid having to Malloc afterwards
584+
for device, param_count in parameter_count.items():
585+
_ = torch.empty(param_count, dtype=dtype, device=device, requires_grad=False)

0 commit comments

Comments
 (0)