Skip to content

Commit 325f493

Browse files
committed
up
2 parents 5b735b7 + 5e181ed commit 325f493

File tree

114 files changed

+7013
-244
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

114 files changed

+7013
-244
lines changed

docs/source/en/_toctree.yml

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,14 @@
2424
title: Reproducibility
2525
- local: using-diffusers/schedulers
2626
title: Load schedulers and models
27+
- local: using-diffusers/models
28+
title: Models
2729
- local: using-diffusers/scheduler_features
2830
title: Scheduler features
2931
- local: using-diffusers/other-formats
3032
title: Model files and layouts
3133
- local: using-diffusers/push_to_hub
32-
title: Push files to the Hub
34+
title: Sharing pipelines and models
3335

3436
- title: Adapters
3537
isExpanded: false
@@ -58,12 +60,6 @@
5860
title: Batch inference
5961
- local: training/distributed_inference
6062
title: Distributed inference
61-
- local: using-diffusers/scheduler_features
62-
title: Scheduler features
63-
- local: using-diffusers/callback
64-
title: Pipeline callbacks
65-
- local: using-diffusers/image_quality
66-
title: Controlling image quality
6763

6864
- title: Inference optimization
6965
isExpanded: false
@@ -92,6 +88,8 @@
9288
title: xDiT
9389
- local: optimization/para_attn
9490
title: ParaAttention
91+
- local: using-diffusers/image_quality
92+
title: FreeU
9593

9694
- title: Hybrid Inference
9795
isExpanded: false

docs/source/en/api/image_processor.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@ All pipelines with [`VaeImageProcessor`] accept PIL Image, PyTorch tensor, or Nu
2020

2121
[[autodoc]] image_processor.VaeImageProcessor
2222

23+
## InpaintProcessor
24+
25+
The [`InpaintProcessor`] accepts `mask` and `image` inputs and process them together. Optionally, it can accept padding_mask_crop and apply mask overlay.
26+
27+
[[autodoc]] image_processor.InpaintProcessor
28+
2329
## VaeImageProcessorLDM3D
2430

2531
The [`VaeImageProcessorLDM3D`] accepts RGB and depth inputs and returns RGB and depth outputs.

docs/source/en/api/pipelines/cogvideox.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ from diffusers.utils import export_to_video
5050
pipeline_quant_config = PipelineQuantizationConfig(
5151
quant_backend="torchao",
5252
quant_kwargs={"quant_type": "int8wo"},
53-
components_to_quantize=["transformer"]
53+
components_to_quantize="transformer"
5454
)
5555

5656
# fp8 layerwise weight-casting

docs/source/en/api/pipelines/hunyuan_video.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ pipeline_quant_config = PipelineQuantizationConfig(
5454
"bnb_4bit_quant_type": "nf4",
5555
"bnb_4bit_compute_dtype": torch.bfloat16
5656
},
57-
components_to_quantize=["transformer"]
57+
components_to_quantize="transformer"
5858
)
5959

6060
pipeline = HunyuanVideoPipeline.from_pretrained(
@@ -91,7 +91,7 @@ pipeline_quant_config = PipelineQuantizationConfig(
9191
"bnb_4bit_quant_type": "nf4",
9292
"bnb_4bit_compute_dtype": torch.bfloat16
9393
},
94-
components_to_quantize=["transformer"]
94+
components_to_quantize="transformer"
9595
)
9696

9797
pipeline = HunyuanVideoPipeline.from_pretrained(
@@ -139,7 +139,7 @@ export_to_video(video, "output.mp4", fps=15)
139139
"bnb_4bit_quant_type": "nf4",
140140
"bnb_4bit_compute_dtype": torch.bfloat16
141141
},
142-
components_to_quantize=["transformer"]
142+
components_to_quantize="transformer"
143143
)
144144

145145
pipeline = HunyuanVideoPipeline.from_pretrained(

docs/source/en/optimization/memory.md

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -291,13 +291,53 @@ Group offloading moves groups of internal layers ([torch.nn.ModuleList](https://
291291
> [!WARNING]
292292
> Group offloading may not work with all models if the forward implementation contains weight-dependent device casting of inputs because it may clash with group offloading's device casting mechanism.
293293
294-
Call [`~ModelMixin.enable_group_offload`] to enable it for standard Diffusers model components that inherit from [`ModelMixin`]. For other model components that don't inherit from [`ModelMixin`], such as a generic [torch.nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html), use [`~hooks.apply_group_offloading`] instead.
295-
296-
The `offload_type` parameter can be set to `block_level` or `leaf_level`.
294+
Enable group offloading by configuring the `offload_type` parameter to `block_level` or `leaf_level`.
297295

298296
- `block_level` offloads groups of layers based on the `num_blocks_per_group` parameter. For example, if `num_blocks_per_group=2` on a model with 40 layers, 2 layers are onloaded and offloaded at a time (20 total onloads/offloads). This drastically reduces memory requirements.
299297
- `leaf_level` offloads individual layers at the lowest level and is equivalent to [CPU offloading](#cpu-offloading). But it can be made faster if you use streams without giving up inference speed.
300298

299+
Group offloading is supported for entire pipelines or individual models. Applying group offloading to the entire pipeline is the easiest option while selectively applying it to individual models gives users more flexibility to use different offloading techniques for different models.
300+
301+
<hfoptions id="group-offloading">
302+
<hfoption id="pipeline">
303+
304+
Call [`~DiffusionPipeline.enable_group_offload`] on a pipeline.
305+
306+
```py
307+
import torch
308+
from diffusers import CogVideoXPipeline
309+
from diffusers.hooks import apply_group_offloading
310+
from diffusers.utils import export_to_video
311+
312+
onload_device = torch.device("cuda")
313+
offload_device = torch.device("cpu")
314+
315+
pipeline = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16)
316+
pipeline.enable_group_offload(
317+
onload_device=onload_device,
318+
offload_device=offload_device,
319+
offload_type="leaf_level",
320+
use_stream=True
321+
)
322+
323+
prompt = (
324+
"A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. "
325+
"The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other "
326+
"pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, "
327+
"casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. "
328+
"The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical "
329+
"atmosphere of this unique musical performance."
330+
)
331+
video = pipeline(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0]
332+
print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
333+
export_to_video(video, "output.mp4", fps=8)
334+
```
335+
336+
</hfoption>
337+
<hfoption id="model">
338+
339+
Call [`~ModelMixin.enable_group_offload`] on standard Diffusers model components that inherit from [`ModelMixin`]. For other model components that don't inherit from [`ModelMixin`], such as a generic [torch.nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html), use [`~hooks.apply_group_offloading`] instead.
340+
301341
```py
302342
import torch
303343
from diffusers import CogVideoXPipeline
@@ -328,6 +368,9 @@ print(f"Max memory reserved: {torch.cuda.max_memory_allocated() / 1024**3:.2f} G
328368
export_to_video(video, "output.mp4", fps=8)
329369
```
330370

371+
</hfoption>
372+
</hfoptions>
373+
331374
#### CUDA stream
332375

333376
The `use_stream` parameter can be activated for CUDA devices that support asynchronous data transfer streams to reduce overall execution time compared to [CPU offloading](#cpu-offloading). It overlaps data transfer and computation by using layer prefetching. The next layer to be executed is loaded onto the GPU while the current layer is still being executed. It can increase CPU memory significantly so ensure you have 2x the amount of memory as the model size.

docs/source/en/quantization/overview.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@ Initialize [`~quantizers.PipelineQuantizationConfig`] with the following paramet
3434
> [!TIP]
3535
> These `quant_kwargs` arguments are different for each backend. Refer to the [Quantization API](../api/quantization) docs to view the arguments for each backend.
3636
37-
- `components_to_quantize` specifies which components of the pipeline to quantize. Typically, you should quantize the most compute intensive components like the transformer. The text encoder is another component to consider quantizing if a pipeline has more than one such as [`FluxPipeline`]. The example below quantizes the T5 text encoder in [`FluxPipeline`] while keeping the CLIP model intact.
37+
- `components_to_quantize` specifies which component(s) of the pipeline to quantize. Typically, you should quantize the most compute intensive components like the transformer. The text encoder is another component to consider quantizing if a pipeline has more than one such as [`FluxPipeline`]. The example below quantizes the T5 text encoder in [`FluxPipeline`] while keeping the CLIP model intact.
38+
39+
`components_to_quantize` accepts either a list for multiple models or a string for a single model.
3840

3941
The example below loads the bitsandbytes backend with the following arguments from [`~quantizers.quantization_config.BitsAndBytesConfig`], `load_in_4bit`, `bnb_4bit_quant_type`, and `bnb_4bit_compute_dtype`.
4042

@@ -62,6 +64,7 @@ pipe = DiffusionPipeline.from_pretrained(
6264
image = pipe("photo of a cute dog").images[0]
6365
```
6466

67+
6568
### Advanced quantization
6669

6770
The `quant_mapping` argument provides more options for how to quantize each individual component in a pipeline, like combining different quantization backends.

docs/source/en/using-diffusers/image_quality.md

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,7 @@ 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-
# Controlling image quality
14-
15-
The components of a diffusion model, like the UNet and scheduler, can be optimized to improve the quality of generated images leading to better details. These techniques are especially useful if you don't have the resources to simply use a larger model for inference. You can enable these techniques during inference without any additional training.
16-
17-
This guide will show you how to turn these techniques on in your pipeline and how to configure them to improve the quality of your generated images.
18-
19-
## Details
13+
# FreeU
2014

2115
[FreeU](https://hf.co/papers/2309.11497) improves image details by rebalancing the UNet's backbone and skip connection weights. The skip connections can cause the model to overlook some of the backbone semantics which may lead to unnatural image details in the generated image. This technique does not require any additional training and can be applied on the fly during inference for tasks like image-to-image and text-to-video.
2216

@@ -139,7 +133,7 @@ export_to_video(video_frames, "teddy_bear.mp4", fps=10)
139133
</hfoption>
140134
</hfoptions>
141135

142-
Call the [`pipelines.StableDiffusionMixin.disable_freeu`] method to disable FreeU.
136+
Call the [`~pipelines.StableDiffusionMixin.disable_freeu`] method to disable FreeU.
143137

144138
```py
145139
pipeline.disable_freeu()

docs/source/en/using-diffusers/loading.md

Lines changed: 6 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -108,50 +108,27 @@ print(pipeline.transformer.dtype, pipeline.vae.dtype)
108108

109109
The `device_map` argument determines individual model or pipeline placement on an accelerator like a GPU. It is especially helpful when there are multiple GPUs.
110110

111-
Diffusers currently provides three options to `device_map`, `"cuda"`, `"balanced"` and `"auto"`. Refer to the table below to compare the three placement strategies.
111+
A pipeline supports two options for `device_map`, `"cuda"` and `"balanced"`. Refer to the table below to compare the placement strategies.
112112

113113
| parameter | description |
114114
|---|---|
115-
| `"cuda"` | places model or pipeline on CUDA device |
116-
| `"balanced"` | evenly distributes model or pipeline on all GPUs |
117-
| `"auto"` | distribute model from fastest device first to slowest |
115+
| `"cuda"` | places pipeline on a supported accelerator device like CUDA |
116+
| `"balanced"` | evenly distributes pipeline on all GPUs |
118117

119118
Use the `max_memory` argument in [`~DiffusionPipeline.from_pretrained`] to allocate a maximum amount of memory to use on each device. By default, Diffusers uses the maximum amount available.
120119

121-
<hfoptions id="device_map">
122-
<hfoption id="pipeline">
123-
124120
```py
125121
import torch
126122
from diffusers import DiffusionPipeline
127123

124+
max_memory = {0: "16GB", 1: "16GB"}
128125
pipeline = DiffusionPipeline.from_pretrained(
129126
"Qwen/Qwen-Image",
130127
torch_dtype=torch.bfloat16,
131128
device_map="cuda",
132129
)
133130
```
134131

135-
</hfoption>
136-
<hfoption id="individual model">
137-
138-
```py
139-
import torch
140-
from diffusers import AutoModel
141-
142-
max_memory = {0: "16GB", 1: "16GB"}
143-
transformer = AutoModel.from_pretrained(
144-
"Qwen/Qwen-Image",
145-
subfolder="transformer",
146-
torch_dtype=torch.bfloat16
147-
device_map="cuda",
148-
max_memory=max_memory
149-
)
150-
```
151-
152-
</hfoption>
153-
</hfoptions>
154-
155132
The `hf_device_map` attribute allows you to access and view the `device_map`.
156133

157134
```py
@@ -189,22 +166,18 @@ pipeline = DiffusionPipeline.from_pretrained(
189166

190167
[`DiffusionPipeline`] is flexible and accommodates loading different models or schedulers. You can experiment with different schedulers to optimize for generation speed or quality, and you can replace models with more performant ones.
191168

192-
The example below swaps the default scheduler to generate higher quality images and a more stable VAE version. Pass the `subfolder` argument in [`~HeunDiscreteScheduler.from_pretrained`] to load the scheduler to the correct subfolder.
169+
The example below uses a more stable VAE version.
193170

194171
```py
195172
import torch
196-
from diffusers import DiffusionPipeline, HeunDiscreteScheduler, AutoModel
173+
from diffusers import DiffusionPipeline, AutoModel
197174

198-
scheduler = HeunDiscreteScheduler.from_pretrained(
199-
"stabilityai/stable-diffusion-xl-base-1.0", subfolder="scheduler"
200-
)
201175
vae = AutoModel.from_pretrained(
202176
"madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16
203177
)
204178

205179
pipeline = DiffusionPipeline.from_pretrained(
206180
"stabilityai/stable-diffusion-xl-base-1.0",
207-
scheduler=scheduler,
208181
vae=vae,
209182
torch_dtype=torch.float16,
210183
device_map="cuda"
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
<!--Copyright 2025 The HuggingFace Team. All rights reserved.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4+
the License. You may obtain a copy of the License at
5+
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
8+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10+
specific language governing permissions and limitations under the License.
11+
-->
12+
13+
[[open-in-colab]]
14+
15+
# Models
16+
17+
A diffusion model relies on a few individual models working together to generate an output. These models are responsible for denoising, encoding inputs, and decoding latents into the actual outputs.
18+
19+
This guide will show you how to load models.
20+
21+
## Loading a model
22+
23+
All models are loaded with the [`~ModelMixin.from_pretrained`] method, which downloads and caches the latest model version. If the latest files are available in the local cache, [`~ModelMixin.from_pretrained`] reuses files in the cache.
24+
25+
Pass the `subfolder` argument to [`~ModelMixin.from_pretrained`] to specify where to load the model weights from. Omit the `subfolder` argument if the repository doesn't have a subfolder structure or if you're loading a standalone model.
26+
27+
```py
28+
from diffusers import QwenImageTransformer2DModel
29+
30+
model = QwenImageTransformer2DModel.from_pretrained("Qwen/Qwen-Image", subfolder="transformer")
31+
```
32+
33+
## AutoModel
34+
35+
[`AutoModel`] detects the model class from a `model_index.json` file or a model's `config.json` file. It fetches the correct model class from these files and delegates the actual loading to the model class. [`AutoModel`] is useful for automatic model type detection without needing to know the exact model class beforehand.
36+
37+
```py
38+
from diffusers import AutoModel
39+
40+
model = AutoModel.from_pretrained(
41+
"Qwen/Qwen-Image", subfolder="transformer"
42+
)
43+
```
44+
45+
## Model data types
46+
47+
Use the `torch_dtype` argument in [`~ModelMixin.from_pretrained`] to load a model with a specific data type. This allows you to load a model in a lower precision to reduce memory usage.
48+
49+
```py
50+
import torch
51+
from diffusers import QwenImageTransformer2DModel
52+
53+
model = QwenImageTransformer2DModel.from_pretrained(
54+
"Qwen/Qwen-Image",
55+
subfolder="transformer",
56+
torch_dtype=torch.bfloat16
57+
)
58+
```
59+
60+
[nn.Module.to](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.to) can also convert to a specific data type on the fly. However, it converts *all* weights to the requested data type unlike `torch_dtype` which respects `_keep_in_fp32_modules`. This argument preserves layers in `torch.float32` for numerical stability and best generation quality (see example [_keep_in_fp32_modules](https://github.com/huggingface/diffusers/blob/f864a9a352fa4a220d860bfdd1782e3e5af96382/src/diffusers/models/transformers/transformer_wan.py#L374))
61+
62+
```py
63+
from diffusers import QwenImageTransformer2DModel
64+
65+
model = QwenImageTransformer2DModel.from_pretrained(
66+
"Qwen/Qwen-Image", subfolder="transformer"
67+
)
68+
model = model.to(dtype=torch.float16)
69+
```
70+
71+
## Device placement
72+
73+
Use the `device_map` argument in [`~ModelMixin.from_pretrained`] to place a model on an accelerator like a GPU. It is especially helpful where there are multiple GPUs.
74+
75+
Diffusers currently provides three options to `device_map` for individual models, `"cuda"`, `"balanced"` and `"auto"`. Refer to the table below to compare the three placement strategies.
76+
77+
| parameter | description |
78+
|---|---|
79+
| `"cuda"` | places pipeline on a supported accelerator (CUDA) |
80+
| `"balanced"` | evenly distributes pipeline on all GPUs |
81+
| `"auto"` | distribute model from fastest device first to slowest |
82+
83+
Use the `max_memory` argument in [`~ModelMixin.from_pretrained`] to allocate a maximum amount of memory to use on each device. By default, Diffusers uses the maximum amount available.
84+
85+
```py
86+
import torch
87+
from diffusers import QwenImagePipeline
88+
89+
max_memory = {0: "16GB", 1: "16GB"}
90+
pipeline = QwenImagePipeline.from_pretrained(
91+
"Qwen/Qwen-Image",
92+
torch_dtype=torch.bfloat16,
93+
device_map="cuda",
94+
max_memory=max_memory
95+
)
96+
```
97+
98+
The `hf_device_map` attribute allows you to access and view the `device_map`.
99+
100+
```py
101+
print(transformer.hf_device_map)
102+
# {'': device(type='cuda')}
103+
```
104+
105+
## Saving models
106+
107+
Save a model with the [`~ModelMixin.save_pretrained`] method.
108+
109+
```py
110+
from diffusers import QwenImageTransformer2DModel
111+
112+
model = QwenImageTransformer2DModel.from_pretrained("Qwen/Qwen-Image", subfolder="transformer")
113+
model.save_pretrained("./local/model")
114+
```
115+
116+
For large models, it is helpful to use `max_shard_size` to save a model as multiple shards. A shard can be loaded faster and save memory (refer to the [parallel loading](./loading#parallel-loading) docs for more details), especially if there is more than one GPU.
117+
118+
```py
119+
model.save_pretrained("./local/model", max_shard_size="5GB")
120+
```

0 commit comments

Comments
 (0)